An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
rector: arrrrr
Andras Bacsai16c0cd10d891
diff --git a/app/Actions/Application/StopApplication.php b/app/Actions/Application/StopApplication.phpindex 642b4ba456..ed929573eb 100644--- a/app/Actions/Application/StopApplication.php+++ b/app/Actions/Application/StopApplication.php@@ -4,6 +4,7 @@ namespace App\Actions\Application;use App\Actions\Server\CleanupDocker;use App\Models\Application;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class StopApplication@@ -23,7 +24,7 @@ class StopApplicationif ($server->isSwarm()) {instant_remote_process(["docker stack rm {$application->uuid}"], $server);- return;+ return null;}$containersToStop = $application->getContainersToStop($previewDeployments);@@ -36,8 +37,10 @@ class StopApplicationif ($dockerCleanup) {CleanupDocker::dispatch($server, true);}- } catch (\Exception $e) {+ } catch (Exception $e) {return $e->getMessage();}++ return null;}}diff --git a/app/Actions/Application/StopApplicationOneServer.php b/app/Actions/Application/StopApplicationOneServer.phpindex b13b10efd6..a55efc3f31 100644--- a/app/Actions/Application/StopApplicationOneServer.php+++ b/app/Actions/Application/StopApplicationOneServer.php@@ -4,6 +4,7 @@ namespace App\Actions\Application;use App\Models\Application;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class StopApplicationOneServer@@ -13,7 +14,7 @@ class StopApplicationOneServerpublic function handle(Application $application, Server $server){if ($application->destination->server->isSwarm()) {- return;+ return null;}if (! $server->isFunctional()) {return 'Server is not functional';@@ -31,8 +32,10 @@ class StopApplicationOneServer}}}- } catch (\Exception $e) {+ } catch (Exception $e) {return $e->getMessage();}++ return null;}}diff --git a/app/Actions/CoolifyTask/PrepareCoolifyTask.php b/app/Actions/CoolifyTask/PrepareCoolifyTask.phpindex 3f76a2e3c7..fd6f697c60 100644--- a/app/Actions/CoolifyTask/PrepareCoolifyTask.php+++ b/app/Actions/CoolifyTask/PrepareCoolifyTask.php@@ -4,6 +4,7 @@ namespace App\Actions\CoolifyTask;use App\Data\CoolifyTaskArgs;use App\Jobs\CoolifyTask;+use Illuminate\Database\Eloquent\Model;use Spatie\Activitylog\Models\Activity;/**@@ -17,36 +18,36 @@ class PrepareCoolifyTaskprotected CoolifyTaskArgs $remoteProcessArgs;- public function __construct(CoolifyTaskArgs $remoteProcessArgs)+ public function __construct(CoolifyTaskArgs $coolifyTaskArgs){- $this->remoteProcessArgs = $remoteProcessArgs;+ $this->remoteProcessArgs = $coolifyTaskArgs;- if ($remoteProcessArgs->model) {- $properties = $remoteProcessArgs->toArray();+ if ($coolifyTaskArgs->model instanceof Model) {+ $properties = $coolifyTaskArgs->toArray();unset($properties['model']);$this->activity = activity()->withProperties($properties)- ->performedOn($remoteProcessArgs->model)- ->event($remoteProcessArgs->type)+ ->performedOn($coolifyTaskArgs->model)+ ->event($coolifyTaskArgs->type)->log('[]');} else {$this->activity = activity()- ->withProperties($remoteProcessArgs->toArray())- ->event($remoteProcessArgs->type)+ ->withProperties($coolifyTaskArgs->toArray())+ ->event($coolifyTaskArgs->type)->log('[]');}}public function __invoke(): Activity{- $job = new CoolifyTask(+ $coolifyTask = new CoolifyTask(activity: $this->activity,ignore_errors: $this->remoteProcessArgs->ignore_errors,call_event_on_finish: $this->remoteProcessArgs->call_event_on_finish,call_event_data: $this->remoteProcessArgs->call_event_data,);- dispatch($job);+ dispatch($coolifyTask);$this->activity->refresh();return $this->activity;diff --git a/app/Actions/CoolifyTask/RunRemoteProcess.php b/app/Actions/CoolifyTask/RunRemoteProcess.phpindex 981b81378e..78e995342c 100644--- a/app/Actions/CoolifyTask/RunRemoteProcess.php+++ b/app/Actions/CoolifyTask/RunRemoteProcess.php@@ -11,7 +11,10 @@ use Illuminate\Process\ProcessResult;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Process;+use JsonException;+use RuntimeException;use Spatie\Activitylog\Models\Activity;+use Throwable;class RunRemoteProcess{@@ -21,9 +24,9 @@ class RunRemoteProcesspublic bool $ignore_errors;- public $call_event_on_finish = null;+ public $call_event_on_finish;- public $call_event_data = null;+ public $call_event_data;protected $time_start;@@ -41,7 +44,7 @@ class RunRemoteProcesspublic function __construct(Activity $activity, bool $hide_from_output = false, bool $ignore_errors = false, $call_event_on_finish = null, $call_event_data = null){if ($activity->getExtraProperty('type') !== ActivityTypes::INLINE->value && $activity->getExtraProperty('type') !== ActivityTypes::COMMAND->value) {- throw new \RuntimeException('Incompatible Activity to run a remote command.');+ throw new RuntimeException('Incompatible Activity to run a remote command.');}$this->activity = $activity;@@ -63,7 +66,7 @@ class RunRemoteProcessassociative: true,flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);- } catch (\JsonException $exception) {+ } catch (JsonException $exception) {return '';}@@ -79,12 +82,12 @@ class RunRemoteProcess$status = ProcessStatus::IN_PROGRESS;$timeout = config('constants.ssh.command_timeout');- $process = Process::timeout($timeout)->start($this->getCommand(), $this->handleOutput(...));+ $invokedProcess = Process::timeout($timeout)->start($this->getCommand(), $this->handleOutput(...));$this->activity->properties = $this->activity->properties->merge([- 'process_id' => $process->id(),+ 'process_id' => $invokedProcess->id(),]);- $processResult = $process->wait();+ $processResult = $invokedProcess->wait();// $processResult = Process::timeout($timeout)->run($this->getCommand(), $this->handleOutput(...));if ($this->activity->properties->get('status') === ProcessStatus::ERROR->value) {$status = ProcessStatus::ERROR;@@ -111,7 +114,7 @@ class RunRemoteProcess]);$this->activity->save();if ($processResult->exitCode() != 0 && ! $this->ignore_errors) {- throw new \RuntimeException($processResult->errorOutput(), $processResult->exitCode());+ throw new RuntimeException($processResult->errorOutput(), $processResult->exitCode());}if ($this->call_event_on_finish) {try {@@ -124,7 +127,7 @@ class RunRemoteProcess'userId' => $this->activity->causer_id,]));}- } catch (\Throwable $e) {+ } catch (Throwable $e) {Log::error('Error calling event: '.$e->getMessage());}}diff --git a/app/Actions/Database/StartClickhouse.php b/app/Actions/Database/StartClickhouse.phpindex f218fcabb0..9d7114b1e6 100644--- a/app/Actions/Database/StartClickhouse.php+++ b/app/Actions/Database/StartClickhouse.php@@ -16,9 +16,9 @@ class StartClickhousepublic string $configuration_dir;- public function handle(StandaloneClickhouse $database)+ public function handle(StandaloneClickhouse $standaloneClickhouse){- $this->database = $database;+ $this->database = $standaloneClickhouse;$container_name = $this->database->uuid;$this->configuration_dir = database_configuration_dir().'/'.$container_name;@@ -103,12 +103,12 @@ class StartClickhouse$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneClickhouse->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneClickhouse->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartDatabase.php b/app/Actions/Database/StartDatabase.phpindex e2fa6fc871..0b2a3ce262 100644--- a/app/Actions/Database/StartDatabase.php+++ b/app/Actions/Database/StartDatabase.php@@ -25,28 +25,28 @@ class StartDatabasereturn 'Server is not functional';}switch ($database->getMorphClass()) {- case \App\Models\StandalonePostgresql::class:+ case StandalonePostgresql::class:$activity = StartPostgresql::run($database);break;- case \App\Models\StandaloneRedis::class:+ case StandaloneRedis::class:$activity = StartRedis::run($database);break;- case \App\Models\StandaloneMongodb::class:+ case StandaloneMongodb::class:$activity = StartMongodb::run($database);break;- case \App\Models\StandaloneMysql::class:+ case StandaloneMysql::class:$activity = StartMysql::run($database);break;- case \App\Models\StandaloneMariadb::class:+ case StandaloneMariadb::class:$activity = StartMariadb::run($database);break;- case \App\Models\StandaloneKeydb::class:+ case StandaloneKeydb::class:$activity = StartKeydb::run($database);break;- case \App\Models\StandaloneDragonfly::class:+ case StandaloneDragonfly::class:$activity = StartDragonfly::run($database);break;- case \App\Models\StandaloneClickhouse::class:+ case StandaloneClickhouse::class:$activity = StartClickhouse::run($database);break;}diff --git a/app/Actions/Database/StartDatabaseProxy.php b/app/Actions/Database/StartDatabaseProxy.phpindex 3ddf6c036b..89ed5935b7 100644--- a/app/Actions/Database/StartDatabaseProxy.php+++ b/app/Actions/Database/StartDatabaseProxy.php@@ -28,7 +28,7 @@ class StartDatabaseProxy$server = data_get($database, 'destination.server');$containerName = data_get($database, 'uuid');$proxyContainerName = "{$database->uuid}-proxy";- if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($database->getMorphClass() === ServiceDatabase::class) {$databaseType = $database->databaseType();// $connectPredefined = data_get($database, 'service.connect_to_docker_network');$network = $database->service->uuid;@@ -36,54 +36,54 @@ class StartDatabaseProxy$proxyContainerName = "{$database->service->uuid}-proxy";switch ($databaseType) {case 'standalone-mariadb':- $type = \App\Models\StandaloneMariadb::class;+ $type = StandaloneMariadb::class;$containerName = "mariadb-{$database->service->uuid}";break;case 'standalone-mongodb':- $type = \App\Models\StandaloneMongodb::class;+ $type = StandaloneMongodb::class;$containerName = "mongodb-{$database->service->uuid}";break;case 'standalone-mysql':- $type = \App\Models\StandaloneMysql::class;+ $type = StandaloneMysql::class;$containerName = "mysql-{$database->service->uuid}";break;case 'standalone-postgresql':- $type = \App\Models\StandalonePostgresql::class;+ $type = StandalonePostgresql::class;$containerName = "postgresql-{$database->service->uuid}";break;case 'standalone-redis':- $type = \App\Models\StandaloneRedis::class;+ $type = StandaloneRedis::class;$containerName = "redis-{$database->service->uuid}";break;case 'standalone-keydb':- $type = \App\Models\StandaloneKeydb::class;+ $type = StandaloneKeydb::class;$containerName = "keydb-{$database->service->uuid}";break;case 'standalone-dragonfly':- $type = \App\Models\StandaloneDragonfly::class;+ $type = StandaloneDragonfly::class;$containerName = "dragonfly-{$database->service->uuid}";break;case 'standalone-clickhouse':- $type = \App\Models\StandaloneClickhouse::class;+ $type = StandaloneClickhouse::class;$containerName = "clickhouse-{$database->service->uuid}";break;}}- if ($type === \App\Models\StandaloneRedis::class) {+ if ($type === StandaloneRedis::class) {$internalPort = 6379;- } elseif ($type === \App\Models\StandalonePostgresql::class) {+ } elseif ($type === StandalonePostgresql::class) {$internalPort = 5432;- } elseif ($type === \App\Models\StandaloneMongodb::class) {+ } elseif ($type === StandaloneMongodb::class) {$internalPort = 27017;- } elseif ($type === \App\Models\StandaloneMysql::class) {+ } elseif ($type === StandaloneMysql::class) {$internalPort = 3306;- } elseif ($type === \App\Models\StandaloneMariadb::class) {+ } elseif ($type === StandaloneMariadb::class) {$internalPort = 3306;- } elseif ($type === \App\Models\StandaloneKeydb::class) {+ } elseif ($type === StandaloneKeydb::class) {$internalPort = 6379;- } elseif ($type === \App\Models\StandaloneDragonfly::class) {+ } elseif ($type === StandaloneDragonfly::class) {$internalPort = 6379;- } elseif ($type === \App\Models\StandaloneClickhouse::class) {+ } elseif ($type === StandaloneClickhouse::class) {$internalPort = 9000;}$configuration_dir = database_proxy_dir($database->uuid);diff --git a/app/Actions/Database/StartDragonfly.php b/app/Actions/Database/StartDragonfly.phpindex 4f9f45b7c7..7ddac1c1dc 100644--- a/app/Actions/Database/StartDragonfly.php+++ b/app/Actions/Database/StartDragonfly.php@@ -16,9 +16,9 @@ class StartDragonflypublic string $configuration_dir;- public function handle(StandaloneDragonfly $database)+ public function handle(StandaloneDragonfly $standaloneDragonfly){- $this->database = $database;+ $this->database = $standaloneDragonfly;$startCommand = "dragonfly --requirepass {$this->database->dragonfly_password}";@@ -100,12 +100,12 @@ class StartDragonfly$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneDragonfly->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneDragonfly->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartKeydb.php b/app/Actions/Database/StartKeydb.phpindex 6c733d3180..8e5da12f4f 100644--- a/app/Actions/Database/StartKeydb.php+++ b/app/Actions/Database/StartKeydb.php@@ -17,9 +17,9 @@ class StartKeydbpublic string $configuration_dir;- public function handle(StandaloneKeydb $database)+ public function handle(StandaloneKeydb $standaloneKeydb){- $this->database = $database;+ $this->database = $standaloneKeydb;$startCommand = "keydb-server --requirepass {$this->database->keydb_password} --appendonly yes";@@ -92,7 +92,7 @@ class StartKeydbif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (! is_null($this->database->keydb_conf) || ! empty($this->database->keydb_conf)) {+ if (! is_null($this->database->keydb_conf) || $this->database->keydb_conf !== null) {$docker_compose['services'][$container_name]['volumes'][] = ['type' => 'bind','source' => $this->configuration_dir.'/keydb.conf',@@ -110,12 +110,12 @@ class StartKeydb$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneKeydb->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneKeydb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartMariadb.php b/app/Actions/Database/StartMariadb.phpindex 299b07385b..f161754d1f 100644--- a/app/Actions/Database/StartMariadb.php+++ b/app/Actions/Database/StartMariadb.php@@ -16,9 +16,9 @@ class StartMariadbpublic string $configuration_dir;- public function handle(StandaloneMariadb $database)+ public function handle(StandaloneMariadb $standaloneMariadb){- $this->database = $database;+ $this->database = $standaloneMariadb;$container_name = $this->database->uuid;$this->configuration_dir = database_configuration_dir().'/'.$container_name;@@ -87,7 +87,7 @@ class StartMariadbif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (! is_null($this->database->mariadb_conf) || ! empty($this->database->mariadb_conf)) {+ if (! is_null($this->database->mariadb_conf) || $this->database->mariadb_conf !== null) {$docker_compose['services'][$container_name]['volumes'][] = ['type' => 'bind','source' => $this->configuration_dir.'/custom-config.cnf',@@ -105,12 +105,12 @@ class StartMariadb$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneMariadb->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneMariadb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartMongodb.php b/app/Actions/Database/StartMongodb.phpindex 89d35ca7b4..f04d3d76b5 100644--- a/app/Actions/Database/StartMongodb.php+++ b/app/Actions/Database/StartMongodb.php@@ -16,9 +16,9 @@ class StartMongodbpublic string $configuration_dir;- public function handle(StandaloneMongodb $database)+ public function handle(StandaloneMongodb $standaloneMongodb){- $this->database = $database;+ $this->database = $standaloneMongodb;$startCommand = 'mongod';@@ -99,7 +99,7 @@ class StartMongodbif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (! is_null($this->database->mongo_conf) || ! empty($this->database->mongo_conf)) {+ if (! is_null($this->database->mongo_conf) || $this->database->mongo_conf !== null) {$docker_compose['services'][$container_name]['volumes'][] = ['type' => 'bind','source' => $this->configuration_dir.'/mongod.conf',@@ -125,12 +125,12 @@ class StartMongodb$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneMongodb->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneMongodb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartMysql.php b/app/Actions/Database/StartMysql.phpindex 73db1512a3..fcdb4225f2 100644--- a/app/Actions/Database/StartMysql.php+++ b/app/Actions/Database/StartMysql.php@@ -16,9 +16,9 @@ class StartMysqlpublic string $configuration_dir;- public function handle(StandaloneMysql $database)+ public function handle(StandaloneMysql $standaloneMysql){- $this->database = $database;+ $this->database = $standaloneMysql;$container_name = $this->database->uuid;$this->configuration_dir = database_configuration_dir().'/'.$container_name;@@ -87,7 +87,7 @@ class StartMysqlif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (! is_null($this->database->mysql_conf) || ! empty($this->database->mysql_conf)) {+ if (! is_null($this->database->mysql_conf) || $this->database->mysql_conf !== null) {$docker_compose['services'][$container_name]['volumes'][] = ['type' => 'bind','source' => $this->configuration_dir.'/custom-config.cnf',@@ -105,12 +105,12 @@ class StartMysql$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneMysql->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneMysql->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartPostgresql.php b/app/Actions/Database/StartPostgresql.phpindex 035849340d..a65ad24ce6 100644--- a/app/Actions/Database/StartPostgresql.php+++ b/app/Actions/Database/StartPostgresql.php@@ -18,9 +18,9 @@ class StartPostgresqlpublic string $configuration_dir;- public function handle(StandalonePostgresql $database)+ public function handle(StandalonePostgresql $standalonePostgresql){- $this->database = $database;+ $this->database = $standalonePostgresql;$container_name = $this->database->uuid;$this->configuration_dir = database_configuration_dir().'/'.$container_name;if (isDev()) {@@ -97,15 +97,13 @@ class StartPostgresqlif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (count($this->init_scripts) > 0) {- foreach ($this->init_scripts as $init_script) {- $docker_compose['services'][$container_name]['volumes'][] = [- 'type' => 'bind',- 'source' => $init_script,- 'target' => '/docker-entrypoint-initdb.d/'.basename($init_script),- 'read_only' => true,- ];- }+ foreach ($this->init_scripts as $init_script) {+ $docker_compose['services'][$container_name]['volumes'][] = [+ 'type' => 'bind',+ 'source' => $init_script,+ 'target' => '/docker-entrypoint-initdb.d/'.basename($init_script),+ 'read_only' => true,+ ];}if (filled($this->database->postgres_conf)) {$docker_compose['services'][$container_name]['volumes'][] = [@@ -129,12 +127,12 @@ class StartPostgresql$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standalonePostgresql->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standalonePostgresql->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StartRedis.php b/app/Actions/Database/StartRedis.phpindex 1beebd134b..a32af8c964 100644--- a/app/Actions/Database/StartRedis.php+++ b/app/Actions/Database/StartRedis.php@@ -17,9 +17,9 @@ class StartRedispublic string $configuration_dir;- public function handle(StandaloneRedis $database)+ public function handle(StandaloneRedis $standaloneRedis){- $this->database = $database;+ $this->database = $standaloneRedis;$container_name = $this->database->uuid;$this->configuration_dir = database_configuration_dir().'/'.$container_name;@@ -96,7 +96,7 @@ class StartRedisif (count($volume_names) > 0) {$docker_compose['volumes'] = $volume_names;}- if (! is_null($this->database->redis_conf) || ! empty($this->database->redis_conf)) {+ if (! is_null($this->database->redis_conf) || $this->database->redis_conf !== null) {$docker_compose['services'][$container_name]['volumes'][] = ['type' => 'bind','source' => $this->configuration_dir.'/redis.conf',@@ -114,12 +114,12 @@ class StartRedis$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";$readme = generate_readme_file($this->database->name, now());$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";- $this->commands[] = "echo 'Pulling {$database->image} image.'";+ $this->commands[] = "echo 'Pulling {$standaloneRedis->image} image.'";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";$this->commands[] = "echo 'Database started.'";- return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');+ return remote_process($this->commands, $standaloneRedis->destination->server, callEventOnFinish: 'DatabaseStatusChanged');}private function generate_local_persistent_volumes()diff --git a/app/Actions/Database/StopDatabase.php b/app/Actions/Database/StopDatabase.phpindex e4cea7cee8..2db2ddfc4d 100644--- a/app/Actions/Database/StopDatabase.php+++ b/app/Actions/Database/StopDatabase.php@@ -26,10 +26,8 @@ class StopDatabase}$this->stopContainer($database, $database->uuid, 300);- if (! $isDeleteOperation) {- if ($dockerCleanup) {- CleanupDocker::dispatch($server, true);- }+ if (! $isDeleteOperation && $dockerCleanup) {+ CleanupDocker::dispatch($server, true);}if ($database->is_public) {@@ -43,10 +41,10 @@ class StopDatabase{$server = $database->destination->server;- $process = Process::timeout($timeout)->start("docker stop --time=$timeout $containerName");+ $invokedProcess = Process::timeout($timeout)->start("docker stop --time=$timeout $containerName");$startTime = time();- while ($process->running()) {+ while ($invokedProcess->running()) {if (time() - $startTime >= $timeout) {$this->forceStopContainer($containerName, $server);break;@@ -66,10 +64,4 @@ class StopDatabase{instant_remote_process(command: ["docker rm -f $containerName"], server: $server, throwError: false);}-- private function deleteConnectedNetworks($uuid, $server)- {- instant_remote_process(["docker network disconnect {$uuid} coolify-proxy"], $server, false);- instant_remote_process(["docker network rm {$uuid}"], $server, false);- }}diff --git a/app/Actions/Database/StopDatabaseProxy.php b/app/Actions/Database/StopDatabaseProxy.phpindex 9ee7943515..451a5d3dde 100644--- a/app/Actions/Database/StopDatabaseProxy.php+++ b/app/Actions/Database/StopDatabaseProxy.php@@ -24,7 +24,7 @@ class StopDatabaseProxy{$server = data_get($database, 'destination.server');$uuid = $database->uuid;- if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($database->getMorphClass() === ServiceDatabase::class) {$uuid = $database->service->uuid;$server = data_get($database, 'service.server');}diff --git a/app/Actions/Docker/GetContainersStatus.php b/app/Actions/Docker/GetContainersStatus.phpindex 706356930b..aa19d680b8 100644--- a/app/Actions/Docker/GetContainersStatus.php+++ b/app/Actions/Docker/GetContainersStatus.php@@ -47,20 +47,20 @@ class GetContainersStatus$this->applications = $this->applications->filter(function ($value, $key) use ($skip_these_applications) {return ! $skip_these_applications->pluck('id')->contains($value->id);});- if ($this->containers === null) {+ if (! $this->containers instanceof Collection) {['containers' => $this->containers, 'containerReplicates' => $this->containerReplicates] = $this->server->getContainers();}if (is_null($this->containers)) {- return;+ return null;}if ($this->containerReplicates) {- foreach ($this->containerReplicates as $containerReplica) {- $name = data_get($containerReplica, 'Name');- $this->containers = $this->containers->map(function ($container) use ($name, $containerReplica) {+ foreach ($this->containerReplicates as $containerReplicate) {+ $name = data_get($containerReplicate, 'Name');+ $this->containers = $this->containers->map(function ($container) use ($name, $containerReplicate) {if (data_get($container, 'Spec.Name') === $name) {- $replicas = data_get($containerReplica, 'Replicas');+ $replicas = data_get($containerReplicate, 'Replicas');$running = str($replicas)->explode('/')[0];$total = str($replicas)->explode('/')[1];if ($running === $total) {@@ -102,7 +102,7 @@ class GetContainersStatusif (str($applicationId)->contains('-')) {$applicationId = str($applicationId)->before('-');}- $preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();+ $preview = ApplicationPreview::query()->where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();if ($preview) {$foundApplicationPreviews[] = $preview->id;$statusFromDb = $preview->status;@@ -112,7 +112,7 @@ class GetContainersStatus$preview->update(['last_online_at' => now()]);}} else {- //Notify user that this container should not be there.+ // Notify user that this container should not be there.}} else {$application = $this->applications->where('id', $applicationId)->first();@@ -125,7 +125,7 @@ class GetContainersStatus$application->update(['last_online_at' => now()]);}} else {- //Notify user that this container should not be there.+ // Notify user that this container should not be there.}}} else {@@ -136,7 +136,7 @@ class GetContainersStatusif ($type === 'service') {$database_id = data_get($labels, 'coolify.service.subId');if ($database_id) {- $service_db = ServiceDatabase::where('id', $database_id)->first();+ $service_db = ServiceDatabase::query()->where('id', $database_id)->first();if ($service_db) {$uuid = data_get($service_db, 'service.uuid');if ($uuid) {@@ -145,9 +145,9 @@ class GetContainersStatus$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {if ($this->server->isSwarm()) {return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";- } else {- return data_get($value, 'Name') === "/$uuid-proxy";}++ return data_get($value, 'Name') === "/$uuid-proxy";})->first();if (! $foundTcpProxy) {StartDatabaseProxy::run($service_db);@@ -173,9 +173,9 @@ class GetContainersStatus$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {if ($this->server->isSwarm()) {return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";- } else {- return data_get($value, 'Name') === "/$uuid-proxy";}++ return data_get($value, 'Name') === "/$uuid-proxy";})->first();if (! $foundTcpProxy) {StartDatabaseProxy::run($database);@@ -223,16 +223,14 @@ class GetContainersStatusforeach ($apps as $app) {if (in_array("$app->id-$app->name", $foundServices)) {continue;- } else {- $exitedServices->push($app);}+ $exitedServices->push($app);}foreach ($dbs as $db) {if (in_array("$db->id-$db->name", $foundServices)) {continue;- } else {- $exitedServices->push($db);}+ $exitedServices->push($db);}}$exitedServices = $exitedServices->unique('uuid');@@ -243,17 +241,11 @@ class GetContainersStatus$name = data_get($exitedService, 'name');$fqdn = data_get($exitedService, 'fqdn');if ($name) {- if ($fqdn) {- $containerName = "$name, available at $fqdn";- } else {- $containerName = $name;- }+ $containerName = $fqdn ? "$name, available at $fqdn" : $name;+ } elseif ($fqdn) {+ $containerName = $fqdn;} else {- if ($fqdn) {- $containerName = $fqdn;- } else {- $containerName = null;- }+ $containerName = null;}$projectUuid = data_get($service, 'environment.project.uuid');$serviceUuid = data_get($service, 'uuid');@@ -269,8 +261,8 @@ class GetContainersStatus}$notRunningApplications = $this->applications->pluck('id')->diff($foundApplications);- foreach ($notRunningApplications as $applicationId) {- $application = $this->applications->where('id', $applicationId)->first();+ foreach ($notRunningApplications as $notRunningApplication) {+ $application = $this->applications->where('id', $notRunningApplication)->first();if (str($application->status)->startsWith('exited')) {continue;}@@ -294,8 +286,8 @@ class GetContainersStatus// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));}$notRunningApplicationPreviews = $previews->pluck('id')->diff($foundApplicationPreviews);- foreach ($notRunningApplicationPreviews as $previewId) {- $preview = $previews->where('id', $previewId)->first();+ foreach ($notRunningApplicationPreviews as $notRunningApplicationPreview) {+ $preview = $previews->where('id', $notRunningApplicationPreview)->first();if (str($preview->status)->startsWith('exited')) {continue;}@@ -319,21 +311,21 @@ class GetContainersStatus// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));}$notRunningDatabases = $databases->pluck('id')->diff($foundDatabases);- foreach ($notRunningDatabases as $database) {- $database = $databases->where('id', $database)->first();- if (str($database->status)->startsWith('exited')) {+ foreach ($notRunningDatabases as $notRunningDatabase) {+ $notRunningDatabase = $databases->where('id', $notRunningDatabase)->first();+ if (str($notRunningDatabase->status)->startsWith('exited')) {continue;}- $database->update(['status' => 'exited']);+ $notRunningDatabase->update(['status' => 'exited']);- $name = data_get($database, 'name');- $fqdn = data_get($database, 'fqdn');+ $name = data_get($notRunningDatabase, 'name');+ $fqdn = data_get($notRunningDatabase, 'fqdn');$containerName = $name;- $projectUuid = data_get($database, 'environment.project.uuid');- $environmentName = data_get($database, 'environment.name');- $databaseUuid = data_get($database, 'uuid');+ $projectUuid = data_get($notRunningDatabase, 'environment.project.uuid');+ $environmentName = data_get($notRunningDatabase, 'environment.name');+ $databaseUuid = data_get($notRunningDatabase, 'uuid');if ($projectUuid && $databaseUuid && $environmentName) {$url = base_url().'/project/'.$projectUuid.'/'.$environmentName.'/database/'.$databaseUuid;@@ -342,5 +334,7 @@ class GetContainersStatus}// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));}++ return null;}}diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.phpindex ea2befd3a8..d67db2a39b 100644--- a/app/Actions/Fortify/CreateNewUser.php+++ b/app/Actions/Fortify/CreateNewUser.php@@ -34,10 +34,10 @@ class CreateNewUser implements CreatesNewUsers'password' => ['required', Password::defaults(), 'confirmed'],])->validate();- if (User::count() == 0) {+ if (User::query()->count() == 0) {// If this is the first user, make them the root user// Team is already created in the database/seeders/ProductionSeeder.php- $user = User::create([+ $user = User::query()->create(['id' => 0,'name' => $input['name'],'email' => strtolower($input['email']),@@ -50,7 +50,7 @@ class CreateNewUser implements CreatesNewUsers$settings->is_registration_enabled = false;$settings->save();} else {- $user = User::create([+ $user = User::query()->create(['name' => $input['name'],'email' => strtolower($input['email']),'password' => Hash::make($input['password']),diff --git a/app/Actions/Proxy/CheckConfiguration.php b/app/Actions/Proxy/CheckConfiguration.phpindex bdeafd0611..70bf5a221a 100644--- a/app/Actions/Proxy/CheckConfiguration.php+++ b/app/Actions/Proxy/CheckConfiguration.php@@ -3,6 +3,7 @@namespace App\Actions\Proxy;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class CheckConfiguration@@ -25,7 +26,7 @@ class CheckConfiguration$proxy_configuration = str(generate_default_proxy_configuration($server))->trim()->value();}if (! $proxy_configuration || is_null($proxy_configuration)) {- throw new \Exception('Could not generate proxy configuration');+ throw new Exception('Could not generate proxy configuration');}return $proxy_configuration;diff --git a/app/Actions/Proxy/CheckProxy.php b/app/Actions/Proxy/CheckProxy.phpindex 6c8dd52347..1dc5540c25 100644--- a/app/Actions/Proxy/CheckProxy.php+++ b/app/Actions/Proxy/CheckProxy.php@@ -4,6 +4,7 @@ namespace App\Actions\Proxy;use App\Enums\ProxyTypes;use App\Models\Server;+use Exception;use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;use Symfony\Component\Yaml\Yaml;@@ -32,80 +33,74 @@ class CheckProxy}['uptime' => $uptime, 'error' => $error] = $server->validateConnection();if (! $uptime) {- throw new \Exception($error);+ throw new Exception($error);}if (! $server->isProxyShouldRun()) {if ($fromUI) {- throw new \Exception('Proxy should not run. You selected the Custom Proxy.');- } else {- return false;+ throw new Exception('Proxy should not run. You selected the Custom Proxy.');}++ return false;}if ($server->isSwarm()) {$status = getContainerStatus($server, 'coolify-proxy_traefik');$server->proxy->set('status', $status);$server->save();- if ($status === 'running') {- return false;- }-- return true;- } else {- $status = getContainerStatus($server, 'coolify-proxy');- if ($status === 'running') {- $server->proxy->set('status', 'running');- $server->save();-- return false;- }- if ($server->settings->is_cloudflare_tunnel) {- return false;- }- $ip = $server->ip;- if ($server->id === 0) {- $ip = 'host.docker.internal';- }- $portsToCheck = ['80', '443'];+ return $status !== 'running';+ }+ $status = getContainerStatus($server, 'coolify-proxy');+ if ($status === 'running') {+ $server->proxy->set('status', 'running');+ $server->save();- try {- if ($server->proxyType() !== ProxyTypes::NONE->value) {- $proxyCompose = CheckConfiguration::run($server);- if (isset($proxyCompose)) {- $yaml = Yaml::parse($proxyCompose);- $portsToCheck = [];- if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {- $ports = data_get($yaml, 'services.traefik.ports');- } elseif ($server->proxyType() === ProxyTypes::CADDY->value) {- $ports = data_get($yaml, 'services.caddy.ports');- }- if (isset($ports)) {- foreach ($ports as $port) {- $portsToCheck[] = str($port)->before(':')->value();- }+ return false;+ }+ if ($server->settings->is_cloudflare_tunnel) {+ return false;+ }+ $ip = $server->ip;+ if ($server->id === 0) {+ $ip = 'host.docker.internal';+ }+ $portsToCheck = ['80', '443'];+ try {+ if ($server->proxyType() !== ProxyTypes::NONE->value) {+ $proxyCompose = CheckConfiguration::run($server);+ if (isset($proxyCompose)) {+ $yaml = Yaml::parse($proxyCompose);+ $portsToCheck = [];+ if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {+ $ports = data_get($yaml, 'services.traefik.ports');+ } elseif ($server->proxyType() === ProxyTypes::CADDY->value) {+ $ports = data_get($yaml, 'services.caddy.ports');+ }+ if (isset($ports)) {+ foreach ($ports as $port) {+ $portsToCheck[] = str($port)->before(':')->value();}}- } else {- $portsToCheck = [];}- } catch (\Exception $e) {- Log::error('Error checking proxy: '.$e->getMessage());- }- if (count($portsToCheck) === 0) {- return false;+ } else {+ $portsToCheck = [];}- foreach ($portsToCheck as $port) {- $connection = @fsockopen($ip, $port);- if (is_resource($connection) && fclose($connection)) {- if ($fromUI) {- throw new \Exception("Port $port is in use.<br>You must stop the process using this port.<br>Docs: <a target='_blank' href='https://coolify.io/docs'>https://coolify.io/docs</a><br>Discord: <a target='_blank' href='https://coollabs.io/discord'>https://coollabs.io/discord</a>");- } else {- return false;- }+ } catch (Exception $e) {+ Log::error('Error checking proxy: '.$e->getMessage());+ }+ if ($portsToCheck === []) {+ return false;+ }+ foreach ($portsToCheck as $portToCheck) {+ $connection = @fsockopen($ip, $portToCheck);+ if (is_resource($connection) && fclose($connection)) {+ if ($fromUI) {+ throw new Exception("Port {$portToCheck} is in use.<br>You must stop the process using this port.<br>Docs: <a target='_blank' href='https://coolify.io/docs'>https://coolify.io/docs</a><br>Discord: <a target='_blank' href='https://coollabs.io/discord'>https://coollabs.io/discord</a>");}- }- return true;+ return false;+ }}++ return true;}}diff --git a/app/Actions/Proxy/StartProxy.php b/app/Actions/Proxy/StartProxy.phpindex 9bc506d9b5..f616f9395c 100644--- a/app/Actions/Proxy/StartProxy.php+++ b/app/Actions/Proxy/StartProxy.php@@ -5,6 +5,7 @@ namespace App\Actions\Proxy;use App\Enums\ProxyTypes;use App\Events\ProxyStarted;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;use Spatie\Activitylog\Models\Activity;@@ -22,7 +23,7 @@ class StartProxy$proxy_path = $server->proxyPath();$configuration = CheckConfiguration::run($server);if (! $configuration) {- throw new \Exception('Configuration is not synced');+ throw new Exception('Configuration is not synced');}SaveConfiguration::run($server, $configuration);$docker_compose_yml_base64 = base64_encode($configuration);@@ -38,10 +39,8 @@ class StartProxy"echo 'Successfully started coolify-proxy.'",]);} else {- if (isDev()) {- if ($proxyType === ProxyTypes::CADDY->value) {- $proxy_path = '/data/coolify/proxy/caddy';- }+ if (isDev() && $proxyType === ProxyTypes::CADDY->value) {+ $proxy_path = '/data/coolify/proxy/caddy';}$caddyfile = 'import /dynamic/*.caddy';$commands = $commands->merge([@@ -65,14 +64,13 @@ class StartProxyif ($async) {return remote_process($commands, $server, callEventOnFinish: 'ProxyStarted', callEventData: $server);- } else {- instant_remote_process($commands, $server);- $server->proxy->set('status', 'running');- $server->proxy->set('type', $proxyType);- $server->save();- ProxyStarted::dispatch($server);-- return 'OK';}+ instant_remote_process($commands, $server);+ $server->proxy->set('status', 'running');+ $server->proxy->set('type', $proxyType);+ $server->save();+ ProxyStarted::dispatch($server);++ return 'OK';}}diff --git a/app/Actions/Server/ConfigureCloudflared.php b/app/Actions/Server/ConfigureCloudflared.phpindex fc04e67a45..9364b268e0 100644--- a/app/Actions/Server/ConfigureCloudflared.php+++ b/app/Actions/Server/ConfigureCloudflared.php@@ -6,6 +6,7 @@ use App\Events\CloudflareTunnelConfigured;use App\Models\Server;use Lorisleiva\Actions\Concerns\AsAction;use Symfony\Component\Yaml\Yaml;+use Throwable;class ConfigureCloudflared{@@ -39,7 +40,7 @@ class ConfigureCloudflared'docker compose up -d --remove-orphans',]);instant_remote_process($commands, $server);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$server->settings->is_cloudflare_tunnel = false;$server->settings->save();throw $e;diff --git a/app/Actions/Server/InstallDocker.php b/app/Actions/Server/InstallDocker.phpindex cbcb20368c..4c06afa8d3 100644--- a/app/Actions/Server/InstallDocker.php+++ b/app/Actions/Server/InstallDocker.php@@ -4,6 +4,7 @@ namespace App\Actions\Server;use App\Models\Server;use App\Models\StandaloneDocker;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class InstallDocker@@ -15,7 +16,7 @@ class InstallDocker$dockerVersion = config('constants.docker.minimum_required_version');$supported_os_type = $server->validateOS();if (! $supported_os_type) {- throw new \Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://coolify.io/docs/installation#manually">documentation</a>.');+ throw new Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://coolify.io/docs/installation#manually">documentation</a>.');}$config = base64_encode('{"log-driver": "json-file",@@ -24,9 +25,9 @@ class InstallDocker"max-file": "3"}}');- $found = StandaloneDocker::where('server_id', $server->id);- if ($found->count() == 0 && $server->id) {- StandaloneDocker::create([+ $builder = StandaloneDocker::query()->where('server_id', $server->id);+ if ($builder->count() == 0 && $server->id) {+ StandaloneDocker::query()->create(['name' => 'coolify','network' => 'coolify','server_id' => $server->id,@@ -45,65 +46,64 @@ class InstallDocker]);return remote_process($command, $server);+ }+ if ($supported_os_type->contains('debian')) {+ $command = $command->merge([+ "echo 'Installing Prerequisites...'",+ 'apt-get update -y',+ 'command -v curl >/dev/null || apt install -y curl',+ 'command -v wget >/dev/null || apt install -y wget',+ 'command -v git >/dev/null || apt install -y git',+ 'command -v jq >/dev/null || apt install -y jq',+ ]);+ } elseif ($supported_os_type->contains('rhel')) {+ $command = $command->merge([+ "echo 'Installing Prerequisites...'",+ 'command -v curl >/dev/null || dnf install -y curl',+ 'command -v wget >/dev/null || dnf install -y wget',+ 'command -v git >/dev/null || dnf install -y git',+ 'command -v jq >/dev/null || dnf install -y jq',+ ]);+ } elseif ($supported_os_type->contains('sles')) {+ $command = $command->merge([+ "echo 'Installing Prerequisites...'",+ 'zypper update -y',+ 'command -v curl >/dev/null || zypper install -y curl',+ 'command -v wget >/dev/null || zypper install -y wget',+ 'command -v git >/dev/null || zypper install -y git',+ 'command -v jq >/dev/null || zypper install -y jq',+ ]);} else {- if ($supported_os_type->contains('debian')) {- $command = $command->merge([- "echo 'Installing Prerequisites...'",- 'apt-get update -y',- 'command -v curl >/dev/null || apt install -y curl',- 'command -v wget >/dev/null || apt install -y wget',- 'command -v git >/dev/null || apt install -y git',- 'command -v jq >/dev/null || apt install -y jq',- ]);- } elseif ($supported_os_type->contains('rhel')) {- $command = $command->merge([- "echo 'Installing Prerequisites...'",- 'command -v curl >/dev/null || dnf install -y curl',- 'command -v wget >/dev/null || dnf install -y wget',- 'command -v git >/dev/null || dnf install -y git',- 'command -v jq >/dev/null || dnf install -y jq',- ]);- } elseif ($supported_os_type->contains('sles')) {- $command = $command->merge([- "echo 'Installing Prerequisites...'",- 'zypper update -y',- 'command -v curl >/dev/null || zypper install -y curl',- 'command -v wget >/dev/null || zypper install -y wget',- 'command -v git >/dev/null || zypper install -y git',- 'command -v jq >/dev/null || zypper install -y jq',- ]);- } else {- throw new \Exception('Unsupported OS');- }+ throw new Exception('Unsupported OS');+ }+ $command = $command->merge([+ "echo 'Installing Docker Engine...'",+ "curl https://releases.rancher.com/install-docker/{$dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$dockerVersion}",+ "echo 'Configuring Docker Engine (merging existing configuration with the required)...'",+ 'test -s /etc/docker/daemon.json && cp /etc/docker/daemon.json "/etc/docker/daemon.json.original-$(date +"%Y%m%d-%H%M%S")"',+ "test ! -s /etc/docker/daemon.json && echo '{$config}' | base64 -d | tee /etc/docker/daemon.json > /dev/null",+ "echo '{$config}' | base64 -d | tee /etc/docker/daemon.json.coolify > /dev/null",+ 'jq . /etc/docker/daemon.json.coolify | tee /etc/docker/daemon.json.coolify.pretty > /dev/null',+ 'mv /etc/docker/daemon.json.coolify.pretty /etc/docker/daemon.json.coolify',+ "jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",+ 'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',+ "echo 'Restarting Docker Engine...'",+ 'systemctl enable docker >/dev/null 2>&1 || true',+ 'systemctl restart docker',+ ]);+ if ($server->isSwarm()) {$command = $command->merge([- "echo 'Installing Docker Engine...'",- "curl https://releases.rancher.com/install-docker/{$dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$dockerVersion}",- "echo 'Configuring Docker Engine (merging existing configuration with the required)...'",- 'test -s /etc/docker/daemon.json && cp /etc/docker/daemon.json "/etc/docker/daemon.json.original-$(date +"%Y%m%d-%H%M%S")"',- "test ! -s /etc/docker/daemon.json && echo '{$config}' | base64 -d | tee /etc/docker/daemon.json > /dev/null",- "echo '{$config}' | base64 -d | tee /etc/docker/daemon.json.coolify > /dev/null",- 'jq . /etc/docker/daemon.json.coolify | tee /etc/docker/daemon.json.coolify.pretty > /dev/null',- 'mv /etc/docker/daemon.json.coolify.pretty /etc/docker/daemon.json.coolify',- "jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",- 'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',- "echo 'Restarting Docker Engine...'",- 'systemctl enable docker >/dev/null 2>&1 || true',- 'systemctl restart docker',+ 'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',+ ]);+ } else {+ $command = $command->merge([+ 'docker network create --attachable coolify >/dev/null 2>&1 || true',+ ]);+ $command = $command->merge([+ "echo 'Done!'",]);- if ($server->isSwarm()) {- $command = $command->merge([- 'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',- ]);- } else {- $command = $command->merge([- 'docker network create --attachable coolify >/dev/null 2>&1 || true',- ]);- $command = $command->merge([- "echo 'Done!'",- ]);- }-- return remote_process($command, $server);}++ return remote_process($command, $server);}}diff --git a/app/Actions/Server/ResourcesCheck.php b/app/Actions/Server/ResourcesCheck.phpindex e6b90ba380..dda446f130 100644--- a/app/Actions/Server/ResourcesCheck.php+++ b/app/Actions/Server/ResourcesCheck.php@@ -14,6 +14,7 @@ use App\Models\StandaloneMysql;use App\Models\StandalonePostgresql;use App\Models\StandaloneRedis;use Lorisleiva\Actions\Concerns\AsAction;+use Throwable;class ResourcesCheck{@@ -23,19 +24,21 @@ class ResourcesCheck{$seconds = 60;try {- Application::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- ServiceApplication::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- ServiceDatabase::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandalonePostgresql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneRedis::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneMongodb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneMysql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneMariadb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneKeydb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneDragonfly::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- StandaloneClickhouse::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);- } catch (\Throwable $e) {+ Application::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ ServiceApplication::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ ServiceDatabase::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandalonePostgresql::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneRedis::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneMongodb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneMysql::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneMariadb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneKeydb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneDragonfly::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ StandaloneClickhouse::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);+ } catch (Throwable $e) {return handleError($e);}++ return null;}}diff --git a/app/Actions/Server/ServerCheck.php b/app/Actions/Server/ServerCheck.phpindex 75b8501f32..ff3cb449cd 100644--- a/app/Actions/Server/ServerCheck.php+++ b/app/Actions/Server/ServerCheck.php@@ -16,6 +16,7 @@ use App\Models\ServiceDatabase;use App\Notifications\Container\ContainerRestarted;use Illuminate\Support\Arr;use Lorisleiva\Actions\Concerns\AsAction;+use Throwable;class ServerCheck{@@ -61,11 +62,11 @@ class ServerCheck}if (isset($containerReplicates)) {- foreach ($containerReplicates as $containerReplica) {- $name = data_get($containerReplica, 'Name');- $this->containers = $this->containers->map(function ($container) use ($name, $containerReplica) {+ foreach ($containerReplicates as $containerReplicate) {+ $name = data_get($containerReplicate, 'Name');+ $this->containers = $this->containers->map(function ($container) use ($name, $containerReplicate) {if (data_get($container, 'Spec.Name') === $name) {- $replicas = data_get($containerReplica, 'Replicas');+ $replicas = data_get($containerReplicate, 'Replicas');$running = str($replicas)->explode('/')[0];$total = str($replicas)->explode('/')[1];if ($running === $total) {@@ -95,9 +96,9 @@ class ServerCheck$foundProxyContainer = $this->containers->filter(function ($value, $key) {if ($this->server->isSwarm()) {return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik';- } else {- return data_get($value, 'Name') === '/coolify-proxy';}++ return data_get($value, 'Name') === '/coolify-proxy';})->first();if (! $foundProxyContainer) {try {@@ -106,7 +107,7 @@ class ServerCheckStartProxy::run($this->server, false);$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));}- } catch (\Throwable $e) {+ } catch (Throwable $e) {}} else {$this->server->proxy->status = data_get($foundProxyContainer, 'State.Status');@@ -116,9 +117,11 @@ class ServerCheck}}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}private function checkLogDrainContainer()@@ -141,12 +144,10 @@ class ServerCheckforeach ($this->containers as $container) {if ($this->isSentinel) {$labels = Arr::undot(data_get($container, 'labels'));+ } elseif ($this->server->isSwarm()) {+ $labels = Arr::undot(data_get($container, 'Spec.Labels'));} else {- if ($this->server->isSwarm()) {- $labels = Arr::undot(data_get($container, 'Spec.Labels'));- } else {- $labels = Arr::undot(data_get($container, 'Config.Labels'));- }+ $labels = Arr::undot(data_get($container, 'Config.Labels'));}$managed = data_get($labels, 'coolify.managed');if (! $managed) {@@ -177,12 +178,12 @@ class ServerCheckif (str($applicationId)->contains('-')) {$applicationId = str($applicationId)->before('-');}- $preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();+ $preview = ApplicationPreview::query()->where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();if ($preview) {$preview->update(['status' => $containerStatus]);}} else {- $application = Application::where('id', $applicationId)->first();+ $application = Application::query()->where('id', $applicationId)->first();if ($application) {$application->update(['status' => $containerStatus,@@ -194,14 +195,14 @@ class ServerCheck// Service$subType = data_get($labels, 'coolify.service.subType');$subId = data_get($labels, 'coolify.service.subId');- $service = Service::where('id', $serviceId)->first();+ $service = Service::query()->where('id', $serviceId)->first();if (! $service) {continue;}if ($subType === 'application') {- $service = ServiceApplication::where('id', $subId)->first();+ $service = ServiceApplication::query()->where('id', $subId)->first();} else {- $service = ServiceDatabase::where('id', $subId)->first();+ $service = ServiceDatabase::query()->where('id', $subId)->first();}if ($service) {$service->update([@@ -214,14 +215,12 @@ class ServerCheck$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {if ($this->isSentinel) {return data_get($value, 'name') === $uuid.'-proxy';- } else {-- if ($this->server->isSwarm()) {- return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";- } else {- return data_get($value, 'Name') === "/$uuid-proxy";- }}+ if ($this->server->isSwarm()) {+ return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";+ }++ return data_get($value, 'Name') === "/$uuid-proxy";})->first();if (! $foundTcpProxy) {StartDatabaseProxy::run($service);@@ -246,14 +245,12 @@ class ServerCheck$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {if ($this->isSentinel) {return data_get($value, 'name') === $uuid.'-proxy';- } else {- if ($this->server->isSwarm()) {- return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";- } else {-- return data_get($value, 'Name') === "/$uuid-proxy";- }}+ if ($this->server->isSwarm()) {+ return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";+ }++ return data_get($value, 'Name') === "/$uuid-proxy";})->first();if (! $foundTcpProxy) {StartDatabaseProxy::run($database);diff --git a/app/Actions/Server/StartLogDrain.php b/app/Actions/Server/StartLogDrain.phpindex 0d28a00994..c3752ef16d 100644--- a/app/Actions/Server/StartLogDrain.php+++ b/app/Actions/Server/StartLogDrain.php@@ -3,7 +3,9 @@namespace App\Actions\Server;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;+use Throwable;class StartLogDrain{@@ -31,9 +33,10 @@ class StartLogDraintry {if ($type === 'none') {return 'No log drain is enabled.';- } elseif ($type === 'newrelic') {+ }+ if ($type === 'newrelic') {if (! $server->settings->is_logdrain_newrelic_enabled) {- throw new \Exception('New Relic log drain is not enabled.');+ throw new Exception('New Relic log drain is not enabled.');}$config = base64_encode("[SERVICE]@@ -68,7 +71,7 @@ class StartLogDrain");} elseif ($type === 'highlight') {if (! $server->settings->is_logdrain_highlight_enabled) {- throw new \Exception('Highlight log drain is not enabled.');+ throw new Exception('Highlight log drain is not enabled.');}$config = base64_encode('[SERVICE]@@ -89,7 +92,7 @@ class StartLogDrain');} elseif ($type === 'axiom') {if (! $server->settings->is_logdrain_axiom_enabled) {- throw new \Exception('Axiom log drain is not enabled.');+ throw new Exception('Axiom log drain is not enabled.');}$config = base64_encode("[SERVICE]@@ -129,12 +132,12 @@ class StartLogDrain");} elseif ($type === 'custom') {if (! $server->settings->is_logdrain_custom_enabled) {- throw new \Exception('Custom log drain is not enabled.');+ throw new Exception('Custom log drain is not enabled.');}$config = base64_encode($server->settings->logdrain_custom_config);$parsers = base64_encode($server->settings->logdrain_custom_config_parser);} else {- throw new \Exception('Unknown log drain type.');+ throw new Exception('Unknown log drain type.');}if ($type !== 'custom') {$parsers = base64_encode("@@ -207,7 +210,7 @@ Files:"touch $config_path/.env",];} else {- throw new \Exception('Unknown log drain type.');+ throw new Exception('Unknown log drain type.');}$restart_command = ["echo 'Starting Fluent Bit'",@@ -216,7 +219,7 @@ Files:$command = array_merge($command, $add_envs_command, $restart_command);return instant_remote_process($command, $server);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}}diff --git a/app/Actions/Server/StartSentinel.php b/app/Actions/Server/StartSentinel.phpindex 587ac4a8db..e36ec34c24 100644--- a/app/Actions/Server/StartSentinel.php+++ b/app/Actions/Server/StartSentinel.php@@ -3,6 +3,7 @@namespace App\Actions\Server;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class StartSentinel@@ -27,7 +28,7 @@ class StartSentinel$mountDir = '/data/coolify/sentinel';$image = "ghcr.io/coollabsio/sentinel:$version";if (! $endpoint) {- throw new \Exception('You should set FQDN in Instance Settings.');+ throw new Exception('You should set FQDN in Instance Settings.');}$environments = ['TOKEN' => $token,diff --git a/app/Actions/Server/StopLogDrain.php b/app/Actions/Server/StopLogDrain.phpindex 96c2466dec..79bd8ee1cc 100644--- a/app/Actions/Server/StopLogDrain.php+++ b/app/Actions/Server/StopLogDrain.php@@ -4,6 +4,7 @@ namespace App\Actions\Server;use App\Models\Server;use Lorisleiva\Actions\Concerns\AsAction;+use Throwable;class StopLogDrain{@@ -13,7 +14,7 @@ class StopLogDrain{try {return instant_remote_process(['docker rm -f coolify-log-drain'], $server, false);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}}diff --git a/app/Actions/Server/UpdateCoolify.php b/app/Actions/Server/UpdateCoolify.phpindex be9b4062c9..add2355a8e 100644--- a/app/Actions/Server/UpdateCoolify.php+++ b/app/Actions/Server/UpdateCoolify.php@@ -25,7 +25,7 @@ class UpdateCoolifyreturn;}$settings = instanceSettings();- $this->server = Server::find(0);+ $this->server = Server::query()->find(0);if (! $this->server) {return;}diff --git a/app/Actions/Server/ValidateServer.php b/app/Actions/Server/ValidateServer.phpindex 55b37a77c0..36f10711f9 100644--- a/app/Actions/Server/ValidateServer.php+++ b/app/Actions/Server/ValidateServer.php@@ -3,6 +3,7 @@namespace App\Actions\Server;use App\Models\Server;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class ValidateServer@@ -34,7 +35,7 @@ class ValidateServer$server->update(['validation_logs' => $this->error,]);- throw new \Exception($this->error);+ throw new Exception($this->error);}$this->supported_os_type = $server->validateOS();if (! $this->supported_os_type) {@@ -42,7 +43,7 @@ class ValidateServer$server->update(['validation_logs' => $this->error,]);- throw new \Exception($this->error);+ throw new Exception($this->error);}$this->docker_installed = $server->validateDockerEngine();@@ -52,18 +53,17 @@ class ValidateServer$server->update(['validation_logs' => $this->error,]);- throw new \Exception($this->error);+ throw new Exception($this->error);}$this->docker_version = $server->validateDockerEngineVersion();if ($this->docker_version) {return 'OK';- } else {- $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="text-black underline dark:text-white" href="https://docs.docker.com/engine/install/#server">documentation</a>.';- $server->update([- 'validation_logs' => $this->error,- ]);- throw new \Exception($this->error);}+ $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="text-black underline dark:text-white" href="https://docs.docker.com/engine/install/#server">documentation</a>.';+ $server->update([+ 'validation_logs' => $this->error,+ ]);+ throw new Exception($this->error);}}diff --git a/app/Actions/Service/DeleteService.php b/app/Actions/Service/DeleteService.phpindex 9b87454dac..65d2fdea24 100644--- a/app/Actions/Service/DeleteService.php+++ b/app/Actions/Service/DeleteService.php@@ -4,6 +4,7 @@ namespace App\Actions\Service;use App\Actions\Server\CleanupDocker;use App\Models\Service;+use Exception;use Illuminate\Support\Facades\Log;use Lorisleiva\Actions\Concerns\AsAction;@@ -32,17 +33,15 @@ class DeleteService$storagesToDelete->push($storage);}}- foreach ($storagesToDelete as $storage) {- $commands[] = "docker volume rm -f $storage->name";+ foreach ($storagesToDelete as $storageToDelete) {+ $commands[] = "docker volume rm -f $storageToDelete->name";}// Execute volume deletion first, this must be done first otherwise volumes will not be deleted.- if (! empty($commands)) {- foreach ($commands as $command) {- $result = instant_remote_process([$command], $server, false);- if ($result !== null && $result !== 0) {- Log::error('Error deleting volumes: '.$result);- }+ foreach ($commands as $command) {+ $result = instant_remote_process([$command], $server, false);+ if ($result !== null && $result !== 0) {+ Log::error('Error deleting volumes: '.$result);}}}@@ -52,8 +51,8 @@ class DeleteService}instant_remote_process(["docker rm -f $service->uuid"], $server, throwError: false);- } catch (\Exception $e) {- throw new \Exception($e->getMessage());+ } catch (Exception $e) {+ throw new Exception($e->getMessage(), $e->getCode(), $e);} finally {if ($deleteConfigurations) {$service->delete_configurations();diff --git a/app/Actions/Service/StopService.php b/app/Actions/Service/StopService.phpindex 95b08b4370..b99cf190ae 100644--- a/app/Actions/Service/StopService.php+++ b/app/Actions/Service/StopService.php@@ -4,6 +4,7 @@ namespace App\Actions\Service;use App\Actions\Server\CleanupDocker;use App\Models\Service;+use Exception;use Lorisleiva\Actions\Concerns\AsAction;class StopService@@ -29,8 +30,10 @@ class StopServiceCleanupDocker::dispatch($server, true);}}- } catch (\Exception $e) {+ } catch (Exception $e) {return $e->getMessage();}++ return null;}}diff --git a/app/Actions/Shared/ComplexStatusCheck.php b/app/Actions/Shared/ComplexStatusCheck.phpindex 5a7ba6637c..1ce30a297a 100644--- a/app/Actions/Shared/ComplexStatusCheck.php+++ b/app/Actions/Shared/ComplexStatusCheck.php@@ -19,12 +19,11 @@ class ComplexStatusCheckif ($is_main_server) {$application->update(['status' => 'exited:unhealthy']);- continue;- } else {- $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);-continue;}+ $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);++ continue;}$container = instant_remote_process(["docker container inspect $(docker container ls -q --filter 'label=coolify.applicationId={$application->id}' --filter 'label=coolify.pullRequestId=0') --format '{{json .}}'"], $server, false);$container = format_docker_command_output_to_json($container);@@ -44,16 +43,14 @@ class ComplexStatusCheck$additional_server->updateExistingPivot($server->id, ['status' => "$containerStatus:$containerHealth"]);}}- } else {- if ($is_main_server) {- $application->update(['status' => 'exited:unhealthy']);+ } elseif ($is_main_server) {+ $application->update(['status' => 'exited:unhealthy']);- continue;- } else {- $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);+ continue;+ } else {+ $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);- continue;- }+ continue;}}}diff --git a/app/Actions/Shared/PullImage.php b/app/Actions/Shared/PullImage.phpindex 4bd1cf4530..38c9b47715 100644--- a/app/Actions/Shared/PullImage.php+++ b/app/Actions/Shared/PullImage.php@@ -9,20 +9,20 @@ class PullImage{use AsAction;- public function handle(Service $resource)+ public function handle(Service $service){- $resource->saveComposeConfigs();+ $service->saveComposeConfigs();- $commands[] = 'cd '.$resource->workdir();- $commands[] = "echo 'Saved configuration files to {$resource->workdir()}.'";+ $commands[] = 'cd '.$service->workdir();+ $commands[] = "echo 'Saved configuration files to {$service->workdir()}.'";$commands[] = 'docker compose pull';- $server = data_get($resource, 'server');+ $server = data_get($service, 'server');if (! $server) {return;}- instant_remote_process($commands, $resource->server);+ instant_remote_process($commands, $service->server);}}diff --git a/app/Console/Commands/AdminRemoveUser.php b/app/Console/Commands/AdminRemoveUser.phpindex d4534399cd..c1b6d58283 100644--- a/app/Console/Commands/AdminRemoveUser.php+++ b/app/Console/Commands/AdminRemoveUser.php@@ -3,6 +3,7 @@namespace App\Console\Commands;use App\Models\User;+use Exception;use Illuminate\Console\Command;class AdminRemoveUser extends Command@@ -46,7 +47,7 @@ class AdminRemoveUser extends Command$team->delete();}$user->delete();- } catch (\Exception $e) {+ } catch (Exception $e) {$this->error('Failed to remove user.');$this->error($e->getMessage());diff --git a/app/Console/Commands/CheckApplicationDeploymentQueue.php b/app/Console/Commands/CheckApplicationDeploymentQueue.phpindex e89d26f2c3..1c8eb25972 100644--- a/app/Console/Commands/CheckApplicationDeploymentQueue.php+++ b/app/Console/Commands/CheckApplicationDeploymentQueue.php@@ -15,7 +15,7 @@ class CheckApplicationDeploymentQueue extends Commandpublic function handle(){$seconds = $this->option('seconds');- $deployments = ApplicationDeploymentQueue::whereIn('status', [+ $deployments = ApplicationDeploymentQueue::query()->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS,ApplicationDeploymentStatus::QUEUED,])->where('created_at', '<=', now()->subSeconds($seconds))->get();@@ -40,11 +40,11 @@ class CheckApplicationDeploymentQueue extends Command}}- private function cancelDeployment(ApplicationDeploymentQueue $deployment)+ private function cancelDeployment(ApplicationDeploymentQueue $applicationDeploymentQueue){- $deployment->update(['status' => ApplicationDeploymentStatus::FAILED]);- if ($deployment->server?->isFunctional()) {- remote_process(['docker rm -f '.$deployment->deployment_uuid], $deployment->server, false);+ $applicationDeploymentQueue->update(['status' => ApplicationDeploymentStatus::FAILED]);+ if ($applicationDeploymentQueue->server?->isFunctional()) {+ remote_process(['docker rm -f '.$applicationDeploymentQueue->deployment_uuid], $applicationDeploymentQueue->server, false);}}}diff --git a/app/Console/Commands/CleanupApplicationDeploymentQueue.php b/app/Console/Commands/CleanupApplicationDeploymentQueue.phpindex 3aae28ae60..badc0737a6 100644--- a/app/Console/Commands/CleanupApplicationDeploymentQueue.php+++ b/app/Console/Commands/CleanupApplicationDeploymentQueue.php@@ -3,6 +3,7 @@namespace App\Console\Commands;use App\Models\ApplicationDeploymentQueue;+use App\Models\Server;use Illuminate\Console\Command;class CleanupApplicationDeploymentQueue extends Command@@ -14,9 +15,9 @@ class CleanupApplicationDeploymentQueue extends Commandpublic function handle(){$team_id = $this->option('team-id');- $servers = \App\Models\Server::where('team_id', $team_id)->get();+ $servers = Server::query()->where('team_id', $team_id)->get();foreach ($servers as $server) {- $deployments = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->where('server_id', $server->id)->get();+ $deployments = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->where('server_id', $server->id)->get();foreach ($deployments as $deployment) {$deployment->update(['status' => 'failed']);instant_remote_process(['docker rm -f '.$deployment->deployment_uuid], $server, false);diff --git a/app/Console/Commands/CleanupDatabase.php b/app/Console/Commands/CleanupDatabase.phpindex a0adc8b36b..7d57b8e8d5 100644--- a/app/Console/Commands/CleanupDatabase.php+++ b/app/Console/Commands/CleanupDatabase.php@@ -18,19 +18,14 @@ class CleanupDatabase extends Command} else {echo "Running database cleanup in dry-run mode...\n";}- if (isCloud()) {- // Later on we can increase this to 180 days or dynamically set- $keep_days = $this->option('keep-days') ?? 60;- } else {- $keep_days = $this->option('keep-days') ?? 60;- }+ $keep_days = isCloud() ? $this->option('keep-days') ?? 60 : $this->option('keep-days') ?? 60;echo "Keep days: $keep_days\n";// Cleanup failed jobs table- $failed_jobs = DB::table('failed_jobs')->where('failed_at', '<', now()->subDays(1));- $count = $failed_jobs->count();+ $builder = DB::table('failed_jobs')->where('failed_at', '<', now()->subDays(1));+ $count = $builder->count();echo "Delete $count entries from failed_jobs.\n";if ($this->option('yes')) {- $failed_jobs->delete();+ $builder->delete();}// Cleanup sessions tablediff --git a/app/Console/Commands/CleanupStuckedResources.php b/app/Console/Commands/CleanupStuckedResources.phpindex def3d5a2c5..c24ec7344f 100644--- a/app/Console/Commands/CleanupStuckedResources.php+++ b/app/Console/Commands/CleanupStuckedResources.php@@ -21,6 +21,7 @@ use App\Models\StandaloneMysql;use App\Models\StandalonePostgresql;use App\Models\StandaloneRedis;use Illuminate\Console\Command;+use Throwable;class CleanupStuckedResources extends Command{@@ -42,18 +43,18 @@ class CleanupStuckedResources extends Commandforeach ($servers as $server) {CleanupHelperContainersJob::dispatch($server);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stucked resources: {$e->getMessage()}\n";}try {- $applicationsDeploymentQueue = ApplicationDeploymentQueue::get();+ $applicationsDeploymentQueue = ApplicationDeploymentQueue::query()->get();foreach ($applicationsDeploymentQueue as $applicationDeploymentQueue) {if (is_null($applicationDeploymentQueue->application)) {echo "Deleting stuck application deployment queue: {$applicationDeploymentQueue->id}\n";$applicationDeploymentQueue->delete();}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck application deployment queue: {$e->getMessage()}\n";}try {@@ -62,18 +63,18 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck application: {$application->name}\n";$application->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck application: {$e->getMessage()}\n";}try {- $applicationsPreviews = ApplicationPreview::get();+ $applicationsPreviews = ApplicationPreview::query()->get();foreach ($applicationsPreviews as $applicationPreview) {if (! data_get($applicationPreview, 'application')) {echo "Deleting stuck application preview: {$applicationPreview->uuid}\n";$applicationPreview->delete();}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck application: {$e->getMessage()}\n";}try {@@ -82,16 +83,16 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck postgresql: {$postgresql->name}\n";$postgresql->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck postgresql: {$e->getMessage()}\n";}try {$redis = StandaloneRedis::withTrashed()->whereNotNull('deleted_at')->get();- foreach ($redis as $redis) {- echo "Deleting stuck redis: {$redis->name}\n";- $redis->forceDelete();+ foreach ($redis as $redi) {+ echo "Deleting stuck redis: {$redi->name}\n";+ $redi->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck redis: {$e->getMessage()}\n";}try {@@ -100,7 +101,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck keydb: {$keydb->name}\n";$keydb->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck keydb: {$e->getMessage()}\n";}try {@@ -109,7 +110,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck dragonfly: {$dragonfly->name}\n";$dragonfly->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck dragonfly: {$e->getMessage()}\n";}try {@@ -118,7 +119,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck clickhouse: {$clickhouse->name}\n";$clickhouse->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck clickhouse: {$e->getMessage()}\n";}try {@@ -127,7 +128,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck mongodb: {$mongodb->name}\n";$mongodb->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck mongodb: {$e->getMessage()}\n";}try {@@ -136,7 +137,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck mysql: {$mysql->name}\n";$mysql->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck mysql: {$e->getMessage()}\n";}try {@@ -145,7 +146,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck mariadb: {$mariadb->name}\n";$mariadb->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck mariadb: {$e->getMessage()}\n";}try {@@ -154,7 +155,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck service: {$service->name}\n";$service->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck service: {$e->getMessage()}\n";}try {@@ -163,7 +164,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck serviceapp: {$serviceApp->name}\n";$serviceApp->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";}try {@@ -172,7 +173,7 @@ class CleanupStuckedResources extends Commandecho "Deleting stuck serviceapp: {$serviceDb->name}\n";$serviceDb->forceDelete();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";}try {@@ -183,7 +184,7 @@ class CleanupStuckedResources extends Command$scheduled_task->delete();}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck scheduledtasks: {$e->getMessage()}\n";}@@ -195,7 +196,7 @@ class CleanupStuckedResources extends Command$scheduled_backup->delete();}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning stuck scheduledbackups: {$e->getMessage()}\n";}@@ -222,7 +223,7 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in application: {$e->getMessage()}\n";}try {@@ -247,32 +248,32 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in postgresql: {$e->getMessage()}\n";}try {$redis = StandaloneRedis::all();- foreach ($redis as $redis) {- if (! data_get($redis, 'environment')) {- echo 'Redis without environment: '.$redis->name.'\n';- $redis->forceDelete();+ foreach ($redis as $redi) {+ if (! data_get($redi, 'environment')) {+ echo 'Redis without environment: '.$redi->name.'\n';+ $redi->forceDelete();continue;}- if (! $redis->destination()) {- echo 'Redis without destination: '.$redis->name.'\n';- $redis->forceDelete();+ if (! $redi->destination()) {+ echo 'Redis without destination: '.$redi->name.'\n';+ $redi->forceDelete();continue;}- if (! data_get($redis, 'destination.server')) {- echo 'Redis without server: '.$redis->name.'\n';- $redis->forceDelete();+ if (! data_get($redi, 'destination.server')) {+ echo 'Redis without server: '.$redi->name.'\n';+ $redi->forceDelete();continue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in redis: {$e->getMessage()}\n";}@@ -298,7 +299,7 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in mongodb: {$e->getMessage()}\n";}@@ -324,7 +325,7 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in mysql: {$e->getMessage()}\n";}@@ -350,7 +351,7 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in mariadb: {$e->getMessage()}\n";}@@ -376,33 +377,33 @@ class CleanupStuckedResources extends Commandcontinue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in service: {$e->getMessage()}\n";}try {$serviceApplications = ServiceApplication::all();- foreach ($serviceApplications as $service) {- if (! data_get($service, 'service')) {- echo 'ServiceApplication without service: '.$service->name.'\n';- $service->forceDelete();+ foreach ($serviceApplications as $serviceApplication) {+ if (! data_get($serviceApplication, 'service')) {+ echo 'ServiceApplication without service: '.$serviceApplication->name.'\n';+ $serviceApplication->forceDelete();continue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in serviceApplications: {$e->getMessage()}\n";}try {$serviceDatabases = ServiceDatabase::all();- foreach ($serviceDatabases as $service) {- if (! data_get($service, 'service')) {- echo 'ServiceDatabase without service: '.$service->name.'\n';- $service->forceDelete();+ foreach ($serviceDatabases as $serviceDatabase) {+ if (! data_get($serviceDatabase, 'service')) {+ echo 'ServiceDatabase without service: '.$serviceDatabase->name.'\n';+ $serviceDatabase->forceDelete();continue;}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in ServiceDatabases: {$e->getMessage()}\n";}}diff --git a/app/Console/Commands/CleanupUnreachableServers.php b/app/Console/Commands/CleanupUnreachableServers.phpindex def01b2651..4182e46680 100644--- a/app/Console/Commands/CleanupUnreachableServers.php+++ b/app/Console/Commands/CleanupUnreachableServers.php@@ -14,7 +14,7 @@ class CleanupUnreachableServers extends Commandpublic function handle(){echo "Running unreachable server cleanup...\n";- $servers = Server::where('unreachable_count', 3)->where('unreachable_notification_sent', true)->where('updated_at', '<', now()->subDays(7))->get();+ $servers = Server::query()->where('unreachable_count', 3)->where('unreachable_notification_sent', true)->where('updated_at', '<', now()->subDays(7))->get();if ($servers->count() > 0) {foreach ($servers as $server) {echo "Cleanup unreachable server ($server->id) with name $server->name";diff --git a/app/Console/Commands/CloudCheckSubscription.php b/app/Console/Commands/CloudCheckSubscription.phpindex 6e237e84b2..ac1d258b83 100644--- a/app/Console/Commands/CloudCheckSubscription.php+++ b/app/Console/Commands/CloudCheckSubscription.php@@ -4,6 +4,7 @@ namespace App\Console\Commands;use App\Models\Team;use Illuminate\Console\Command;+use Stripe\StripeClient;class CloudCheckSubscription extends Command{@@ -26,19 +27,19 @@ class CloudCheckSubscription extends Command*/public function handle(){- $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));- $activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->get();- foreach ($activeSubscribers as $team) {- $stripeSubscriptionId = $team->subscription->stripe_subscription_id;- $stripeInvoicePaid = $team->subscription->stripe_invoice_paid;- $stripeCustomerId = $team->subscription->stripe_customer_id;+ $stripeClient = new StripeClient(config('subscription.stripe_api_key'));+ $activeSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', true)->get();+ foreach ($activeSubscribers as $activeSubscriber) {+ $stripeSubscriptionId = $activeSubscriber->subscription->stripe_subscription_id;+ $stripeInvoicePaid = $activeSubscriber->subscription->stripe_invoice_paid;+ $stripeCustomerId = $activeSubscriber->subscription->stripe_customer_id;if (! $stripeSubscriptionId) {- echo "Team {$team->id} has no subscription, but invoice status is: {$stripeInvoicePaid}\n";+ echo "Team {$activeSubscriber->id} has no subscription, but invoice status is: {$stripeInvoicePaid}\n";echo "Link on Stripe: https://dashboard.stripe.com/customers/{$stripeCustomerId}\n";continue;}- $subscription = $stripe->subscriptions->retrieve($stripeSubscriptionId);+ $subscription = $stripeClient->subscriptions->retrieve($stripeSubscriptionId);if ($subscription->status === 'active') {continue;}diff --git a/app/Console/Commands/CloudCleanupSubscriptions.php b/app/Console/Commands/CloudCleanupSubscriptions.phpindex 9dc6e24f57..f6afeeadf3 100644--- a/app/Console/Commands/CloudCleanupSubscriptions.php+++ b/app/Console/Commands/CloudCleanupSubscriptions.php@@ -4,7 +4,9 @@ namespace App\Console\Commands;use App\Events\ServerReachabilityChanged;use App\Models\Team;+use Exception;use Illuminate\Console\Command;+use Stripe\StripeClient;class CloudCleanupSubscriptions extends Command{@@ -21,7 +23,7 @@ class CloudCleanupSubscriptions extends Commandreturn;}$this->info('Cleaning up subcriptions teams');- $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));+ $stripeClient = new StripeClient(config('subscription.stripe_api_key'));$teams = Team::all()->filter(function ($team) {return $team->id !== 0;@@ -47,34 +49,33 @@ class CloudCleanupSubscriptions extends Command$this->disableServers($team);continue;- } else {- $subscription = $stripe->subscriptions->retrieve(data_get($team, 'subscription.stripe_subscription_id'), []);- $status = data_get($subscription, 'status');- if ($status === 'active' || $status === 'past_due') {- $team->subscription->update([- 'stripe_invoice_paid' => true,- 'stripe_trial_already_ended' => false,- ]);+ }+ $subscription = $stripeClient->subscriptions->retrieve(data_get($team, 'subscription.stripe_subscription_id'), []);+ $status = data_get($subscription, 'status');+ if ($status === 'active' || $status === 'past_due') {+ $team->subscription->update([+ 'stripe_invoice_paid' => true,+ 'stripe_trial_already_ended' => false,+ ]);- continue;- }- $this->info('Subscription status: '.$status);- $this->info('Subscription id: '.data_get($team, 'subscription.stripe_subscription_id'));- $confirm = $this->confirm('Do you want to cancel the subscription?', true);- if (! $confirm) {- $this->info("Skipping team {$team->id}");- } else {- $this->info("Cancelling subscription for team {$team->id}");- $team->subscription->update([- 'stripe_invoice_paid' => false,- 'stripe_trial_already_ended' => false,- 'stripe_subscription_id' => null,- ]);- $this->disableServers($team);- }+ continue;+ }+ $this->info('Subscription status: '.$status);+ $this->info('Subscription id: '.data_get($team, 'subscription.stripe_subscription_id'));+ $confirm = $this->confirm('Do you want to cancel the subscription?', true);+ if (! $confirm) {+ $this->info("Skipping team {$team->id}");+ } else {+ $this->info("Cancelling subscription for team {$team->id}");+ $team->subscription->update([+ 'stripe_invoice_paid' => false,+ 'stripe_trial_already_ended' => false,+ 'stripe_subscription_id' => null,+ ]);+ $this->disableServers($team);}}- } catch (\Exception $e) {+ } catch (Exception $e) {$this->error($e->getMessage());return;diff --git a/app/Console/Commands/Dev.php b/app/Console/Commands/Dev.phpindex 257de0a927..9beb4f4b64 100644--- a/app/Console/Commands/Dev.php+++ b/app/Console/Commands/Dev.php@@ -33,7 +33,7 @@ class Dev extends Command// Generate OpenAPI documentationecho "Generating OpenAPI documentation.\n";// https://github.com/OAI/OpenAPI-Specification/releases- $process = Process::run([+ $processResult = Process::run(['/var/www/html/vendor/bin/openapi','app','-o',@@ -41,11 +41,11 @@ class Dev extends Command'--version','3.1.0',]);- $error = $process->errorOutput();+ $error = $processResult->errorOutput();$error = preg_replace('/^.*an object literal,.*$/m', '', $error);$error = preg_replace('/^\h*\v+/m', '', $error);echo $error;- echo $process->output();+ echo $processResult->output();// Convert YAML to JSON$yaml = file_get_contents('openapi.yaml');$json = json_encode(Yaml::parse($yaml), JSON_PRETTY_PRINT);@@ -69,7 +69,7 @@ class Dev extends Command}// Seed database if it's empty- $settings = InstanceSettings::find(0);+ $settings = InstanceSettings::query()->find(0);if (! $settings) {echo "Initializing instance, seeding database.\n";Artisan::call('migrate --seed');diff --git a/app/Console/Commands/Emails.php b/app/Console/Commands/Emails.phpindex 33ddf3019f..a55c515d70 100644--- a/app/Console/Commands/Emails.php+++ b/app/Console/Commands/Emails.php@@ -12,7 +12,6 @@ use App\Notifications\Application\DeploymentFailed;use App\Notifications\Application\DeploymentSuccess;use App\Notifications\Application\StatusChanged;use App\Notifications\Database\BackupFailed;-use App\Notifications\Database\BackupSuccess;use App\Notifications\Test;use Exception;use Illuminate\Console\Command;@@ -43,7 +42,7 @@ class Emails extends Command/*** Execute the console command.*/- private ?MailMessage $mail = null;+ private ?MailMessage $mailMessage = null;private ?string $email = null;@@ -69,15 +68,13 @@ class Emails extends Command$emailsGathered = ['realusers-before-trial', 'realusers-server-lost-connection'];if (isDev()) {$this->email = '[email protected]';- } else {- if (! in_array($type, $emailsGathered)) {- $this->email = text('Email Address to send to:');- }+ } elseif (! in_array($type, $emailsGathered)) {+ $this->email = text('Email Address to send to:');}set_transanctional_email_settings();- $this->mail = new MailMessage;- $this->mail->subject('Test Email');+ $this->mailMessage = new MailMessage;+ $this->mailMessage->subject('Test Email');switch ($type) {case 'updates':$teams = Team::all();@@ -102,18 +99,18 @@ class Emails extends Command$confirmed = confirm('Are you sure?');if ($confirmed) {foreach ($emails as $email) {- $this->mail = new MailMessage;- $this->mail->subject('One-click Services, Docker Compose support');+ $this->mailMessage = new MailMessage;+ $this->mailMessage->subject('One-click Services, Docker Compose support');$unsubscribeUrl = route('unsubscribe.marketing.emails', ['token' => encrypt($email),]);- $this->mail->view('emails.updates', ['unsubscribeUrl' => $unsubscribeUrl]);+ $this->mailMessage->view('emails.updates', ['unsubscribeUrl' => $unsubscribeUrl]);$this->sendEmail($email);}}break;case 'emails-test':- $this->mail = (new Test)->toMail();+ $this->mailMessage = (new Test)->toMail();$this->sendEmail();break;case 'application-deployment-success-daily':@@ -123,41 +120,41 @@ class Emails extends Commandif ($deployments->isEmpty()) {continue;}- $this->mail = (new DeploymentSuccess($application, 'test'))->toMail();+ $this->mailMessage = (new DeploymentSuccess($application, 'test'))->toMail();$this->sendEmail();}break;case 'application-deployment-success':$application = Application::all()->first();- $this->mail = (new DeploymentSuccess($application, 'test'))->toMail();+ $this->mailMessage = (new DeploymentSuccess($application, 'test'))->toMail();$this->sendEmail();break;case 'application-deployment-failed':$application = Application::all()->first();$preview = ApplicationPreview::all()->first();if (! $preview) {- $preview = ApplicationPreview::create([+ $preview = ApplicationPreview::query()->create(['application_id' => $application->id,'pull_request_id' => 1,'pull_request_html_url' => 'http://example.com','fqdn' => $application->fqdn,]);}- $this->mail = (new DeploymentFailed($application, 'test'))->toMail();+ $this->mailMessage = (new DeploymentFailed($application, 'test'))->toMail();$this->sendEmail();- $this->mail = (new DeploymentFailed($application, 'test', $preview))->toMail();+ $this->mailMessage = (new DeploymentFailed($application, 'test', $preview))->toMail();$this->sendEmail();break;case 'application-status-changed':$application = Application::all()->first();- $this->mail = (new StatusChanged($application))->toMail();+ $this->mailMessage = (new StatusChanged($application))->toMail();$this->sendEmail();break;case 'backup-failed':$backup = ScheduledDatabaseBackup::all()->first();$db = StandalonePostgresql::all()->first();if (! $backup) {- $backup = ScheduledDatabaseBackup::create([+ $backup = ScheduledDatabaseBackup::query()->create(['enabled' => true,'frequency' => 'daily','save_s3' => false,@@ -167,14 +164,14 @@ class Emails extends Command]);}$output = 'Because of an error, the backup of the database '.$db->name.' failed.';- $this->mail = (new BackupFailed($backup, $db, $output))->toMail();+ $this->mailMessage = (new BackupFailed($backup, $db, $output))->toMail();$this->sendEmail();break;case 'backup-success':$backup = ScheduledDatabaseBackup::all()->first();$db = StandalonePostgresql::all()->first();if (! $backup) {- $backup = ScheduledDatabaseBackup::create([+ $backup = ScheduledDatabaseBackup::query()->create(['enabled' => true,'frequency' => 'daily','save_s3' => false,@@ -183,7 +180,7 @@ class Emails extends Command'team_id' => 0,]);}- //$this->mail = (new BackupSuccess($backup->frequency, $db->name))->toMail();+ // $this->mail = (new BackupSuccess($backup->frequency, $db->name))->toMail();$this->sendEmail();break;// case 'invitation-link':@@ -201,10 +198,10 @@ class Emails extends Command// $this->sendEmail();// break;case 'realusers-before-trial':- $this->mail = new MailMessage;- $this->mail->view('emails.before-trial-conversion');- $this->mail->subject('Trial period has been added for all subscription plans.');- $teams = Team::doesntHave('subscription')->where('id', '!=', 0)->get();+ $this->mailMessage = new MailMessage;+ $this->mailMessage->view('emails.before-trial-conversion');+ $this->mailMessage->subject('Trial period has been added for all subscription plans.');+ $teams = Team::query()->doesntHave('subscription')->where('id', '!=', 0)->get();if (! $teams || $teams->isEmpty()) {echo 'No teams found.'.PHP_EOL;@@ -232,7 +229,7 @@ class Emails extends Commandbreak;case 'realusers-server-lost-connection':$serverId = text('Server Id');- $server = Server::find($serverId);+ $server = Server::query()->find($serverId);if (! $server) {throw new Exception('Server not found');}@@ -247,13 +244,13 @@ class Emails extends Commandforeach ($admins as $admin) {$this->info($admin);}- $this->mail = new MailMessage;- $this->mail->view('emails.server-lost-connection', [+ $this->mailMessage = new MailMessage;+ $this->mailMessage->view('emails.server-lost-connection', ['name' => $server->name,]);- $this->mail->subject('Action required: Server '.$server->name.' lost connection.');- foreach ($admins as $email) {- $this->sendEmail($email);+ $this->mailMessage->subject('Action required: Server '.$server->name.' lost connection.');+ foreach ($admins as $admin) {+ $this->sendEmail($admin);}break;}@@ -269,8 +266,8 @@ class Emails extends Command[],fn (Message $message) => $message->to($this->email)- ->subject($this->mail->subject)- ->html((string) $this->mail->render())+ ->subject($this->mailMessage->subject)+ ->html((string) $this->mailMessage->render()));$this->info("Email sent to $this->email successfully. 📧");}diff --git a/app/Console/Commands/Horizon.php b/app/Console/Commands/Horizon.phpindex d3e35ca5a1..0debcae889 100644--- a/app/Console/Commands/Horizon.php+++ b/app/Console/Commands/Horizon.php@@ -16,8 +16,7 @@ class Horizon extends Command$this->info('Horizon is enabled on this server.');$this->call('horizon');exit(0);- } else {- exit(0);}+ exit(0);}}diff --git a/app/Console/Commands/Init.php b/app/Console/Commands/Init.phpindex cc9bee0a53..0197a91da9 100644--- a/app/Console/Commands/Init.php+++ b/app/Console/Commands/Init.php@@ -15,6 +15,7 @@ use Illuminate\Console\Command;use Illuminate\Support\Facades\Artisan;use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;+use Throwable;class Init extends Command{@@ -22,7 +23,7 @@ class Init extends Commandprotected $description = 'Cleanup instance related stuffs';- public $servers = null;+ public $servers;public function handle(){@@ -35,8 +36,7 @@ class Init extends Command}$this->servers = Server::all();- if (isCloud()) {- } else {+ if (! isCloud()) {$this->send_alive_signal();get_public_ips();}@@ -61,14 +61,14 @@ class Init extends Commandtry {$this->pullHelperImage();- } catch (\Throwable $e) {+ } catch (Throwable $e) {//}if (isCloud()) {try {$this->pullTemplatesFromCDN();- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Could not pull templates from CDN: {$e->getMessage()}\n";}}@@ -76,13 +76,13 @@ class Init extends Commandif (! isCloud()) {try {$this->pullTemplatesFromCDN();- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Could not pull templates from CDN: {$e->getMessage()}\n";}try {$localhost = $this->servers->where('id', 0)->first();$localhost->setupDynamicProxyConfiguration();- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Could not setup dynamic configuration: {$e->getMessage()}\n";}$settings = instanceSettings();@@ -119,8 +119,8 @@ class Init extends Commandprivate function update_user_emails(){try {- User::whereRaw('email ~ \'[A-Z]\'')->get()->each(fn (User $user) => $user->update(['email' => strtolower($user->email)]));- } catch (\Throwable $e) {+ User::query()->whereRaw('email ~ \'[A-Z]\'')->get()->each(fn (User $user) => $user->update(['email' => strtolower($user->email)]));+ } catch (Throwable $e) {echo "Error in updating user emails: {$e->getMessage()}\n";}}@@ -128,8 +128,8 @@ class Init extends Commandprivate function update_traefik_labels(){try {- Server::where('proxy->type', 'TRAEFIK_V2')->update(['proxy->type' => 'TRAEFIK']);- } catch (\Throwable $e) {+ Server::query()->where('proxy->type', 'TRAEFIK_V2')->update(['proxy->type' => 'TRAEFIK']);+ } catch (Throwable $e) {echo "Error in updating traefik labels: {$e->getMessage()}\n";}}@@ -149,10 +149,12 @@ class Init extends Commandreturn instant_remote_process(["rm -f $file",], $server, false);- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning up unnecessary dynamic proxy configuration: {$e->getMessage()}\n";}}++ return null;}private function cleanup_unused_network_from_coolify_proxy()@@ -168,19 +170,19 @@ class Init extends Command['networks' => $networks, 'allNetworks' => $allNetworks] = collectDockerNetworksByServer($server);$removeNetworks = $allNetworks->diff($networks);$commands = collect();- foreach ($removeNetworks as $network) {- $out = instant_remote_process(["docker network inspect -f json $network | jq '.[].Containers | if . == {} then null else . end'"], $server, false);- if (empty($out)) {- $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");- $commands->push("docker network rm $network >/dev/null 2>&1 || true");+ foreach ($removeNetworks as $removeNetwork) {+ $out = instant_remote_process(["docker network inspect -f json {$removeNetwork} | jq '.[].Containers | if . == {} then null else . end'"], $server, false);+ if ($out === null || $out === '' || $out === '0') {+ $commands->push("docker network disconnect {$removeNetwork} coolify-proxy >/dev/null 2>&1 || true");+ $commands->push("docker network rm {$removeNetwork} >/dev/null 2>&1 || true");} else {$data = collect(json_decode($out, true));if ($data->count() === 1) {// If only coolify-proxy itself is connected to that network (it should not be possible, but who knows)$isCoolifyProxyItself = data_get($data->first(), 'Name') === 'coolify-proxy';if ($isCoolifyProxyItself) {- $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");- $commands->push("docker network rm $network >/dev/null 2>&1 || true");+ $commands->push("docker network disconnect {$removeNetwork} coolify-proxy >/dev/null 2>&1 || true");+ $commands->push("docker network rm {$removeNetwork} >/dev/null 2>&1 || true");}}}@@ -188,7 +190,7 @@ class Init extends Commandif ($commands->isNotEmpty()) {remote_process(command: $commands, type: ActivityTypes::INLINE->value, server: $server, ignore_errors: false);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in cleaning up unused networks from coolify proxy: {$e->getMessage()}\n";}}@@ -202,20 +204,20 @@ class Init extends Commandif ($database && $database->trashed()) {echo "Restoring coolify db backup\n";$database->restore();- $scheduledBackup = ScheduledDatabaseBackup::find(0);+ $scheduledBackup = ScheduledDatabaseBackup::query()->find(0);if (! $scheduledBackup) {- ScheduledDatabaseBackup::create([+ ScheduledDatabaseBackup::query()->create(['id' => 0,'enabled' => true,'save_s3' => false,'frequency' => '0 0 * * *','database_id' => $database->id,- 'database_type' => \App\Models\StandalonePostgresql::class,+ 'database_type' => StandalonePostgresql::class,'team_id' => 0,]);}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in restoring coolify db backup: {$e->getMessage()}\n";}}@@ -234,7 +236,7 @@ class Init extends Command}try {Http::get("https://undead.coolify.io/v4/alive?appId=$id&version=$version");- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error in sending live signal: {$e->getMessage()}\n";}}@@ -246,12 +248,12 @@ class Init extends Commandif (isCloud()) {return;}- $queued_inprogress_deployments = ApplicationDeploymentQueue::whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value])->get();- foreach ($queued_inprogress_deployments as $deployment) {- $deployment->status = ApplicationDeploymentStatus::FAILED->value;- $deployment->save();+ $queued_inprogress_deployments = ApplicationDeploymentQueue::query()->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value])->get();+ foreach ($queued_inprogress_deployments as $queued_inprogress_deployment) {+ $queued_inprogress_deployment->status = ApplicationDeploymentStatus::FAILED->value;+ $queued_inprogress_deployment->save();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {echo "Error: {$e->getMessage()}\n";}}diff --git a/app/Console/Commands/Migration.php b/app/Console/Commands/Migration.phpindex 44c17203bf..3f6e498ec3 100644--- a/app/Console/Commands/Migration.php+++ b/app/Console/Commands/Migration.php@@ -16,9 +16,8 @@ class Migration extends Command$this->info('Migration is enabled on this server.');$this->call('migrate', ['--force' => true, '--isolated' => true]);exit(0);- } else {- $this->info('Migration is disabled on this server.');- exit(0);}+ $this->info('Migration is disabled on this server.');+ exit(0);}}diff --git a/app/Console/Commands/OpenApi.php b/app/Console/Commands/OpenApi.phpindex 6cbcb310c3..a321706998 100644--- a/app/Console/Commands/OpenApi.php+++ b/app/Console/Commands/OpenApi.php@@ -16,7 +16,7 @@ class OpenApi extends Command// Generate OpenAPI documentationecho "Generating OpenAPI documentation.\n";// https://github.com/OAI/OpenAPI-Specification/releases- $process = Process::run([+ $processResult = Process::run(['/var/www/html/vendor/bin/openapi','app','-o',@@ -24,10 +24,10 @@ class OpenApi extends Command'--version','3.1.0',]);- $error = $process->errorOutput();+ $error = $processResult->errorOutput();$error = preg_replace('/^.*an object literal,.*$/m', '', $error);$error = preg_replace('/^\h*\v+/m', '', $error);echo $error;- echo $process->output();+ echo $processResult->output();}}diff --git a/app/Console/Commands/RootChangeEmail.php b/app/Console/Commands/RootChangeEmail.phpindex c87a545c5b..2027cdc493 100644--- a/app/Console/Commands/RootChangeEmail.php+++ b/app/Console/Commands/RootChangeEmail.php@@ -3,6 +3,7 @@namespace App\Console\Commands;use App\Models\User;+use Exception;use Illuminate\Console\Command;class RootChangeEmail extends Command@@ -31,9 +32,9 @@ class RootChangeEmail extends Command$email = $this->ask('Give me a new email for root user');$this->info('Updating root email...');try {- User::find(0)->update(['email' => $email]);+ User::query()->find(0)->update(['email' => $email]);$this->info('Root user\'s email updated successfully.');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->error('Failed to update root user\'s email.');return;diff --git a/app/Console/Commands/RootResetPassword.php b/app/Console/Commands/RootResetPassword.phpindex f36c11a4f1..5b2210a6c4 100644--- a/app/Console/Commands/RootResetPassword.php+++ b/app/Console/Commands/RootResetPassword.php@@ -3,6 +3,7 @@namespace App\Console\Commands;use App\Models\User;+use Exception;use Illuminate\Console\Command;use Illuminate\Support\Facades\Hash;@@ -32,16 +33,16 @@ class RootResetPassword extends Command$this->info('You are about to reset the root password.');$password = password('Give me a new password for root user: ');$passwordAgain = password('Again');- if ($password != $passwordAgain) {+ if ($password !== $passwordAgain) {$this->error('Passwords do not match.');return;}$this->info('Updating root password...');try {- User::find(0)->update(['password' => Hash::make($password)]);+ User::query()->find(0)->update(['password' => Hash::make($password)]);$this->info('Root password updated successfully.');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->error('Failed to update root password.');return;diff --git a/app/Console/Commands/Scheduler.php b/app/Console/Commands/Scheduler.phpindex ee64368c3d..90bbf29795 100644--- a/app/Console/Commands/Scheduler.php+++ b/app/Console/Commands/Scheduler.php@@ -16,8 +16,7 @@ class Scheduler extends Command$this->info('Scheduler is enabled on this server.');$this->call('schedule:work');exit(0);- } else {- exit(0);}+ exit(0);}}diff --git a/app/Console/Commands/Seeder.php b/app/Console/Commands/Seeder.phpindex e37b6a9d27..66f066515d 100644--- a/app/Console/Commands/Seeder.php+++ b/app/Console/Commands/Seeder.php@@ -16,9 +16,8 @@ class Seeder extends Command$this->info('Seeder is enabled on this server.');$this->call('db:seed', ['--class' => 'ProductionSeeder', '--force' => true]);exit(0);- } else {- $this->info('Seeder is disabled on this server.');- exit(0);}+ $this->info('Seeder is disabled on this server.');+ exit(0);}}diff --git a/app/Console/Commands/ServicesDelete.php b/app/Console/Commands/ServicesDelete.phpindex b5a74166a5..fc2dad7706 100644--- a/app/Console/Commands/ServicesDelete.php+++ b/app/Console/Commands/ServicesDelete.php@@ -62,8 +62,8 @@ class ServicesDelete extends Commandoptions: $servers->pluck('name', 'id')->sortKeys(),);- foreach ($serversToDelete as $server) {- $toDelete = $servers->where('id', $server)->first();+ foreach ($serversToDelete as $serverToDelete) {+ $toDelete = $servers->where('id', $serverToDelete)->first();if ($toDelete) {$this->info($toDelete);$confirmed = confirm('Are you sure you want to delete all selected resources?');@@ -88,8 +88,8 @@ class ServicesDelete extends Command$applications->pluck('name', 'id')->sortKeys(),);- foreach ($applicationsToDelete as $application) {- $toDelete = $applications->where('id', $application)->first();+ foreach ($applicationsToDelete as $applicationToDelete) {+ $toDelete = $applications->where('id', $applicationToDelete)->first();if ($toDelete) {$this->info($toDelete);$confirmed = confirm('Are you sure you want to delete all selected resources? ');@@ -114,8 +114,8 @@ class ServicesDelete extends Command$databases->pluck('name', 'id')->sortKeys(),);- foreach ($databasesToDelete as $database) {- $toDelete = $databases->where('id', $database)->first();+ foreach ($databasesToDelete as $databaseToDelete) {+ $toDelete = $databases->where('id', $databaseToDelete)->first();if ($toDelete) {$this->info($toDelete);$confirmed = confirm('Are you sure you want to delete all selected resources?');@@ -140,8 +140,8 @@ class ServicesDelete extends Command$services->pluck('name', 'id')->sortKeys(),);- foreach ($servicesToDelete as $service) {- $toDelete = $services->where('id', $service)->first();+ foreach ($servicesToDelete as $serviceToDelete) {+ $toDelete = $services->where('id', $serviceToDelete)->first();if ($toDelete) {$this->info($toDelete);$confirmed = confirm('Are you sure you want to delete all selected resources?');diff --git a/app/Console/Commands/ServicesGenerate.php b/app/Console/Commands/ServicesGenerate.phpindex b45707c5c0..208031a15b 100644--- a/app/Console/Commands/ServicesGenerate.php+++ b/app/Console/Commands/ServicesGenerate.php@@ -45,7 +45,7 @@ class ServicesGenerate extends Command$data = collect(explode(PHP_EOL, $content))->mapWithKeys(function ($line): array {preg_match('/^#(?<key>.*):(?<value>.*)$/U', $line, $m);- return $m ? [trim($m['key']) => trim($m['value'])] : [];+ return $m !== [] ? [trim($m['key']) => trim($m['value'])] : [];});if (str($data->get('ignore'))->toBoolean()) {diff --git a/app/Console/Commands/SyncBunny.php b/app/Console/Commands/SyncBunny.phpindex df19038286..697808eade 100644--- a/app/Console/Commands/SyncBunny.php+++ b/app/Console/Commands/SyncBunny.php@@ -6,6 +6,7 @@ use Illuminate\Console\Command;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Pool;use Illuminate\Support\Facades\Http;+use Throwable;use function Laravel\Prompts\confirm;@@ -114,7 +115,8 @@ class SyncBunny extends Command$this->info('Service template uploaded & purged...');return;- } elseif ($only_version) {+ }+ if ($only_version) {if ($nightly) {$this->info('About to sync NIGHLTY versions.json to BunnyCDN.');} else {@@ -123,7 +125,6 @@ class SyncBunny extends Command$file = file_get_contents($versions_location);$json = json_decode($file, true);$actual_version = data_get($json, 'coolify.v4.version');-$confirmed = confirm("Are you sure you want to sync to {$actual_version}?");if (! $confirmed) {return;@@ -152,7 +153,7 @@ class SyncBunny extends Command$pool->purge("$bunny_cdn/$bunny_cdn_path/$install_script"),]);$this->info('All files uploaded & purged...');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->error('Error: '.$e->getMessage());}}diff --git a/app/Console/Kernel.php b/app/Console/Kernel.phpindex e8781b01ef..d097869429 100644--- a/app/Console/Kernel.php+++ b/app/Console/Kernel.php@@ -6,13 +6,11 @@ use App\Jobs\CheckAndStartSentinelJob;use App\Jobs\CheckForUpdatesJob;use App\Jobs\CheckHelperImageJob;use App\Jobs\CleanupInstanceStuffsJob;-use App\Jobs\CleanupStaleMultiplexedConnections;use App\Jobs\DatabaseBackupJob;use App\Jobs\DockerCleanupJob;use App\Jobs\PullTemplatesFromCDN;use App\Jobs\ScheduledTaskJob;use App\Jobs\ServerCheckJob;-use App\Jobs\ServerCleanupMux;use App\Jobs\ServerStorageCheckJob;use App\Jobs\UpdateCoolifyJob;use App\Models\InstanceSettings;@@ -28,9 +26,9 @@ class Kernel extends ConsoleKernel{private $allServers;- private Schedule $scheduleInstance;+ private Schedule $schedule;- private InstanceSettings $settings;+ private InstanceSettings $instanceSettings;private string $updateCheckFrequency;@@ -38,13 +36,13 @@ class Kernel extends ConsoleKernelprotected function schedule(Schedule $schedule): void{- $this->scheduleInstance = $schedule;- $this->allServers = Server::where('ip', '!=', '1.2.3.4');+ $this->schedule = $schedule;+ $this->allServers = Server::query()->where('ip', '!=', '1.2.3.4');- $this->settings = instanceSettings();- $this->updateCheckFrequency = $this->settings->update_check_frequency ?: '0 * * * *';+ $this->instanceSettings = instanceSettings();+ $this->updateCheckFrequency = $this->instanceSettings->update_check_frequency ?: '0 * * * *';- $this->instanceTimezone = $this->settings->instance_timezone ?: config('app.timezone');+ $this->instanceTimezone = $this->instanceSettings->instance_timezone ?: config('app.timezone');if (validate_timezone($this->instanceTimezone) === false) {$this->instanceTimezone = config('app.timezone');@@ -54,9 +52,9 @@ class Kernel extends ConsoleKernelif (isDev()) {// Instance Jobs- $this->scheduleInstance->command('horizon:snapshot')->everyMinute();- $this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();- $this->scheduleInstance->job(new CheckHelperImageJob)->everyTenMinutes()->onOneServer();+ $this->schedule->command('horizon:snapshot')->everyMinute();+ $this->schedule->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();+ $this->schedule->job(new CheckHelperImageJob)->everyTenMinutes()->onOneServer();// Server Jobs$this->checkResources();@@ -64,16 +62,16 @@ class Kernel extends ConsoleKernel$this->checkScheduledBackups();$this->checkScheduledTasks();- $this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();+ $this->schedule->command('uploads:clear')->everyTwoMinutes();} else {// Instance Jobs- $this->scheduleInstance->command('horizon:snapshot')->everyFiveMinutes();- $this->scheduleInstance->command('cleanup:unreachable-servers')->daily()->onOneServer();+ $this->schedule->command('horizon:snapshot')->everyFiveMinutes();+ $this->schedule->command('cleanup:unreachable-servers')->daily()->onOneServer();- $this->scheduleInstance->job(new PullTemplatesFromCDN)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();+ $this->schedule->job(new PullTemplatesFromCDN)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();- $this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();+ $this->schedule->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();$this->scheduleUpdates();// Server Jobs@@ -84,8 +82,8 @@ class Kernel extends ConsoleKernel$this->checkScheduledBackups();$this->checkScheduledTasks();- $this->scheduleInstance->command('cleanup:database --yes')->daily();- $this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();+ $this->schedule->command('cleanup:database --yes')->daily();+ $this->schedule->command('uploads:clear')->everyTwoMinutes();}}@@ -94,12 +92,12 @@ class Kernel extends ConsoleKernel$servers = $this->allServers->whereRelation('settings', 'is_usable', true)->whereRelation('settings', 'is_reachable', true)->get();foreach ($servers as $server) {if ($server->isSentinelEnabled()) {- $this->scheduleInstance->job(function () use ($server) {+ $this->schedule->job(function () use ($server) {CheckAndStartSentinelJob::dispatch($server);})->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();}}- $this->scheduleInstance->job(new CheckHelperImageJob)+ $this->schedule->job(new CheckHelperImageJob)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();@@ -107,14 +105,14 @@ class Kernel extends ConsoleKernelprivate function scheduleUpdates(): void{- $this->scheduleInstance->job(new CheckForUpdatesJob)+ $this->schedule->job(new CheckForUpdatesJob)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();- if ($this->settings->is_auto_update_enabled) {- $autoUpdateFrequency = $this->settings->auto_update_frequency;- $this->scheduleInstance->job(new UpdateCoolifyJob)+ if ($this->instanceSettings->is_auto_update_enabled) {+ $autoUpdateFrequency = $this->instanceSettings->auto_update_frequency;+ $this->schedule->job(new UpdateCoolifyJob)->cron($autoUpdateFrequency)->timezone($this->instanceTimezone)->onOneServer();@@ -125,7 +123,7 @@ class Kernel extends ConsoleKernel{if (isCloud()) {$servers = $this->allServers->whereHas('team.subscription')->get();- $own = Team::find(0)->servers;+ $own = Team::query()->find(0)->servers;$servers = $servers->merge($own);} else {$servers = $this->allServers->get();@@ -142,23 +140,23 @@ class Kernel extends ConsoleKernelif (Carbon::parse($lastSentinelUpdate)->isBefore(now()->subSeconds($server->waitBeforeDoingSshCheck()))) {// Check container status every minute if Sentinel does not activatedif (isCloud()) {- $this->scheduleInstance->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyFiveMinutes()->onOneServer();+ $this->schedule->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyFiveMinutes()->onOneServer();} else {- $this->scheduleInstance->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyMinute()->onOneServer();+ $this->schedule->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyMinute()->onOneServer();}// $this->scheduleInstance->job(new \App\Jobs\ServerCheckNewJob($server))->everyFiveMinutes()->onOneServer();- $this->scheduleInstance->job(new ServerStorageCheckJob($server))->cron($server->settings->server_disk_usage_check_frequency)->timezone($serverTimezone)->onOneServer();+ $this->schedule->job(new ServerStorageCheckJob($server))->cron($server->settings->server_disk_usage_check_frequency)->timezone($serverTimezone)->onOneServer();}- $this->scheduleInstance->job(new DockerCleanupJob($server))->cron($server->settings->docker_cleanup_frequency)->timezone($serverTimezone)->onOneServer();+ $this->schedule->job(new DockerCleanupJob($server))->cron($server->settings->docker_cleanup_frequency)->timezone($serverTimezone)->onOneServer();// Cleanup multiplexed connections every hour// $this->scheduleInstance->job(new ServerCleanupMux($server))->hourly()->onOneServer();// Temporary solution until we have better memory management for Sentinelif ($server->isSentinelEnabled()) {- $this->scheduleInstance->job(function () use ($server) {+ $this->schedule->job(function () use ($server) {$server->restartContainer('coolify-sentinel');})->daily()->onOneServer();}@@ -167,7 +165,7 @@ class Kernel extends ConsoleKernelprivate function checkScheduledBackups(): void{- $scheduled_backups = ScheduledDatabaseBackup::where('enabled', true)->get();+ $scheduled_backups = ScheduledDatabaseBackup::query()->where('enabled', true)->get();if ($scheduled_backups->isEmpty()) {return;}@@ -187,7 +185,7 @@ class Kernel extends ConsoleKernel$scheduled_backup->frequency = VALID_CRON_STRINGS[$scheduled_backup->frequency];}$serverTimezone = data_get($server->settings, 'server_timezone', $this->instanceTimezone);- $this->scheduleInstance->job(new DatabaseBackupJob(+ $this->schedule->job(new DatabaseBackupJob(backup: $scheduled_backup))->cron($scheduled_backup->frequency)->timezone($serverTimezone)->onOneServer();}@@ -195,7 +193,7 @@ class Kernel extends ConsoleKernelprivate function checkScheduledTasks(): void{- $scheduled_tasks = ScheduledTask::where('enabled', true)->get();+ $scheduled_tasks = ScheduledTask::query()->where('enabled', true)->get();if ($scheduled_tasks->isEmpty()) {return;}@@ -208,15 +206,11 @@ class Kernel extends ConsoleKernelcontinue;}- if ($application) {- if (str($application->status)->contains('running') === false) {- continue;- }+ if ($application && str($application->status)->contains('running') === false) {+ continue;}- if ($service) {- if (str($service->status)->contains('running') === false) {- continue;- }+ if ($service && str($service->status)->contains('running') === false) {+ continue;}$server = $scheduled_task->server();@@ -228,7 +222,7 @@ class Kernel extends ConsoleKernel$scheduled_task->frequency = VALID_CRON_STRINGS[$scheduled_task->frequency];}$serverTimezone = data_get($server->settings, 'server_timezone', $this->instanceTimezone);- $this->scheduleInstance->job(new ScheduledTaskJob(+ $this->schedule->job(new ScheduledTaskJob(task: $scheduled_task))->cron($scheduled_task->frequency)->timezone($serverTimezone)->onOneServer();}diff --git a/app/Data/ServerMetadata.php b/app/Data/ServerMetadata.phpindex d95944b15a..dadba854af 100644--- a/app/Data/ServerMetadata.php+++ b/app/Data/ServerMetadata.php@@ -9,7 +9,7 @@ use Spatie\LaravelData\Data;class ServerMetadata extends Data{public function __construct(- public ?ProxyTypes $type,- public ?ProxyStatus $status+ public ?ProxyTypes $proxyTypes,+ public ?ProxyStatus $proxyStatus) {}}diff --git a/app/Events/ApplicationStatusChanged.php b/app/Events/ApplicationStatusChanged.phpindex 4433248aad..ae24aefa23 100644--- a/app/Events/ApplicationStatusChanged.php+++ b/app/Events/ApplicationStatusChanged.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -20,7 +21,7 @@ class ApplicationStatusChanged implements ShouldBroadcast$teamId = auth()->user()->currentTeam()->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/BackupCreated.php b/app/Events/BackupCreated.phpindex 45b2aacb7a..633ac59bcf 100644--- a/app/Events/BackupCreated.php+++ b/app/Events/BackupCreated.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -20,7 +21,7 @@ class BackupCreated implements ShouldBroadcast$teamId = auth()->user()->currentTeam()->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/CloudflareTunnelConfigured.php b/app/Events/CloudflareTunnelConfigured.phpindex 3d7076d0da..d412d332a2 100644--- a/app/Events/CloudflareTunnelConfigured.php+++ b/app/Events/CloudflareTunnelConfigured.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -20,7 +21,7 @@ class CloudflareTunnelConfigured implements ShouldBroadcast$teamId = auth()->user()->currentTeam()->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/DatabaseProxyStopped.php b/app/Events/DatabaseProxyStopped.phpindex 96b35a5cac..57313e5df5 100644--- a/app/Events/DatabaseProxyStopped.php+++ b/app/Events/DatabaseProxyStopped.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -21,7 +22,7 @@ class DatabaseProxyStopped implements ShouldBroadcast$teamId = Auth::user()?->currentTeam()?->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/DatabaseStatusChanged.php b/app/Events/DatabaseStatusChanged.phpindex 913b21bc22..360592a3bd 100644--- a/app/Events/DatabaseStatusChanged.php+++ b/app/Events/DatabaseStatusChanged.php@@ -13,7 +13,7 @@ class DatabaseStatusChanged implements ShouldBroadcast{use Dispatchable, InteractsWithSockets, SerializesModels;- public $userId = null;+ public $userId;public function __construct($userId = null){@@ -21,7 +21,7 @@ class DatabaseStatusChanged implements ShouldBroadcast$userId = Auth::id() ?? null;}if (is_null($userId)) {- return false;+ return;}$this->userId = $userId;diff --git a/app/Events/FileStorageChanged.php b/app/Events/FileStorageChanged.phpindex 57004cf4c3..c3b16daa1f 100644--- a/app/Events/FileStorageChanged.php+++ b/app/Events/FileStorageChanged.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -17,7 +18,7 @@ class FileStorageChanged implements ShouldBroadcastpublic function __construct($teamId = null){if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/ProxyStatusChanged.php b/app/Events/ProxyStatusChanged.phpindex 35eedef70e..2c79bb9444 100644--- a/app/Events/ProxyStatusChanged.php+++ b/app/Events/ProxyStatusChanged.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -20,7 +21,7 @@ class ProxyStatusChanged implements ShouldBroadcast$teamId = auth()->user()->currentTeam()->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/RestoreJobFinished.php b/app/Events/RestoreJobFinished.phpindex d3adb77984..014e0f19ed 100644--- a/app/Events/RestoreJobFinished.php+++ b/app/Events/RestoreJobFinished.php@@ -17,18 +17,15 @@ class RestoreJobFinished$tmpPath = data_get($data, 'tmpPath');$container = data_get($data, 'container');$serverId = data_get($data, 'serverId');- if (filled($scriptPath) && filled($tmpPath) && filled($container) && filled($serverId)) {- if (str($tmpPath)->startsWith('/tmp/')- && str($scriptPath)->startsWith('/tmp/')- && ! str($tmpPath)->contains('..')- && ! str($scriptPath)->contains('..')- && strlen($tmpPath) > 5 // longer than just "/tmp/"- && strlen($scriptPath) > 5- ) {- $commands[] = "docker exec {$container} sh -c 'rm {$scriptPath}'";- $commands[] = "docker exec {$container} sh -c 'rm {$tmpPath}'";- instant_remote_process($commands, Server::find($serverId), throwError: true);- }+ if (filled($scriptPath) && filled($tmpPath) && filled($container) && filled($serverId) && (str($tmpPath)->startsWith('/tmp/')+ && str($scriptPath)->startsWith('/tmp/')+ && ! str($tmpPath)->contains('..')+ && ! str($scriptPath)->contains('..')+ && strlen($tmpPath) > 5 // longer than just "/tmp/"+ && strlen($scriptPath) > 5)) {+ $commands[] = "docker exec {$container} sh -c 'rm {$scriptPath}'";+ $commands[] = "docker exec {$container} sh -c 'rm {$tmpPath}'";+ instant_remote_process($commands, Server::query()->find($serverId), throwError: true);}}}diff --git a/app/Events/ScheduledTaskDone.php b/app/Events/ScheduledTaskDone.phpindex c8b5547f61..5a1a8f0d5b 100644--- a/app/Events/ScheduledTaskDone.php+++ b/app/Events/ScheduledTaskDone.php@@ -2,6 +2,7 @@namespace App\Events;+use Exception;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;@@ -20,7 +21,7 @@ class ScheduledTaskDone implements ShouldBroadcast$teamId = auth()->user()->currentTeam()->id ?? null;}if (is_null($teamId)) {- throw new \Exception('Team id is null');+ throw new Exception('Team id is null');}$this->teamId = $teamId;}diff --git a/app/Events/ServiceStatusChanged.php b/app/Events/ServiceStatusChanged.phpindex 3950022e10..2782464e1a 100644--- a/app/Events/ServiceStatusChanged.php+++ b/app/Events/ServiceStatusChanged.php@@ -21,7 +21,7 @@ class ServiceStatusChanged implements ShouldBroadcast$userId = Auth::id() ?? null;}if (is_null($userId)) {- return false;+ return;}$this->userId = $userId;}diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.phpindex 8c89bb07f9..5acba98432 100644--- a/app/Exceptions/Handler.php+++ b/app/Exceptions/Handler.php@@ -16,7 +16,7 @@ class Handler extends ExceptionHandler/*** A list of exception types with their corresponding custom log levels.*- * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>+ * @var array<class-string<Throwable>, \Psr\Log\LogLevel::*>*/protected $levels = [//@@ -25,7 +25,7 @@ class Handler extends ExceptionHandler/*** A list of the exception types that are not reported.*- * @var array<int, class-string<\Throwable>>+ * @var array<int, class-string<Throwable>>*/protected $dontReport = [ProcessException::class,@@ -42,15 +42,15 @@ class Handler extends ExceptionHandler'password_confirmation',];- private InstanceSettings $settings;+ private InstanceSettings $instanceSettings;- protected function unauthenticated($request, AuthenticationException $exception)+ protected function unauthenticated($request, AuthenticationException $authenticationException){- if ($request->is('api/*') || $request->expectsJson() || $this->shouldReturnJson($request, $exception)) {- return response()->json(['message' => $exception->getMessage()], 401);+ if ($request->is('api/*') || $request->expectsJson() || $this->shouldReturnJson($request, $authenticationException)) {+ return response()->json(['message' => $authenticationException->getMessage()], 401);}- return redirect()->guest($exception->redirectTo($request) ?? route('login'));+ return redirect()->guest($authenticationException->redirectTo($request) ?? route('login'));}/**@@ -58,21 +58,21 @@ class Handler extends ExceptionHandler*/public function register(): void{- $this->reportable(function (Throwable $e) {+ $this->reportable(function (Throwable $throwable) {if (isDev()) {return;}- if ($e instanceof RuntimeException) {+ if ($throwable instanceof RuntimeException) {return;}- $this->settings = instanceSettings();- if ($this->settings->do_not_track) {+ $this->instanceSettings = instanceSettings();+ if ($this->instanceSettings->do_not_track) {return;}app('sentry')->configureScope(function (Scope $scope) {$email = auth()?->user() ? auth()->user()->email : 'guest';- $instanceAdmin = User::find(0)->email ?? 'admin@localhost';+ $instanceAdmin = User::query()->find(0)->email ?? 'admin@localhost';$scope->setUser(['email' => $email,@@ -81,10 +81,10 @@ class Handler extends ExceptionHandler);});- if (str($e->getMessage())->contains('No space left on device')) {+ if (str($throwable->getMessage())->contains('No space left on device')) {return;}- Integration::captureUnhandledException($e);+ Integration::captureUnhandledException($throwable);});}}diff --git a/app/Helpers/SshMultiplexingHelper.php b/app/Helpers/SshMultiplexingHelper.phpindex 8da476b9e0..1a10222bf9 100644--- a/app/Helpers/SshMultiplexingHelper.php+++ b/app/Helpers/SshMultiplexingHelper.php@@ -6,12 +6,13 @@ use App\Models\PrivateKey;use App\Models\Server;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Process;+use RuntimeException;class SshMultiplexingHelper{public static function serverSshConfiguration(Server $server){- $privateKey = PrivateKey::findOrFail($server->private_key_id);+ $privateKey = PrivateKey::query()->findOrFail($server->private_key_id);$sshKeyLocation = $privateKey->getKeyLocation();$muxFilename = '/var/www/html/storage/app/ssh/mux/mux_'.$server->uuid;@@ -35,9 +36,9 @@ class SshMultiplexingHelper$checkCommand .= '-o ProxyCommand="cloudflared access ssh --hostname %h" ';}$checkCommand .= "{$server->user}@{$server->ip}";- $process = Process::run($checkCommand);+ $processResult = Process::run($checkCommand);- if ($process->exitCode() !== 0) {+ if ($processResult->exitCode() !== 0) {return self::establishNewMultiplexedConnection($server);}@@ -60,12 +61,9 @@ class SshMultiplexingHelper}$establishCommand .= self::getCommonSshOptions($server, $sshKeyLocation, $connectionTimeout, $serverInterval);$establishCommand .= "{$server->user}@{$server->ip}";- $establishProcess = Process::run($establishCommand);- if ($establishProcess->exitCode() !== 0) {- return false;- }+ $processResult = Process::run($establishCommand);- return true;+ return $processResult->exitCode() === 0;}public static function removeMuxFile(Server $server)@@ -103,15 +101,14 @@ class SshMultiplexingHelper}$scp_command .= self::getCommonSshOptions($server, $sshKeyLocation, config('constants.ssh.connection_timeout'), config('constants.ssh.server_interval'), isScp: true);- $scp_command .= "{$source} {$server->user}@{$server->ip}:{$dest}";- return $scp_command;+ return $scp_command."{$source} {$server->user}@{$server->ip}:{$dest}";}public static function generateSshCommand(Server $server, string $command){if ($server->settings->force_disabled) {- throw new \RuntimeException('Server is disabled.');+ throw new RuntimeException('Server is disabled.');}$sshConfig = self::serverSshConfiguration($server);@@ -140,11 +137,9 @@ class SshMultiplexingHelper$delimiter = base64_encode($delimiter);$command = str_replace($delimiter, '', $command);- $ssh_command .= "{$server->user}@{$server->ip} 'bash -se' << \\$delimiter".PHP_EOL+ return $ssh_command.("{$server->user}@{$server->ip} 'bash -se' << \\$delimiter".PHP_EOL.$command.PHP_EOL- .$delimiter;-- return $ssh_command;+ .$delimiter);}private static function isMultiplexingEnabled(): bool@@ -156,9 +151,9 @@ class SshMultiplexingHelper{$keyLocation = $privateKey->getKeyLocation();$checkKeyCommand = "ls $keyLocation 2>/dev/null";- $keyCheckProcess = Process::run($checkKeyCommand);+ $processResult = Process::run($checkKeyCommand);- if ($keyCheckProcess->exitCode() !== 0) {+ if ($processResult->exitCode() !== 0) {$privateKey->storeInFileSystem();}}diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.phpindex 19975041ba..fa009a2deb 100644--- a/app/Http/Controllers/Api/ApplicationsController.php+++ b/app/Http/Controllers/Api/ApplicationsController.php@@ -15,6 +15,7 @@ use App\Models\PrivateKey;use App\Models\Project;use App\Models\Server;use App\Models\Service;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use Illuminate\Validation\Rule;use OpenApi\Attributes as OA;@@ -89,7 +90,7 @@ class ApplicationsController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $projects = Project::where('team_id', $teamId)->get();+ $projects = Project::query()->where('team_id', $teamId)->get();$applications = collect();$applications->push($projects->pluck('applications')->flatten());$applications = $applications->flatten();@@ -717,7 +718,7 @@ class ApplicationsController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -731,12 +732,10 @@ class ApplicationsController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -825,15 +824,12 @@ class ApplicationsController extends Controllerif ($request->build_pack === 'dockercompose') {$request->offsetSet('ports_exposes', '80');}-$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}-$application = new Application;removeUnnecessaryFieldsFromRequest($request);-$application->fill($request->all());$dockerComposeDomainsJson = collect();if ($request->has('docker_compose_domains')) {@@ -848,7 +844,6 @@ class ApplicationsController extends Controllerif ($dockerComposeDomainsJson->count() > 0) {$application->docker_compose_domains = $dockerComposeDomainsJson;}-$application->fqdn = $fqdn;$application->destination_id = $destination->id;$application->destination_type = $destination->getMorphClass();@@ -868,27 +863,24 @@ class ApplicationsController extends Controller$application->save();}$application->isConfigurationChanged(true);-if ($instantDeploy) {$deployment_uuid = new Cuid2;-queue_application_deployment(application: $application,deployment_uuid: $deployment_uuid,no_questions_asked: true,is_api: true,);- } else {- if ($application->build_pack === 'dockercompose') {- LoadComposeFile::dispatch($application);- }+ } elseif ($application->build_pack === 'dockercompose') {+ LoadComposeFile::dispatch($application);}return response()->json(serializeApiResponse(['uuid' => data_get($application, 'uuid'),'domains' => data_get($application, 'domains'),]))->setStatusCode(201);- } elseif ($type === 'private-gh-app') {+ }+ if ($type === 'private-gh-app') {$validationRules = ['git_repository' => 'string|required','git_branch' => 'string|required',@@ -900,7 +892,6 @@ class ApplicationsController extends Controller'docker_compose_raw' => 'string|nullable',];$validationRules = array_merge(sharedDataApplications(), $validationRules);-$validator = customApiValidator($request->all(), $validationRules);if ($validator->fails()) {return response()->json([@@ -908,16 +899,14 @@ class ApplicationsController extends Controller'errors' => $validator->errors(),], 422);}-if (! $request->has('name')) {$request->offsetSet('name', generate_application_name($request->git_repository, $request->git_branch));}if ($request->build_pack === 'dockercompose') {$request->offsetSet('ports_exposes', '80');}-$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$githubApp = GithubApp::whereTeamId($teamId)->where('uuid', $githubAppUuid)->first();@@ -930,9 +919,7 @@ class ApplicationsController extends Controller}$application = new Application;removeUnnecessaryFieldsFromRequest($request);-$application->fill($request->all());-$dockerComposeDomainsJson = collect();if ($request->has('docker_compose_domains')) {$yaml = Yaml::parse($application->docker_compose_raw);@@ -969,28 +956,24 @@ class ApplicationsController extends Controller$application->save();}$application->isConfigurationChanged(true);-if ($instantDeploy) {$deployment_uuid = new Cuid2;-queue_application_deployment(application: $application,deployment_uuid: $deployment_uuid,no_questions_asked: true,is_api: true,);- } else {- if ($application->build_pack === 'dockercompose') {- LoadComposeFile::dispatch($application);- }+ } elseif ($application->build_pack === 'dockercompose') {+ LoadComposeFile::dispatch($application);}return response()->json(serializeApiResponse(['uuid' => data_get($application, 'uuid'),'domains' => data_get($application, 'domains'),]))->setStatusCode(201);- } elseif ($type === 'private-deploy-key') {-+ }+ if ($type === 'private-deploy-key') {$validationRules = ['git_repository' => 'string|required','git_branch' => 'string|required',@@ -1001,10 +984,8 @@ class ApplicationsController extends Controller'docker_compose_location' => 'string','docker_compose_raw' => 'string|nullable',];-$validationRules = array_merge(sharedDataApplications(), $validationRules);$validator = customApiValidator($request->all(), $validationRules);-if ($validator->fails()) {return response()->json(['message' => 'Validation failed.',@@ -1017,21 +998,17 @@ class ApplicationsController extends Controllerif ($request->build_pack === 'dockercompose') {$request->offsetSet('ports_exposes', '80');}-$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$privateKey = PrivateKey::whereTeamId($teamId)->where('uuid', $request->private_key_uuid)->first();if (! $privateKey) {return response()->json(['message' => 'Private Key not found.'], 404);}-$application = new Application;removeUnnecessaryFieldsFromRequest($request);-$application->fill($request->all());-$dockerComposeDomainsJson = collect();if ($request->has('docker_compose_domains')) {$yaml = Yaml::parse($application->docker_compose_raw);@@ -1066,33 +1043,29 @@ class ApplicationsController extends Controller$application->save();}$application->isConfigurationChanged(true);-if ($instantDeploy) {$deployment_uuid = new Cuid2;-queue_application_deployment(application: $application,deployment_uuid: $deployment_uuid,no_questions_asked: true,is_api: true,);- } else {- if ($application->build_pack === 'dockercompose') {- LoadComposeFile::dispatch($application);- }+ } elseif ($application->build_pack === 'dockercompose') {+ LoadComposeFile::dispatch($application);}return response()->json(serializeApiResponse(['uuid' => data_get($application, 'uuid'),'domains' => data_get($application, 'domains'),]))->setStatusCode(201);- } elseif ($type === 'dockerfile') {+ }+ if ($type === 'dockerfile') {$validationRules = ['dockerfile' => 'string|required',];$validationRules = array_merge(sharedDataApplications(), $validationRules);$validator = customApiValidator($request->all(), $validationRules);-if ($validator->fails()) {return response()->json(['message' => 'Validation failed.',@@ -1102,9 +1075,8 @@ class ApplicationsController extends Controllerif (! $request->has('name')) {$request->offsetSet('name', 'dockerfile-'.new Cuid2);}-$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}if (! isBase64Encoded($request->dockerfile)) {@@ -1126,12 +1098,10 @@ class ApplicationsController extends Controller}$dockerFile = base64_decode($request->dockerfile);removeUnnecessaryFieldsFromRequest($request);-$port = get_port_from_dockerfile($request->dockerfile);if (! $port) {$port = 80;}-$application = new Application;$application->fill($request->all());$application->fqdn = $fqdn;@@ -1141,8 +1111,6 @@ class ApplicationsController extends Controller$application->destination_id = $destination->id;$application->destination_type = $destination->getMorphClass();$application->environment_id = $environment->id;--$application->git_repository = 'coollabsio/coolify';$application->git_branch = 'main';$application->save();@@ -1156,7 +1124,6 @@ class ApplicationsController extends Controller$application->save();}$application->isConfigurationChanged(true);-if ($instantDeploy) {$deployment_uuid = new Cuid2;@@ -1172,7 +1139,8 @@ class ApplicationsController extends Controller'uuid' => data_get($application, 'uuid'),'domains' => data_get($application, 'domains'),]))->setStatusCode(201);- } elseif ($type === 'dockerimage') {+ }+ if ($type === 'dockerimage') {$validationRules = ['docker_registry_image_name' => 'string|required','docker_registry_image_tag' => 'string',@@ -1180,7 +1148,6 @@ class ApplicationsController extends Controller];$validationRules = array_merge(sharedDataApplications(), $validationRules);$validator = customApiValidator($request->all(), $validationRules);-if ($validator->fails()) {return response()->json(['message' => 'Validation failed.',@@ -1191,7 +1158,7 @@ class ApplicationsController extends Controller$request->offsetSet('name', 'docker-image-'.new Cuid2);}$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}if (! $request->docker_registry_image_tag) {@@ -1199,14 +1166,12 @@ class ApplicationsController extends Controller}$application = new Application;removeUnnecessaryFieldsFromRequest($request);-$application->fill($request->all());$application->fqdn = $fqdn;$application->build_pack = 'dockerimage';$application->destination_id = $destination->id;$application->destination_type = $destination->getMorphClass();$application->environment_id = $environment->id;-$application->git_repository = 'coollabsio/coolify';$application->git_branch = 'main';$application->save();@@ -1220,7 +1185,6 @@ class ApplicationsController extends Controller$application->save();}$application->isConfigurationChanged(true);-if ($instantDeploy) {$deployment_uuid = new Cuid2;@@ -1236,16 +1200,14 @@ class ApplicationsController extends Controller'uuid' => data_get($application, 'uuid'),'domains' => data_get($application, 'domains'),]))->setStatusCode(201);- } elseif ($type === 'dockercompose') {+ }+ if ($type === 'dockercompose') {$allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'instant_deploy', 'docker_compose_raw'];-$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1261,7 +1223,6 @@ class ApplicationsController extends Controller];$validationRules = array_merge(sharedDataApplications(), $validationRules);$validator = customApiValidator($request->all(), $validationRules);-if ($validator->fails()) {return response()->json(['message' => 'Validation failed.',@@ -1269,7 +1230,7 @@ class ApplicationsController extends Controller], 422);}$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}if (! isBase64Encoded($request->docker_compose_raw)) {@@ -1291,23 +1252,19 @@ class ApplicationsController extends Controller}$dockerCompose = base64_decode($request->docker_compose_raw);$dockerComposeRaw = Yaml::dump(Yaml::parse($dockerCompose), 10, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);-// $isValid = validateComposeFile($dockerComposeRaw, $server_id);// if ($isValid !== 'OK') {// return $this->dispatch('error', "Invalid docker-compose file.\n$isValid");// }-$service = new Service;removeUnnecessaryFieldsFromRequest($request);$service->fill($request->all());-$service->docker_compose_raw = $dockerComposeRaw;$service->environment_id = $environment->id;$service->server_id = $server->id;$service->destination_id = $destination->id;$service->destination_type = $destination->getMorphClass();$service->save();-$service->name = "service-$service->uuid";$service->parse(isNew: true);if ($instantDeploy) {@@ -1447,7 +1404,7 @@ class ApplicationsController extends Controllerpublic function delete_by_uuid(Request $request){$teamId = getTeamIdFromToken();- $cleanup = filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);+ filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);if (is_null($teamId)) {return invalidTokenResponse();}@@ -1602,7 +1559,7 @@ class ApplicationsController extends Controller], 400);}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();@@ -1664,16 +1621,14 @@ class ApplicationsController extends Controller}}$return = $this->validateDataApplications($request, $server);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1696,7 +1651,7 @@ class ApplicationsController extends Controllerreturn $domain;});- if (count($errors) > 0) {+ if ($errors !== []) {return response()->json(['message' => 'Validation failed.','errors' => $errors,@@ -1755,11 +1710,11 @@ class ApplicationsController extends Controller$application->save();if ($instantDeploy) {- $deployment_uuid = new Cuid2;+ $cuid2 = new Cuid2;queue_application_deployment(application: $application,- deployment_uuid: $deployment_uuid,+ deployment_uuid: $cuid2,is_api: true,);}@@ -1935,7 +1890,7 @@ class ApplicationsController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();@@ -1956,12 +1911,10 @@ class ApplicationsController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1995,43 +1948,38 @@ class ApplicationsController extends Controller$env->save();return response()->json($this->removeSensitiveData($env))->setStatusCode(201);- } else {- return response()->json([- 'message' => 'Environment variable not found.',- ], 404);}- } else {- $env = $application->environment_variables->where('key', $key)->first();- if ($env) {- $env->value = $request->value;- if ($env->is_build_time != $is_build_time) {- $env->is_build_time = $is_build_time;- }- if ($env->is_literal != $is_literal) {- $env->is_literal = $is_literal;- }- if ($env->is_preview != $is_preview) {- $env->is_preview = $is_preview;- }- if ($env->is_multiline != $request->is_multiline) {- $env->is_multiline = $request->is_multiline;- }- if ($env->is_shown_once != $request->is_shown_once) {- $env->is_shown_once = $request->is_shown_once;- }- $env->save();- return response()->json($this->removeSensitiveData($env))->setStatusCode(201);- } else {- return response()->json([- 'message' => 'Environment variable not found.',- ], 404);+ return response()->json([+ 'message' => 'Environment variable not found.',+ ], 404);+ }+ $env = $application->environment_variables->where('key', $key)->first();+ if ($env) {+ $env->value = $request->value;+ if ($env->is_build_time != $is_build_time) {+ $env->is_build_time = $is_build_time;+ }+ if ($env->is_literal != $is_literal) {+ $env->is_literal = $is_literal;+ }+ if ($env->is_preview != $is_preview) {+ $env->is_preview = $is_preview;+ }+ if ($env->is_multiline != $request->is_multiline) {+ $env->is_multiline = $request->is_multiline;+ }+ if ($env->is_shown_once != $request->is_shown_once) {+ $env->is_shown_once = $request->is_shown_once;}+ $env->save();++ return response()->json($this->removeSensitiveData($env))->setStatusCode(201);}return response()->json([- 'message' => 'Something is not okay. Are you okay?',- ], 500);+ 'message' => 'Environment variable not found.',+ ], 404);}#[OA\Patch(@@ -2124,7 +2072,7 @@ class ApplicationsController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();@@ -2330,12 +2278,10 @@ class ApplicationsController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -2352,51 +2298,44 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Environment variable already exists. Use PATCH request to update it.',], 409);- } else {- $env = $application->environment_variables()->create([- 'key' => $request->key,- 'value' => $request->value,- 'is_preview' => $request->is_preview ?? false,- 'is_build_time' => $request->is_build_time ?? false,- 'is_literal' => $request->is_literal ?? false,- 'is_multiline' => $request->is_multiline ?? false,- 'is_shown_once' => $request->is_shown_once ?? false,- 'resourceable_type' => get_class($application),- 'resourceable_id' => $application->id,- ]);-- return response()->json([- 'uuid' => $env->uuid,- ])->setStatusCode(201);}- } else {- $env = $application->environment_variables->where('key', $key)->first();- if ($env) {- return response()->json([- 'message' => 'Environment variable already exists. Use PATCH request to update it.',- ], 409);- } else {- $env = $application->environment_variables()->create([- 'key' => $request->key,- 'value' => $request->value,- 'is_preview' => $request->is_preview ?? false,- 'is_build_time' => $request->is_build_time ?? false,- 'is_literal' => $request->is_literal ?? false,- 'is_multiline' => $request->is_multiline ?? false,- 'is_shown_once' => $request->is_shown_once ?? false,- 'resourceable_type' => get_class($application),- 'resourceable_id' => $application->id,- ]);+ $env = $application->environment_variables()->create([+ 'key' => $request->key,+ 'value' => $request->value,+ 'is_preview' => $request->is_preview ?? false,+ 'is_build_time' => $request->is_build_time ?? false,+ 'is_literal' => $request->is_literal ?? false,+ 'is_multiline' => $request->is_multiline ?? false,+ 'is_shown_once' => $request->is_shown_once ?? false,+ 'resourceable_type' => get_class($application),+ 'resourceable_id' => $application->id,+ ]);- return response()->json([- 'uuid' => $env->uuid,- ])->setStatusCode(201);- }+ return response()->json([+ 'uuid' => $env->uuid,+ ])->setStatusCode(201);}+ $env = $application->environment_variables->where('key', $key)->first();+ if ($env) {+ return response()->json([+ 'message' => 'Environment variable already exists. Use PATCH request to update it.',+ ], 409);+ }+ $env = $application->environment_variables()->create([+ 'key' => $request->key,+ 'value' => $request->value,+ 'is_preview' => $request->is_preview ?? false,+ 'is_build_time' => $request->is_build_time ?? false,+ 'is_literal' => $request->is_literal ?? false,+ 'is_multiline' => $request->is_multiline ?? false,+ 'is_shown_once' => $request->is_shown_once ?? false,+ 'resourceable_type' => get_class($application),+ 'resourceable_id' => $application->id,+ ]);return response()->json([- 'message' => 'Something went wrong.',- ], 500);+ 'uuid' => $env->uuid,+ ])->setStatusCode(201);}#[OA\Delete(@@ -2473,7 +2412,7 @@ class ApplicationsController extends Controller'message' => 'Application not found.',], 404);}- $found_env = EnvironmentVariable::where('uuid', $request->env_uuid)+ $found_env = EnvironmentVariable::query()->where('uuid', $request->env_uuid)->where('resourceable_type', Application::class)->where('resourceable_id', $application->id)->first();@@ -2576,11 +2515,11 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Application not found.'], 404);}- $deployment_uuid = new Cuid2;+ $cuid2 = new Cuid2;queue_application_deployment(application: $application,- deployment_uuid: $deployment_uuid,+ deployment_uuid: $cuid2,force_rebuild: $force,is_api: true,no_questions_asked: $instant_deploy@@ -2589,7 +2528,7 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Deployment request queued.',- 'deployment_uuid' => $deployment_uuid->toString(),+ 'deployment_uuid' => $cuid2->toString(),],200);@@ -2737,11 +2676,11 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Application not found.'], 404);}- $deployment_uuid = new Cuid2;+ $cuid2 = new Cuid2;queue_application_deployment(application: $application,- deployment_uuid: $deployment_uuid,+ deployment_uuid: $cuid2,restart_only: true,is_api: true,);@@ -2749,7 +2688,7 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Restart request queued.',- 'deployment_uuid' => $deployment_uuid->toString(),+ 'deployment_uuid' => $cuid2->toString(),],);}@@ -2836,7 +2775,7 @@ class ApplicationsController extends Controllerreturn response()->json(['message' => 'Application not found.'], 404);}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -2844,12 +2783,10 @@ class ApplicationsController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -2932,7 +2869,7 @@ class ApplicationsController extends Controllerreturn str($domain)->trim()->lower();});- if (count($errors) > 0) {+ if ($errors !== []) {return response()->json(['message' => 'Validation failed.','errors' => $errors,@@ -2947,5 +2884,7 @@ class ApplicationsController extends Controller], 422);}}++ return null;}}diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.phpindex 504665f6a8..74d0dd88e2 100644--- a/app/Http/Controllers/Api/DatabasesController.php+++ b/app/Http/Controllers/Api/DatabasesController.php@@ -12,6 +12,7 @@ use App\Http\Controllers\Controller;use App\Jobs\DeleteResourceJob;use App\Models\Project;use App\Models\Server;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use OpenApi\Attributes as OA;@@ -73,7 +74,7 @@ class DatabasesController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $projects = Project::where('team_id', $teamId)->get();+ $projects = Project::query()->where('team_id', $teamId)->get();$databases = collect();foreach ($projects as $project) {$databases = $databases->merge($project->databases());@@ -246,7 +247,7 @@ class DatabasesController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -276,10 +277,8 @@ class DatabasesController extends Controllerif (! $database) {return response()->json(['message' => 'Database not found.'], 404);}- if ($request->is_public && $request->public_port) {- if (isPublicPortAlreadyUsed($database->destination->server, $request->public_port, $database->id)) {- return response()->json(['message' => 'Public port already used by another database.'], 400);- }+ if ($request->is_public && $request->public_port && isPublicPortAlreadyUsed($database->destination->server, $request->public_port, $database->id)) {+ return response()->json(['message' => 'Public port already used by another database.'], 400);}switch ($database->type()) {case 'standalone-postgresql':@@ -472,12 +471,10 @@ class DatabasesController extends Controllerbreak;}$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1019,7 +1016,7 @@ class DatabasesController extends Controllerreturn $this->create_database($request, NewDatabaseTypes::MONGODB);}- public function create_database(Request $request, NewDatabaseTypes $type)+ public function create_database(Request $request, NewDatabaseTypes $newDatabaseTypes){$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];@@ -1029,17 +1026,15 @@ class DatabasesController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if (! empty($extraFields)) {+ if ($extraFields !== []) {$errors = collect([]);- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField);}return response()->json([@@ -1080,10 +1075,8 @@ class DatabasesController extends Controllerreturn response()->json(['message' => 'Server has multiple destinations and you do not set destination_uuid.'], 400);}$destination = $destinations->first();- if ($request->has('public_port') && $request->is_public) {- if (isPublicPortAlreadyUsed($server, $request->public_port)) {- return response()->json(['message' => 'Public port already used by another database.'], 400);- }+ if ($request->has('public_port') && $request->is_public && isPublicPortAlreadyUsed($server, $request->public_port)) {+ return response()->json(['message' => 'Public port already used by another database.'], 400);}$validator = customApiValidator($request->all(), ['name' => 'string|max:255',@@ -1111,17 +1104,15 @@ class DatabasesController extends Controller'errors' => $validator->errors(),], 422);}- if ($request->public_port) {- if ($request->public_port < 1024 || $request->public_port > 65535) {- return response()->json([- 'message' => 'Validation failed.',- 'errors' => [- 'public_port' => 'The public port should be between 1024 and 65535.',- ],- ], 422);- }+ if ($request->public_port && ($request->public_port < 1024 || $request->public_port > 65535)) {+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => [+ 'public_port' => 'The public port should be between 1024 and 65535.',+ ],+ ], 422);}- if ($type === NewDatabaseTypes::POSTGRESQL) {+ if ($newDatabaseTypes === NewDatabaseTypes::POSTGRESQL) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];$validator = customApiValidator($request->all(), ['postgres_user' => 'string',@@ -1132,12 +1123,10 @@ class DatabasesController extends Controller'postgres_conf' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1180,19 +1169,18 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::MARIADB) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::MARIADB) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];$validator = customApiValidator($request->all(), ['clickhouse_admin_user' => 'string','clickhouse_admin_password' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1225,7 +1213,6 @@ class DatabasesController extends Controllerif ($instantDeploy) {StartDatabase::dispatch($database);}-$database->refresh();$payload = ['uuid' => $database->uuid,@@ -1236,7 +1223,8 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::MYSQL) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::MYSQL) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];$validator = customApiValidator($request->all(), ['mysql_root_password' => 'string',@@ -1246,12 +1234,10 @@ class DatabasesController extends Controller'mysql_conf' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1284,7 +1270,6 @@ class DatabasesController extends Controllerif ($instantDeploy) {StartDatabase::dispatch($database);}-$database->refresh();$payload = ['uuid' => $database->uuid,@@ -1295,19 +1280,18 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::REDIS) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::REDIS) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];$validator = customApiValidator($request->all(), ['redis_password' => 'string','redis_conf' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1340,7 +1324,6 @@ class DatabasesController extends Controllerif ($instantDeploy) {StartDatabase::dispatch($database);}-$database->refresh();$payload = ['uuid' => $database->uuid,@@ -1351,19 +1334,17 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::DRAGONFLY) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::DRAGONFLY) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];$validator = customApiValidator($request->all(), ['dragonfly_password' => 'string',]);-$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1371,7 +1352,6 @@ class DatabasesController extends Controller'errors' => $errors,], 422);}-removeUnnecessaryFieldsFromRequest($request);$database = create_standalone_dragonfly($environment->id, $destination->uuid, $request->all());if ($instantDeploy) {@@ -1381,19 +1361,18 @@ class DatabasesController extends Controllerreturn response()->json(serializeApiResponse(['uuid' => $database->uuid,]))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::KEYDB) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::KEYDB) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];$validator = customApiValidator($request->all(), ['keydb_password' => 'string','keydb_conf' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1426,7 +1405,6 @@ class DatabasesController extends Controllerif ($instantDeploy) {StartDatabase::dispatch($database);}-$database->refresh();$payload = ['uuid' => $database->uuid,@@ -1437,19 +1415,18 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::CLICKHOUSE) {+ }+ if ($newDatabaseTypes === NewDatabaseTypes::CLICKHOUSE) {$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];$validator = customApiValidator($request->all(), ['clickhouse_admin_user' => 'string','clickhouse_admin_password' => 'string',]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -1462,7 +1439,6 @@ class DatabasesController extends Controllerif ($instantDeploy) {StartDatabase::dispatch($database);}-$database->refresh();$payload = ['uuid' => $database->uuid,@@ -1473,67 +1449,61 @@ class DatabasesController extends Controller}return response()->json(serializeApiResponse($payload))->setStatusCode(201);- } elseif ($type === NewDatabaseTypes::MONGODB) {- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];- $validator = customApiValidator($request->all(), [- 'mongo_conf' => 'string',- 'mongo_initdb_root_username' => 'string',- 'mongo_initdb_root_password' => 'string',- 'mongo_initdb_database' => 'string',- ]);- $extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {- $errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }- }+ }+ $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];+ $validator = customApiValidator($request->all(), [+ 'mongo_conf' => 'string',+ 'mongo_initdb_root_username' => 'string',+ 'mongo_initdb_root_password' => 'string',+ 'mongo_initdb_database' => 'string',+ ]);+ $extraFields = array_diff(array_keys($request->all()), $allowedFields);+ if ($validator->fails() || $extraFields !== []) {+ $errors = $validator->errors();+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');+ }+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => $errors,+ ], 422);+ }+ removeUnnecessaryFieldsFromRequest($request);+ if ($request->has('mongo_conf')) {+ if (! isBase64Encoded($request->mongo_conf)) {return response()->json(['message' => 'Validation failed.',- 'errors' => $errors,+ 'errors' => [+ 'mongo_conf' => 'The mongo_conf should be base64 encoded.',+ ],], 422);}- removeUnnecessaryFieldsFromRequest($request);- if ($request->has('mongo_conf')) {- if (! isBase64Encoded($request->mongo_conf)) {- return response()->json([- 'message' => 'Validation failed.',- 'errors' => [- 'mongo_conf' => 'The mongo_conf should be base64 encoded.',- ],- ], 422);- }- $mongoConf = base64_decode($request->mongo_conf);- if (mb_detect_encoding($mongoConf, 'ASCII', true) === false) {- return response()->json([- 'message' => 'Validation failed.',- 'errors' => [- 'mongo_conf' => 'The mongo_conf should be base64 encoded.',- ],- ], 422);- }- $request->offsetSet('mongo_conf', $mongoConf);- }- $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->all());- if ($instantDeploy) {- StartDatabase::dispatch($database);- }-- $database->refresh();- $payload = [- 'uuid' => $database->uuid,- 'internal_db_url' => $database->internal_db_url,- ];- if ($database->is_public && $database->public_port) {- $payload['external_db_url'] = $database->external_db_url;+ $mongoConf = base64_decode($request->mongo_conf);+ if (mb_detect_encoding($mongoConf, 'ASCII', true) === false) {+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => [+ 'mongo_conf' => 'The mongo_conf should be base64 encoded.',+ ],+ ], 422);}-- return response()->json(serializeApiResponse($payload))->setStatusCode(201);+ $request->offsetSet('mongo_conf', $mongoConf);+ }+ $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->all());+ if ($instantDeploy) {+ StartDatabase::dispatch($database);+ }+ $database->refresh();+ $payload = [+ 'uuid' => $database->uuid,+ 'internal_db_url' => $database->internal_db_url,+ ];+ if ($database->is_public && $database->public_port) {+ $payload['external_db_url'] = $database->external_db_url;}- return response()->json(['message' => 'Invalid database type requested.'], 400);+ return response()->json(serializeApiResponse($payload))->setStatusCode(201);}#[OA\Delete(@@ -1594,7 +1564,7 @@ class DatabasesController extends Controllerpublic function delete_by_uuid(Request $request){$teamId = getTeamIdFromToken();- $cleanup = filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);+ filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);if (is_null($teamId)) {return invalidTokenResponse();}diff --git a/app/Http/Controllers/Api/DeployController.php b/app/Http/Controllers/Api/DeployController.phpindex 73b452f865..2a6c37e0b6 100644--- a/app/Http/Controllers/Api/DeployController.php+++ b/app/Http/Controllers/Api/DeployController.php@@ -5,8 +5,10 @@ namespace App\Http\Controllers\Api;use App\Actions\Database\StartDatabase;use App\Actions\Service\StartService;use App\Http\Controllers\Controller;+use App\Models\Application;use App\Models\ApplicationDeploymentQueue;use App\Models\Server;+use App\Models\Service;use App\Models\Tag;use Illuminate\Http\Request;use OpenApi\Attributes as OA;@@ -65,7 +67,7 @@ class DeployController extends Controllerreturn invalidTokenResponse();}$servers = Server::whereTeamId($teamId)->get();- $deployments_per_server = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $servers->pluck('id'))->get()->sortBy('id');+ $deployments_per_server = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $servers->pluck('id'))->get()->sortBy('id');$deployments_per_server = $deployments_per_server->map(function ($deployment) {return $this->removeSensitiveData($deployment);});@@ -121,7 +123,7 @@ class DeployController extends Controllerif (! $uuid) {return response()->json(['message' => 'UUID is required.'], 400);}- $deployment = ApplicationDeploymentQueue::where('deployment_uuid', $uuid)->first();+ $deployment = ApplicationDeploymentQueue::query()->where('deployment_uuid', $uuid)->first();if (! $deployment) {return response()->json(['message' => 'Deployment not found.'], 404);}@@ -196,7 +198,8 @@ class DeployController extends Controller}if ($tags) {return $this->by_tags($tags, $teamId, $force);- } elseif ($uuids) {+ }+ if ($uuids) {return $this->by_uuids($uuids, $teamId, $force);}@@ -245,7 +248,7 @@ class DeployController extends Controller$deployments = collect();$payload = collect();foreach ($tags as $tag) {- $found_tag = Tag::where(['name' => $tag, 'team_id' => $team_id])->first();+ $found_tag = Tag::query()->where(['name' => $tag, 'team_id' => $team_id])->first();if (! $found_tag) {// $message->push("Tag {$tag} not found.");continue;@@ -257,15 +260,15 @@ class DeployController extends Controllercontinue;}- foreach ($applications as $resource) {- ['message' => $return_message, 'deployment_uuid' => $deployment_uuid] = $this->deploy_resource($resource, $force);+ foreach ($applications as $application) {+ ['message' => $return_message, 'deployment_uuid' => $deployment_uuid] = $this->deploy_resource($application, $force);if ($deployment_uuid) {- $deployments->push(['resource_uuid' => $resource->uuid, 'deployment_uuid' => $deployment_uuid->toString()]);+ $deployments->push(['resource_uuid' => $application->uuid, 'deployment_uuid' => $deployment_uuid->toString()]);}$message = $message->merge($return_message);}- foreach ($services as $resource) {- ['message' => $return_message] = $this->deploy_resource($resource, $force);+ foreach ($services as $service) {+ ['message' => $return_message] = $this->deploy_resource($service, $force);$message = $message->merge($return_message);}}@@ -289,7 +292,7 @@ class DeployController extends Controllerreturn ['message' => "Resource ($resource) not found.", 'deployment_uuid' => $deployment_uuid];}switch ($resource?->getMorphClass()) {- case \App\Models\Application::class:+ case Application::class:$deployment_uuid = new Cuid2;queue_application_deployment(application: $resource,@@ -298,7 +301,7 @@ class DeployController extends Controller);$message = "Application {$resource->name} deployment queued.";break;- case \App\Models\Service::class:+ case Service::class:StartService::run($resource);$message = "Service {$resource->name} started. It could take a while, be patient.";break;diff --git a/app/Http/Controllers/Api/ProjectController.php b/app/Http/Controllers/Api/ProjectController.phpindex de008c84ea..c79338ac4f 100644--- a/app/Http/Controllers/Api/ProjectController.php+++ b/app/Http/Controllers/Api/ProjectController.php@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api;use App\Http\Controllers\Controller;use App\Models\Project;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use OpenApi\Attributes as OA;@@ -96,6 +97,7 @@ class ProjectController extends Controller}$project->load(['environments']);+return response()->json(serializeApiResponse($project),);@@ -223,7 +225,7 @@ class ProjectController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -232,12 +234,10 @@ class ProjectController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -246,7 +246,7 @@ class ProjectController extends Controller], 422);}- $project = Project::create([+ $project = Project::query()->create(['name' => $request->name,'description' => $request->description,'team_id' => $teamId,@@ -321,7 +321,7 @@ class ProjectController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -330,12 +330,10 @@ class ProjectController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([diff --git a/app/Http/Controllers/Api/ResourcesController.php b/app/Http/Controllers/Api/ResourcesController.phpindex ad12c83ab8..f3f6b72acf 100644--- a/app/Http/Controllers/Api/ResourcesController.php+++ b/app/Http/Controllers/Api/ResourcesController.php@@ -43,7 +43,7 @@ class ResourcesController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $projects = Project::where('team_id', $teamId)->get();+ $projects = Project::query()->where('team_id', $teamId)->get();$resources = collect();$resources->push($projects->pluck('applications')->flatten());$resources->push($projects->pluck('services')->flatten());diff --git a/app/Http/Controllers/Api/SecurityController.php b/app/Http/Controllers/Api/SecurityController.phpindex a14b0da20e..27b1129c1d 100644--- a/app/Http/Controllers/Api/SecurityController.php+++ b/app/Http/Controllers/Api/SecurityController.php@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api;use App\Http\Controllers\Controller;use App\Models\PrivateKey;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use OpenApi\Attributes as OA;@@ -58,7 +59,7 @@ class SecurityController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $keys = PrivateKey::where('team_id', $teamId)->get();+ $keys = PrivateKey::query()->where('team_id', $teamId)->get();return response()->json($this->removeSensitiveData($keys));}@@ -102,7 +103,7 @@ class SecurityController extends Controllerreturn invalidTokenResponse();}- $key = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();+ $key = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();if (is_null($key)) {return response()->json([@@ -172,7 +173,7 @@ class SecurityController extends Controllerreturn invalidTokenResponse();}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -195,7 +196,7 @@ class SecurityController extends Controllerif (! $request->description) {$request->offsetSet('description', 'Created by Coolify via API');}- $key = PrivateKey::create([+ $privateKey = PrivateKey::query()->create(['team_id' => $teamId,'name' => $request->name,'description' => $request->description,@@ -203,7 +204,7 @@ class SecurityController extends Controller]);return response()->json(serializeApiResponse([- 'uuid' => $key->uuid,+ 'uuid' => $privateKey->uuid,]))->setStatusCode(201);}@@ -267,7 +268,7 @@ class SecurityController extends Controllerreturn invalidTokenResponse();}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}@@ -278,12 +279,10 @@ class SecurityController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -291,7 +290,7 @@ class SecurityController extends Controller'errors' => $errors,], 422);}- $foundKey = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();+ $foundKey = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();if (is_null($foundKey)) {return response()->json(['message' => 'Private Key not found.',@@ -355,7 +354,7 @@ class SecurityController extends Controllerreturn response()->json(['message' => 'UUID is required.'], 422);}- $key = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();+ $key = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();if (is_null($key)) {return response()->json(['message' => 'Private Key not found.'], 404);}diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.phpindex b1deb53218..a5de2a17de 100644--- a/app/Http/Controllers/Api/ServersController.php+++ b/app/Http/Controllers/Api/ServersController.php@@ -11,6 +11,7 @@ use App\Models\Application;use App\Models\PrivateKey;use App\Models\Project;use App\Models\Server as ModelsServer;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use OpenApi\Attributes as OA;use Stringable;@@ -294,7 +295,7 @@ class ServersController extends Controllerreturn response()->json(serializeApiResponse($domains));}- $projects = Project::where('team_id', $teamId)->get();+ $projects = Project::query()->where('team_id', $teamId)->get();$domains = collect();$applications = $projects->pluck('applications')->flatten();$settings = instanceSettings();@@ -305,8 +306,8 @@ class ServersController extends Controller$f = str($fqdn)->replace('http://', '')->replace('https://', '')->explode('/');return str(str($f[0])->explode(':')[0]);- })->filter(function (Stringable $fqdn) {- return $fqdn->isNotEmpty();+ })->filter(function (Stringable $stringable) {+ return $stringable->isNotEmpty();});if ($ip === 'host.docker.internal') {@@ -341,13 +342,13 @@ class ServersController extends Controllerforeach ($services as $service) {$service_applications = $service->applications;if ($service_applications->count() > 0) {- foreach ($service_applications as $application) {- $fqdn = str($application->fqdn)->explode(',')->map(function ($fqdn) {+ foreach ($service_applications as $service_application) {+ $fqdn = str($service_application->fqdn)->explode(',')->map(function ($fqdn) {$f = str($fqdn)->replace('http://', '')->replace('https://', '')->explode('/');return str(str($f[0])->explode(':')[0]);- })->filter(function (Stringable $fqdn) {- return $fqdn->isNotEmpty();+ })->filter(function (Stringable $stringable) {+ return $stringable->isNotEmpty();});if ($ip === 'host.docker.internal') {if ($settings->public_ipv4) {@@ -459,7 +460,7 @@ class ServersController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -475,12 +476,10 @@ class ServersController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -616,7 +615,7 @@ class ServersController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -632,12 +631,10 @@ class ServersController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.phpindex 03d9d209cc..0bcb3ea974 100644--- a/app/Http/Controllers/Api/ServicesController.php+++ b/app/Http/Controllers/Api/ServicesController.php@@ -11,6 +11,7 @@ use App\Models\EnvironmentVariable;use App\Models\Project;use App\Models\Server;use App\Models\Service;+use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use OpenApi\Attributes as OA;@@ -75,7 +76,7 @@ class ServicesController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $projects = Project::where('team_id', $teamId)->get();+ $projects = Project::query()->where('team_id', $teamId)->get();$services = collect();foreach ($projects as $project) {$services->push($project->services()->get());@@ -245,7 +246,7 @@ class ServicesController extends Controller}$return = validateIncomingRequest($request);- if ($return instanceof \Illuminate\Http\JsonResponse) {+ if ($return instanceof JsonResponse) {return $return;}$validator = customApiValidator($request->all(), [@@ -261,12 +262,10 @@ class ServicesController extends Controller]);$extraFields = array_diff(array_keys($request->all()), $allowedFields);- if ($validator->fails() || ! empty($extraFields)) {+ if ($validator->fails() || $extraFields !== []) {$errors = $validator->errors();- if (! empty($extraFields)) {- foreach ($extraFields as $field) {- $errors->add($field, 'This field is not allowed.');- }+ foreach ($extraFields as $extraField) {+ $errors->add($extraField, 'This field is not allowed.');}return response()->json([@@ -315,7 +314,7 @@ class ServicesController extends Controller$oneClickDotEnvs = data_get($services, "$oneClickServiceName.envs", null);if ($oneClickDotEnvs) {$oneClickDotEnvs = str(base64_decode($oneClickDotEnvs))->split('/\r\n|\r|\n/')->filter(function ($value) {- return ! empty($value);+ return $value !== '' && $value !== '0';});}if ($oneClickService) {@@ -331,7 +330,7 @@ class ServicesController extends Controllerif ($oneClickServiceName === 'cloudflared') {data_set($service_payload, 'connect_to_docker_network', true);}- $service = Service::create($service_payload);+ $service = Service::query()->create($service_payload);$service->name = "$oneClickServiceName-".$service->uuid;$service->save();if ($oneClickDotEnvs?->count() > 0) {@@ -343,7 +342,7 @@ class ServicesController extends Controller$command = $value->after('SERVICE_')->beforeLast('_');$generatedValue = generateEnvValue($command->value(), $service);}- EnvironmentVariable::create([+ EnvironmentVariable::query()->create(['key' => $key,'value' => $generatedValue,'resourceable_id' => $service->id,@@ -373,11 +372,9 @@ class ServicesController extends Controller}return response()->json(['message' => 'Service not found.'], 404);- } else {- return response()->json(['message' => 'Invalid service type.', 'valid_service_types' => $serviceKeys], 400);}- return response()->json(['message' => 'Invalid service type.'], 400);+ return response()->json(['message' => 'Invalid service type.', 'valid_service_types' => $serviceKeys], 400);}#[OA\Get(@@ -428,7 +425,7 @@ class ServicesController extends Controllerif (! $request->uuid) {return response()->json(['message' => 'UUID is required.'], 404);}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -493,7 +490,7 @@ class ServicesController extends Controllerif (! $request->uuid) {return response()->json(['message' => 'UUID is required.'], 404);}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -566,7 +563,7 @@ class ServicesController extends Controllerif (is_null($teamId)) {return invalidTokenResponse();}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -670,7 +667,7 @@ class ServicesController extends Controllerreturn invalidTokenResponse();}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -791,7 +788,7 @@ class ServicesController extends Controllerreturn invalidTokenResponse();}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -907,7 +904,7 @@ class ServicesController extends Controllerreturn invalidTokenResponse();}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -1009,12 +1006,12 @@ class ServicesController extends Controllerreturn invalidTokenResponse();}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}- $env = EnvironmentVariable::where('uuid', $request->env_uuid)+ $env = EnvironmentVariable::query()->where('uuid', $request->env_uuid)->where('resourceable_type', Service::class)->where('resourceable_id', $service->id)->first();@@ -1089,7 +1086,7 @@ class ServicesController extends Controllerif (! $uuid) {return response()->json(['message' => 'UUID is required.'], 400);}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -1167,7 +1164,7 @@ class ServicesController extends Controllerif (! $uuid) {return response()->json(['message' => 'UUID is required.'], 400);}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}@@ -1245,7 +1242,7 @@ class ServicesController extends Controllerif (! $uuid) {return response()->json(['message' => 'UUID is required.'], 400);}- $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();+ $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();if (! $service) {return response()->json(['message' => 'Service not found.'], 404);}diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.phpindex 522683efaa..03d78bc0dd 100644--- a/app/Http/Controllers/Controller.php+++ b/app/Http/Controllers/Controller.php@@ -39,9 +39,9 @@ class Controller extends BaseControllerreturn view('auth.verify-email');}- public function email_verify(EmailVerificationRequest $request)+ public function email_verify(EmailVerificationRequest $emailVerificationRequest){- $request->fulfill();+ $emailVerificationRequest->fulfill();return redirect(RouteServiceProvider::HOME);}@@ -139,9 +139,10 @@ class Controller extends BaseControllerrefreshSession($invitation->team);return redirect()->route('team.index');- } else {- abort(400, 'Invitation expired.');}+ abort(400, 'Invitation expired.');++ return null;}public function revoke_invitation()diff --git a/app/Http/Controllers/MagicController.php b/app/Http/Controllers/MagicController.phpindex 59c9b8b94e..3bb905dbef 100644--- a/app/Http/Controllers/MagicController.php+++ b/app/Http/Controllers/MagicController.php@@ -46,10 +46,7 @@ class MagicController extends Controllerpublic function newProject(){- $project = Project::firstOrCreate(- ['name' => request()->query('name') ?? generate_random_name()],- ['team_id' => currentTeam()->id]- );+ $project = Project::query()->firstOrCreate(['name' => request()->query('name') ?? generate_random_name()], ['team_id' => currentTeam()->id]);return response()->json(['project_uuid' => $project->uuid,@@ -58,10 +55,7 @@ class MagicController extends Controllerpublic function newEnvironment(){- $environment = Environment::firstOrCreate(- ['name' => request()->query('name') ?? generate_random_name()],- ['project_id' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->firstOrFail()->id]- );+ $environment = Environment::query()->firstOrCreate(['name' => request()->query('name') ?? generate_random_name()], ['project_id' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->firstOrFail()->id]);return response()->json(['environment_name' => $environment->name,@@ -70,12 +64,10 @@ class MagicController extends Controllerpublic function newTeam(){- $team = Team::create(- [- 'name' => request()->query('name') ?? generate_random_name(),- 'personal_team' => false,- ],- );+ $team = Team::query()->create([+ 'name' => request()->query('name') ?? generate_random_name(),+ 'personal_team' => false,+ ]);auth()->user()->teams()->attach($team, ['role' => 'admin']);refreshSession();diff --git a/app/Http/Controllers/OauthController.php b/app/Http/Controllers/OauthController.phpindex 3a3f18c9c4..b4a1806c17 100644--- a/app/Http/Controllers/OauthController.php+++ b/app/Http/Controllers/OauthController.php@@ -3,6 +3,7 @@namespace App\Http\Controllers;use App\Models\User;+use Exception;use Illuminate\Support\Facades\Auth;use Symfony\Component\HttpKernel\Exception\HttpException;@@ -26,7 +27,7 @@ class OauthController extends Controllerabort(403, 'Registration is disabled');}- $user = User::create([+ $user = User::query()->create(['name' => $oauthUser->name,'email' => $oauthUser->email,]);@@ -34,7 +35,7 @@ class OauthController extends ControllerAuth::login($user);return redirect('/');- } catch (\Exception $e) {+ } catch (Exception $e) {$errorCode = $e instanceof HttpException ? 'auth.failed' : 'auth.failed.callback';return redirect()->route('login')->withErrors([__($errorCode)]);diff --git a/app/Http/Controllers/UploadController.php b/app/Http/Controllers/UploadController.phpindex 4d34a10007..57a5b33030 100644--- a/app/Http/Controllers/UploadController.php+++ b/app/Http/Controllers/UploadController.php@@ -17,13 +17,13 @@ class UploadController extends BaseControllerif (is_null($resource)) {return response()->json(['error' => 'You do not have permission for this database'], 500);}- $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));+ $fileReceiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));- if ($receiver->isUploaded() === false) {+ if ($fileReceiver->isUploaded() === false) {throw new UploadMissingFileException;}- $save = $receiver->receive();+ $save = $fileReceiver->receive();if ($save->isFinished()) {return $this->saveFile($save->getFile(), $resource);@@ -57,22 +57,22 @@ class UploadController extends BaseController// 'mime_type' => $mime// ]);// }- protected function saveFile(UploadedFile $file, $resource)+ protected function saveFile(UploadedFile $uploadedFile, $resource){- $mime = str_replace('/', '-', $file->getMimeType());+ $mime = str_replace('/', '-', $uploadedFile->getMimeType());$filePath = "upload/{$resource->uuid}";$finalPath = storage_path('app/'.$filePath);- $file->move($finalPath, 'restore');+ $uploadedFile->move($finalPath, 'restore');return response()->json(['mime_type' => $mime,]);}- protected function createFilename(UploadedFile $file)+ protected function createFilename(UploadedFile $uploadedFile){- $extension = $file->getClientOriginalExtension();- $filename = str_replace('.'.$extension, '', $file->getClientOriginalName()); // Filename without extension+ $extension = $uploadedFile->getClientOriginalExtension();+ $filename = str_replace('.'.$extension, '', $uploadedFile->getClientOriginalName()); // Filename without extension$filename .= '_'.md5(time()).'.'.$extension;diff --git a/app/Http/Controllers/Webhook/Bitbucket.php b/app/Http/Controllers/Webhook/Bitbucket.phpindex 8c74f95e5c..7e2b91616a 100644--- a/app/Http/Controllers/Webhook/Bitbucket.php+++ b/app/Http/Controllers/Webhook/Bitbucket.php@@ -30,7 +30,7 @@ class Bitbucket extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Bitbicket::manual_bitbucket", $json);- return;+ return null;}$return_payloads = collect([]);$payload = $request->collect();@@ -63,7 +63,7 @@ class Bitbucket extends Controller$pull_request_html_url = data_get($payload, 'pullrequest.links.html.href');$commit = data_get($payload, 'pullrequest.source.commit.hash');}- $applications = Application::where('git_repository', 'like', "%$full_name%");+ $applications = Application::query()->where('git_repository', 'like', "%$full_name%");$applications = $applications->where('git_branch', $branch)->get();if ($applications->isEmpty()) {return response([@@ -122,10 +122,10 @@ class Bitbucket extends Controllerif ($x_bitbucket_event === 'pullrequest:created') {if ($application->isPRDeployable()) {$deployment_uuid = new Cuid2;- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found) {if ($application->build_pack === 'dockercompose') {- $pr_app = ApplicationPreview::create([+ $pr_app = ApplicationPreview::query()->create(['git_type' => 'bitbucket','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -134,7 +134,7 @@ class Bitbucket extends Controller]);$pr_app->generate_preview_fqdn_compose();} else {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['git_type' => 'bitbucket','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -165,7 +165,7 @@ class Bitbucket extends Controller}}if ($x_bitbucket_event === 'pullrequest:rejected' || $x_bitbucket_event === 'pullrequest:fulfilled') {- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if ($found) {$found->delete();$container_name = generateApplicationContainerName($application, $pull_request_id);diff --git a/app/Http/Controllers/Webhook/Gitea.php b/app/Http/Controllers/Webhook/Gitea.phpindex cc53f20344..8ddea3bc37 100644--- a/app/Http/Controllers/Webhook/Gitea.php+++ b/app/Http/Controllers/Webhook/Gitea.php@@ -25,7 +25,7 @@ class Gitea extends Controllerreturn Str::contains($file, $x_gitea_delivery);})->first();if ($gitea_delivery_found) {- return;+ return null;}$data = ['attributes' => $request->attributes->all(),@@ -40,7 +40,7 @@ class Gitea extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Gitea::manual_{$x_gitea_delivery}", $json);- return;+ return null;}$x_gitea_event = Str::lower($request->header('X-Gitea-Event'));$x_hub_signature_256 = Str::after($request->header('X-Hub-Signature-256'), 'sha256=');@@ -76,7 +76,7 @@ class Gitea extends Controllerif (! $branch) {return response('Nothing to do. No branch found in the request.');}- $applications = Application::where('git_repository', 'like', "%$full_name%");+ $applications = Application::query()->where('git_repository', 'like', "%$full_name%");if ($x_gitea_event === 'push') {$applications = $applications->where('git_branch', $branch)->get();if ($applications->isEmpty()) {@@ -155,10 +155,10 @@ class Gitea extends Controllerif ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {if ($application->isPRDeployable()) {$deployment_uuid = new Cuid2;- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found) {if ($application->build_pack === 'dockercompose') {- $pr_app = ApplicationPreview::create([+ $pr_app = ApplicationPreview::query()->create(['git_type' => 'gitea','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -167,7 +167,7 @@ class Gitea extends Controller]);$pr_app->generate_preview_fqdn_compose();} else {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['git_type' => 'gitea','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -198,7 +198,7 @@ class Gitea extends Controller}}if ($action === 'closed') {- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if ($found) {$found->delete();$container_name = generateApplicationContainerName($application, $pull_request_id);diff --git a/app/Http/Controllers/Webhook/Github.php b/app/Http/Controllers/Webhook/Github.phpindex ac1d4ded21..d3a1234801 100644--- a/app/Http/Controllers/Webhook/Github.php+++ b/app/Http/Controllers/Webhook/Github.php@@ -31,7 +31,7 @@ class Github extends Controllerreturn Str::contains($file, $x_github_delivery);})->first();if ($github_delivery_found) {- return;+ return null;}$data = ['attributes' => $request->attributes->all(),@@ -46,7 +46,7 @@ class Github extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::manual_{$x_github_delivery}", $json);- return;+ return null;}$x_github_event = Str::lower($request->header('X-GitHub-Event'));$x_hub_signature_256 = Str::after($request->header('X-Hub-Signature-256'), 'sha256=');@@ -82,7 +82,7 @@ class Github extends Controllerif (! $branch) {return response('Nothing to do. No branch found in the request.');}- $applications = Application::where('git_repository', 'like', "%$full_name%");+ $applications = Application::query()->where('git_repository', 'like', "%$full_name%");if ($x_github_event === 'push') {$applications = $applications->where('git_branch', $branch)->get();if ($applications->isEmpty()) {@@ -161,10 +161,10 @@ class Github extends Controllerif ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {if ($application->isPRDeployable()) {$deployment_uuid = new Cuid2;- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found) {if ($application->build_pack === 'dockercompose') {- $pr_app = ApplicationPreview::create([+ $pr_app = ApplicationPreview::query()->create(['git_type' => 'github','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -173,7 +173,7 @@ class Github extends Controller]);$pr_app->generate_preview_fqdn_compose();} else {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['git_type' => 'github','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -204,7 +204,7 @@ class Github extends Controller}}if ($action === 'closed') {- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if ($found) {$found->delete();$container_name = generateApplicationContainerName($application, $pull_request_id);@@ -245,7 +245,7 @@ class Github extends Controllerreturn Str::contains($file, $x_github_delivery);})->first();if ($github_delivery_found) {- return;+ return null;}$data = ['attributes' => $request->attributes->all(),@@ -260,7 +260,7 @@ class Github extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::normal_{$x_github_delivery}", $json);- return;+ return null;}$x_github_event = Str::lower($request->header('X-GitHub-Event'));$x_github_hook_installation_target_id = $request->header('X-GitHub-Hook-Installation-Target-Id');@@ -270,16 +270,14 @@ class Github extends Controller// Just pongreturn response('pong');}- $github_app = GithubApp::where('app_id', $x_github_hook_installation_target_id)->first();+ $github_app = GithubApp::query()->where('app_id', $x_github_hook_installation_target_id)->first();if (is_null($github_app)) {return response('Nothing to do. No GitHub App found.');}$webhook_secret = data_get($github_app, 'webhook_secret');$hmac = hash_hmac('sha256', $request->getContent(), $webhook_secret);- if (config('app.env') !== 'local') {- if (! hash_equals($x_hub_signature_256, $hmac)) {- return response('Invalid signature.');- }+ if (config('app.env') !== 'local' && ! hash_equals($x_hub_signature_256, $hmac)) {+ return response('Invalid signature.');}if ($x_github_event === 'installation' || $x_github_event === 'installation_repositories') {// Installation handled by setup redirect url. Repositories queried on-demand.@@ -312,7 +310,7 @@ class Github extends Controllerif (! $id || ! $branch) {return response('Nothing to do. No id or branch found.');}- $applications = Application::where('repository_project_id', $id)->whereRelation('source', 'is_public', false);+ $applications = Application::query()->where('repository_project_id', $id)->whereRelation('source', 'is_public', false);if ($x_github_event === 'push') {$applications = $applications->where('git_branch', $branch)->get();if ($applications->isEmpty()) {@@ -381,9 +379,9 @@ class Github extends Controllerif ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {if ($application->isPRDeployable()) {$deployment_uuid = new Cuid2;- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found) {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['git_type' => 'github','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -413,7 +411,7 @@ class Github extends Controller}}if ($action === 'closed' || $action === 'close') {- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if ($found) {$containers = getCurrentApplicationContainerStatus($application->destination->server, $application->id, $pull_request_id);if ($containers->isNotEmpty()) {@@ -453,7 +451,7 @@ class Github extends Controllertry {$code = $request->get('code');$state = $request->get('state');- $github_app = GithubApp::where('uuid', $state)->firstOrFail();+ $github_app = GithubApp::query()->where('uuid', $state)->firstOrFail();$api_url = data_get($github_app, 'api_url');$data = Http::withBody(null)->accept('application/vnd.github+json')->post("$api_url/app-manifests/$code/conversions")->throw()->json();$id = data_get($data, 'id');@@ -462,7 +460,7 @@ class Github extends Controller$client_secret = data_get($data, 'client_secret');$private_key = data_get($data, 'pem');$webhook_secret = data_get($data, 'webhook_secret');- $private_key = PrivateKey::create([+ $private_key = PrivateKey::query()->create(['name' => "github-app-{$slug}",'private_key' => $private_key,'team_id' => $github_app->team_id,@@ -501,11 +499,11 @@ class Github extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::install_{$installation_id}", $json);- return;+ return null;}$source = $request->get('source');$setup_action = $request->get('setup_action');- $github_app = GithubApp::where('uuid', $source)->firstOrFail();+ $github_app = GithubApp::query()->where('uuid', $source)->firstOrFail();if ($setup_action === 'install') {$github_app->installation_id = $installation_id;$github_app->save();diff --git a/app/Http/Controllers/Webhook/Gitlab.php b/app/Http/Controllers/Webhook/Gitlab.phpindex d8dcc0c3ba..e97614a6f2 100644--- a/app/Http/Controllers/Webhook/Gitlab.php+++ b/app/Http/Controllers/Webhook/Gitlab.php@@ -31,7 +31,7 @@ class Gitlab extends Controller$json = json_encode($data);Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Gitlab::manual_gitlab", $json);- return;+ return null;}$return_payloads = collect([]);@@ -93,7 +93,7 @@ class Gitlab extends Controllerreturn response($return_payloads);}}- $applications = Application::where('git_repository', 'like', "%$full_name%");+ $applications = Application::query()->where('git_repository', 'like', "%$full_name%");if ($x_gitlab_event === 'push') {$applications = $applications->where('git_branch', $branch)->get();if ($applications->isEmpty()) {@@ -181,10 +181,10 @@ class Gitlab extends Controllerif ($action === 'open' || $action === 'opened' || $action === 'synchronize' || $action === 'reopened' || $action === 'reopen' || $action === 'update') {if ($application->isPRDeployable()) {$deployment_uuid = new Cuid2;- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found) {if ($application->build_pack === 'dockercompose') {- $pr_app = ApplicationPreview::create([+ $pr_app = ApplicationPreview::query()->create(['git_type' => 'gitlab','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -193,7 +193,7 @@ class Gitlab extends Controller]);$pr_app->generate_preview_fqdn_compose();} else {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['git_type' => 'gitlab','application_id' => $application->id,'pull_request_id' => $pull_request_id,@@ -223,7 +223,7 @@ class Gitlab extends Controller]);}} elseif ($action === 'closed' || $action === 'close' || $action === 'merge') {- $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();if ($found) {$found->delete();$container_name = generateApplicationContainerName($application, $pull_request_id);diff --git a/app/Http/Controllers/Webhook/Stripe.php b/app/Http/Controllers/Webhook/Stripe.phpindex 83ba16699a..9e07ebaf9e 100644--- a/app/Http/Controllers/Webhook/Stripe.php+++ b/app/Http/Controllers/Webhook/Stripe.php@@ -40,7 +40,7 @@ class Stripe extends Controllerreturn response('Webhook received. Cool cool cool cool cool.', 200);}- $this->webhook = Webhook::create([+ $this->webhook = Webhook::query()->create(['type' => 'stripe','payload' => $request->getContent(),]);diff --git a/app/Http/Kernel.php b/app/Http/Kernel.phpindex a1ce20295b..5ba787bed9 100644--- a/app/Http/Kernel.php+++ b/app/Http/Kernel.php@@ -2,7 +2,35 @@namespace App\Http;+use App\Http\Middleware\ApiAbility;+use App\Http\Middleware\ApiSensitiveData;+use App\Http\Middleware\Authenticate;+use App\Http\Middleware\CheckForcePasswordReset;+use App\Http\Middleware\DecideWhatToDoWithUser;+use App\Http\Middleware\EncryptCookies;+use App\Http\Middleware\PreventRequestsDuringMaintenance;+use App\Http\Middleware\RedirectIfAuthenticated;+use App\Http\Middleware\TrimStrings;+use App\Http\Middleware\TrustProxies;+use App\Http\Middleware\ValidateSignature;+use App\Http\Middleware\VerifyCsrfToken;+use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;+use Illuminate\Auth\Middleware\Authorize;+use Illuminate\Auth\Middleware\EnsureEmailIsVerified;+use Illuminate\Auth\Middleware\RequirePassword;+use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;use Illuminate\Foundation\Http\Kernel as HttpKernel;+use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;+use Illuminate\Foundation\Http\Middleware\ValidatePostSize;+use Illuminate\Http\Middleware\HandleCors;+use Illuminate\Http\Middleware\SetCacheHeaders;+use Illuminate\Routing\Middleware\SubstituteBindings;+use Illuminate\Routing\Middleware\ThrottleRequests;+use Illuminate\Session\Middleware\AuthenticateSession;+use Illuminate\Session\Middleware\StartSession;+use Illuminate\View\Middleware\ShareErrorsFromSession;+use Laravel\Sanctum\Http\Middleware\CheckAbilities;+use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;class Kernel extends HttpKernel{@@ -15,12 +43,12 @@ class Kernel extends HttpKernel*/protected $middleware = [// \App\Http\Middleware\TrustHosts::class,- \App\Http\Middleware\TrustProxies::class,- \Illuminate\Http\Middleware\HandleCors::class,- \App\Http\Middleware\PreventRequestsDuringMaintenance::class,- \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,- \App\Http\Middleware\TrimStrings::class,- \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,+ TrustProxies::class,+ HandleCors::class,+ PreventRequestsDuringMaintenance::class,+ ValidatePostSize::class,+ TrimStrings::class,+ ConvertEmptyStringsToNull::class,];@@ -31,21 +59,21 @@ class Kernel extends HttpKernel*/protected $middlewareGroups = ['web' => [- \App\Http\Middleware\EncryptCookies::class,- \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,- \Illuminate\Session\Middleware\StartSession::class,- \Illuminate\View\Middleware\ShareErrorsFromSession::class,- \App\Http\Middleware\VerifyCsrfToken::class,- \Illuminate\Routing\Middleware\SubstituteBindings::class,- \App\Http\Middleware\CheckForcePasswordReset::class,- \App\Http\Middleware\DecideWhatToDoWithUser::class,+ EncryptCookies::class,+ AddQueuedCookiesToResponse::class,+ StartSession::class,+ ShareErrorsFromSession::class,+ VerifyCsrfToken::class,+ SubstituteBindings::class,+ CheckForcePasswordReset::class,+ DecideWhatToDoWithUser::class,],'api' => [// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,- \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',- \Illuminate\Routing\Middleware\SubstituteBindings::class,+ ThrottleRequests::class.':api',+ SubstituteBindings::class,],];@@ -57,19 +85,19 @@ class Kernel extends HttpKernel* @var array<string, class-string|string>*/protected $middlewareAliases = [- 'auth' => \App\Http\Middleware\Authenticate::class,- 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,- 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,- 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,- 'can' => \Illuminate\Auth\Middleware\Authorize::class,- 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,- 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,- 'signed' => \App\Http\Middleware\ValidateSignature::class,- 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,- 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,- 'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,- 'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,- 'api.ability' => \App\Http\Middleware\ApiAbility::class,- 'api.sensitive' => \App\Http\Middleware\ApiSensitiveData::class,+ 'auth' => Authenticate::class,+ 'auth.basic' => AuthenticateWithBasicAuth::class,+ 'auth.session' => AuthenticateSession::class,+ 'cache.headers' => SetCacheHeaders::class,+ 'can' => Authorize::class,+ 'guest' => RedirectIfAuthenticated::class,+ 'password.confirm' => RequirePassword::class,+ 'signed' => ValidateSignature::class,+ 'throttle' => ThrottleRequests::class,+ 'verified' => EnsureEmailIsVerified::class,+ 'abilities' => CheckAbilities::class,+ 'ability' => CheckForAnyAbility::class,+ 'api.ability' => ApiAbility::class,+ 'api.sensitive' => ApiSensitiveData::class,];}diff --git a/app/Http/Middleware/ApiAbility.php b/app/Http/Middleware/ApiAbility.phpindex 324eeebaa3..7ad16472ad 100644--- a/app/Http/Middleware/ApiAbility.php+++ b/app/Http/Middleware/ApiAbility.php@@ -2,6 +2,8 @@namespace App\Http\Middleware;+use Exception;+use Illuminate\Auth\AuthenticationException;use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;class ApiAbility extends CheckForAnyAbility@@ -14,11 +16,11 @@ class ApiAbility extends CheckForAnyAbility}return parent::handle($request, $next, ...$abilities);- } catch (\Illuminate\Auth\AuthenticationException $e) {+ } catch (AuthenticationException $e) {return response()->json(['message' => 'Unauthenticated.',], 401);- } catch (\Exception $e) {+ } catch (Exception $e) {return response()->json(['message' => 'Missing required permissions: '.implode(', ', $abilities),], 403);diff --git a/app/Http/Middleware/ApiAllowed.php b/app/Http/Middleware/ApiAllowed.phpindex dc6be5da3d..7c14b7921b 100644--- a/app/Http/Middleware/ApiAllowed.php+++ b/app/Http/Middleware/ApiAllowed.php@@ -18,12 +18,10 @@ class ApiAllowedreturn response()->json(['success' => true, 'message' => 'API is disabled.'], 403);}- if (! isDev()) {- if ($settings->allowed_ips) {- $allowedIps = explode(',', $settings->allowed_ips);- if (! in_array($request->ip(), $allowedIps)) {- return response()->json(['success' => true, 'message' => 'You are not allowed to access the API.'], 403);- }+ if (! isDev() && $settings->allowed_ips) {+ $allowedIps = explode(',', $settings->allowed_ips);+ if (! in_array($request->ip(), $allowedIps)) {+ return response()->json(['success' => true, 'message' => 'You are not allowed to access the API.'], 403);}}diff --git a/app/Http/Middleware/CheckForcePasswordReset.php b/app/Http/Middleware/CheckForcePasswordReset.phpindex 78b1f896c4..3e8fa9d02d 100644--- a/app/Http/Middleware/CheckForcePasswordReset.php+++ b/app/Http/Middleware/CheckForcePasswordReset.php@@ -11,7 +11,7 @@ class CheckForcePasswordReset/*** Handle an incoming request.*- * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next+ * @param Closure(Request):Response $next*/public function handle(Request $request, Closure $next): Response{diff --git a/app/Http/Middleware/DecideWhatToDoWithUser.php b/app/Http/Middleware/DecideWhatToDoWithUser.phpindex 8b1c550dfe..f9e979de74 100644--- a/app/Http/Middleware/DecideWhatToDoWithUser.php+++ b/app/Http/Middleware/DecideWhatToDoWithUser.php@@ -33,14 +33,12 @@ class DecideWhatToDoWithUserreturn redirect()->route('verify.email');}- if (! isSubscriptionActive() && ! isSubscriptionOnGracePeriod()) {- if (! in_array($request->path(), allowedPathsForUnsubscribedAccounts())) {- if (Str::startsWith($request->path(), 'invitations')) {- return $next($request);- }-- return redirect()->route('subscription.index');+ if (! isSubscriptionActive() && ! isSubscriptionOnGracePeriod() && ! in_array($request->path(), allowedPathsForUnsubscribedAccounts())) {+ if (Str::startsWith($request->path(), 'invitations')) {+ return $next($request);}++ return redirect()->route('subscription.index');}if (showBoarding() && ! in_array($request->path(), allowedPathsForBoardingAccounts())) {if (Str::startsWith($request->path(), 'invitations')) {diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.phpindex afc78c4e53..075438ee52 100644--- a/app/Http/Middleware/RedirectIfAuthenticated.php+++ b/app/Http/Middleware/RedirectIfAuthenticated.php@@ -13,11 +13,11 @@ class RedirectIfAuthenticated/*** Handle an incoming request.*- * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next+ * @param Closure(Request):Response $next*/public function handle(Request $request, Closure $next, string ...$guards): Response{- $guards = empty($guards) ? [null] : $guards;+ $guards = $guards === [] ? [null] : $guards;foreach ($guards as $guard) {if (Auth::guard($guard)->check()) {diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.phpindex addaf436ae..0aa812e12d 100644--- a/app/Jobs/ApplicationDeploymentJob.php+++ b/app/Jobs/ApplicationDeploymentJob.php@@ -88,7 +88,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueprivate bool $is_this_additional_server = false;- private ?ApplicationPreview $preview = null;+ private ?ApplicationPreview $applicationPreview = null;private ?string $git_type = null;@@ -174,8 +174,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->nixpacks_plan_json = collect([]);- $this->application_deployment_queue = ApplicationDeploymentQueue::find($application_deployment_queue_id);- $this->application = Application::find($this->application_deployment_queue->application_id);+ $this->application_deployment_queue = ApplicationDeploymentQueue::query()->find($application_deployment_queue_id);+ $this->application = Application::query()->find($this->application_deployment_queue->application_id);$this->build_pack = data_get($this->application, 'build_pack');$this->build_args = collect([]);@@ -199,7 +199,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueif ($source) {$this->source = $source->getMorphClass()::where('id', $this->application->source->id)->first();}- $this->server = Server::find($this->application_deployment_queue->server_id);+ $this->server = Server::query()->find($this->application_deployment_queue->server_id);$this->timeout = $this->server->settings->dynamic_timeout;$this->destination = $this->server->destinations()->where('id', $this->application_deployment_queue->destination_id)->first();$this->server = $this->mainServer = $this->destination->server;@@ -225,14 +225,12 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue// Set preview fqdnif ($this->pull_request_id !== 0) {- $this->preview = $this->application->generate_preview_fqdn($this->pull_request_id);+ $this->applicationPreview = $this->application->generate_preview_fqdn($this->pull_request_id);if ($this->application->is_github_based()) {- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::IN_PROGRESS);+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::IN_PROGRESS);}- if ($this->application->build_pack === 'dockerfile') {- if (data_get($this->application, 'dockerfile_location')) {- $this->dockerfile_location = $this->application->dockerfile_location;- }+ if ($this->application->build_pack === 'dockerfile' && data_get($this->application, 'dockerfile_location')) {+ $this->dockerfile_location = $this->application->dockerfile_location;}}}@@ -263,15 +261,15 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueif (count($allContainers) > 0) {$allContainers = $allContainers[0];$allContainers = collect($allContainers)->sort()->values();- foreach ($allContainers as $container) {- $containerName = data_get($container, 'Name');+ foreach ($allContainers as $allContainer) {+ $containerName = data_get($allContainer, 'Name');if ($containerName === 'coolify-proxy') {continue;}if (preg_match('/-(\d{12})/', $containerName)) {continue;}- $containerIp = data_get($container, 'IPv4Address');+ $containerIp = data_get($allContainer, 'IPv4Address');if ($containerName && $containerIp) {$containerIp = str($containerIp)->before('/');$ips->put($containerName, $containerIp->value());@@ -312,7 +310,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->decide_what_to_do();} catch (Exception $e) {if ($this->pull_request_id !== 0 && $this->application->is_github_based()) {- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::ERROR);+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::ERROR);}$this->fail($e);throw $e;@@ -340,7 +338,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->just_restart();return;- } elseif ($this->pull_request_id !== 0) {+ }+ if ($this->pull_request_id !== 0) {$this->deploy_pull_request();} elseif ($this->application->dockerfile) {$this->deploy_simple_dockerfile();@@ -364,10 +363,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueGetContainersStatus::dispatch($this->server);}$this->next(ApplicationDeploymentStatus::FINISHED->value);- if ($this->pull_request_id !== 0) {- if ($this->application->is_github_based()) {- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED);- }+ if ($this->pull_request_id !== 0 && $this->application->is_github_based()) {+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED);}$this->run_post_deployment_command();$this->application->isConfigurationChanged(true);@@ -470,7 +467,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$yaml = $composeFile = $this->application->docker_compose_raw;$this->save_environment_variables();} else {- $composeFile = $this->application->parse(pull_request_id: $this->pull_request_id, preview_id: data_get($this->preview, 'id'));+ $composeFile = $this->application->parse(pull_request_id: $this->pull_request_id, preview_id: data_get($this->applicationPreview, 'id'));$this->save_environment_variables();if (! is_null($this->env_filename)) {$services = collect(data_get($composeFile, 'services', []));@@ -553,34 +550,32 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue['command' => $command, 'hidden' => true],);}+ } elseif ($this->docker_compose_custom_start_command) {+ $this->write_deployment_configurations();+ $this->execute_remote_command(+ [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$this->docker_compose_custom_start_command}"), 'hidden' => true],+ );} else {- if ($this->docker_compose_custom_start_command) {+ $command = "{$this->coolify_variables} docker compose";+ if ($this->preserveRepository) {+ if ($this->env_filename) {+ $command .= " --env-file {$server_workdir}/{$this->env_filename}";+ }+ $command .= " --project-name {$this->application->uuid} --project-directory {$server_workdir} -f {$server_workdir}{$this->docker_compose_location} up -d";$this->write_deployment_configurations();+$this->execute_remote_command(- [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$this->docker_compose_custom_start_command}"), 'hidden' => true],+ ['command' => $command, 'hidden' => true],);} else {- $command = "{$this->coolify_variables} docker compose";- if ($this->preserveRepository) {- if ($this->env_filename) {- $command .= " --env-file {$server_workdir}/{$this->env_filename}";- }- $command .= " --project-name {$this->application->uuid} --project-directory {$server_workdir} -f {$server_workdir}{$this->docker_compose_location} up -d";- $this->write_deployment_configurations();-- $this->execute_remote_command(- ['command' => $command, 'hidden' => true],- );- } else {- if ($this->env_filename) {- $command .= " --env-file {$this->workdir}/{$this->env_filename}";- }- $command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up -d";- $this->execute_remote_command(- [executeInDocker($this->deployment_uuid, $command), 'hidden' => true],- );- $this->write_deployment_configurations();+ if ($this->env_filename) {+ $command .= " --env-file {$this->workdir}/{$this->env_filename}";}+ $command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up -d";+ $this->execute_remote_command(+ [executeInDocker($this->deployment_uuid, $command), 'hidden' => true],+ );+ $this->write_deployment_configurations();}}@@ -688,7 +683,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->server = $this->build_server;}}- if (isset($this->docker_compose_base64)) {+ if ($this->docker_compose_base64 !== null) {if ($this->use_build_server) {$this->server = $this->original_server;}@@ -773,9 +768,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue}} catch (Exception $e) {$this->application_deployment_queue->addLogEntry('Failed to push image to docker registry. Please check debug logs for more information.');- if ($forceFail) {- throw new RuntimeException($e->getMessage(), 69420);- }+ throw new RuntimeException($e->getMessage(), 69420, $e);}}@@ -846,9 +839,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->rolling_update();return true;- } else {- $this->application_deployment_queue->addLogEntry('Configuration changed. Rebuilding image.');}+ $this->application_deployment_queue->addLogEntry('Configuration changed. Rebuilding image.');} else {$this->application_deployment_queue->addLogEntry("Image not found ({$this->production_image_name}). Building new image.");}@@ -908,11 +900,11 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue}}if ($this->application->environment_variables_preview->where('key', 'COOLIFY_FQDN')->isEmpty()) {- $envs->push("COOLIFY_FQDN={$this->preview->fqdn}");- $envs->push("COOLIFY_DOMAIN_URL={$this->preview->fqdn}");+ $envs->push("COOLIFY_FQDN={$this->applicationPreview->fqdn}");+ $envs->push("COOLIFY_DOMAIN_URL={$this->applicationPreview->fqdn}");}if ($this->application->environment_variables_preview->where('key', 'COOLIFY_URL')->isEmpty()) {- $url = str($this->preview->fqdn)->replace('http://', '')->replace('https://', '');+ $url = str($this->applicationPreview->fqdn)->replace('http://', '')->replace('https://', '');$envs->push("COOLIFY_URL={$url}");$envs->push("COOLIFY_DOMAIN_FQDN={$url}");}@@ -927,24 +919,20 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueadd_coolify_default_environment_variables($this->application, $envs, $this->application->environment_variables_preview);- foreach ($sorted_environment_variables_preview as $env) {- $real_value = $env->real_value;- if ($env->version === '4.0.0-beta.239') {- $real_value = $env->real_value;+ foreach ($sorted_environment_variables_preview as $sorted_environment_variable_preview) {+ $real_value = $sorted_environment_variable_preview->real_value;+ if ($sorted_environment_variable_preview->version === '4.0.0-beta.239') {+ $real_value = $sorted_environment_variable_preview->real_value;+ } elseif ($sorted_environment_variable_preview->is_literal || $sorted_environment_variable_preview->is_multiline) {+ $real_value = '\''.$real_value.'\'';} else {- if ($env->is_literal || $env->is_multiline) {- $real_value = '\''.$real_value.'\'';- } else {- $real_value = escapeEnvVariables($env->real_value);- }+ $real_value = escapeEnvVariables($sorted_environment_variable_preview->real_value);}- $envs->push($env->key.'='.$real_value);+ $envs->push($sorted_environment_variable_preview->key.'='.$real_value);}// Add PORT if not exists, use the first port as default- if ($this->build_pack !== 'dockercompose') {- if ($this->application->environment_variables_preview->where('key', 'PORT')->isEmpty()) {- $envs->push("PORT={$ports[0]}");- }+ if ($this->build_pack !== 'dockercompose' && $this->application->environment_variables_preview->where('key', 'PORT')->isEmpty()) {+ $envs->push("PORT={$ports[0]}");}// Add HOST if not existsif ($this->application->environment_variables_preview->where('key', 'HOST')->isEmpty()) {@@ -986,24 +974,20 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueadd_coolify_default_environment_variables($this->application, $envs, $this->application->environment_variables);- foreach ($sorted_environment_variables as $env) {- $real_value = $env->real_value;- if ($env->version === '4.0.0-beta.239') {- $real_value = $env->real_value;+ foreach ($sorted_environment_variables as $sorted_environment_variable) {+ $real_value = $sorted_environment_variable->real_value;+ if ($sorted_environment_variable->version === '4.0.0-beta.239') {+ $real_value = $sorted_environment_variable->real_value;+ } elseif ($sorted_environment_variable->is_literal || $sorted_environment_variable->is_multiline) {+ $real_value = '\''.$real_value.'\'';} else {- if ($env->is_literal || $env->is_multiline) {- $real_value = '\''.$real_value.'\'';- } else {- $real_value = escapeEnvVariables($env->real_value);- }+ $real_value = escapeEnvVariables($sorted_environment_variable->real_value);}- $envs->push($env->key.'='.$real_value);+ $envs->push($sorted_environment_variable->key.'='.$real_value);}// Add PORT if not exists, use the first port as default- if ($this->build_pack !== 'dockercompose') {- if ($this->application->environment_variables->where('key', 'PORT')->isEmpty()) {- $envs->push("PORT={$ports[0]}");- }+ if ($this->build_pack !== 'dockercompose' && $this->application->environment_variables->where('key', 'PORT')->isEmpty()) {+ $envs->push("PORT={$ports[0]}");}// Add HOST if not existsif ($this->application->environment_variables->where('key', 'HOST')->isEmpty()) {@@ -1067,11 +1051,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueprivate function elixir_finetunes(){- if ($this->pull_request_id === 0) {- $envType = 'environment_variables';- } else {- $envType = 'environment_variables_preview';- }+ $envType = $this->pull_request_id === 0 ? 'environment_variables' : 'environment_variables_preview';$mix_env = $this->application->{$envType}->where('key', 'MIX_ENV')->first();if ($mix_env) {if ($mix_env->is_build_time === false) {@@ -1106,11 +1086,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueprivate function laravel_finetunes(){- if ($this->pull_request_id === 0) {- $envType = 'environment_variables';- } else {- $envType = 'environment_variables_preview';- }+ $envType = $this->pull_request_id === 0 ? 'environment_variables' : 'environment_variables_preview';$nixpacks_php_fallback_path = $this->application->{$envType}->where('key', 'NIXPACKS_PHP_FALLBACK_PATH')->first();$nixpacks_php_root_dir = $this->application->{$envType}->where('key', 'NIXPACKS_PHP_ROOT_DIR')->first();@@ -1194,7 +1170,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$this->application_deployment_queue->addLogEntry('Custom healthcheck found, skipping default healthcheck.');}// ray('New container name: ', $this->container_name);- if ($this->container_name) {+ if ($this->container_name !== '' && $this->container_name !== '0') {$counter = 1;$this->application_deployment_queue->addLogEntry('Waiting for healthcheck to pass on the new container.');if ($this->full_healthcheck_url) {@@ -1344,12 +1320,10 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueuethrow new RuntimeException('Docker config file (~/.docker/config.json) not found on the build server. Please run "docker login" to login to the docker registry on the server.');}$runCommand = "docker run -d --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";+ } elseif ($this->dockerConfigFileExists === 'OK') {+ $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";} else {- if ($this->dockerConfigFileExists === 'OK') {- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";- } else {- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";- }+ $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";}$this->application_deployment_queue->addLogEntry("Preparing container with helper image: $helperImage.");$this->execute_remote_command(@@ -1389,7 +1363,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueuereturn;}foreach ($destination_ids as $destination_id) {- $destination = StandaloneDocker::find($destination_id);+ $destination = StandaloneDocker::query()->find($destination_id);$server = $destination->server;if ($server->team_id !== $this->mainServer->team_id) {$this->application_deployment_queue->addLogEntry("Skipping deployment to {$server->name}. Not in the same team?!");@@ -1417,17 +1391,13 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueprivate function set_coolify_variables(){$this->coolify_variables = "SOURCE_COMMIT={$this->commit} ";- if ($this->pull_request_id === 0) {- $fqdn = $this->application->fqdn;- } else {- $fqdn = $this->preview->fqdn;- }+ $fqdn = $this->pull_request_id === 0 ? $this->application->fqdn : $this->applicationPreview->fqdn;if (isset($fqdn)) {$this->coolify_variables .= "COOLIFY_FQDN={$fqdn} ";$url = str($fqdn)->replace('http://', '')->replace('https://', '');$this->coolify_variables .= "COOLIFY_URL={$url} ";}- if (isset($this->application->git_branch)) {+ if (property_exists($this->application, 'git_branch') && $this->application->git_branch !== null) {$this->coolify_variables .= "COOLIFY_BRANCH={$this->application->git_branch} ";}}@@ -1598,9 +1568,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueueif ($this->application->install_command) {$nixpacks_command .= " --install-cmd \"{$this->application->install_command}\"";}- $nixpacks_command .= " {$this->workdir}";- return $nixpacks_command;+ return $nixpacks_command." {$this->workdir}";}private function generate_nixpacks_env_variables()@@ -1666,7 +1635,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue});if ($found_caddy_labels->count() === 0) {if ($this->pull_request_id !== 0) {- $domains = str(data_get($this->preview, 'fqdn'))->explode(',');+ $domains = str(data_get($this->applicationPreview, 'fqdn'))->explode(',');} else {$domains = str(data_get($this->application, 'fqdn'))->explode(',');}@@ -1682,13 +1651,11 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue}$this->application->custom_labels = base64_encode($labels->implode("\n"));$this->application->save();- } else {- if (! $this->application->settings->is_container_label_readonly_enabled) {- $labels = collect(generateLabelsApplication($this->application, $this->preview));- }+ } elseif (! $this->application->settings->is_container_label_readonly_enabled) {+ $labels = collect(generateLabelsApplication($this->application, $this->applicationPreview));}if ($this->pull_request_id !== 0) {- $labels = collect(generateLabelsApplication($this->application, $this->preview));+ $labels = collect(generateLabelsApplication($this->application, $this->applicationPreview));}if ($this->application->settings->is_container_label_escape_enabled) {$labels = $labels->map(function ($value, $key) {@@ -1874,23 +1841,21 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue$docker_compose['services'][$this->application->uuid] = array_merge_recursive($docker_compose['services'][$this->application->uuid], $custom_compose);}}- } else {- if (count($custom_compose) > 0) {- $ipv4 = data_get($custom_compose, 'ip.0');- $ipv6 = data_get($custom_compose, 'ip6.0');- data_forget($custom_compose, 'ip');- data_forget($custom_compose, 'ip6');- if ($ipv4 || $ipv6) {- data_forget($docker_compose['services'][$this->container_name], 'networks');- }- if ($ipv4) {- $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv4_address'] = $ipv4;- }- if ($ipv6) {- $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv6_address'] = $ipv6;- }- $docker_compose['services'][$this->container_name] = array_merge_recursive($docker_compose['services'][$this->container_name], $custom_compose);+ } elseif (count($custom_compose) > 0) {+ $ipv4 = data_get($custom_compose, 'ip.0');+ $ipv6 = data_get($custom_compose, 'ip6.0');+ data_forget($custom_compose, 'ip');+ data_forget($custom_compose, 'ip6');+ if ($ipv4 || $ipv6) {+ data_forget($docker_compose['services'][$this->container_name], 'networks');+ }+ if ($ipv4) {+ $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv4_address'] = $ipv4;}+ if ($ipv6) {+ $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv6_address'] = $ipv6;+ }+ $docker_compose['services'][$this->container_name] = array_merge_recursive($docker_compose['services'][$this->container_name], $custom_compose);}}@@ -2105,86 +2070,82 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");'hidden' => true,]);- } else {+ } elseif ($this->application->dockerfile) {// Pure Dockerfile based deployment- if ($this->application->dockerfile) {- if ($this->force_rebuild) {- $build_command = "docker build --no-cache --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- } else {- $build_command = "docker build --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- }+ if ($this->force_rebuild) {+ $build_command = "docker build --no-cache --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";+ } else {+ $build_command = "docker build --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";+ }+ $base64_build_command = base64_encode($build_command);+ $this->execute_remote_command(+ [+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),+ 'hidden' => true,+ ]+ );+ } elseif ($this->application->build_pack === 'nixpacks') {+ $this->nixpacks_plan = base64_encode($this->nixpacks_plan);+ $this->execute_remote_command([executeInDocker($this->deployment_uuid, "echo '{$this->nixpacks_plan}' | base64 -d | tee /artifacts/thegameplan.json > /dev/null"), 'hidden' => true]);+ if ($this->force_rebuild) {+ $this->execute_remote_command([+ executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --no-cache --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),+ 'hidden' => true,+ ]);+ $build_command = "docker build --no-cache {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";+ } else {+ $this->execute_remote_command([+ executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --cache-key '{$this->application->uuid}' --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),+ 'hidden' => true,+ ]);+ $build_command = "docker build {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";+ }+ $base64_build_command = base64_encode($build_command);+ $this->execute_remote_command(+ [+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),+ 'hidden' => true,+ ]+ );+ $this->execute_remote_command([executeInDocker($this->deployment_uuid, 'rm /artifacts/thegameplan.json'), 'hidden' => true]);+ } else {+ if ($this->force_rebuild) {+ $build_command = "docker build --no-cache {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";$base64_build_command = base64_encode($build_command);- $this->execute_remote_command(- [- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),- 'hidden' => true,- ]- );} else {- if ($this->application->build_pack === 'nixpacks') {- $this->nixpacks_plan = base64_encode($this->nixpacks_plan);- $this->execute_remote_command([executeInDocker($this->deployment_uuid, "echo '{$this->nixpacks_plan}' | base64 -d | tee /artifacts/thegameplan.json > /dev/null"), 'hidden' => true]);- if ($this->force_rebuild) {- $this->execute_remote_command([- executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --no-cache --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),- 'hidden' => true,- ]);- $build_command = "docker build --no-cache {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- } else {- $this->execute_remote_command([- executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --cache-key '{$this->application->uuid}' --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),- 'hidden' => true,- ]);- $build_command = "docker build {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- }- $base64_build_command = base64_encode($build_command);- $this->execute_remote_command(- [- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),- 'hidden' => true,- ]- );- $this->execute_remote_command([executeInDocker($this->deployment_uuid, 'rm /artifacts/thegameplan.json'), 'hidden' => true]);- } else {- if ($this->force_rebuild) {- $build_command = "docker build --no-cache {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- $base64_build_command = base64_encode($build_command);- } else {- $build_command = "docker build {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";- $base64_build_command = base64_encode($build_command);- }- $this->execute_remote_command(- [- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),- 'hidden' => true,- ],- [- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),- 'hidden' => true,- ]- );- }+ $build_command = "docker build {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";+ $base64_build_command = base64_encode($build_command);}+ $this->execute_remote_command(+ [+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),+ 'hidden' => true,+ ],+ [+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),+ 'hidden' => true,+ ]+ );}$this->application_deployment_queue->addLogEntry('Building docker image completed.');}@@ -2214,7 +2175,7 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");["docker kill $containerName", 'hidden' => true, 'ignore_errors' => true]);}- } catch (\Exception $error) {+ } catch (Exception $error) {$this->application_deployment_queue->addLogEntry("Error stopping container $containerName: ".$error->getMessage(), 'stderr');}@@ -2267,16 +2228,14 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");[executeInDocker($this->deployment_uuid, "docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} pull"), 'hidden' => true],[executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} up --build -d"), 'hidden' => true],);+ } elseif ($this->use_build_server) {+ $this->execute_remote_command(+ ["{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->configuration_dir} -f {$this->configuration_dir}{$this->docker_compose_location} up --build -d", 'hidden' => true],+ );} else {- if ($this->use_build_server) {- $this->execute_remote_command(- ["{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->configuration_dir} -f {$this->configuration_dir}{$this->docker_compose_location} up --build -d", 'hidden' => true],- );- } else {- $this->execute_remote_command(- [executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up --build -d"), 'hidden' => true],- );- }+ $this->execute_remote_command(+ [executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up --build -d"), 'hidden' => true],+ );}$this->application_deployment_queue->addLogEntry('New container started.');}@@ -2398,7 +2357,7 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");]);}if ($this->application_deployment_queue->status === ApplicationDeploymentStatus::FAILED->value) {- $this->application->environment->project->team?->notify(new DeploymentFailed($this->application, $this->deployment_uuid, $this->preview));+ $this->application->environment->project->team?->notify(new DeploymentFailed($this->application, $this->deployment_uuid, $this->applicationPreview));return;}@@ -2406,20 +2365,20 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");if (! $this->only_this_server) {$this->deploy_to_additional_destinations();}- $this->application->environment->project->team?->notify(new DeploymentSuccess($this->application, $this->deployment_uuid, $this->preview));+ $this->application->environment->project->team?->notify(new DeploymentSuccess($this->application, $this->deployment_uuid, $this->applicationPreview));}}- public function failed(Throwable $exception): void+ public function failed(Throwable $throwable): void{$this->next(ApplicationDeploymentStatus::FAILED->value);$this->application_deployment_queue->addLogEntry('Oops something is not okay, are you okay? 😢', 'stderr');- if (str($exception->getMessage())->isNotEmpty()) {- $this->application_deployment_queue->addLogEntry($exception->getMessage(), 'stderr');+ if (str($throwable->getMessage())->isNotEmpty()) {+ $this->application_deployment_queue->addLogEntry($throwable->getMessage(), 'stderr');}if ($this->application->build_pack !== 'dockercompose') {- $code = $exception->getCode();+ $code = $throwable->getCode();if ($code !== 69420) {// 69420 means failed to push the image to the registry, so we don't need to remove the new version as it is the currently running oneif ($this->application->settings->is_consistent_container_name_enabled || str($this->application->settings->custom_internal_name)->isNotEmpty()) {diff --git a/app/Jobs/ApplicationPullRequestUpdateJob.php b/app/Jobs/ApplicationPullRequestUpdateJob.phpindex ef8e6efb6e..195f997b61 100755--- a/app/Jobs/ApplicationPullRequestUpdateJob.php+++ b/app/Jobs/ApplicationPullRequestUpdateJob.php@@ -11,6 +11,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueue{@@ -22,8 +23,8 @@ class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueuepublic function __construct(public Application $application,- public ApplicationPreview $preview,- public ProcessStatus $status,+ public ApplicationPreview $applicationPreview,+ public ProcessStatus $processStatus,public ?string $deployment_uuid = null) {$this->onQueue('high');@@ -33,39 +34,42 @@ class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueue{try {if ($this->application->is_public_repository()) {- return;+ return null;}- if ($this->status === ProcessStatus::CLOSED) {+ if ($this->processStatus === ProcessStatus::CLOSED) {$this->delete_comment();- return;- } elseif ($this->status === ProcessStatus::IN_PROGRESS) {+ return null;+ }+ if ($this->processStatus === ProcessStatus::IN_PROGRESS) {$this->body = "The preview deployment is in progress. 🟡\n\n";- } elseif ($this->status === ProcessStatus::FINISHED) {+ } elseif ($this->processStatus === ProcessStatus::FINISHED) {$this->body = "The preview deployment is ready. 🟢\n\n";- if ($this->preview->fqdn) {- $this->body .= "[Open Preview]({$this->preview->fqdn}) | ";+ if ($this->applicationPreview->fqdn) {+ $this->body .= "[Open Preview]({$this->applicationPreview->fqdn}) | ";}- } elseif ($this->status === ProcessStatus::ERROR) {+ } elseif ($this->processStatus === ProcessStatus::ERROR) {$this->body = "The preview deployment failed. 🔴\n\n";}$this->build_logs_url = base_url()."/project/{$this->application->environment->project->uuid}/{$this->application->environment->name}/application/{$this->application->uuid}/deployment/{$this->deployment_uuid}";$this->body .= '[Open Build Logs]('.$this->build_logs_url.")\n\n\n";$this->body .= 'Last updated at: '.now()->toDateTimeString().' CET';- if ($this->preview->pull_request_issue_comment_id) {+ if ($this->applicationPreview->pull_request_issue_comment_id) {$this->update_comment();} else {$this->create_comment();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return $e;}++ return null;}private function update_comment(){- ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'patch', data: [+ ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->applicationPreview->pull_request_issue_comment_id}", method: 'patch', data: ['body' => $this->body,], throwError: false);if (data_get($data, 'message') === 'Not Found') {@@ -75,15 +79,15 @@ class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueueprivate function create_comment(){- ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/{$this->preview->pull_request_id}/comments", method: 'post', data: [+ ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/{$this->applicationPreview->pull_request_id}/comments", method: 'post', data: ['body' => $this->body,]);- $this->preview->pull_request_issue_comment_id = $data['id'];- $this->preview->save();+ $this->applicationPreview->pull_request_issue_comment_id = $data['id'];+ $this->applicationPreview->save();}private function delete_comment(){- githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'delete');+ githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->applicationPreview->pull_request_issue_comment_id}", method: 'delete');}}diff --git a/app/Jobs/CheckAndStartSentinelJob.php b/app/Jobs/CheckAndStartSentinelJob.phpindex 788db89eaa..37d669d234 100644--- a/app/Jobs/CheckAndStartSentinelJob.php+++ b/app/Jobs/CheckAndStartSentinelJob.php@@ -34,19 +34,18 @@ class CheckAndStartSentinelJob implements ShouldBeEncrypted, ShouldQueue}// If sentinel is running, check if it needs an update$runningVersion = instant_remote_process(['docker exec coolify-sentinel sh -c "curl http://127.0.0.1:8888/api/version"'], $this->server, false);- if (empty($runningVersion)) {+ if ($runningVersion === null || $runningVersion === '' || $runningVersion === '0') {$runningVersion = '0.0.0';}if ($latestVersion === '0.0.0' && $runningVersion === '0.0.0') {StartSentinel::run(server: $this->server, restart: true, latestVersion: 'latest');return;- } else {- if (version_compare($runningVersion, $latestVersion, '<')) {- StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);+ }+ if (version_compare($runningVersion, $latestVersion, '<')) {+ StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);- return;- }+ return;}}}diff --git a/app/Jobs/CheckForUpdatesJob.php b/app/Jobs/CheckForUpdatesJob.phpindex 1d3a345e15..2995dad02f 100644--- a/app/Jobs/CheckForUpdatesJob.php+++ b/app/Jobs/CheckForUpdatesJob.php@@ -10,6 +10,7 @@ use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;+use Throwable;class CheckForUpdatesJob implements ShouldBeEncrypted, ShouldQueue{@@ -37,7 +38,7 @@ class CheckForUpdatesJob implements ShouldBeEncrypted, ShouldQueue$settings->update(['new_version_available' => false]);}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {// Consider implementing a notification to administrators}}diff --git a/app/Jobs/CheckHelperImageJob.php b/app/Jobs/CheckHelperImageJob.phpindex 6abb8a1502..5269e2d224 100644--- a/app/Jobs/CheckHelperImageJob.php+++ b/app/Jobs/CheckHelperImageJob.php@@ -9,6 +9,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Http;+use Throwable;class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueue{@@ -16,8 +17,6 @@ class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueuepublic $timeout = 1000;- public function __construct() {}-public function handle(): void{try {@@ -31,7 +30,7 @@ class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueue$settings->update(['helper_version' => $latest_version]);}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {send_internal_notification('CheckHelperImageJob failed with: '.$e->getMessage());throw $e;}diff --git a/app/Jobs/CleanupHelperContainersJob.php b/app/Jobs/CleanupHelperContainersJob.phpindex f185ab7812..f3a081d2b3 100644--- a/app/Jobs/CleanupHelperContainersJob.php+++ b/app/Jobs/CleanupHelperContainersJob.php@@ -10,6 +10,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class CleanupHelperContainersJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue{@@ -27,7 +28,7 @@ class CleanupHelperContainersJob implements ShouldBeEncrypted, ShouldBeUnique, Sinstant_remote_process(['docker container rm -f '.$containerId], $this->server, false);}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {send_internal_notification('CleanupHelperContainersJob failed with error: '.$e->getMessage());}}diff --git a/app/Jobs/CleanupInstanceStuffsJob.php b/app/Jobs/CleanupInstanceStuffsJob.phpindex 84f14ed02a..35db942947 100644--- a/app/Jobs/CleanupInstanceStuffsJob.php+++ b/app/Jobs/CleanupInstanceStuffsJob.php@@ -12,13 +12,12 @@ use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Log;+use Throwable;class CleanupInstanceStuffsJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue{use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;- public function __construct() {}-public function middleware(): array{return [(new WithoutOverlapping('cleanup-instance-stuffs'))->dontRelease()];@@ -28,7 +27,7 @@ class CleanupInstanceStuffsJob implements ShouldBeEncrypted, ShouldBeUnique, Sho{try {$this->cleanupInvitationLink();- } catch (\Throwable $e) {+ } catch (Throwable $e) {Log::error('CleanupInstanceStuffsJob failed with error: '.$e->getMessage());}}diff --git a/app/Jobs/CleanupStaleMultiplexedConnections.php b/app/Jobs/CleanupStaleMultiplexedConnections.phpindex 6d49bee4b0..126adf37ed 100644--- a/app/Jobs/CleanupStaleMultiplexedConnections.php+++ b/app/Jobs/CleanupStaleMultiplexedConnections.php@@ -28,7 +28,7 @@ class CleanupStaleMultiplexedConnections implements ShouldQueueforeach ($muxFiles as $muxFile) {$serverUuid = $this->extractServerUuidFromMuxFile($muxFile);- $server = Server::where('uuid', $serverUuid)->first();+ $server = Server::query()->where('uuid', $serverUuid)->first();if (! $server) {$this->removeMultiplexFile($muxFile);@@ -57,7 +57,7 @@ class CleanupStaleMultiplexedConnections implements ShouldQueueprivate function cleanupNonExistentServerConnections(){$muxFiles = Storage::disk('ssh-mux')->files();- $existingServerUuids = Server::pluck('uuid')->toArray();+ $existingServerUuids = Server::query()->pluck('uuid')->toArray();foreach ($muxFiles as $muxFile) {$serverUuid = $this->extractServerUuidFromMuxFile($muxFile);diff --git a/app/Jobs/CoolifyTask.php b/app/Jobs/CoolifyTask.phpindex 49a5ba8dd2..ba63ffdc0a 100755--- a/app/Jobs/CoolifyTask.php+++ b/app/Jobs/CoolifyTask.php@@ -33,13 +33,13 @@ class CoolifyTask implements ShouldBeEncrypted, ShouldQueue*/public function handle(): void{- $remote_process = resolve(RunRemoteProcess::class, [+ $runRemoteProcess = resolve(RunRemoteProcess::class, ['activity' => $this->activity,'ignore_errors' => $this->ignore_errors,'call_event_on_finish' => $this->call_event_on_finish,'call_event_data' => $this->call_event_data,]);- $remote_process();+ $runRemoteProcess();}}diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.phpindex 6730dceb72..5fc602c6e9 100644--- a/app/Jobs/DatabaseBackupJob.php+++ b/app/Jobs/DatabaseBackupJob.php@@ -16,6 +16,7 @@ use App\Models\Team;use App\Notifications\Database\BackupFailed;use App\Notifications\Database\BackupSuccess;use Carbon\Carbon;+use Exception;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldBeEncrypted;use Illuminate\Contracts\Queue\ShouldQueue;@@ -23,6 +24,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Str;+use Throwable;class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue{@@ -56,7 +58,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueuepublic ?S3Storage $s3 = null;- public function __construct(public ScheduledDatabaseBackup $backup)+ public function __construct(public ScheduledDatabaseBackup $scheduledDatabaseBackup){$this->onQueue('high');}@@ -66,26 +68,26 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueuetry {$databasesToBackup = null;- $this->team = Team::find($this->backup->team_id);+ $this->team = Team::query()->find($this->scheduledDatabaseBackup->team_id);if (! $this->team) {- $this->backup->delete();+ $this->scheduledDatabaseBackup->delete();return;}- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {- $this->database = data_get($this->backup, 'database');+ if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {+ $this->database = data_get($this->scheduledDatabaseBackup, 'database');$this->server = $this->database->service->server;- $this->s3 = $this->backup->s3;+ $this->s3 = $this->scheduledDatabaseBackup->s3;} else {- $this->database = data_get($this->backup, 'database');+ $this->database = data_get($this->scheduledDatabaseBackup, 'database');$this->server = $this->database->destination->server;- $this->s3 = $this->backup->s3;+ $this->s3 = $this->scheduledDatabaseBackup->s3;}if (is_null($this->server)) {- throw new \Exception('Server not found?!');+ throw new Exception('Server not found?!');}if (is_null($this->database)) {- throw new \Exception('Database not found?!');+ throw new Exception('Database not found?!');}BackupCreated::dispatch($this->team->id);@@ -94,7 +96,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif (! $status->startsWith('running') && $this->database->id !== 0) {return;}- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {+ if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {$databaseType = $this->database->databaseType();$serviceUuid = $this->database->service->uuid;$serviceName = str($this->database->service->name)->slug();@@ -108,21 +110,13 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue$user = $envs->filter(function ($env) {return str($env)->startsWith('POSTGRES_USER=');})->first();- if ($user) {- $this->database->postgres_user = str($user)->after('POSTGRES_USER=')->value();- } else {- $this->database->postgres_user = 'postgres';- }+ $this->database->postgres_user = $user ? str($user)->after('POSTGRES_USER=')->value() : 'postgres';$db = $envs->filter(function ($env) {return str($env)->startsWith('POSTGRES_DB=');})->first();- if ($db) {- $databasesToBackup = str($db)->after('POSTGRES_DB=')->value();- } else {- $databasesToBackup = $this->database->postgres_user;- }+ $databasesToBackup = $db ? str($db)->after('POSTGRES_DB=')->value() : $this->database->postgres_user;$this->postgres_password = $envs->filter(function ($env) {return str($env)->startsWith('POSTGRES_PASSWORD=');})->first();@@ -150,7 +144,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($db) {$databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value();} else {- throw new \Exception('MYSQL_DATABASE not found');+ throw new Exception('MYSQL_DATABASE not found');}} elseif (str($databaseType)->contains('mariadb')) {$this->container_name = "{$this->database->name}-$serviceUuid";@@ -186,7 +180,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($db) {$databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value();} else {- throw new \Exception('MARIADB_DATABASE or MYSQL_DATABASE not found');+ throw new Exception('MARIADB_DATABASE or MYSQL_DATABASE not found');}}}@@ -195,7 +189,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue$this->container_name = $this->database->uuid;$this->directory_name = $databaseName.'-'.$this->container_name;$databaseType = $this->database->type();- $databasesToBackup = data_get($this->backup, 'databases_to_backup');+ $databasesToBackup = data_get($this->scheduledDatabaseBackup, 'databases_to_backup');}if (blank($databasesToBackup)) {if (str($databaseType)->contains('postgres')) {@@ -209,26 +203,24 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue} else {return;}+ } elseif (str($databaseType)->contains('postgres')) {+ // Format: db1,db2,db3+ $databasesToBackup = explode(',', $databasesToBackup);+ $databasesToBackup = array_map('trim', $databasesToBackup);+ } elseif (str($databaseType)->contains('mongodb')) {+ // Format: db1:collection1,collection2|db2:collection3,collection4+ $databasesToBackup = explode('|', $databasesToBackup);+ $databasesToBackup = array_map('trim', $databasesToBackup);+ } elseif (str($databaseType)->contains('mysql')) {+ // Format: db1,db2,db3+ $databasesToBackup = explode(',', $databasesToBackup);+ $databasesToBackup = array_map('trim', $databasesToBackup);+ } elseif (str($databaseType)->contains('mariadb')) {+ // Format: db1,db2,db3+ $databasesToBackup = explode(',', $databasesToBackup);+ $databasesToBackup = array_map('trim', $databasesToBackup);} else {- if (str($databaseType)->contains('postgres')) {- // Format: db1,db2,db3- $databasesToBackup = explode(',', $databasesToBackup);- $databasesToBackup = array_map('trim', $databasesToBackup);- } elseif (str($databaseType)->contains('mongodb')) {- // Format: db1:collection1,collection2|db2:collection3,collection4- $databasesToBackup = explode('|', $databasesToBackup);- $databasesToBackup = array_map('trim', $databasesToBackup);- } elseif (str($databaseType)->contains('mysql')) {- // Format: db1,db2,db3- $databasesToBackup = explode(',', $databasesToBackup);- $databasesToBackup = array_map('trim', $databasesToBackup);- } elseif (str($databaseType)->contains('mariadb')) {- // Format: db1,db2,db3- $databasesToBackup = explode(',', $databasesToBackup);- $databasesToBackup = array_map('trim', $databasesToBackup);- } else {- return;- }+ return;}$this->backup_dir = backup_dir().'/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name;if ($this->database->name === 'coolify-db') {@@ -237,82 +229,80 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue$ip = Str::slug($this->server->ip);$this->backup_dir = backup_dir().'/coolify'."/coolify-db-$ip";}- foreach ($databasesToBackup as $database) {+ foreach ($databasesToBackup as $databaseToBackup) {$size = 0;try {if (str($databaseType)->contains('postgres')) {- $this->backup_file = "/pg-dump-$database-".Carbon::now()->timestamp.'.dmp';- if ($this->backup->dump_all) {+ $this->backup_file = "/pg-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';+ if ($this->scheduledDatabaseBackup->dump_all) {$this->backup_file = '/pg-dump-all-'.Carbon::now()->timestamp.'.gz';}$this->backup_location = $this->backup_dir.$this->backup_file;- $this->backup_log = ScheduledDatabaseBackupExecution::create([- 'database_name' => $database,+ $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([+ 'database_name' => $databaseToBackup,'filename' => $this->backup_location,- 'scheduled_database_backup_id' => $this->backup->id,+ 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,]);- $this->backup_standalone_postgresql($database);+ $this->backup_standalone_postgresql($databaseToBackup);} elseif (str($databaseType)->contains('mongodb')) {- if ($database === '*') {- $database = 'all';+ if ($databaseToBackup === '*') {+ $databaseToBackup = 'all';$databaseName = 'all';+ } elseif (str($databaseToBackup)->contains(':')) {+ $databaseName = str($databaseToBackup)->before(':');} else {- if (str($database)->contains(':')) {- $databaseName = str($database)->before(':');- } else {- $databaseName = $database;- }+ $databaseName = $databaseToBackup;}$this->backup_file = "/mongo-dump-$databaseName-".Carbon::now()->timestamp.'.tar.gz';$this->backup_location = $this->backup_dir.$this->backup_file;- $this->backup_log = ScheduledDatabaseBackupExecution::create([+ $this->backup_log = ScheduledDatabaseBackupExecution::query()->create(['database_name' => $databaseName,'filename' => $this->backup_location,- 'scheduled_database_backup_id' => $this->backup->id,+ 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,]);- $this->backup_standalone_mongodb($database);+ $this->backup_standalone_mongodb($databaseToBackup);} elseif (str($databaseType)->contains('mysql')) {- $this->backup_file = "/mysql-dump-$database-".Carbon::now()->timestamp.'.dmp';- if ($this->backup->dump_all) {+ $this->backup_file = "/mysql-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';+ if ($this->scheduledDatabaseBackup->dump_all) {$this->backup_file = '/mysql-dump-all-'.Carbon::now()->timestamp.'.gz';}$this->backup_location = $this->backup_dir.$this->backup_file;- $this->backup_log = ScheduledDatabaseBackupExecution::create([- 'database_name' => $database,+ $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([+ 'database_name' => $databaseToBackup,'filename' => $this->backup_location,- 'scheduled_database_backup_id' => $this->backup->id,+ 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,]);- $this->backup_standalone_mysql($database);+ $this->backup_standalone_mysql($databaseToBackup);} elseif (str($databaseType)->contains('mariadb')) {- $this->backup_file = "/mariadb-dump-$database-".Carbon::now()->timestamp.'.dmp';- if ($this->backup->dump_all) {+ $this->backup_file = "/mariadb-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';+ if ($this->scheduledDatabaseBackup->dump_all) {$this->backup_file = '/mariadb-dump-all-'.Carbon::now()->timestamp.'.gz';}$this->backup_location = $this->backup_dir.$this->backup_file;- $this->backup_log = ScheduledDatabaseBackupExecution::create([- 'database_name' => $database,+ $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([+ 'database_name' => $databaseToBackup,'filename' => $this->backup_location,- 'scheduled_database_backup_id' => $this->backup->id,+ 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,]);- $this->backup_standalone_mariadb($database);+ $this->backup_standalone_mariadb($databaseToBackup);} else {- throw new \Exception('Unsupported database type');+ throw new Exception('Unsupported database type');}$size = $this->calculate_size();$this->remove_old_backups();- if ($this->backup->save_s3) {+ if ($this->scheduledDatabaseBackup->save_s3) {$this->upload_to_s3();}- $this->team->notify(new BackupSuccess($this->backup, $this->database, $database));+ $this->team->notify(new BackupSuccess($this->scheduledDatabaseBackup, $this->database, $databaseToBackup));$this->backup_log->update(['status' => 'success','message' => $this->backup_output,'size' => $size,]);- } catch (\Throwable $e) {- if ($this->backup_log) {+ } catch (Throwable $e) {+ if ($this->backup_log instanceof ScheduledDatabaseBackupExecution) {$this->backup_log->update(['status' => 'failed','message' => $this->backup_output,@@ -320,13 +310,13 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue'filename' => null,]);}- $this->team?->notify(new BackupFailed($this->backup, $this->database, $this->backup_output, $database));+ $this->team?->notify(new BackupFailed($this->scheduledDatabaseBackup, $this->database, $this->backup_output, $databaseToBackup));}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {throw $e;} finally {- if ($this->team) {+ if ($this->team instanceof Team) {BackupCreated::dispatch($this->team->id);}}@@ -358,12 +348,10 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue} else {$commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --archive > $this->backup_location";}+ } elseif (str($this->database->image)->startsWith('mongo:4')) {+ $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";} else {- if (str($this->database->image)->startsWith('mongo:4')) {- $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";- } else {- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";- }+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";}}$this->backup_output = instant_remote_process($commands, $this->server);@@ -371,7 +359,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($this->backup_output === '') {$this->backup_output = null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->add_to_backup_output($e->getMessage());throw $e;}@@ -385,7 +373,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($this->postgres_password) {$backupCommand .= " -e PGPASSWORD=$this->postgres_password";}- if ($this->backup->dump_all) {+ if ($this->scheduledDatabaseBackup->dump_all) {$backupCommand .= " $this->container_name pg_dumpall --username {$this->database->postgres_user} | gzip > $this->backup_location";} else {$backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username {$this->database->postgres_user} $database > $this->backup_location";@@ -397,7 +385,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($this->backup_output === '') {$this->backup_output = null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->add_to_backup_output($e->getMessage());throw $e;}@@ -407,7 +395,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue{try {$commands[] = 'mkdir -p '.$this->backup_dir;- if ($this->backup->dump_all) {+ if ($this->scheduledDatabaseBackup->dump_all) {$commands[] = "docker exec $this->container_name mysqldump -u root -p{$this->database->mysql_root_password} --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location";} else {$commands[] = "docker exec $this->container_name mysqldump -u root -p{$this->database->mysql_root_password} $database > $this->backup_location";@@ -417,7 +405,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($this->backup_output === '') {$this->backup_output = null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->add_to_backup_output($e->getMessage());throw $e;}@@ -427,7 +415,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue{try {$commands[] = 'mkdir -p '.$this->backup_dir;- if ($this->backup->dump_all) {+ if ($this->scheduledDatabaseBackup->dump_all) {$commands[] = "docker exec $this->container_name mariadb-dump -u root -p{$this->database->mariadb_root_password} --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location";} else {$commands[] = "docker exec $this->container_name mariadb-dump -u root -p{$this->database->mariadb_root_password} $database > $this->backup_location";@@ -437,7 +425,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif ($this->backup_output === '') {$this->backup_output = null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->add_to_backup_output($e->getMessage());throw $e;}@@ -445,11 +433,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueprivate function add_to_backup_output($output): void{- if ($this->backup_output) {- $this->backup_output = $this->backup_output."\n".$output;- } else {- $this->backup_output = $output;- }+ $this->backup_output = $this->backup_output ? $this->backup_output."\n".$output : $output;}private function calculate_size()@@ -459,10 +443,10 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueprivate function remove_old_backups(): void{- if ($this->backup->number_of_backups_locally === 0) {- $deletable = $this->backup->executions()->where('status', 'success');+ if ($this->scheduledDatabaseBackup->number_of_backups_locally === 0) {+ $deletable = $this->scheduledDatabaseBackup->executions()->where('status', 'success');} else {- $deletable = $this->backup->executions()->where('status', 'success')->skip($this->backup->number_of_backups_locally - 1);+ $deletable = $this->scheduledDatabaseBackup->executions()->where('status', 'success')->skip($this->scheduledDatabaseBackup->number_of_backups_locally - 1);}foreach ($deletable->get() as $execution) {delete_backup_locally($execution->filename, $this->server);@@ -482,7 +466,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue$bucket = $this->s3->bucket;$endpoint = $this->s3->endpoint;$this->s3->testConnection(shouldSave: true);- if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {+ if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {$network = $this->database->service->destination->network;} else {$network = $this->database->destination->network;@@ -493,29 +477,29 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueueif (isDev()) {if ($this->database->name === 'coolify-db') {$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/coolify/coolify-db-'.$this->server->ip.$this->backup_file;- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";} else {$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name.$this->backup_file;- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";}} else {- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";}if ($this->s3->isHetzner()) {$endpointWithoutBucket = 'https://'.str($endpoint)->after('https://')->after('.')->value();- $commands[] = "docker exec backup-of-{$this->backup->uuid} mc alias set --path=off --api=S3v4 temporary {$endpointWithoutBucket} $key $secret";+ $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc alias set --path=off --api=S3v4 temporary {$endpointWithoutBucket} $key $secret";} else {- $commands[] = "docker exec backup-of-{$this->backup->uuid} mc config host add temporary {$endpoint} $key $secret";+ $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc config host add temporary {$endpoint} $key $secret";}- $commands[] = "docker exec backup-of-{$this->backup->uuid} mc cp $this->backup_location temporary/$bucket{$this->backup_dir}/";+ $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc cp $this->backup_location temporary/$bucket{$this->backup_dir}/";instant_remote_process($commands, $this->server);$this->add_to_backup_output('Uploaded to S3.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->add_to_backup_output($e->getMessage());throw $e;} finally {- $command = "docker rm -f backup-of-{$this->backup->uuid}";+ $command = "docker rm -f backup-of-{$this->scheduledDatabaseBackup->uuid}";instant_remote_process([$command], $this->server);}}diff --git a/app/Jobs/DeleteResourceJob.php b/app/Jobs/DeleteResourceJob.phpindex 8b9228e5f5..b8fe20f68d 100644--- a/app/Jobs/DeleteResourceJob.php+++ b/app/Jobs/DeleteResourceJob.php@@ -24,6 +24,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Artisan;+use Throwable;class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueue{@@ -80,7 +81,7 @@ class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueue|| $this->resource instanceof StandaloneKeydb|| $this->resource instanceof StandaloneDragonfly|| $this->resource instanceof StandaloneClickhouse;- $server = data_get($this->resource, 'server') ?? data_get($this->resource, 'destination.server');+ $server = data_get($this->resource, 'server', data_get($this->resource, 'destination.server'));if (($this->dockerCleanup || $isDatabase) && $server) {CleanupDocker::dispatch($server, true);}@@ -88,7 +89,7 @@ class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueueif ($this->deleteConnectedNetworks && ! $isDatabase) {$this->resource?->delete_connected_networks($this->resource->uuid);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {throw $e;} finally {$this->resource->forceDelete();diff --git a/app/Jobs/DockerCleanupJob.php b/app/Jobs/DockerCleanupJob.phpindex 103c137b9f..03db120272 100644--- a/app/Jobs/DockerCleanupJob.php+++ b/app/Jobs/DockerCleanupJob.php@@ -13,6 +13,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Queue\SerializesModels;+use Throwable;class DockerCleanupJob implements ShouldBeEncrypted, ShouldQueue{@@ -66,7 +67,7 @@ class DockerCleanupJob implements ShouldBeEncrypted, ShouldQueue} else {$this->server->team?->notify(new DockerCleanupSuccess($this->server, 'No cleanup needed for '.$this->server->name));}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->server->team?->notify(new DockerCleanupFailed($this->server, 'Docker cleanup job failed with the following error: '.$e->getMessage()));throw $e;}diff --git a/app/Jobs/GithubAppPermissionJob.php b/app/Jobs/GithubAppPermissionJob.phpindex d483fe4c2d..95f4911ae7 100644--- a/app/Jobs/GithubAppPermissionJob.php+++ b/app/Jobs/GithubAppPermissionJob.php@@ -10,6 +10,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Http;+use Throwable;class GithubAppPermissionJob implements ShouldBeEncrypted, ShouldQueue{@@ -22,25 +23,25 @@ class GithubAppPermissionJob implements ShouldBeEncrypted, ShouldQueuereturn isDev() ? 1 : 3;}- public function __construct(public GithubApp $github_app) {}+ public function __construct(public GithubApp $githubApp) {}public function handle(){try {- $github_access_token = generate_github_jwt_token($this->github_app);+ $github_access_token = generate_github_jwt_token($this->githubApp);$response = Http::withHeaders(['Authorization' => "Bearer $github_access_token",'Accept' => 'application/vnd.github+json',- ])->get("{$this->github_app->api_url}/app");+ ])->get("{$this->githubApp->api_url}/app");$response = $response->json();$permissions = data_get($response, 'permissions');- $this->github_app->contents = data_get($permissions, 'contents');- $this->github_app->metadata = data_get($permissions, 'metadata');- $this->github_app->pull_requests = data_get($permissions, 'pull_requests');- $this->github_app->administration = data_get($permissions, 'administration');- $this->github_app->save();- $this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');- } catch (\Throwable $e) {+ $this->githubApp->contents = data_get($permissions, 'contents');+ $this->githubApp->metadata = data_get($permissions, 'metadata');+ $this->githubApp->pull_requests = data_get($permissions, 'pull_requests');+ $this->githubApp->administration = data_get($permissions, 'administration');+ $this->githubApp->save();+ $this->githubApp->makeVisible('client_secret')->makeVisible('webhook_secret');+ } catch (Throwable $e) {send_internal_notification('GithubAppPermissionJob failed with: '.$e->getMessage());throw $e;}diff --git a/app/Jobs/PullTemplatesFromCDN.php b/app/Jobs/PullTemplatesFromCDN.phpindex 45c536e062..1c82b27183 100644--- a/app/Jobs/PullTemplatesFromCDN.php+++ b/app/Jobs/PullTemplatesFromCDN.php@@ -10,6 +10,7 @@ use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\File;use Illuminate\Support\Facades\Http;+use Throwable;class PullTemplatesFromCDN implements ShouldBeEncrypted, ShouldQueue{@@ -35,7 +36,7 @@ class PullTemplatesFromCDN implements ShouldBeEncrypted, ShouldQueue} else {send_internal_notification('PullTemplatesAndVersions failed with: '.$response->status().' '.$response->body());}- } catch (\Throwable $e) {+ } catch (Throwable $e) {send_internal_notification('PullTemplatesAndVersions failed with: '.$e->getMessage());}}diff --git a/app/Jobs/PushServerUpdateJob.php b/app/Jobs/PushServerUpdateJob.phpindex 24f8d1e6be..7c7b39be92 100644--- a/app/Jobs/PushServerUpdateJob.php+++ b/app/Jobs/PushServerUpdateJob.php@@ -14,6 +14,7 @@ use App\Models\Server;use App\Models\ServiceApplication;use App\Models\ServiceDatabase;use App\Notifications\Container\ContainerRestarted;+use Exception;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldBeEncrypted;use Illuminate\Contracts\Queue\ShouldQueue;@@ -21,6 +22,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Collection;+use Throwable;class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue{@@ -92,7 +94,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue{// TODO: Swarm is not supported yetif (! $this->data) {- throw new \Exception('No data provided');+ throw new Exception('No data provided');}$data = collect($this->data);@@ -154,7 +156,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue}$this->updateApplicationPreviewStatus($applicationId, $containerStatus);}- } catch (\Exception $e) {+ } catch (Exception $e) {}} elseif ($labels->has('coolify.serviceId')) {$serviceId = $labels->get('coolify.serviceId');@@ -173,14 +175,12 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueueif ($name === 'coolify-proxy' && $this->isRunning($containerStatus)) {$this->foundProxy = true;} elseif ($type === 'service' && $this->isRunning($containerStatus)) {- } else {- if ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) {- $this->foundDatabaseUuids->push($uuid);- if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) {- $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true);- } else {- $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false);- }+ } elseif ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) {+ $this->foundDatabaseUuids->push($uuid);+ if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) {+ $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true);+ } else {+ $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false);}}}@@ -224,7 +224,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue$notFoundApplicationIds = $this->allApplicationIds->diff($this->foundApplicationIds);if ($notFoundApplicationIds->isNotEmpty()) {$notFoundApplicationIds->each(function ($applicationId) {- $application = Application::find($applicationId);+ $application = Application::query()->find($applicationId);if ($application) {$application->status = 'exited';$application->save();@@ -238,7 +238,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue$notFoundApplicationPreviewsIds = $this->allApplicationPreviewsIds->diff($this->foundApplicationPreviewsIds);if ($notFoundApplicationPreviewsIds->isNotEmpty()) {$notFoundApplicationPreviewsIds->each(function ($applicationPreviewId) {- $applicationPreview = ApplicationPreview::find($applicationPreviewId);+ $applicationPreview = ApplicationPreview::query()->find($applicationPreviewId);if ($applicationPreview) {$applicationPreview->status = 'exited';$applicationPreview->save();@@ -257,7 +257,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueueStartProxy::run($this->server, false);$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));}- } catch (\Throwable $e) {+ } catch (Throwable $e) {}} else {$connectProxyToDockerNetworks = connectProxyToNetworks($this->server);@@ -327,7 +327,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue$notFoundServiceDatabaseIds = $this->allServiceDatabaseIds->diff($this->foundServiceDatabaseIds);if ($notFoundServiceApplicationIds->isNotEmpty()) {$notFoundServiceApplicationIds->each(function ($serviceApplicationId) {- $application = ServiceApplication::find($serviceApplicationId);+ $application = ServiceApplication::query()->find($serviceApplicationId);if ($application) {$application->status = 'exited';$application->save();@@ -336,7 +336,7 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue}if ($notFoundServiceDatabaseIds->isNotEmpty()) {$notFoundServiceDatabaseIds->each(function ($serviceDatabaseId) {- $database = ServiceDatabase::find($serviceDatabaseId);+ $database = ServiceDatabase::query()->find($serviceDatabaseId);if ($database) {$database->status = 'exited';$database->save();diff --git a/app/Jobs/ScheduledTaskJob.php b/app/Jobs/ScheduledTaskJob.phpindex 90a10f3e99..de4b0757c5 100644--- a/app/Jobs/ScheduledTaskJob.php+++ b/app/Jobs/ScheduledTaskJob.php@@ -11,11 +11,14 @@ use App\Models\Service;use App\Models\Team;use App\Notifications\ScheduledTask\TaskFailed;use App\Notifications\ScheduledTask\TaskSuccess;+use Exception;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use RuntimeException;+use Throwable;class ScheduledTaskJob implements ShouldQueue{@@ -49,9 +52,9 @@ class ScheduledTaskJob implements ShouldQueue} elseif ($application = $task->application()->first()) {$this->resource = $application;} else {- throw new \RuntimeException('ScheduledTaskJob failed: No resource found.');+ throw new RuntimeException('ScheduledTaskJob failed: No resource found.');}- $this->team = Team::findOrFail($task->team_id);+ $this->team = Team::query()->findOrFail($task->team_id);$this->server_timezone = $this->getServerTimezone();}@@ -59,17 +62,15 @@ class ScheduledTaskJob implements ShouldQueue{if ($this->resource instanceof Application) {return $this->resource->destination->server->settings->server_timezone;- } elseif ($this->resource instanceof Service) {- return $this->resource->server->settings->server_timezone;}- return 'UTC';+ return $this->resource->server->settings->server_timezone;}public function handle(): void{try {- $this->task_log = ScheduledTaskExecution::create([+ $this->task_log = ScheduledTaskExecution::query()->create(['scheduled_task_id' => $this->task->id,]);@@ -95,17 +96,17 @@ class ScheduledTaskJob implements ShouldQueue});}if (count($this->containers) == 0) {- throw new \Exception('ScheduledTaskJob failed: No containers running.');+ throw new Exception('ScheduledTaskJob failed: No containers running.');}if (count($this->containers) > 1 && empty($this->task->container)) {- throw new \Exception('ScheduledTaskJob failed: More than one container exists but no container name was provided.');+ throw new Exception('ScheduledTaskJob failed: More than one container exists but no container name was provided.');}- foreach ($this->containers as $containerName) {- if (count($this->containers) == 1 || str_starts_with($containerName, $this->task->container.'-'.$this->resource->uuid)) {+ foreach ($this->containers as $container) {+ if (count($this->containers) == 1 || str_starts_with($container, $this->task->container.'-'.$this->resource->uuid)) {$cmd = "sh -c '".str_replace("'", "'\''", $this->task->command)."'";- $exec = "docker exec {$containerName} {$cmd}";+ $exec = "docker exec {$container} {$cmd}";$this->task_output = instant_remote_process([$exec], $this->server, true);$this->task_log->update(['status' => 'success',@@ -119,9 +120,9 @@ class ScheduledTaskJob implements ShouldQueue}// No valid container was found.- throw new \Exception('ScheduledTaskJob failed: No valid container was found. Is the container name correct?');- } catch (\Throwable $e) {- if ($this->task_log) {+ throw new Exception('ScheduledTaskJob failed: No valid container was found. Is the container name correct?');+ } catch (Throwable $e) {+ if ($this->task_log instanceof ScheduledTaskExecution) {$this->task_log->update(['status' => 'failed','message' => $this->task_output ?? $e->getMessage(),diff --git a/app/Jobs/SendMessageToDiscordJob.php b/app/Jobs/SendMessageToDiscordJob.phpindex 99aeaeea27..4545cfdfbf 100644--- a/app/Jobs/SendMessageToDiscordJob.php+++ b/app/Jobs/SendMessageToDiscordJob.php@@ -30,7 +30,7 @@ class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueuepublic int $maxExceptions = 5;public function __construct(- public DiscordMessage $message,+ public DiscordMessage $discordMessage,public string $webhookUrl) {$this->onQueue('high');@@ -41,6 +41,6 @@ class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueue*/public function handle(): void{- Http::post($this->webhookUrl, $this->message->toPayload());+ Http::post($this->webhookUrl, $this->discordMessage->toPayload());}}diff --git a/app/Jobs/SendMessageToPushoverJob.php b/app/Jobs/SendMessageToPushoverJob.phpindex 834a32b07b..fa1acbeb53 100644--- a/app/Jobs/SendMessageToPushoverJob.php+++ b/app/Jobs/SendMessageToPushoverJob.php@@ -10,6 +10,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Http;+use RuntimeException;class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueue{@@ -30,7 +31,7 @@ class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueuepublic int $maxExceptions = 5;public function __construct(- public PushoverMessage $message,+ public PushoverMessage $pushoverMessage,public string $token,public string $user,) {@@ -42,9 +43,9 @@ class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueue*/public function handle(): void{- $response = Http::post('https://api.pushover.net/1/messages.json', $this->message->toPayload($this->token, $this->user));+ $response = Http::post('https://api.pushover.net/1/messages.json', $this->pushoverMessage->toPayload($this->token, $this->user));if ($response->failed()) {- throw new \RuntimeException('Pushover notification failed with ' . $response->status() . ' status code.' . $response->body());+ throw new RuntimeException('Pushover notification failed with '.$response->status().' status code.'.$response->body());}}}diff --git a/app/Jobs/SendMessageToSlackJob.php b/app/Jobs/SendMessageToSlackJob.phpindex 470002d233..c27f45ad4d 100644--- a/app/Jobs/SendMessageToSlackJob.php+++ b/app/Jobs/SendMessageToSlackJob.php@@ -15,7 +15,7 @@ class SendMessageToSlackJob implements ShouldQueueuse Dispatchable, InteractsWithQueue, Queueable, SerializesModels;public function __construct(- private SlackMessage $message,+ private SlackMessage $slackMessage,private string $webhookUrl) {$this->onQueue('high');@@ -35,20 +35,20 @@ class SendMessageToSlackJob implements ShouldQueue],'attachments' => [[- 'color' => $this->message->color,+ 'color' => $this->slackMessage->color,'blocks' => [['type' => 'header','text' => ['type' => 'plain_text',- 'text' => $this->message->title,+ 'text' => $this->slackMessage->title,],],['type' => 'section','text' => ['type' => 'mrkdwn',- 'text' => $this->message->description,+ 'text' => $this->slackMessage->description,],],],diff --git a/app/Jobs/SendMessageToTelegramJob.php b/app/Jobs/SendMessageToTelegramJob.phpindex 6b0a64ae39..734e47c885 100644--- a/app/Jobs/SendMessageToTelegramJob.php+++ b/app/Jobs/SendMessageToTelegramJob.php@@ -10,6 +10,7 @@ use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;+use RuntimeException;class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue{@@ -44,18 +45,16 @@ class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue{$url = 'https://api.telegram.org/bot'.$this->token.'/sendMessage';$inlineButtons = [];- if (! empty($this->buttons)) {- foreach ($this->buttons as $button) {- $buttonUrl = data_get($button, 'url');- $text = data_get($button, 'text', 'Click here');- if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) {- $buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);- }- $inlineButtons[] = [- 'text' => $text,- 'url' => $buttonUrl,- ];+ foreach ($this->buttons as $button) {+ $buttonUrl = data_get($button, 'url');+ $text = data_get($button, 'text', 'Click here');+ if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) {+ $buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);}+ $inlineButtons[] = [+ 'text' => $text,+ 'url' => $buttonUrl,+ ];}$payload = [// 'parse_mode' => 'markdown',@@ -72,7 +71,7 @@ class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue}$response = Http::post($url, $payload);if ($response->failed()) {- throw new \RuntimeException('Telegram notification failed with '.$response->status().' status code.'.$response->body());+ throw new RuntimeException('Telegram notification failed with '.$response->status().' status code.'.$response->body());}}}diff --git a/app/Jobs/ServerCheckJob.php b/app/Jobs/ServerCheckJob.phpindex 9818d5c6a0..847db6bb8a 100644--- a/app/Jobs/ServerCheckJob.php+++ b/app/Jobs/ServerCheckJob.php@@ -15,6 +15,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Queue\SerializesModels;+use Throwable;class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue{@@ -60,9 +61,9 @@ class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue$foundProxyContainer = $this->containers->filter(function ($value, $key) {if ($this->server->isSwarm()) {return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik';- } else {- return data_get($value, 'Name') === '/coolify-proxy';}++ return data_get($value, 'Name') === '/coolify-proxy';})->first();if (! $foundProxyContainer) {try {@@ -71,7 +72,7 @@ class ServerCheckJob implements ShouldBeEncrypted, ShouldQueueStartProxy::run($this->server, false);$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));}- } catch (\Throwable $e) {+ } catch (Throwable $e) {}} else {$this->server->proxy->status = data_get($foundProxyContainer, 'State.Status');@@ -81,9 +82,11 @@ class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue}}}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}private function checkLogDrainContainer()diff --git a/app/Jobs/ServerCheckNewJob.php b/app/Jobs/ServerCheckNewJob.phpindex 3e8e60a31d..21114f035e 100644--- a/app/Jobs/ServerCheckNewJob.php+++ b/app/Jobs/ServerCheckNewJob.php@@ -11,6 +11,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class ServerCheckNewJob implements ShouldBeEncrypted, ShouldQueue{@@ -27,8 +28,10 @@ class ServerCheckNewJob implements ShouldBeEncrypted, ShouldQueuetry {ServerCheck::run($this->server);ResourcesCheck::dispatch($this->server);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}}diff --git a/app/Jobs/ServerCleanupMux.php b/app/Jobs/ServerCleanupMux.phpindex b793c3eca6..8b00e62470 100644--- a/app/Jobs/ServerCleanupMux.php+++ b/app/Jobs/ServerCleanupMux.php@@ -10,6 +10,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class ServerCleanupMux implements ShouldBeEncrypted, ShouldQueue{@@ -33,8 +34,10 @@ class ServerCleanupMux implements ShouldBeEncrypted, ShouldQueuereturn 'Server is not reachable or not ready.';}SshMultiplexingHelper::removeMuxFile($this->server);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}}diff --git a/app/Jobs/ServerLimitCheckJob.php b/app/Jobs/ServerLimitCheckJob.phpindex aa82c6dade..ecfbf9a84f 100644--- a/app/Jobs/ServerLimitCheckJob.php+++ b/app/Jobs/ServerLimitCheckJob.php@@ -11,6 +11,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class ServerLimitCheckJob implements ShouldBeEncrypted, ShouldQueue{@@ -46,10 +47,12 @@ class ServerLimitCheckJob implements ShouldBeEncrypted, ShouldQueue}});}- } catch (\Throwable $e) {+ } catch (Throwable $e) {send_internal_notification('ServerLimitCheckJob failed with: '.$e->getMessage());return handleError($e);}++ return null;}}diff --git a/app/Jobs/ServerStorageCheckJob.php b/app/Jobs/ServerStorageCheckJob.phpindex 9a8d86be1e..499027f1ea 100644--- a/app/Jobs/ServerStorageCheckJob.php+++ b/app/Jobs/ServerStorageCheckJob.php@@ -11,6 +11,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\RateLimiter;+use Throwable;class ServerStorageCheckJob implements ShouldBeEncrypted, ShouldQueue{@@ -58,8 +59,10 @@ class ServerStorageCheckJob implements ShouldBeEncrypted, ShouldQueue} else {RateLimiter::hit('high-disk-usage:'.$this->server->id, 600);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}}diff --git a/app/Jobs/StripeProcessJob.php b/app/Jobs/StripeProcessJob.phpindex d61c738f4a..9fabc1ecfb 100644--- a/app/Jobs/StripeProcessJob.php+++ b/app/Jobs/StripeProcessJob.php@@ -4,9 +4,12 @@ namespace App\Jobs;use App\Models\Subscription;use App\Models\Team;+use Exception;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Support\Str;+use RuntimeException;+use Stripe\StripeClient;class StripeProcessJob implements ShouldQueue{@@ -33,26 +36,26 @@ class StripeProcessJob implements ShouldQueue$data = data_get($this->event, 'data.object');switch ($type) {case 'radar.early_fraud_warning.created':- $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));+ $stripeClient = new StripeClient(config('subscription.stripe_api_key'));$id = data_get($data, 'id');$charge = data_get($data, 'charge');if ($charge) {- $stripe->refunds->create(['charge' => $charge]);+ $stripeClient->refunds->create(['charge' => $charge]);}$pi = data_get($data, 'payment_intent');- $piData = $stripe->paymentIntents->retrieve($pi, []);+ $piData = $stripeClient->paymentIntents->retrieve($pi, []);$customerId = data_get($piData, 'customer');- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if ($subscription) {$subscriptionId = data_get($subscription, 'stripe_subscription_id');- $stripe->subscriptions->cancel($subscriptionId, []);+ $stripeClient->subscriptions->cancel($subscriptionId, []);$subscription->update(['stripe_invoice_paid' => false,]);send_internal_notification("Early fraud warning created Refunded, subscription canceled. Charge: {$charge}, id: {$id}, pi: {$pi}");} else {send_internal_notification("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");- throw new \RuntimeException("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");+ throw new RuntimeException("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");}break;case 'checkout.session.completed':@@ -65,13 +68,13 @@ class StripeProcessJob implements ShouldQueue$teamId = Str::after($clientReferenceId, ':');$subscriptionId = data_get($data, 'subscription');$customerId = data_get($data, 'customer');- $team = Team::find($teamId);+ $team = Team::query()->find($teamId);$found = $team->members->where('id', $userId)->first();if (! $found->isAdmin()) {send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");- throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");+ throw new RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");}- $subscription = Subscription::where('team_id', $teamId)->first();+ $subscription = Subscription::query()->where('team_id', $teamId)->first();if ($subscription) {send_internal_notification('Old subscription activated for team: '.$teamId);$subscription->update([@@ -81,7 +84,7 @@ class StripeProcessJob implements ShouldQueue]);} else {send_internal_notification('New subscription for team: '.$teamId);- Subscription::create([+ Subscription::query()->create(['team_id' => $teamId,'stripe_subscription_id' => $subscriptionId,'stripe_customer_id' => $customerId,@@ -96,26 +99,26 @@ class StripeProcessJob implements ShouldQueuesend_internal_notification('Subscription excluded.');break;}- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if ($subscription) {$subscription->update(['stripe_invoice_paid' => true,]);} else {- throw new \RuntimeException("No subscription found for customer: {$customerId}");+ throw new RuntimeException("No subscription found for customer: {$customerId}");}break;case 'invoice.payment_failed':$customerId = data_get($data, 'customer');- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if (! $subscription) {send_internal_notification('invoice.payment_failed failed but no subscription found in Coolify for customer: '.$customerId);- throw new \RuntimeException("No subscription found for customer: {$customerId}");+ throw new RuntimeException("No subscription found for customer: {$customerId}");}$team = data_get($subscription, 'team');if (! $team) {send_internal_notification('invoice.payment_failed failed but no team found in Coolify for customer: '.$customerId);- throw new \RuntimeException("No team found in Coolify for customer: {$customerId}");+ throw new RuntimeException("No team found in Coolify for customer: {$customerId}");}if (! $subscription->stripe_invoice_paid) {SubscriptionInvoiceFailedJob::dispatch($team);@@ -126,10 +129,10 @@ class StripeProcessJob implements ShouldQueuebreak;case 'payment_intent.payment_failed':$customerId = data_get($data, 'customer');- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if (! $subscription) {send_internal_notification('payment_intent.payment_failed, no subscription found in Coolify for customer: '.$customerId);- throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}");+ throw new RuntimeException("No subscription found in Coolify for customer: {$customerId}");}if ($subscription->stripe_invoice_paid) {send_internal_notification('payment_intent.payment_failed but invoice is active for customer: '.$customerId);@@ -144,49 +147,48 @@ class StripeProcessJob implements ShouldQueue$teamId = data_get($data, 'metadata.team_id');$userId = data_get($data, 'metadata.user_id');if (! $teamId || ! $userId) {- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if ($subscription) {- throw new \RuntimeException("Subscription already exists for customer: {$customerId}");+ throw new RuntimeException("Subscription already exists for customer: {$customerId}");}- throw new \RuntimeException('No team id or user id found');+ throw new RuntimeException('No team id or user id found');}- $team = Team::find($teamId);+ $team = Team::query()->find($teamId);$found = $team->members->where('id', $userId)->first();if (! $found->isAdmin()) {send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");- throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");+ throw new RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");}- $subscription = Subscription::where('team_id', $teamId)->first();+ $subscription = Subscription::query()->where('team_id', $teamId)->first();if ($subscription) {send_internal_notification("Subscription already exists for team: {$teamId}");- throw new \RuntimeException("Subscription already exists for team: {$teamId}");- } else {- Subscription::create([- 'team_id' => $teamId,- 'stripe_subscription_id' => $subscriptionId,- 'stripe_customer_id' => $customerId,- 'stripe_invoice_paid' => false,- ]);+ throw new RuntimeException("Subscription already exists for team: {$teamId}");}+ Subscription::query()->create([+ 'team_id' => $teamId,+ 'stripe_subscription_id' => $subscriptionId,+ 'stripe_customer_id' => $customerId,+ 'stripe_invoice_paid' => false,+ ]);case 'customer.subscription.updated':$teamId = data_get($data, 'metadata.team_id');$userId = data_get($data, 'metadata.user_id');$customerId = data_get($data, 'customer');$status = data_get($data, 'status');- $subscriptionId = data_get($data, 'items.data.0.subscription') ?? data_get($data, 'id');- $planId = data_get($data, 'items.data.0.plan.id') ?? data_get($data, 'plan.id');+ $subscriptionId = data_get($data, 'items.data.0.subscription', data_get($data, 'id'));+ $planId = data_get($data, 'items.data.0.plan.id', data_get($data, 'plan.id'));if (Str::contains($excludedPlans, $planId)) {send_internal_notification('Subscription excluded.');break;}- $subscription = Subscription::where('stripe_customer_id', $customerId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();if (! $subscription) {if ($status === 'incomplete_expired') {send_internal_notification('Subscription incomplete expired');- throw new \RuntimeException('Subscription incomplete expired');+ throw new RuntimeException('Subscription incomplete expired');}if ($teamId) {- $subscription = Subscription::create([+ $subscription = Subscription::query()->create(['team_id' => $teamId,'stripe_subscription_id' => $subscriptionId,'stripe_customer_id' => $customerId,@@ -194,7 +196,7 @@ class StripeProcessJob implements ShouldQueue]);} else {send_internal_notification('No subscription and team id found');- throw new \RuntimeException('No subscription and team id found');+ throw new RuntimeException('No subscription and team id found');}}$cancelAtPeriodEnd = data_get($data, 'cancel_at_period_end');@@ -217,19 +219,15 @@ class StripeProcessJob implements ShouldQueue'stripe_plan_id' => $planId,'stripe_cancel_at_period_end' => $cancelAtPeriodEnd,]);- if ($status === 'paused' || $status === 'incomplete_expired') {- if ($subscription->stripe_subscription_id === $subscriptionId) {- $subscription->update([- 'stripe_invoice_paid' => false,- ]);- }+ if (($status === 'paused' || $status === 'incomplete_expired') && $subscription->stripe_subscription_id === $subscriptionId) {+ $subscription->update([+ 'stripe_invoice_paid' => false,+ ]);}- if ($status === 'active') {- if ($subscription->stripe_subscription_id === $subscriptionId) {- $subscription->update([- 'stripe_invoice_paid' => true,- ]);- }+ if ($status === 'active' && $subscription->stripe_subscription_id === $subscriptionId) {+ $subscription->update([+ 'stripe_invoice_paid' => true,+ ]);}if ($feedback) {$reason = "Cancellation feedback for {$customerId}: '".$feedback."'";@@ -242,24 +240,24 @@ class StripeProcessJob implements ShouldQueuecase 'customer.subscription.deleted':$customerId = data_get($data, 'customer');$subscriptionId = data_get($data, 'id');- $subscription = Subscription::where('stripe_customer_id', $customerId)->where('stripe_subscription_id', $subscriptionId)->first();+ $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->where('stripe_subscription_id', $subscriptionId)->first();if ($subscription) {$team = data_get($subscription, 'team');if ($team) {$team->subscriptionEnded();} else {send_internal_notification('Subscription deleted but no team found in Coolify for customer: '.$customerId);- throw new \RuntimeException("No team found in Coolify for customer: {$customerId}");+ throw new RuntimeException("No team found in Coolify for customer: {$customerId}");}} else {send_internal_notification('Subscription deleted but no subscription found in Coolify for customer: '.$customerId);- throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}");+ throw new RuntimeException("No subscription found in Coolify for customer: {$customerId}");}break;default:- throw new \RuntimeException("Unhandled event type: {$type}");+ throw new RuntimeException("Unhandled event type: {$type}");}- } catch (\Exception $e) {+ } catch (Exception $e) {send_internal_notification('StripeProcessJob error: '.$e->getMessage());}}diff --git a/app/Jobs/SubscriptionInvoiceFailedJob.php b/app/Jobs/SubscriptionInvoiceFailedJob.phpindex dc511f4452..a425928270 100755--- a/app/Jobs/SubscriptionInvoiceFailedJob.php+++ b/app/Jobs/SubscriptionInvoiceFailedJob.php@@ -10,6 +10,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Throwable;class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue{@@ -24,17 +25,17 @@ class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue{try {$session = getStripeCustomerPortalSession($this->team);- $mail = new MailMessage;- $mail->view('emails.subscription-invoice-failed', [+ $mailMessage = new MailMessage;+ $mailMessage->view('emails.subscription-invoice-failed', ['stripeCustomerPortal' => $session->url,]);- $mail->subject('Your last payment was failed for Coolify Cloud.');- $this->team->members()->each(function ($member) use ($mail) {+ $mailMessage->subject('Your last payment was failed for Coolify Cloud.');+ $this->team->members()->each(function ($member) use ($mailMessage) {if ($member->isAdmin()) {- send_user_an_email($mail, $member->email);+ send_user_an_email($mailMessage, $member->email);}});- } catch (\Throwable $e) {+ } catch (Throwable $e) {send_internal_notification('SubscriptionInvoiceFailedJob failed with: '.$e->getMessage());throw $e;}diff --git a/app/Jobs/UpdateCoolifyJob.php b/app/Jobs/UpdateCoolifyJob.phpindex f0e43cbc0a..958039e9e2 100644--- a/app/Jobs/UpdateCoolifyJob.php+++ b/app/Jobs/UpdateCoolifyJob.php@@ -11,6 +11,7 @@ use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Log;+use Throwable;class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueue{@@ -34,7 +35,7 @@ class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueuereturn;}- $server = Server::findOrFail(0);+ $server = Server::query()->findOrFail(0);if (! $server) {Log::error('Server not found. Cannot proceed with update.');@@ -46,7 +47,7 @@ class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueue$settings->update(['new_version_available' => false]);Log::info('Coolify update completed successfully.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {Log::error('UpdateCoolifyJob failed: '.$e->getMessage());// Consider implementing a notification to administrators}diff --git a/app/Listeners/MaintenanceModeDisabledNotification.php b/app/Listeners/MaintenanceModeDisabledNotification.phpindex 6c3ab83d8f..085dc569fe 100644--- a/app/Listeners/MaintenanceModeDisabledNotification.php+++ b/app/Listeners/MaintenanceModeDisabledNotification.php@@ -6,12 +6,11 @@ use Illuminate\Foundation\Events\MaintenanceModeDisabled as EventsMaintenanceModuse Illuminate\Support\Facades\Request;use Illuminate\Support\Facades\Storage;use Symfony\Component\HttpFoundation\Request as SymfonyRequest;+use Throwable;class MaintenanceModeDisabledNotification{- public function __construct() {}-- public function handle(EventsMaintenanceModeDisabled $event): void+ public function handle(EventsMaintenanceModeDisabled $eventsMaintenanceModeDisabled): void{$files = Storage::disk('webhooks-during-maintenance')->files();$files = collect($files);@@ -39,7 +38,7 @@ class MaintenanceModeDisabledNotificationtry {$instance = new $class;$instance->$method($request);- } catch (\Throwable $th) {+ } catch (Throwable $th) {} finally {Storage::disk('webhooks-during-maintenance')->delete($file);}diff --git a/app/Listeners/MaintenanceModeEnabledNotification.php b/app/Listeners/MaintenanceModeEnabledNotification.phpindex 5aab248ea8..37170a0341 100644--- a/app/Listeners/MaintenanceModeEnabledNotification.php+++ b/app/Listeners/MaintenanceModeEnabledNotification.php@@ -17,5 +17,5 @@ class MaintenanceModeEnabledNotification/*** Handle the event.*/- public function handle(EventsMaintenanceModeEnabled $event): void {}+ public function handle(EventsMaintenanceModeEnabled $eventsMaintenanceModeEnabled): void {}}diff --git a/app/Listeners/ProxyStartedNotification.php b/app/Listeners/ProxyStartedNotification.phpindex 9045b1e5c1..ffd6858cfb 100644--- a/app/Listeners/ProxyStartedNotification.php+++ b/app/Listeners/ProxyStartedNotification.php@@ -9,11 +9,9 @@ class ProxyStartedNotification{public Server $server;- public function __construct() {}-- public function handle(ProxyStarted $event): void+ public function handle(ProxyStarted $proxyStarted): void{- $this->server = data_get($event, 'data');+ $this->server = data_get($proxyStarted, 'data');$this->server->setupDefaultRedirect();$this->server->setupDynamicProxyConfiguration();$this->server->proxy->force_stop = false;diff --git a/app/Livewire/ActivityMonitor.php b/app/Livewire/ActivityMonitor.phpindex 2e36f34ee7..18e1a565ea 100644--- a/app/Livewire/ActivityMonitor.php+++ b/app/Livewire/ActivityMonitor.php@@ -36,7 +36,7 @@ class ActivityMonitor extends Componentpublic function hydrateActivity(){- $this->activity = Activity::find($this->activityId);+ $this->activity = Activity::query()->find($this->activityId);}public function polling()@@ -51,22 +51,20 @@ class ActivityMonitor extends Component// // $this->setStatus(ProcessStatus::ERROR);// }$this->isPollingActive = false;- if ($exit_code === 0) {- if ($this->eventToDispatch !== null) {- if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {- $causer_id = data_get($this->activity, 'causer_id');- $user = User::find($causer_id);- if ($user) {- foreach ($user->teams as $team) {- $teamId = $team->id;- $this->eventToDispatch::dispatch($teamId);- }+ if ($exit_code === 0 && $this->eventToDispatch !== null) {+ if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {+ $causer_id = data_get($this->activity, 'causer_id');+ $user = User::query()->find($causer_id);+ if ($user) {+ foreach ($user->teams as $team) {+ $teamId = $team->id;+ $this->eventToDispatch::dispatch($teamId);}-- return;}- $this->dispatch($this->eventToDispatch);++ return;}+ $this->dispatch($this->eventToDispatch);}}}diff --git a/app/Livewire/Admin/Index.php b/app/Livewire/Admin/Index.phpindex b5f6d29294..88fc2aa9dd 100644--- a/app/Livewire/Admin/Index.php+++ b/app/Livewire/Admin/Index.php@@ -6,7 +6,6 @@ use App\Models\Team;use App\Models\User;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Auth;-use Illuminate\Support\Facades\Cache;use Livewire\Component;class Index extends Component@@ -28,25 +27,29 @@ class Index extends Componentreturn redirect()->route('dashboard');}$this->getSubscribers();++ return null;}public function back(){if (session('impersonating')) {session()->forget('impersonating');- $user = User::find(0);+ $user = User::query()->find(0);$team_to_switch_to = $user->teams->first();Auth::login($user);refreshSession($team_to_switch_to);return redirect(request()->header('Referer'));}++ return null;}public function submitSearch(){if ($this->search !== '') {- $this->foundUsers = User::where(function ($query) {+ $this->foundUsers = User::query()->where(function ($query) {$query->where('name', 'like', "%{$this->search}%")->orWhere('email', 'like', "%{$this->search}%");})->get();@@ -55,8 +58,8 @@ class Index extends Componentpublic function getSubscribers(){- $this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count();- $this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count();+ $this->inactiveSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', false)->count();+ $this->activeSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', true)->count();}public function switchUser(int $user_id)@@ -65,7 +68,7 @@ class Index extends Componentreturn redirect()->route('dashboard');}session(['impersonating' => true]);- $user = User::find($user_id);+ $user = User::query()->find($user_id);$team_to_switch_to = $user->teams->first();// Cache::forget("team:{$user->id}");Auth::login($user);diff --git a/app/Livewire/Boarding/Index.php b/app/Livewire/Boarding/Index.phpindex 15eabfec57..18e8cc85b6 100644--- a/app/Livewire/Boarding/Index.php+++ b/app/Livewire/Boarding/Index.php@@ -7,8 +7,10 @@ use App\Models\PrivateKey;use App\Models\Project;use App\Models\Server;use App\Models\Team;+use Exception;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class Index extends Component@@ -90,6 +92,8 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$this->remoteServerDescription = 'Created by Coolify';$this->remoteServerHost = 'coolify-testing-host';}++ return null;}public function explanation()@@ -98,6 +102,8 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==return $this->setServerType('remote');}$this->currentState = 'select-server-type';++ return null;}public function restartBoarding()@@ -107,7 +113,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==public function skipBoarding(){- Team::find(currentTeam()->id)->update([+ Team::query()->find(currentTeam()->id)->update(['show_boarding' => false,]);refreshSession();@@ -119,15 +125,16 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA=={$this->selectedServerType = $type;if ($this->selectedServerType === 'localhost') {- $this->createdServer = Server::find(0);+ $this->createdServer = Server::query()->find(0);$this->selectedExistingServer = 0;if (! $this->createdServer) {return $this->dispatch('error', 'Localhost server is not found. Something went wrong during installation. Please try to reinstall or contact support.');}$this->serverPublicKey = $this->createdServer->privateKey->getPublicKey();- return $this->validateServer('localhost');- } elseif ($this->selectedServerType === 'remote') {+ return $this->validateServer();+ }+ if ($this->selectedServerType === 'remote') {if (isDev()) {$this->privateKeys = PrivateKey::ownedByCurrentTeam(['name'])->get();} else {@@ -142,15 +149,17 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$this->updateServerDetails();$this->currentState = 'select-existing-server';- return;+ return null;}$this->currentState = 'private-key';}++ return null;}public function selectExistingServer(){- $this->createdServer = Server::find($this->selectedExistingServer);+ $this->createdServer = Server::query()->find($this->selectedExistingServer);if (! $this->createdServer) {$this->dispatch('error', 'Server is not found.');$this->currentState = 'private-key';@@ -165,7 +174,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==private function updateServerDetails(){- if ($this->createdServer) {+ if ($this->createdServer instanceof Server) {$this->remoteServerPort = $this->createdServer->port;$this->remoteServerUser = $this->createdServer->user;}@@ -184,7 +193,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==return;}- $this->createdPrivateKey = PrivateKey::where('team_id', currentTeam()->id)->where('id', $this->selectedExistingPrivateKey)->first();+ $this->createdPrivateKey = PrivateKey::query()->where('team_id', currentTeam()->id)->where('id', $this->selectedExistingPrivateKey)->first();$this->privateKey = $this->createdPrivateKey->private_key;$this->currentState = 'create-server';}@@ -223,7 +232,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$this->createdPrivateKey = $privateKey;$this->currentState = 'create-server';- } catch (\Exception $e) {+ } catch (Exception $e) {$this->addError('privateKey', 'Failed to save private key: '.$e->getMessage());}}@@ -242,7 +251,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==if ($foundServer) {return $this->dispatch('error', 'IP address is already in use by another team.');}- $this->createdServer = Server::create([+ $this->createdServer = Server::query()->create(['name' => $this->remoteServerName,'ip' => $this->remoteServerHost,'port' => $this->remoteServerPort,@@ -256,6 +265,8 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$this->createdServer->settings->save();$this->selectedExistingServer = $this->createdServer->id;$this->currentState = 'validate-server';++ return null;}public function installServer()@@ -275,7 +286,7 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA=='is_reachable' => true,]);$this->serverReachable = true;- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->serverReachable = false;$this->createdServer->settings()->update(['is_reachable' => false,@@ -289,19 +300,21 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$dockerVersion = checkMinimumDockerEngineVersion($dockerVersion);if (is_null($dockerVersion)) {$this->currentState = 'validate-server';- throw new \Exception('Docker not found or old version is installed.');+ throw new Exception('Docker not found or old version is installed.');}$this->createdServer->settings()->update(['is_usable' => true,]);$this->getProxyType();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->createdServer->settings()->update(['is_usable' => false,]);return handleError(error: $e, livewire: $this);}++ return null;}public function selectProxy(?string $proxyType = null)@@ -313,11 +326,13 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==$this->createdServer->proxy->status = 'exited';$this->createdServer->save();$this->getProjects();++ return null;}public function getProjects(){- $this->projects = Project::ownedByCurrentTeam(['name'])->get();+ $this->projects = Project::ownedByCurrentTeam()->get();if ($this->projects->count() > 0) {$this->selectedProject = $this->projects->first()->id;}@@ -326,13 +341,13 @@ uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==public function selectExistingProject(){- $this->createdProject = Project::find($this->selectedProject);+ $this->createdProject = Project::query()->find($this->selectedProject);$this->currentState = 'create-resource';}public function createNewProject(){- $this->createdProject = Project::create([+ $this->createdProject = Project::query()->create(['name' => 'My first project','team_id' => currentTeam()->id,'uuid' => (string) new Cuid2,diff --git a/app/Livewire/Dashboard.php b/app/Livewire/Dashboard.phpindex c3cb797bff..7c876f1f5c 100644--- a/app/Livewire/Dashboard.php+++ b/app/Livewire/Dashboard.php@@ -38,7 +38,7 @@ class Dashboard extends Componentpublic function loadDeployments(){- $this->deploymentsPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $this->servers->pluck('id'))->get([+ $this->deploymentsPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $this->servers->pluck('id'))->get(['id','application_id','application_name',@@ -52,7 +52,7 @@ class Dashboard extends Componentpublic function navigateToProject($projectUuid){- $project = Project::where('uuid', $projectUuid)->first();+ $project = Project::query()->where('uuid', $projectUuid)->first();if ($project && $project->environments->count() === 1) {return Redirect::route('project.resource.index', [diff --git a/app/Livewire/Destination/New/Docker.php b/app/Livewire/Destination/New/Docker.phpindex 337f1d0673..ecbb063eb7 100644--- a/app/Livewire/Destination/New/Docker.php+++ b/app/Livewire/Destination/New/Docker.php@@ -5,9 +5,11 @@ namespace App\Livewire\Destination\New;use App\Models\Server;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class Docker extends Component@@ -63,31 +65,31 @@ class Docker extends Componentif ($this->isSwarm) {$found = $this->selectedServer->swarmDockers()->where('network', $this->network)->first();if ($found) {- throw new \Exception('Network already added to this server.');- } else {- $docker = SwarmDocker::create([- 'name' => $this->name,- 'network' => $this->network,- 'server_id' => $this->selectedServer->id,- ]);+ throw new Exception('Network already added to this server.');}+ $docker = SwarmDocker::query()->create([+ 'name' => $this->name,+ 'network' => $this->network,+ 'server_id' => $this->selectedServer->id,+ ]);} else {$found = $this->selectedServer->standaloneDockers()->where('network', $this->network)->first();if ($found) {- throw new \Exception('Network already added to this server.');- } else {- $docker = StandaloneDocker::create([- 'name' => $this->name,- 'network' => $this->network,- 'server_id' => $this->selectedServer->id,- ]);+ throw new Exception('Network already added to this server.');}+ $docker = StandaloneDocker::query()->create([+ 'name' => $this->name,+ 'network' => $this->network,+ 'server_id' => $this->selectedServer->id,+ ]);}$connectProxyToDockerNetworks = connectProxyToNetworks($this->selectedServer);instant_remote_process($connectProxyToDockerNetworks, $this->selectedServer, false);$this->dispatch('reloadWindow');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Destination/Show.php b/app/Livewire/Destination/Show.phpindex 5c4d6c1701..6cacfd4784 100644--- a/app/Livewire/Destination/Show.php+++ b/app/Livewire/Destination/Show.php@@ -8,6 +8,7 @@ use App\Models\SwarmDocker;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Show extends Component{@@ -40,9 +41,11 @@ class Show extends Component}$this->destination = $destination;$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -65,15 +68,17 @@ class Show extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Destination saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function delete(){try {- if ($this->destination->getMorphClass() === \App\Models\StandaloneDocker::class) {+ if ($this->destination->getMorphClass() === StandaloneDocker::class) {if ($this->destination->attachedTo()) {return $this->dispatch('error', 'You must delete all resources before deleting this destination.');}@@ -83,7 +88,7 @@ class Show extends Component$this->destination->delete();return redirect()->route('destination.index');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/ForcePasswordReset.php b/app/Livewire/ForcePasswordReset.phpindex 61a2a20e95..09cdea8847 100644--- a/app/Livewire/ForcePasswordReset.php+++ b/app/Livewire/ForcePasswordReset.php@@ -6,6 +6,7 @@ use DanHarrin\LivewireRateLimiting\WithRateLimiting;use Illuminate\Support\Facades\Hash;use Illuminate\Validation\Rules\Password;use Livewire\Component;+use Throwable;class ForcePasswordReset extends Component{@@ -31,6 +32,8 @@ class ForcePasswordReset extends Componentreturn redirect()->route('dashboard');}$this->email = auth()->user()->email;++ return null;}public function render()@@ -57,7 +60,7 @@ class ForcePasswordReset extends Component}return redirect()->route('dashboard');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Help.php b/app/Livewire/Help.phpindex f51527fbeb..864cece058 100644--- a/app/Livewire/Help.php+++ b/app/Livewire/Help.php@@ -7,6 +7,7 @@ use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Support\Facades\Http;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Help extends Component{@@ -25,14 +26,14 @@ class Help extends Component$this->rateLimit(3, 30);$settings = instanceSettings();- $mail = new MailMessage;- $mail->view(+ $mailMessage = new MailMessage;+ $mailMessage->view('emails.help',['description' => $this->description,]);- $mail->subject("[HELP]: {$this->subject}");+ $mailMessage->subject("[HELP]: {$this->subject}");$type = set_transanctional_email_settings($settings);// Sending feedback through Cloud API@@ -42,13 +43,15 @@ class Help extends Component'content' => 'User: `'.auth()->user()?->email.'` with subject: `'.$this->subject.'` has the following problem: `'.$this->description.'`',]);} else {- send_user_an_email($mail, auth()->user()?->email, '[email protected]');+ send_user_an_email($mailMessage, auth()->user()?->email, '[email protected]');}$this->dispatch('success', 'Feedback sent.', 'We will get in touch with you as soon as possible.');$this->reset('description', 'subject');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/NavbarDeleteTeam.php b/app/Livewire/NavbarDeleteTeam.phpindex e97cceb0da..639a9543f9 100644--- a/app/Livewire/NavbarDeleteTeam.php+++ b/app/Livewire/NavbarDeleteTeam.php@@ -19,12 +19,10 @@ class NavbarDeleteTeam extends Componentpublic function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}$currentTeam = currentTeam();diff --git a/app/Livewire/NewActivityMonitor.php b/app/Livewire/NewActivityMonitor.phpindex a9334e7108..bd1474c915 100644--- a/app/Livewire/NewActivityMonitor.php+++ b/app/Livewire/NewActivityMonitor.php@@ -14,7 +14,7 @@ class NewActivityMonitor extends Componentpublic $eventToDispatch = 'activityFinished';- public $eventData = null;+ public $eventData;public $isPollingActive = false;@@ -35,7 +35,7 @@ class NewActivityMonitor extends Componentpublic function hydrateActivity(){- $this->activity = Activity::find($this->activityId);+ $this->activity = Activity::query()->find($this->activityId);}public function polling()@@ -53,7 +53,7 @@ class NewActivityMonitor extends Componentif ($this->eventToDispatch !== null) {if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {$causer_id = data_get($this->activity, 'causer_id');- $user = User::find($causer_id);+ $user = User::query()->find($causer_id);if ($user) {foreach ($user->teams as $team) {$teamId = $team->id;diff --git a/app/Livewire/Notifications/Discord.php b/app/Livewire/Notifications/Discord.phpindex 57007813ee..0544b75667 100644--- a/app/Livewire/Notifications/Discord.php+++ b/app/Livewire/Notifications/Discord.php@@ -7,6 +7,7 @@ use App\Models\Team;use App\Notifications\Test;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Discord extends Component{@@ -62,9 +63,11 @@ class Discord extends Component$this->team = auth()->user()->currentTeam();$this->settings = $this->team->discordNotificationSettings;$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -117,20 +120,24 @@ class Discord extends Component'discordWebhookUrl.required' => 'Discord Webhook URL is required.',]);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->discordEnabled = false;return handleError($e, $this);}++ return null;}public function instantSave(){try {$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -139,9 +146,11 @@ class Discord extends Component$this->resetErrorBag();$this->syncData(true);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function saveModel()@@ -156,9 +165,11 @@ class Discord extends Componenttry {$this->team->notify(new Test(channel: 'discord'));$this->dispatch('success', 'Test notification sent.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Notifications/Email.php b/app/Livewire/Notifications/Email.phpindex 3ed20f907c..dc26bf915f 100644--- a/app/Livewire/Notifications/Email.php+++ b/app/Livewire/Notifications/Email.php@@ -5,10 +5,12 @@ namespace App\Livewire\Notifications;use App\Models\EmailNotificationSettings;use App\Models\Team;use App\Notifications\Test;+use Exception;use Illuminate\Support\Facades\RateLimiter;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Email extends Component{@@ -109,9 +111,11 @@ class Email extends Component$this->settings = $this->team->emailNotificationSettings;$this->syncData();$this->testEmailAddress = auth()->user()->email;- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -185,9 +189,11 @@ class Email extends Componenttry {$this->resetErrorBag();$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function saveModel()@@ -210,9 +216,9 @@ class Email extends Component$this->resendEnabled = false;$this->saveModel();- return;+ return null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {if ($type === 'SMTP') {$this->smtpEnabled = false;} elseif ($type === 'Resend') {@@ -223,6 +229,8 @@ class Email extends Component} finally {$this->dispatch('refresh');}++ return null;}public function submitSmtp()@@ -266,11 +274,13 @@ class Email extends Component$this->settings->save();$this->dispatch('success', 'SMTP settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->smtpEnabled = false;return handleError($e);}++ return null;}public function submitResend()@@ -301,9 +311,11 @@ class Email extends Component$this->settings->save();$this->dispatch('success', 'Resend settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function sendTestEmail()@@ -327,11 +339,13 @@ class Email extends Component);if (! $executed) {- throw new \Exception('Too many messages sent!');+ throw new Exception('Too many messages sent!');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function copyFromInstanceSettings()diff --git a/app/Livewire/Notifications/Pushover.php b/app/Livewire/Notifications/Pushover.phpindex f1e4c464da..0c14fa023d 100644--- a/app/Livewire/Notifications/Pushover.php+++ b/app/Livewire/Notifications/Pushover.php@@ -8,6 +8,7 @@ use App\Notifications\Test;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Pushover extends Component{@@ -70,9 +71,11 @@ class Pushover extends Component$this->team = auth()->user()->currentTeam();$this->settings = $this->team->pushoverNotificationSettings;$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -129,24 +132,28 @@ class Pushover extends Component'pushoverApiToken.required' => 'Pushover API Token is required.',]);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->pushoverEnabled = false;return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function instantSave(){try {$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function submit()@@ -155,9 +162,11 @@ class Pushover extends Component$this->resetErrorBag();$this->syncData(true);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function saveModel()@@ -172,9 +181,11 @@ class Pushover extends Componenttry {$this->team->notify(new Test(channel: 'pushover'));$this->dispatch('success', 'Test notification sent.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Notifications/Slack.php b/app/Livewire/Notifications/Slack.phpindex f47ad8a979..03fa171c21 100644--- a/app/Livewire/Notifications/Slack.php+++ b/app/Livewire/Notifications/Slack.php@@ -8,6 +8,7 @@ use App\Notifications\Test;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Slack extends Component{@@ -67,9 +68,11 @@ class Slack extends Component$this->team = auth()->user()->currentTeam();$this->settings = $this->team->slackNotificationSettings;$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -122,24 +125,28 @@ class Slack extends Component'slackWebhookUrl.required' => 'Slack Webhook URL is required.',]);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->slackEnabled = false;return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function instantSave(){try {$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function submit()@@ -148,9 +155,11 @@ class Slack extends Component$this->resetErrorBag();$this->syncData(true);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function saveModel()@@ -165,9 +174,11 @@ class Slack extends Componenttry {$this->team->notify(new Test(channel: 'slack'));$this->dispatch('success', 'Test notification sent.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Notifications/Telegram.php b/app/Livewire/Notifications/Telegram.phpindex 01afb4ac67..2f6c6f3be9 100644--- a/app/Livewire/Notifications/Telegram.php+++ b/app/Livewire/Notifications/Telegram.php@@ -8,6 +8,7 @@ use App\Notifications\Test;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Telegram extends Component{@@ -106,9 +107,11 @@ class Telegram extends Component$this->team = auth()->user()->currentTeam();$this->settings = $this->team->telegramNotificationSettings;$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -183,11 +186,13 @@ class Telegram extends Component{try {$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function submit()@@ -196,9 +201,11 @@ class Telegram extends Component$this->resetErrorBag();$this->syncData(true);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSaveTelegramEnabled()@@ -212,13 +219,15 @@ class Telegram extends Component'telegramChatId.required' => 'Telegram Chat ID is required.',]);$this->saveModel();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->telegramEnabled = false;return handleError($e, $this);} finally {$this->dispatch('refresh');}++ return null;}public function saveModel()@@ -233,9 +242,11 @@ class Telegram extends Componenttry {$this->team->notify(new Test(channel: 'telegram'));$this->dispatch('success', 'Test notification sent.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Profile/Index.php b/app/Livewire/Profile/Index.phpindex 53314cd5c3..70f82da153 100644--- a/app/Livewire/Profile/Index.php+++ b/app/Livewire/Profile/Index.php@@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Hash;use Illuminate\Validation\Rules\Password;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Index extends Component{@@ -41,9 +42,11 @@ class Index extends Component]);$this->dispatch('success', 'Profile updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function resetPassword()@@ -56,12 +59,12 @@ class Index extends Componentif (! Hash::check($this->current_password, auth()->user()->password)) {$this->dispatch('error', 'Current password is incorrect.');- return;+ return null;}if ($this->new_password !== $this->new_password_confirmation) {$this->dispatch('error', 'The two new passwords does not match.');- return;+ return null;}auth()->user()->update(['password' => Hash::make($this->new_password),@@ -70,9 +73,11 @@ class Index extends Component$this->current_password = '';$this->new_password = '';$this->new_password_confirmation = '';- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/AddEmpty.php b/app/Livewire/Project/AddEmpty.phpindex 07873c059d..f91c977c68 100644--- a/app/Livewire/Project/AddEmpty.php+++ b/app/Livewire/Project/AddEmpty.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project;use App\Models\Project;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class AddEmpty extends Component@@ -19,7 +20,7 @@ class AddEmpty extends Component{try {$this->validate();- $project = Project::create([+ $project = Project::query()->create(['name' => $this->name,'description' => $this->description,'team_id' => currentTeam()->id,@@ -27,7 +28,7 @@ class AddEmpty extends Component]);return redirect()->route('project.show', $project->uuid);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/Application/Advanced.php b/app/Livewire/Project/Application/Advanced.phpindex cb63f0e1a6..99b40c62d0 100644--- a/app/Livewire/Project/Application/Advanced.php+++ b/app/Livewire/Project/Application/Advanced.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Application;use App\Models\Application;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Advanced extends Component{@@ -71,9 +72,11 @@ class Advanced extends Component{try {$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -127,14 +130,12 @@ class Advanced extends Componentpublic function instantSave(){try {- if ($this->isLogDrainEnabled) {- if (! $this->application->destination->server->isLogDrainEnabled()) {- $this->isLogDrainEnabled = false;- $this->syncData(true);- $this->dispatch('error', 'Log drain is not enabled on this server.');-- return;- }+ if ($this->isLogDrainEnabled && ! $this->application->destination->server->isLogDrainEnabled()) {+ $this->isLogDrainEnabled = false;+ $this->syncData(true);+ $this->dispatch('error', 'Log drain is not enabled on this server.');++ return null;}if ($this->application->isForceHttpsEnabled() !== $this->isForceHttpsEnabled ||$this->application->isGzipEnabled() !== $this->isGzipEnabled ||@@ -151,9 +152,11 @@ class Advanced extends Component$this->syncData(true);$this->dispatch('success', 'Settings saved.');$this->dispatch('configurationChanged');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -165,13 +168,15 @@ class Advanced extends Component$this->gpuDeviceIds = null;$this->syncData(true);- return;+ return null;}$this->syncData(true);$this->dispatch('success', 'Settings saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function saveCustomName()diff --git a/app/Livewire/Project/Application/Deployment/Index.php b/app/Livewire/Project/Application/Deployment/Index.phpindex b847c40ef1..e03a28cb53 100644--- a/app/Livewire/Project/Application/Deployment/Index.php+++ b/app/Livewire/Project/Application/Deployment/Index.php@@ -49,6 +49,8 @@ class Index extends Component$this->current_url = url()->current();$this->show_pull_request_only();$this->show_more();++ return null;}private function show_pull_request_only()@@ -78,9 +80,9 @@ class Index extends Componentpublic function previous_page(?int $take = null){if ($take) {- $this->skip = $this->skip - $take;+ $this->skip -= $take;}- $this->skip = $this->skip - $this->default_take;+ $this->skip -= $this->default_take;if ($this->skip < 0) {$this->show_prev = false;$this->skip = 0;@@ -91,7 +93,7 @@ class Index extends Componentpublic function next_page(?int $take = null){if ($take) {- $this->skip = $this->skip + $take;+ $this->skip += $take;}$this->show_prev = true;$this->load_deployments();diff --git a/app/Livewire/Project/Application/Deployment/Show.php b/app/Livewire/Project/Application/Deployment/Show.phpindex 4e86b5c7e4..3289efe26e 100644--- a/app/Livewire/Project/Application/Deployment/Show.php+++ b/app/Livewire/Project/Application/Deployment/Show.php@@ -34,7 +34,7 @@ class Show extends Componentif (! $application) {return redirect()->route('dashboard');}- $application_deployment_queue = ApplicationDeploymentQueue::where('deployment_uuid', $deploymentUuid)->first();+ $application_deployment_queue = ApplicationDeploymentQueue::query()->where('deployment_uuid', $deploymentUuid)->first();if (! $application_deployment_queue) {return redirect()->route('project.application.deployment.index', ['project_uuid' => $project->uuid,@@ -45,6 +45,8 @@ class Show extends Component$this->application = $application;$this->application_deployment_queue = $application_deployment_queue;$this->deployment_uuid = $deploymentUuid;++ return null;}public function refreshQueue()diff --git a/app/Livewire/Project/Application/DeploymentNavbar.php b/app/Livewire/Project/Application/DeploymentNavbar.phpindex 87b40d4dc1..b88bafbd7c 100644--- a/app/Livewire/Project/Application/DeploymentNavbar.php+++ b/app/Livewire/Project/Application/DeploymentNavbar.php@@ -8,6 +8,7 @@ use App\Models\ApplicationDeploymentQueue;use App\Models\Server;use Illuminate\Support\Carbon;use Livewire\Component;+use Throwable;class DeploymentNavbar extends Component{@@ -45,9 +46,11 @@ class DeploymentNavbar extends Component{try {force_start_deployment($this->application_deployment_queue);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function cancel()@@ -57,9 +60,9 @@ class DeploymentNavbar extends Component$server_id = $this->application_deployment_queue->server_id ?? $this->application->destination->server_id;try {if ($this->application->settings->is_build_server_enabled) {- $server = Server::find($build_server_id);+ $server = Server::query()->find($build_server_id);} else {- $server = Server::find($server_id);+ $server = Server::query()->find($server_id);}if ($this->application_deployment_queue->logs) {$previous_logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR);@@ -78,7 +81,7 @@ class DeploymentNavbar extends Component]);}instant_remote_process([$kill_command], $server);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->application_deployment_queue->update([@@ -87,5 +90,7 @@ class DeploymentNavbar extends Component]);next_after_cancel($server);}++ return null;}}diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.phpindex d1cc3476cd..8622055018 100644--- a/app/Livewire/Project/Application/General.php+++ b/app/Livewire/Project/Application/General.php@@ -6,7 +6,9 @@ use App\Actions\Application\GenerateConfig;use App\Models\Application;use Illuminate\Support\Collection;use Livewire\Component;+use Livewire\Features\SupportEvents\Event;use Spatie\Url\Url;+use Throwable;use Visus\Cuid2\Cuid2;class General extends Component@@ -141,7 +143,7 @@ class General extends Componentreturn;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->dispatch('error', $e->getMessage());}if ($this->application->build_pack === 'dockercompose') {@@ -179,13 +181,11 @@ class General extends Componentif ($this->ports_exposes !== $this->application->ports_exposes || $this->is_container_label_escape_enabled !== $this->application->settings->is_container_label_escape_enabled) {$this->resetDefaultLabels(false);}- if ($this->is_preserve_repository_enabled !== $this->application->settings->is_preserve_repository_enabled) {- if ($this->application->settings->is_preserve_repository_enabled === false) {- $this->application->fileStorages->each(function ($storage) {- $storage->is_based_on_git = $this->application->settings->is_preserve_repository_enabled;- $storage->save();- });- }+ if ($this->is_preserve_repository_enabled !== $this->application->settings->is_preserve_repository_enabled && $this->application->settings->is_preserve_repository_enabled === false) {+ $this->application->fileStorages->each(function ($storage) {+ $storage->is_based_on_git = $this->application->settings->is_preserve_repository_enabled;+ $storage->save();+ });}}@@ -193,7 +193,7 @@ class General extends Component{try {if ($isInit && $this->application->docker_compose_raw) {- return;+ return null;}// Must reload the application to get the latest database changes@@ -204,14 +204,14 @@ class General extends Componentif (is_null($this->parsedServices)) {$this->dispatch('error', 'Failed to parse your docker-compose file. Please check the syntax and try again.');- return;+ return null;}$this->application->parse();$this->dispatch('success', 'Docker compose file loaded.');$this->dispatch('compose_loaded');$this->dispatch('refreshStorages');$this->dispatch('refreshEnvs');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->application->docker_compose_location = $this->initialDockerComposeLocation;$this->application->save();@@ -219,12 +219,14 @@ class General extends Component} finally {$this->initLoadingCompose = false;}++ return null;}public function generateDomain(string $serviceName){- $uuid = new Cuid2;- $domain = generateFqdn($this->application->destination->server, $uuid);+ $cuid2 = new Cuid2;+ $domain = generateFqdn($this->application->destination->server, $cuid2);$this->parsedServiceDomains[$serviceName]['domain'] = $domain;$this->application->docker_compose_domains = json_encode($this->parsedServiceDomains);$this->application->save();@@ -295,7 +297,7 @@ class General extends Component{try {if ($this->application->settings->is_container_label_readonly_enabled && ! $manualReset) {- return;+ return null;}$this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n");$this->ports_exposes = $this->application->ports_exposes;@@ -306,9 +308,11 @@ class General extends Component$this->loadComposeFile();}$this->dispatch('configurationChanged');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function checkFqdns($showToaster = true)@@ -334,14 +338,16 @@ class General extends Componentif ($has_www === 0 && $this->application->redirect === 'www') {$this->dispatch('error', 'You want to redirect to www, but you do not have a www domain set.<br><br>Please add www to your domain list and as an A DNS record (if applicable).');- return;+ return null;}$this->application->save();$this->resetDefaultLabels();$this->dispatch('success', 'Redirect updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit($showToaster = true)@@ -377,8 +383,8 @@ class General extends Componentif ($this->application->build_pack === 'dockercompose' && $this->initialDockerComposeLocation !== $this->application->docker_compose_location) {$compose_return = $this->loadComposeFile();- if ($compose_return instanceof \Livewire\Features\SupportEvents\Event) {- return;+ if ($compose_return instanceof Event) {+ return null;}}$this->validate();@@ -410,8 +416,8 @@ class General extends Componentif ($this->application->build_pack === 'dockercompose') {$this->application->docker_compose_domains = json_encode($this->parsedServiceDomains);- foreach ($this->parsedServiceDomains as $serviceName => $service) {- $domain = data_get($service, 'domain');+ foreach ($this->parsedServiceDomains as $parsedServiceDomain) {+ $domain = data_get($parsedServiceDomain, 'domain');if ($domain) {if (! validate_dns_entry($domain, $this->application->destination->server)) {$showToaster && $this->dispatch('error', 'Validating DNS failed.', "Make sure you have added the DNS records correctly.<br><br>$domain->{$this->application->destination->server->ip}<br><br>Check this <a target='_blank' class='underline dark:text-white' href='https://coolify.io/docs/knowledge-base/dns-configuration'>documentation</a> for further help.");@@ -425,8 +431,10 @@ class General extends Component}$this->application->custom_labels = base64_encode($this->customLabels);$this->application->save();- $showToaster && ! $warning && $this->dispatch('success', 'Application settings updated!');- } catch (\Throwable $e) {+ if ($showToaster && ! $warning) {+ $this->dispatch('success', 'Application settings updated!');+ }+ } catch (Throwable $e) {$originalFqdn = $this->application->getOriginal('fqdn');if ($originalFqdn !== $this->application->fqdn) {$this->application->fqdn = $originalFqdn;@@ -436,6 +444,8 @@ class General extends Component} finally {$this->dispatch('configurationChanged');}++ return null;}public function downloadConfig()diff --git a/app/Livewire/Project/Application/Heading.php b/app/Livewire/Project/Application/Heading.phpindex 0afc9123a2..26d9275dc4 100644--- a/app/Livewire/Project/Application/Heading.php+++ b/app/Livewire/Project/Application/Heading.php@@ -66,22 +66,22 @@ class Heading extends Componentif ($this->application->build_pack === 'dockercompose' && is_null($this->application->docker_compose_raw)) {$this->dispatch('error', 'Failed to deploy', 'Please load a Compose file first.');- return;+ return null;}if ($this->application->destination->server->isSwarm() && str($this->application->docker_registry_image_name)->isEmpty()) {$this->dispatch('error', 'Failed to deploy.', 'To deploy to a Swarm cluster you must set a Docker image name first.');- return;+ return null;}if (data_get($this->application, 'settings.is_build_server_enabled') && str($this->application->docker_registry_image_name)->isEmpty()) {$this->dispatch('error', 'Failed to deploy.', 'To use a build server, you must first set a Docker image.<br>More information here: <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/build-server">documentation</a>');- return;+ return null;}if ($this->application->additional_servers->count() > 0 && str($this->application->docker_registry_image_name)->isEmpty()) {$this->dispatch('error', 'Failed to deploy.', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.<br>More information here: <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/multiple-servers">documentation</a>');- return;+ return null;}$this->setDeploymentUuid();queue_application_deployment(@@ -123,7 +123,7 @@ class Heading extends Componentif ($this->application->additional_servers->count() > 0 && str($this->application->docker_registry_image_name)->isEmpty()) {$this->dispatch('error', 'Failed to deploy', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.<br>More information here: <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/multiple-servers">documentation</a>');- return;+ return null;}$this->setDeploymentUuid();queue_application_deployment(diff --git a/app/Livewire/Project/Application/Preview/Form.php b/app/Livewire/Project/Application/Preview/Form.phpindex edcab44c88..208574de97 100644--- a/app/Livewire/Project/Application/Preview/Form.php+++ b/app/Livewire/Project/Application/Preview/Form.php@@ -6,6 +6,7 @@ use App\Models\Application;use Livewire\Attributes\Validate;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class Form extends Component{@@ -19,9 +20,11 @@ class Form extends Componenttry {$this->previewUrlTemplate = $this->application->preview_url_template;$this->generateRealUrl();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -33,9 +36,11 @@ class Form extends Component$this->application->save();$this->dispatch('success', 'Preview url template updated.');$this->generateRealUrl();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function resetToDefault()@@ -46,9 +51,11 @@ class Form extends Component$this->application->save();$this->generateRealUrl();$this->dispatch('success', 'Preview url template updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function generateRealUrl()diff --git a/app/Livewire/Project/Application/Previews.php b/app/Livewire/Project/Application/Previews.phpindex bdf62706c3..16235e7ce5 100644--- a/app/Livewire/Project/Application/Previews.php+++ b/app/Livewire/Project/Application/Previews.php@@ -6,11 +6,13 @@ use App\Actions\Docker\GetContainersStatus;use App\Models\Application;use App\Models\ApplicationPreview;use Carbon\Carbon;+use Exception;use Illuminate\Process\InvokedProcess;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Process;use Livewire\Component;use Spatie\Url\Url;+use Throwable;use Visus\Cuid2\Cuid2;class Previews extends Component@@ -41,11 +43,13 @@ class Previews extends Component['rate_limit_remaining' => $rate_limit_remaining, 'data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/pulls");$this->rate_limit_remaining = $rate_limit_remaining;$this->pull_requests = $data->sortBy('number')->values();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->rate_limit_remaining = 0;return handleError($e, $this);}++ return null;}public function save_preview($preview_id)@@ -65,13 +69,19 @@ class Previews extends Component}if (! $preview) {- throw new \Exception('Preview not found');+ throw new Exception('Preview not found');+ }+ if ($success) {+ $preview->save();}- $success && $preview->save();- $success && $this->dispatch('success', 'Preview saved.<br><br>Do not forget to redeploy the preview to apply the changes.');- } catch (\Throwable $e) {+ if ($success) {+ $this->dispatch('success', 'Preview saved.<br><br>Do not forget to redeploy the preview to apply the changes.');+ }+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function generate_preview($preview_id)@@ -95,8 +105,8 @@ class Previews extends Component$template = $this->application->preview_url_template;$host = $url->getHost();$schema = $url->getScheme();- $random = new Cuid2;- $preview_fqdn = str_replace('{{random}}', $random, $template);+ $cuid2 = new Cuid2;+ $preview_fqdn = str_replace('{{random}}', $cuid2, $template);$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);$preview_fqdn = str_replace('{{pr_id}}', $preview->pull_request_id, $preview_fqdn);$preview_fqdn = "$schema://$preview_fqdn";@@ -110,9 +120,9 @@ class Previews extends Componenttry {if ($this->application->build_pack === 'dockercompose') {$this->setDeploymentUuid();- $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found && ! is_null($pull_request_html_url)) {- $found = ApplicationPreview::create([+ $found = ApplicationPreview::query()->create(['application_id' => $this->application->id,'pull_request_id' => $pull_request_id,'pull_request_html_url' => $pull_request_html_url,@@ -123,9 +133,9 @@ class Previews extends Component$this->application->refresh();} else {$this->setDeploymentUuid();- $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found && ! is_null($pull_request_html_url)) {- $found = ApplicationPreview::create([+ $found = ApplicationPreview::query()->create(['application_id' => $this->application->id,'pull_request_id' => $pull_request_id,'pull_request_html_url' => $pull_request_html_url,@@ -136,9 +146,11 @@ class Previews extends Component$this->dispatch('update_links');$this->dispatch('success', 'Preview added.');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function add_and_deploy(int $pull_request_id, ?string $pull_request_html_url = null)@@ -151,9 +163,9 @@ class Previews extends Component{try {$this->setDeploymentUuid();- $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();+ $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();if (! $found && ! is_null($pull_request_html_url)) {- ApplicationPreview::create([+ ApplicationPreview::query()->create(['application_id' => $this->application->id,'pull_request_id' => $pull_request_id,'pull_request_html_url' => $pull_request_html_url,@@ -173,7 +185,7 @@ class Previews extends Component'deployment_uuid' => $this->deployment_uuid,'environment_uuid' => $this->parameters['environment_uuid'],]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}@@ -201,9 +213,11 @@ class Previews extends Component$this->application->refresh();$this->dispatch('containerStatusUpdated');$this->dispatch('success', 'Preview Deployment stopped.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function delete(int $pull_request_id)@@ -219,7 +233,7 @@ class Previews extends Component$this->stopContainers($containers, $server, $timeout);}- ApplicationPreview::where('application_id', $this->application->id)+ ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first()->delete();@@ -227,9 +241,11 @@ class Previews extends Component$this->application->refresh();$this->dispatch('update_links');$this->dispatch('success', 'Preview deleted.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}private function stopContainers(array $containers, $server, int $timeout)@@ -241,7 +257,7 @@ class Previews extends Component}$startTime = Carbon::now()->getTimestamp();- while (count($processes) > 0) {+ while ($processes !== []) {$finishedProcesses = array_filter($processes, function ($process) {return ! $process->running();});diff --git a/app/Livewire/Project/Application/PreviewsCompose.php b/app/Livewire/Project/Application/PreviewsCompose.phpindex b3e838bb3f..cc9a016c57 100644--- a/app/Livewire/Project/Application/PreviewsCompose.php+++ b/app/Livewire/Project/Application/PreviewsCompose.php@@ -44,8 +44,8 @@ class PreviewsCompose extends Component$template = $this->preview->application->preview_url_template;$host = $url->getHost();$schema = $url->getScheme();- $random = new Cuid2;- $preview_fqdn = str_replace('{{random}}', $random, $template);+ $cuid2 = new Cuid2;+ $preview_fqdn = str_replace('{{random}}', $cuid2, $template);$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);$preview_fqdn = str_replace('{{pr_id}}', $this->preview->pull_request_id, $preview_fqdn);$preview_fqdn = "$schema://$preview_fqdn";diff --git a/app/Livewire/Project/Application/Rollback.php b/app/Livewire/Project/Application/Rollback.phpindex ff5db1e08c..fe06912fc6 100644--- a/app/Livewire/Project/Application/Rollback.php+++ b/app/Livewire/Project/Application/Rollback.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Application;use App\Models\Application;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class Rollback extends Component@@ -23,11 +24,11 @@ class Rollback extends Componentpublic function rollbackImage($commit){- $deployment_uuid = new Cuid2;+ $cuid2 = new Cuid2;queue_application_deployment(application: $this->application,- deployment_uuid: $deployment_uuid,+ deployment_uuid: $cuid2,commit: $commit,rollback: true,force_rebuild: false,@@ -36,7 +37,7 @@ class Rollback extends Componentreturn redirect()->route('project.application.deployment.show', ['project_uuid' => $this->parameters['project_uuid'],'application_uuid' => $this->parameters['application_uuid'],- 'deployment_uuid' => $deployment_uuid,+ 'deployment_uuid' => $cuid2,'environment_uuid' => $this->parameters['environment_uuid'],]);}@@ -73,7 +74,7 @@ class Rollback extends Component$showToast && $this->dispatch('success', 'Images loaded.');return [];- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/Application/Source.php b/app/Livewire/Project/Application/Source.phpindex ade297d501..bd80ba0cfe 100644--- a/app/Livewire/Project/Application/Source.php+++ b/app/Livewire/Project/Application/Source.php@@ -7,6 +7,7 @@ use App\Models\PrivateKey;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Source extends Component{@@ -35,7 +36,7 @@ class Source extends Componenttry {$this->syncData();$this->getPrivateKeys();- } catch (\Throwable $e) {+ } catch (Throwable $e) {handleError($e, $this);}}@@ -75,9 +76,11 @@ class Source extends Component$this->application->refresh();$this->privateKeyName = $this->application->private_key->name;$this->dispatch('success', 'Private key updated!');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -88,8 +91,10 @@ class Source extends Component}$this->syncData(true);$this->dispatch('success', 'Application source updated!');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Application/Swarm.php b/app/Livewire/Project/Application/Swarm.phpindex 197dc41ed3..ea3c3f7c0d 100644--- a/app/Livewire/Project/Application/Swarm.php+++ b/app/Livewire/Project/Application/Swarm.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Application;use App\Models\Application;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Swarm extends Component{@@ -23,9 +24,11 @@ class Swarm extends Component{try {$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -53,9 +56,11 @@ class Swarm extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Swarm settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -63,9 +68,11 @@ class Swarm extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Swarm settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/CloneMe.php b/app/Livewire/Project/CloneMe.phpindex 593355c443..172d1860f1 100644--- a/app/Livewire/Project/CloneMe.php+++ b/app/Livewire/Project/CloneMe.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project;use App\Models\Environment;use App\Models\Project;use App\Models\Server;+use Exception;use Livewire\Component;use Visus\Cuid2\Cuid2;@@ -43,11 +44,11 @@ class CloneMe extends Componentpublic function mount($project_uuid){$this->project_uuid = $project_uuid;- $this->project = Project::where('uuid', $project_uuid)->firstOrFail();+ $this->project = Project::query()->where('uuid', $project_uuid)->firstOrFail();$this->environment = $this->project->environments->where('uuid', $this->environment_uuid)->first();$this->project_id = $this->project->id;$this->servers = currentTeam()->servers;- $this->newName = str($this->project->name.'-clone-'.(string) new Cuid2)->slug();+ $this->newName = str($this->project->name.'-clone-'.new Cuid2)->slug();}public function render()@@ -77,11 +78,11 @@ class CloneMe extends Component'newName' => 'required',]);if ($type === 'project') {- $foundProject = Project::where('name', $this->newName)->first();+ $foundProject = Project::query()->where('name', $this->newName)->first();if ($foundProject) {- throw new \Exception('Project with the same name already exists.');+ throw new Exception('Project with the same name already exists.');}- $project = Project::create([+ $project = Project::query()->create(['name' => $this->newName,'team_id' => currentTeam()->id,'description' => $this->project->description.' (clone)',@@ -96,7 +97,7 @@ class CloneMe extends Component} else {$foundEnv = $this->project->environments()->where('name', $this->newName)->first();if ($foundEnv) {- throw new \Exception('Environment with the same name already exists.');+ throw new Exception('Environment with the same name already exists.');}$project = $this->project;$environment = $this->project->environments()->create([@@ -126,9 +127,9 @@ class CloneMe extends Component$newEnvironmentVariable->save();}$persistentVolumes = $application->persistentStorages()->get();- foreach ($persistentVolumes as $volume) {- $newPersistentVolume = $volume->replicate()->fill([- 'name' => $newApplication->uuid.'-'.str($volume->name)->afterLast('-'),+ foreach ($persistentVolumes as $persistentVolume) {+ $newPersistentVolume = $persistentVolume->replicate()->fill([+ 'name' => $newApplication->uuid.'-'.str($persistentVolume->name)->afterLast('-'),'resource_id' => $newApplication->id,]);$newPersistentVolume->save();@@ -178,7 +179,7 @@ class CloneMe extends Component'project_uuid' => $project->uuid,'environment_uuid' => $environment->uuid,]);- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/Database/Backup/Execution.php b/app/Livewire/Project/Database/Backup/Execution.phpindex 4ac3b2e2c5..35818d35c9 100644--- a/app/Livewire/Project/Database/Backup/Execution.php+++ b/app/Livewire/Project/Database/Backup/Execution.php@@ -39,6 +39,8 @@ class Execution extends Component$this->backup = $backup;$this->executions = $executions;$this->s3s = currentTeam()->s3s;++ return null;}public function render()diff --git a/app/Livewire/Project/Database/Backup/Index.php b/app/Livewire/Project/Database/Backup/Index.phpindex 2df32ec7bf..072b88a2b1 100644--- a/app/Livewire/Project/Database/Backup/Index.php+++ b/app/Livewire/Project/Database/Backup/Index.php@@ -2,6 +2,10 @@namespace App\Livewire\Project\Database\Backup;+use App\Models\StandaloneClickhouse;+use App\Models\StandaloneDragonfly;+use App\Models\StandaloneKeydb;+use App\Models\StandaloneRedis;use Livewire\Component;class Index extends Component@@ -24,10 +28,10 @@ class Index extends Component}// No backupsif (- $database->getMorphClass() === \App\Models\StandaloneRedis::class ||- $database->getMorphClass() === \App\Models\StandaloneKeydb::class ||- $database->getMorphClass() === \App\Models\StandaloneDragonfly::class ||- $database->getMorphClass() === \App\Models\StandaloneClickhouse::class+ $database->getMorphClass() === StandaloneRedis::class ||+ $database->getMorphClass() === StandaloneKeydb::class ||+ $database->getMorphClass() === StandaloneDragonfly::class ||+ $database->getMorphClass() === StandaloneClickhouse::class) {return redirect()->route('project.database.configuration', ['project_uuid' => $project->uuid,@@ -36,6 +40,8 @@ class Index extends Component]);}$this->database = $database;++ return null;}public function render()diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.phpindex 0dea0496ca..d5b05aeda7 100644--- a/app/Livewire/Project/Database/BackupEdit.php+++ b/app/Livewire/Project/Database/BackupEdit.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Database;use App\Models\InstanceSettings;use App\Models\ScheduledDatabaseBackup;+use App\Models\ServiceDatabase;use Exception;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;@@ -11,6 +12,7 @@ use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class BackupEdit extends Component{@@ -66,6 +68,8 @@ class BackupEdit extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -94,12 +98,10 @@ class BackupEdit extends Componentpublic function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}try {@@ -112,7 +114,7 @@ class BackupEdit extends Component$this->backup->delete();- if ($this->backup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($this->backup->database->getMorphClass() === ServiceDatabase::class) {$previousUrl = url()->previous();$url = Url::fromString($previousUrl);$url = $url->withoutQueryParameter('selectedBackupId');@@ -120,10 +122,10 @@ class BackupEdit extends Component$url = $url->getPath()."#{$url->getFragment()}";return redirect($url);- } else {- return redirect()->route('project.database.backup.index', $this->parameters);}- } catch (\Throwable $e) {++ return redirect()->route('project.database.backup.index', $this->parameters);+ } catch (Throwable $e) {return handleError($e, $this);}}@@ -133,7 +135,7 @@ class BackupEdit extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Backup updated successfully.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->dispatch('error', $e->getMessage());}}@@ -145,7 +147,7 @@ class BackupEdit extends Component}$isValid = validate_cron_expression($this->backup->frequency);if (! $isValid) {- throw new \Exception('Invalid Cron / Human expression');+ throw new Exception('Invalid Cron / Human expression');}$this->validate();}@@ -155,7 +157,7 @@ class BackupEdit extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Backup updated successfully.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->dispatch('error', $e->getMessage());}}@@ -166,7 +168,7 @@ class BackupEdit extends Component$backupFolder = null;foreach ($executions as $execution) {- if ($this->backup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($this->backup->database->getMorphClass() === ServiceDatabase::class) {$server = $this->backup->database->service->destination->server;} else {$server = $this->backup->database->destination->server;diff --git a/app/Livewire/Project/Database/BackupExecutions.php b/app/Livewire/Project/Database/BackupExecutions.phpindex f91b8bfaf3..090eb25640 100644--- a/app/Livewire/Project/Database/BackupExecutions.php+++ b/app/Livewire/Project/Database/BackupExecutions.php@@ -4,6 +4,10 @@ namespace App\Livewire\Project\Database;use App\Models\InstanceSettings;use App\Models\ScheduledDatabaseBackup;+use App\Models\ServiceDatabase;+use DateTime;+use DateTimeZone;+use Exception;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Component;@@ -33,7 +37,7 @@ class BackupExecutions extends Componentpublic function cleanupFailed(){- if ($this->backup) {+ if ($this->backup instanceof ScheduledDatabaseBackup) {$this->backup->executions()->where('status', 'failed')->delete();$this->refreshBackupExecutions();$this->dispatch('success', 'Failed backups cleaned up.');@@ -42,12 +46,10 @@ class BackupExecutions extends Componentpublic function deleteBackup($executionId, $password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return;}$execution = $this->backup->executions()->where('id', $executionId)->first();@@ -57,7 +59,7 @@ class BackupExecutions extends Componentreturn;}- if ($execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class) {delete_backup_locally($execution->filename, $execution->scheduledDatabaseBackup->database->service->destination->server);} else {delete_backup_locally($execution->filename, $execution->scheduledDatabaseBackup->database->destination->server);@@ -83,15 +85,15 @@ class BackupExecutions extends Componentpublic function refreshBackupExecutions(): void{- if ($this->backup) {+ if ($this->backup instanceof ScheduledDatabaseBackup) {$this->executions = $this->backup->executions()->get();}}- public function mount(ScheduledDatabaseBackup $backup)+ public function mount(ScheduledDatabaseBackup $scheduledDatabaseBackup){- $this->backup = $backup;- $this->database = $backup->database;+ $this->backup = $scheduledDatabaseBackup;+ $this->database = $scheduledDatabaseBackup->database;$this->refreshBackupExecutions();}@@ -100,7 +102,7 @@ class BackupExecutions extends Componentif ($this->database) {$server = null;- if ($this->database instanceof \App\Models\ServiceDatabase) {+ if ($this->database instanceof ServiceDatabase) {$server = $this->database->service->destination->server;} elseif ($this->database->destination && $this->database->destination->server) {$server = $this->database->destination->server;@@ -126,11 +128,11 @@ class BackupExecutions extends Componentpublic function formatDateInServerTimezone($date){$serverTimezone = $this->getServerTimezone();- $dateObj = new \DateTime($date);+ $dateObj = new DateTime($date);try {- $dateObj->setTimezone(new \DateTimeZone($serverTimezone));- } catch (\Exception) {- $dateObj->setTimezone(new \DateTimeZone('UTC'));+ $dateObj->setTimezone(new DateTimeZone($serverTimezone));+ } catch (Exception) {+ $dateObj->setTimezone(new DateTimeZone('UTC'));}return $dateObj->format('Y-m-d H:i:s T');diff --git a/app/Livewire/Project/Database/Clickhouse/General.php b/app/Livewire/Project/Database/Clickhouse/General.phpindex 2d39c5151f..1bbce0ac41 100644--- a/app/Livewire/Project/Database/Clickhouse/General.php+++ b/app/Livewire/Project/Database/Clickhouse/General.php@@ -10,6 +10,7 @@ use Exception;use Illuminate\Support\Facades\Auth;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class General extends Component{@@ -67,9 +68,11 @@ class General extends Componenttry {$this->syncData();$this->server = data_get($this->database, 'destination.server');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -113,7 +116,7 @@ class General extends Component$this->isLogDrainEnabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->syncData(true);@@ -122,6 +125,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -131,14 +136,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->isPublic = false;- return;+ return null;}if ($this->isPublic) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->isPublic = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -148,12 +153,14 @@ class General extends Component}$this->dbUrlPublic = $this->database->external_db_url;$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isPublic = ! $this->isPublic;$this->syncData(true);return handleError($e, $this);}++ return null;}public function databaseProxyStopped()@@ -178,5 +185,7 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}}diff --git a/app/Livewire/Project/Database/CreateScheduledBackup.php b/app/Livewire/Project/Database/CreateScheduledBackup.phpindex 01108c2900..fa7d9f4af9 100644--- a/app/Livewire/Project/Database/CreateScheduledBackup.php+++ b/app/Livewire/Project/Database/CreateScheduledBackup.php@@ -3,10 +3,12 @@namespace App\Livewire\Project\Database;use App\Models\ScheduledDatabaseBackup;+use App\Models\ServiceDatabase;use Illuminate\Support\Collection;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class CreateScheduledBackup extends Component{@@ -33,9 +35,11 @@ class CreateScheduledBackup extends Componentif ($this->definedS3s->count() > 0) {$this->s3StorageId = $this->definedS3s->first()->id;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -47,7 +51,7 @@ class CreateScheduledBackup extends Componentif (! $isValid) {$this->dispatch('error', 'Invalid Cron / Human expression.');- return;+ return null;}$payload = [@@ -68,17 +72,19 @@ class CreateScheduledBackup extends Component$payload['databases_to_backup'] = $this->database->mariadb_database;}- $databaseBackup = ScheduledDatabaseBackup::create($payload);- if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ $databaseBackup = ScheduledDatabaseBackup::query()->create($payload);+ if ($this->database->getMorphClass() === ServiceDatabase::class) {$this->dispatch('refreshScheduledBackups', $databaseBackup->id);} else {$this->dispatch('refreshScheduledBackups');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->frequency = '';}++ return null;}}diff --git a/app/Livewire/Project/Database/Dragonfly/General.php b/app/Livewire/Project/Database/Dragonfly/General.phpindex ea6cd46b04..b5b85fee29 100644--- a/app/Livewire/Project/Database/Dragonfly/General.php+++ b/app/Livewire/Project/Database/Dragonfly/General.php@@ -10,6 +10,7 @@ use Exception;use Illuminate\Support\Facades\Auth;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class General extends Component{@@ -64,9 +65,11 @@ class General extends Componenttry {$this->syncData();$this->server = data_get($this->database, 'destination.server');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -108,7 +111,7 @@ class General extends Component$this->isLogDrainEnabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->syncData(true);@@ -117,6 +120,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -126,14 +131,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->isPublic = false;- return;+ return null;}if ($this->isPublic) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->isPublic = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -143,12 +148,14 @@ class General extends Component}$this->dbUrlPublic = $this->database->external_db_url;$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isPublic = ! $this->isPublic;$this->syncData(true);return handleError($e, $this);}++ return null;}public function databaseProxyStopped()@@ -173,5 +180,7 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}}diff --git a/app/Livewire/Project/Database/Import.php b/app/Livewire/Project/Database/Import.phpindex dc330b3af8..699f0be6cc 100644--- a/app/Livewire/Project/Database/Import.php+++ b/app/Livewire/Project/Database/Import.php@@ -3,9 +3,18 @@namespace App\Livewire\Project\Database;use App\Models\Server;+use App\Models\StandaloneClickhouse;+use App\Models\StandaloneDragonfly;+use App\Models\StandaloneKeydb;+use App\Models\StandaloneMariadb;+use App\Models\StandaloneMongodb;+use App\Models\StandaloneMysql;+use App\Models\StandalonePostgresql;+use App\Models\StandaloneRedis;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Storage;use Livewire\Component;+use Throwable;class Import extends Component{@@ -72,7 +81,7 @@ class Import extends Componentpublic function updatedDumpAll($value){switch ($this->resource->getMorphClass()) {- case \App\Models\StandaloneMariadb::class:+ case StandaloneMariadb::class:if ($value === true) {$this->mariadbRestoreCommand = <<<'EOD'for pid in $(mariadb -u root -p$MARIADB_ROOT_PASSWORD -N -e "SELECT id FROM information_schema.processlist WHERE user != 'root';"); do@@ -87,7 +96,7 @@ EOD;$this->mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE';}break;- case \App\Models\StandaloneMysql::class:+ case StandaloneMysql::class:if ($value === true) {$this->mysqlRestoreCommand = <<<'EOD'for pid in $(mysql -u root -p$MYSQL_ROOT_PASSWORD -N -e "SELECT id FROM information_schema.processlist WHERE user != 'root';"); do@@ -102,7 +111,7 @@ EOD;$this->mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE';}break;- case \App\Models\StandalonePostgresql::class:+ case StandalonePostgresql::class:if ($value === true) {$this->postgresqlRestoreCommand = <<<'EOD'psql -U $POSTGRES_USER -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" && \@@ -136,10 +145,10 @@ EOD;}if (- $this->resource->getMorphClass() === \App\Models\StandaloneRedis::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneKeydb::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneDragonfly::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneClickhouse::class+ $this->resource->getMorphClass() === StandaloneRedis::class ||+ $this->resource->getMorphClass() === StandaloneKeydb::class ||+ $this->resource->getMorphClass() === StandaloneDragonfly::class ||+ $this->resource->getMorphClass() === StandaloneClickhouse::class) {$this->unsupported = true;}@@ -153,14 +162,16 @@ EOD;if (blank($result)) {$this->dispatch('error', 'The file does not exist or has been deleted.');- return;+ return null;}$this->filename = $this->customLocation;$this->dispatch('success', 'The file exists.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}++ return null;}public function runImport()@@ -168,7 +179,7 @@ EOD;if ($this->filename === '') {$this->dispatch('error', 'Please select a file to import.');- return;+ return null;}try {$this->importCommands = [];@@ -182,7 +193,7 @@ EOD;if (! Storage::exists($backupFileName)) {$this->dispatch('error', 'The file does not exist or has been deleted.');- return;+ return null;}$tmpPath = '/tmp/'.basename($backupFileName).'_'.$this->resource->uuid;instant_scp($path, $tmpPath, $this->server);@@ -194,7 +205,7 @@ EOD;$scriptPath = "/tmp/restore_{$this->resource->uuid}.sh";switch ($this->resource->getMorphClass()) {- case \App\Models\StandaloneMariadb::class:+ case StandaloneMariadb::class:$restoreCommand = $this->mariadbRestoreCommand;if ($this->dumpAll) {$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mariadb -u root -p\$MARIADB_ROOT_PASSWORD";@@ -202,7 +213,7 @@ EOD;$restoreCommand .= " < {$tmpPath}";}break;- case \App\Models\StandaloneMysql::class:+ case StandaloneMysql::class:$restoreCommand = $this->mysqlRestoreCommand;if ($this->dumpAll) {$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mysql -u root -p\$MYSQL_ROOT_PASSWORD";@@ -210,7 +221,7 @@ EOD;$restoreCommand .= " < {$tmpPath}";}break;- case \App\Models\StandalonePostgresql::class:+ case StandalonePostgresql::class:$restoreCommand = $this->postgresqlRestoreCommand;if ($this->dumpAll) {$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | psql -U \$POSTGRES_USER postgres";@@ -218,7 +229,7 @@ EOD;$restoreCommand .= " {$tmpPath}";}break;- case \App\Models\StandaloneMongodb::class:+ case StandaloneMongodb::class:$restoreCommand = $this->mongodbRestoreCommand;if ($this->dumpAll === false) {$restoreCommand .= " {$tmpPath}";@@ -234,7 +245,7 @@ EOD;$this->importCommands[] = "docker exec {$this->container} sh -c '{$scriptPath}'";$this->importCommands[] = "docker exec {$this->container} sh -c 'echo \"Import finished with exit code $?\"'";- if (! empty($this->importCommands)) {+ if ($this->importCommands !== []) {$activity = remote_process($this->importCommands, $this->server, ignore_errors: true, callEventOnFinish: 'RestoreJobFinished', callEventData: ['scriptPath' => $scriptPath,'tmpPath' => $tmpPath,@@ -243,11 +254,13 @@ EOD;]);$this->dispatch('activityMonitor', $activity->id);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->filename = null;$this->importCommands = [];}++ return null;}}diff --git a/app/Livewire/Project/Database/InitScript.php b/app/Livewire/Project/Database/InitScript.phpindex e3baa1c8ee..06b3138c53 100644--- a/app/Livewire/Project/Database/InitScript.php+++ b/app/Livewire/Project/Database/InitScript.php@@ -30,6 +30,8 @@ class InitScript extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -43,6 +45,8 @@ class InitScript extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function delete()@@ -52,5 +56,7 @@ class InitScript extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Database/Keydb/General.php b/app/Livewire/Project/Database/Keydb/General.phpindex e768495eb8..fbeb66fc4c 100644--- a/app/Livewire/Project/Database/Keydb/General.php+++ b/app/Livewire/Project/Database/Keydb/General.php@@ -10,6 +10,7 @@ use Exception;use Illuminate\Support\Facades\Auth;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class General extends Component{@@ -67,9 +68,11 @@ class General extends Componenttry {$this->syncData();$this->server = data_get($this->database, 'destination.server');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -113,7 +116,7 @@ class General extends Component$this->isLogDrainEnabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->syncData(true);@@ -122,6 +125,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -131,14 +136,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->isPublic = false;- return;+ return null;}if ($this->isPublic) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->isPublic = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -148,12 +153,14 @@ class General extends Component}$this->dbUrlPublic = $this->database->external_db_url;$this->syncData(true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isPublic = ! $this->isPublic;$this->syncData(true);return handleError($e, $this);}++ return null;}public function databaseProxyStopped()@@ -178,5 +185,7 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}}diff --git a/app/Livewire/Project/Database/Mariadb/General.php b/app/Livewire/Project/Database/Mariadb/General.phpindex c9d473223f..38a81026b9 100644--- a/app/Livewire/Project/Database/Mariadb/General.php+++ b/app/Livewire/Project/Database/Mariadb/General.php@@ -8,6 +8,7 @@ use App\Models\Server;use App\Models\StandaloneMariadb;use Exception;use Livewire\Component;+use Throwable;class General extends Component{@@ -66,7 +67,7 @@ class General extends Component$this->database->is_log_drain_enabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->database->save();$this->dispatch('success', 'Database updated.');@@ -74,6 +75,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -94,6 +97,8 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}public function instantSave()@@ -103,14 +108,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->database->is_public = false;- return;+ return null;}if ($this->database->is_public) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->database->is_public = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -120,11 +125,13 @@ class General extends Component}$this->db_url_public = $this->database->external_db_url;$this->database->save();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->database->is_public = ! $this->database->is_public;return handleError($e, $this);}++ return null;}public function refresh(): voiddiff --git a/app/Livewire/Project/Database/Mongodb/General.php b/app/Livewire/Project/Database/Mongodb/General.phpindex e19895dae6..1cc777022d 100644--- a/app/Livewire/Project/Database/Mongodb/General.php+++ b/app/Livewire/Project/Database/Mongodb/General.php@@ -8,6 +8,7 @@ use App\Models\Server;use App\Models\StandaloneMongodb;use Exception;use Livewire\Component;+use Throwable;class General extends Component{@@ -64,7 +65,7 @@ class General extends Component$this->database->is_log_drain_enabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->database->save();$this->dispatch('success', 'Database updated.');@@ -72,6 +73,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -95,6 +98,8 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}public function instantSave()@@ -104,14 +109,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->database->is_public = false;- return;+ return null;}if ($this->database->is_public) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->database->is_public = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -121,11 +126,13 @@ class General extends Component}$this->db_url_public = $this->database->external_db_url;$this->database->save();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->database->is_public = ! $this->database->is_public;return handleError($e, $this);}++ return null;}public function refresh(): voiddiff --git a/app/Livewire/Project/Database/Mysql/General.php b/app/Livewire/Project/Database/Mysql/General.phpindex 7d5270ddf5..afcb8077f0 100644--- a/app/Livewire/Project/Database/Mysql/General.php+++ b/app/Livewire/Project/Database/Mysql/General.php@@ -8,6 +8,7 @@ use App\Models\Server;use App\Models\StandaloneMysql;use Exception;use Livewire\Component;+use Throwable;class General extends Component{@@ -66,7 +67,7 @@ class General extends Component$this->database->is_log_drain_enabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->database->save();$this->dispatch('success', 'Database updated.');@@ -74,6 +75,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -94,6 +97,8 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}public function instantSave()@@ -103,14 +108,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->database->is_public = false;- return;+ return null;}if ($this->database->is_public) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->database->is_public = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -120,11 +125,13 @@ class General extends Component}$this->db_url_public = $this->database->external_db_url;$this->database->save();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->database->is_public = ! $this->database->is_public;return handleError($e, $this);}++ return null;}public function refresh(): voiddiff --git a/app/Livewire/Project/Database/Postgresql/General.php b/app/Livewire/Project/Database/Postgresql/General.phpindex 88dd5c1a86..17502f8171 100644--- a/app/Livewire/Project/Database/Postgresql/General.php+++ b/app/Livewire/Project/Database/Postgresql/General.php@@ -8,6 +8,7 @@ use App\Models\Server;use App\Models\StandalonePostgresql;use Exception;use Livewire\Component;+use Throwable;class General extends Component{@@ -81,7 +82,7 @@ class General extends Component$this->database->is_log_drain_enabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->database->save();$this->dispatch('success', 'Database updated.');@@ -89,6 +90,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -98,14 +101,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->database->is_public = false;- return;+ return null;}if ($this->database->is_public) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->database->is_public = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -115,11 +118,13 @@ class General extends Component}$this->db_url_public = $this->database->external_db_url;$this->database->save();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->database->is_public = ! $this->database->is_public;return handleError($e, $this);}++ return null;}public function save_init_script($script)@@ -143,7 +148,7 @@ class General extends Component$delete_command = "rm -f $old_file_path";try {instant_remote_process([$delete_command], $this->server);- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', 'Failed to remove old init script from server: '.$e->getMessage());return;@@ -184,7 +189,7 @@ class General extends Component$command = "rm -f $file_path";try {instant_remote_process([$command], $this->server);- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', 'Failed to remove init script from server: '.$e->getMessage());return;@@ -223,7 +228,7 @@ class General extends Componentreturn;}- if (! isset($this->database->init_scripts)) {+ if (! property_exists($this->database, 'init_scripts') || $this->database->init_scripts === null) {$this->database->init_scripts = [];}$this->database->init_scripts = array_merge($this->database->init_scripts, [@@ -257,5 +262,7 @@ class General extends Component$this->dispatch('configurationChanged');}}++ return null;}}diff --git a/app/Livewire/Project/Database/Redis/General.php b/app/Livewire/Project/Database/Redis/General.phpindex 25a96b2926..ff7e55a66f 100644--- a/app/Livewire/Project/Database/Redis/General.php+++ b/app/Livewire/Project/Database/Redis/General.php@@ -8,6 +8,7 @@ use App\Models\Server;use App\Models\StandaloneRedis;use Exception;use Livewire\Component;+use Throwable;class General extends Component{@@ -70,7 +71,7 @@ class General extends Component$this->database->is_log_drain_enabled = false;$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');- return;+ return null;}$this->database->save();$this->dispatch('success', 'Database updated.');@@ -78,6 +79,8 @@ class General extends Component} catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -103,6 +106,8 @@ class General extends Component} finally {$this->dispatch('refreshEnvs');}++ return null;}public function instantSave()@@ -112,14 +117,14 @@ class General extends Component$this->dispatch('error', 'Public port is required.');$this->database->is_public = false;- return;+ return null;}if ($this->database->is_public) {if (! str($this->database->status)->startsWith('running')) {$this->dispatch('error', 'Database must be started to be publicly accessible.');$this->database->is_public = false;- return;+ return null;}StartDatabaseProxy::run($this->database);$this->dispatch('success', 'Database is now publicly accessible.');@@ -129,11 +134,13 @@ class General extends Component}$this->db_url_public = $this->database->external_db_url;$this->database->save();- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->database->is_public = ! $this->database->is_public;return handleError($e, $this);}++ return null;}public function refresh(): voiddiff --git a/app/Livewire/Project/Database/ScheduledBackups.php b/app/Livewire/Project/Database/ScheduledBackups.phpindex 412240bd4e..a6fa103b8d 100644--- a/app/Livewire/Project/Database/ScheduledBackups.php+++ b/app/Livewire/Project/Database/ScheduledBackups.php@@ -3,6 +3,7 @@namespace App\Livewire\Project\Database;use App\Models\ScheduledDatabaseBackup;+use App\Models\ServiceDatabase;use Livewire\Component;class ScheduledBackups extends Component@@ -29,11 +30,7 @@ class ScheduledBackups extends Component$this->setSelectedBackup($this->selectedBackupId, true);}$this->parameters = get_route_parameters();- if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) {- $this->type = 'service-database';- } else {- $this->type = 'database';- }+ $this->type = $this->database->getMorphClass() === ServiceDatabase::class ? 'service-database' : 'database';$this->s3s = currentTeam()->s3s;}diff --git a/app/Livewire/Project/DeleteEnvironment.php b/app/Livewire/Project/DeleteEnvironment.phpindex 1ee5de2691..e27b89be88 100644--- a/app/Livewire/Project/DeleteEnvironment.php+++ b/app/Livewire/Project/DeleteEnvironment.php@@ -3,6 +3,7 @@namespace App\Livewire\Project;use App\Models\Environment;+use Exception;use Livewire\Component;class DeleteEnvironment extends Component@@ -18,11 +19,13 @@ class DeleteEnvironment extends Componentpublic function mount(){try {- $this->environmentName = Environment::findOrFail($this->environment_id)->name;+ $this->environmentName = Environment::query()->findOrFail($this->environment_id)->name;$this->parameters = get_route_parameters();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function delete()@@ -30,7 +33,7 @@ class DeleteEnvironment extends Component$this->validate(['environment_id' => 'required|int',]);- $environment = Environment::findOrFail($this->environment_id);+ $environment = Environment::query()->findOrFail($this->environment_id);if ($environment->isEmpty()) {$environment->delete();diff --git a/app/Livewire/Project/DeleteProject.php b/app/Livewire/Project/DeleteProject.phpindex f320a19b0f..bade13e6fb 100644--- a/app/Livewire/Project/DeleteProject.php+++ b/app/Livewire/Project/DeleteProject.php@@ -18,7 +18,7 @@ class DeleteProject extends Componentpublic function mount(){$this->parameters = get_route_parameters();- $this->projectName = Project::findOrFail($this->project_id)->name;+ $this->projectName = Project::query()->findOrFail($this->project_id)->name;}public function delete()@@ -26,7 +26,7 @@ class DeleteProject extends Component$this->validate(['project_id' => 'required|int',]);- $project = Project::findOrFail($this->project_id);+ $project = Project::query()->findOrFail($this->project_id);if ($project->isEmpty()) {$project->delete();diff --git a/app/Livewire/Project/Edit.php b/app/Livewire/Project/Edit.phpindex 463febb10d..c9f83304b0 100644--- a/app/Livewire/Project/Edit.php+++ b/app/Livewire/Project/Edit.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project;use App\Models\Project;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Edit extends Component{@@ -19,11 +20,13 @@ class Edit extends Componentpublic function mount(string $project_uuid){try {- $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();+ $this->project = Project::query()->where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -45,8 +48,10 @@ class Edit extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Project updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/EnvironmentEdit.php b/app/Livewire/Project/EnvironmentEdit.phpindex e98b088ecf..7e93a5fcac 100644--- a/app/Livewire/Project/EnvironmentEdit.php+++ b/app/Livewire/Project/EnvironmentEdit.php@@ -7,6 +7,7 @@ use App\Models\Project;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class EnvironmentEdit extends Component{@@ -29,9 +30,11 @@ class EnvironmentEdit extends Component$this->project = Project::ownedByCurrentTeam()->where('uuid', $project_uuid)->firstOrFail();$this->environment = $this->project->environments()->where('uuid', $environment_uuid)->firstOrFail();$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncData(bool $toModel = false)@@ -56,9 +59,11 @@ class EnvironmentEdit extends Component'environment_uuid' => $this->environment->uuid,'project_uuid' => $this->project->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Index.php b/app/Livewire/Project/Index.phpindex 06bf88219b..75597d8f5c 100644--- a/app/Livewire/Project/Index.php+++ b/app/Livewire/Project/Index.php@@ -34,7 +34,7 @@ class Index extends Componentpublic function navigateToProject($projectUuid){- $project = Project::where('uuid', $projectUuid)->first();+ $project = Project::query()->where('uuid', $projectUuid)->first();if ($project && $project->environments->count() === 1) {return Redirect::route('project.resource.index', [diff --git a/app/Livewire/Project/New/DockerCompose.php b/app/Livewire/Project/New/DockerCompose.phpindex 27975eaa2b..d8425e34fe 100644--- a/app/Livewire/Project/New/DockerCompose.php+++ b/app/Livewire/Project/New/DockerCompose.php@@ -7,9 +7,11 @@ use App\Models\Project;use App\Models\Service;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Illuminate\Support\Str;use Livewire\Component;use Symfony\Component\Yaml\Yaml;+use Throwable;class DockerCompose extends Component{@@ -58,20 +60,20 @@ class DockerCompose extends Componentreturn $this->dispatch('error', "Invalid docker-compose file.\n$isValid");}- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();+ $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();$destination_uuid = $this->query['destination'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();- $service = Service::create([+ $service = Service::query()->create(['name' => 'service'.Str::random(10),'docker_compose_raw' => $this->dockerComposeRaw,'environment_id' => $environment->id,@@ -82,7 +84,7 @@ class DockerCompose extends Component$variables = parseEnvFormatToArray($this->envFile);foreach ($variables as $key => $variable) {- EnvironmentVariable::create([+ EnvironmentVariable::query()->create(['key' => $key,'value' => $variable,'is_build_time' => false,@@ -100,7 +102,7 @@ class DockerCompose extends Component'environment_uuid' => $environment->uuid,'project_uuid' => $project->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/New/DockerImage.php b/app/Livewire/Project/New/DockerImage.phpindex 9429244377..cd8f7c4ece 100644--- a/app/Livewire/Project/New/DockerImage.php+++ b/app/Livewire/Project/New/DockerImage.php@@ -6,6 +6,7 @@ use App\Models\Application;use App\Models\Project;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Livewire\Component;use Visus\Cuid2\Cuid2;@@ -28,32 +29,28 @@ class DockerImage extends Component$this->validate(['dockerImage' => 'required',]);- $image = str($this->dockerImage)->before(':');- if (str($this->dockerImage)->contains(':')) {- $tag = str($this->dockerImage)->after(':');- } else {- $tag = 'latest';- }+ $stringable = str($this->dockerImage)->before(':');+ $tag = str($this->dockerImage)->contains(':') ? str($this->dockerImage)->after(':') : 'latest';$destination_uuid = $this->query['destination'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();+ $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();- $application = Application::create([+ $application = Application::query()->create(['name' => 'docker-image-'.new Cuid2,'repository_project_id' => 0,'git_repository' => 'coollabsio/coolify','git_branch' => 'main','build_pack' => 'dockerimage','ports_exposes' => 80,- 'docker_registry_image_name' => $image,+ 'docker_registry_image_name' => $stringable,'docker_registry_image_tag' => $tag,'environment_id' => $environment->id,'destination_id' => $destination->id,diff --git a/app/Livewire/Project/New/EmptyProject.php b/app/Livewire/Project/New/EmptyProject.phpindex 54cfc4b4d8..2f1eda3f7f 100644--- a/app/Livewire/Project/New/EmptyProject.php+++ b/app/Livewire/Project/New/EmptyProject.php@@ -10,7 +10,7 @@ class EmptyProject extends Component{public function createEmptyProject(){- $project = Project::create([+ $project = Project::query()->create(['name' => generate_random_name(),'team_id' => currentTeam()->id,'uuid' => (string) new Cuid2,diff --git a/app/Livewire/Project/New/GithubPrivateRepository.php b/app/Livewire/Project/New/GithubPrivateRepository.phpindex 370d005557..3363e596bd 100644--- a/app/Livewire/Project/New/GithubPrivateRepository.php+++ b/app/Livewire/Project/New/GithubPrivateRepository.php@@ -7,9 +7,11 @@ use App\Models\GithubApp;use App\Models\Project;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Route;use Livewire\Component;+use Throwable;class GithubPrivateRepository extends Component{@@ -104,7 +106,7 @@ class GithubPrivateRepository extends Component$this->repositories = collect();$this->page = 1;$this->selected_github_app_id = $github_app_id;- $this->github_app = GithubApp::where('id', $github_app_id)->first();+ $this->github_app = GithubApp::query()->where('id', $github_app_id)->first();$this->token = generate_github_installation_token($this->github_app);$this->loadRepositoryByPage();if ($this->repositories->count() < $this->total_repositories_count) {@@ -129,10 +131,12 @@ class GithubPrivateRepository extends Component}if ($json['total_count'] === 0) {- return;+ return null;}$this->total_repositories_count = $json['total_count'];$this->repositories = $this->repositories->concat(collect($json['repositories']));++ return null;}public function loadBranches()@@ -161,25 +165,27 @@ class GithubPrivateRepository extends Component$this->total_branches_count = count($json);$this->branches = $this->branches->concat(collect($json));++ return null;}public function submit(){try {$destination_uuid = $this->query['destination'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();+ $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();- $application = Application::create([+ $application = Application::query()->create(['name' => generate_application_name($this->selected_repository_owner.'/'.$this->selected_repository_repo, $this->selected_branch_name),'repository_project_id' => $this->selected_repository_id,'git_repository' => "{$this->selected_repository_owner}/{$this->selected_repository_repo}",@@ -214,7 +220,7 @@ class GithubPrivateRepository extends Component'environment_uuid' => $environment->uuid,'project_uuid' => $project->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.phpindex 01b0c9ae85..74ef258734 100644--- a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php+++ b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php@@ -9,9 +9,11 @@ use App\Models\PrivateKey;use App\Models\Project;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Illuminate\Support\Str;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class GithubPrivateRepositoryDeployKey extends Component{@@ -81,9 +83,9 @@ class GithubPrivateRepositoryDeployKey extends Component$this->parameters = get_route_parameters();$this->query = request()->query();if (isDev()) {- $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->get();+ $this->private_keys = PrivateKey::query()->where('team_id', currentTeam()->id)->get();} else {- $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->where('id', '!=', 0)->get();+ $this->private_keys = PrivateKey::query()->where('team_id', currentTeam()->id)->where('id', '!=', 0)->get();}}@@ -124,18 +126,18 @@ class GithubPrivateRepositoryDeployKey extends Component$this->validate();try {$destination_uuid = $this->query['destination'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();$this->get_git_source();- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();+ $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();if ($this->git_source === 'other') {$application_init = [@@ -173,7 +175,7 @@ class GithubPrivateRepositoryDeployKey extends Component$application_init['docker_compose_location'] = $this->docker_compose_location;$application_init['base_directory'] = $this->base_directory;}- $application = Application::create($application_init);+ $application = Application::query()->create($application_init);$application->settings->is_static = $this->is_static;$application->settings->save();@@ -187,7 +189,7 @@ class GithubPrivateRepositoryDeployKey extends Component'environment_uuid' => $environment->uuid,'project_uuid' => $project->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}@@ -199,7 +201,7 @@ class GithubPrivateRepositoryDeployKey extends Component$this->git_repository = $this->repository_url_parsed->getSegment(1).'/'.$this->repository_url_parsed->getSegment(2);if ($this->git_host === 'github.com') {- $this->git_source = GithubApp::where('name', 'Public GitHub')->first();+ $this->git_source = GithubApp::query()->where('name', 'Public GitHub')->first();return;}diff --git a/app/Livewire/Project/New/PublicGitRepository.php b/app/Livewire/Project/New/PublicGitRepository.phpindex 2f2331fc00..31866c936f 100644--- a/app/Livewire/Project/New/PublicGitRepository.php+++ b/app/Livewire/Project/New/PublicGitRepository.php@@ -10,8 +10,10 @@ use App\Models\Service;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;use Carbon\Carbon;+use Exception;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class PublicGitRepository extends Component{@@ -93,7 +95,7 @@ class PublicGitRepository extends Componentpublic function updatedBaseDirectory(){- if ($this->base_directory) {+ if ($this->base_directory !== '' && $this->base_directory !== '0') {$this->base_directory = rtrim($this->base_directory, '/');if (! str($this->base_directory)->startsWith('/')) {$this->base_directory = '/'.$this->base_directory;@@ -153,12 +155,12 @@ class PublicGitRepository extends Component(! str($this->repository_url)->contains('github.com') ||! str($this->repository_url)->contains('git.sr.ht'))) {- $this->repository_url = $this->repository_url.'.git';+ $this->repository_url .= '.git';}if (str($this->repository_url)->contains('github.com') && str($this->repository_url)->endsWith('.git')) {$this->repository_url = str($this->repository_url)->beforeLast('.git')->value();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}try {@@ -166,24 +168,26 @@ class PublicGitRepository extends Component$this->getGitSource();$this->getBranch();$this->selectedBranch = $this->git_branch;- } catch (\Throwable $e) {+ } catch (Throwable $e) {if ($this->rate_limit_remaining == 0) {$this->selectedBranch = $this->git_branch;$this->branchFound = true;- return;+ return null;}if (! $this->branchFound && $this->git_branch === 'main') {try {$this->git_branch = 'master';$this->getBranch();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}} else {return handleError($e, $this);}}++ return null;}private function getGitSource()@@ -197,7 +201,7 @@ class PublicGitRepository extends Component$this->git_branch = 'main';}if ($this->git_host === 'github.com') {- $this->git_source = GithubApp::where('name', 'Public GitHub')->first();+ $this->git_source = GithubApp::query()->where('name', 'Public GitHub')->first();return;}@@ -212,7 +216,7 @@ class PublicGitRepository extends Componentreturn;}- if ($this->git_source->getMorphClass() === \App\Models\GithubApp::class) {+ if ($this->git_source->getMorphClass() === GithubApp::class) {['rate_limit_remaining' => $this->rate_limit_remaining, 'rate_limit_reset' => $this->rate_limit_reset] = githubApi(source: $this->git_source, endpoint: "/repos/{$this->git_repository}/branches/{$this->git_branch}");$this->rate_limit_reset = Carbon::parse((int) $this->rate_limit_reset)->format('Y-M-d H:i:s');$this->branchFound = true;@@ -227,16 +231,16 @@ class PublicGitRepository extends Component$project_uuid = $this->parameters['project_uuid'];$environment_uuid = $this->parameters['environment_uuid'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();- $project = Project::where('uuid', $project_uuid)->first();+ $project = Project::query()->where('uuid', $project_uuid)->first();$environment = $project->load(['environments'])->environments->where('uuid', $environment_uuid)->first();if ($this->build_pack === 'dockercompose' && isDev() && $this->new_compose_services) {@@ -256,15 +260,13 @@ class PublicGitRepository extends Component$new_service['source_id'] = $this->git_source->id;$new_service['source_type'] = $this->git_source->getMorphClass();}- $service = Service::create($new_service);+ $service = Service::query()->create($new_service);return redirect()->route('project.service.configuration', ['service_uuid' => $service->uuid,'environment_uuid' => $environment->uuid,'project_uuid' => $project->uuid,]);-- return;}if ($this->git_source === 'other') {$application_init = [@@ -303,7 +305,7 @@ class PublicGitRepository extends Component$application_init['docker_compose_location'] = $this->docker_compose_location;$application_init['base_directory'] = $this->base_directory;}- $application = Application::create($application_init);+ $application = Application::query()->create($application_init);$application->settings->is_static = $this->isStatic;$application->settings->save();@@ -322,7 +324,7 @@ class PublicGitRepository extends Component'environment_uuid' => $environment->uuid,'project_uuid' => $project->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/New/Select.php b/app/Livewire/Project/New/Select.phpindex b645a89150..e05f53230e 100644--- a/app/Livewire/Project/New/Select.php+++ b/app/Livewire/Project/New/Select.php@@ -205,12 +205,10 @@ class Select extends Component{if ($this->includeSwarm) {$this->servers = $this->allServers;+ } elseif ($this->allServers instanceof Collection) {+ $this->servers = $this->allServers->where('settings.is_swarm_worker', false)->where('settings.is_swarm_manager', false)->where('settings.is_build_server', false);} else {- if ($this->allServers instanceof Collection) {- $this->servers = $this->allServers->where('settings.is_swarm_worker', false)->where('settings.is_swarm_manager', false)->where('settings.is_build_server', false);- } else {- $this->servers = $this->allServers;- }+ $this->servers = $this->allServers;}}@@ -218,7 +216,7 @@ class Select extends Component{$type = str($type)->lower()->slug()->value();if ($this->loading) {- return;+ return null;}$this->loading = true;$this->type = $type;@@ -252,7 +250,7 @@ class Select extends Componentif ($type === 'existing-postgresql') {$this->current_step = $type;- return;+ return null;}if (count($this->servers) === 1) {$server = $this->servers->first();@@ -267,6 +265,8 @@ class Select extends Component}}$this->current_step = 'servers';++ return null;}public function setServer(Server $server)@@ -285,6 +285,8 @@ class Select extends Component}}$this->current_step = 'destinations';++ return null;}public function setDestination(string $destination_uuid)@@ -321,6 +323,8 @@ class Select extends Component'server_id' => $this->server_id,]);}++ return null;}public function loadServers()diff --git a/app/Livewire/Project/New/SimpleDockerfile.php b/app/Livewire/Project/New/SimpleDockerfile.phpindex c3ed6039a0..f40c36bac1 100644--- a/app/Livewire/Project/New/SimpleDockerfile.php+++ b/app/Livewire/Project/New/SimpleDockerfile.php@@ -7,6 +7,7 @@ use App\Models\GithubApp;use App\Models\Project;use App\Models\StandaloneDocker;use App\Models\SwarmDocker;+use Exception;use Livewire\Component;use Visus\Cuid2\Cuid2;@@ -36,23 +37,23 @@ CMD ["nginx", "-g", "daemon off;"]'dockerfile' => 'required',]);$destination_uuid = $this->query['destination'];- $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();+ $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();if (! $destination) {- $destination = SwarmDocker::where('uuid', $destination_uuid)->first();+ $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();}if (! $destination) {- throw new \Exception('Destination not found. What?!');+ throw new Exception('Destination not found. What?!');}$destination_class = $destination->getMorphClass();- $project = Project::where('uuid', $this->parameters['project_uuid'])->first();+ $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();$port = get_port_from_dockerfile($this->dockerfile);if (! $port) {$port = 80;}- $application = Application::create([+ $application = Application::query()->create(['name' => 'dockerfile-'.new Cuid2,'repository_project_id' => 0,'git_repository' => 'coollabsio/coolify',diff --git a/app/Livewire/Project/Resource/Create.php b/app/Livewire/Project/Resource/Create.phpindex 0faf0b8da2..ac177b0b37 100644--- a/app/Livewire/Project/Resource/Create.php+++ b/app/Livewire/Project/Resource/Create.php@@ -67,7 +67,7 @@ class Create extends Component$oneClickDotEnvs = data_get($services, "$oneClickServiceName.envs", null);if ($oneClickDotEnvs) {$oneClickDotEnvs = str(base64_decode($oneClickDotEnvs))->split('/\r\n|\r|\n/')->filter(function ($value) {- return ! empty($value);+ return $value !== '' && $value !== '0';});}if ($oneClickService) {@@ -84,7 +84,7 @@ class Create extends Componentif ($oneClickServiceName === 'cloudflared') {data_set($service_payload, 'connect_to_docker_network', true);}- $service = Service::create($service_payload);+ $service = Service::query()->create($service_payload);$service->name = "$oneClickServiceName-".$service->uuid;$service->save();if ($oneClickDotEnvs?->count() > 0) {@@ -92,7 +92,7 @@ class Create extends Component$key = str()->before($value, '=');$value = str(str()->after($value, '='));if ($value) {- EnvironmentVariable::create([+ EnvironmentVariable::query()->create(['key' => $key,'value' => $value,'resourceable_id' => $service->id,@@ -114,6 +114,8 @@ class Create extends Component}$this->type = $type->value();}++ return null;}public function render()diff --git a/app/Livewire/Project/Resource/EnvironmentSelect.php b/app/Livewire/Project/Resource/EnvironmentSelect.phpindex a38d750daa..e7c2c2bd61 100644--- a/app/Livewire/Project/Resource/EnvironmentSelect.php+++ b/app/Livewire/Project/Resource/EnvironmentSelect.php@@ -25,11 +25,11 @@ class EnvironmentSelect extends Componentreturn redirect()->route('project.show', ['project_uuid' => $this->project_uuid,]);- } else {- return redirect()->route('project.resource.index', [- 'project_uuid' => $this->project_uuid,- 'environment_uuid' => $value,- ]);}++ return redirect()->route('project.resource.index', [+ 'project_uuid' => $this->project_uuid,+ 'environment_uuid' => $value,+ ]);}}diff --git a/app/Livewire/Project/Service/Configuration.php b/app/Livewire/Project/Service/Configuration.phpindex 4a5e8627fa..a1f1d0aa5a 100644--- a/app/Livewire/Project/Service/Configuration.php+++ b/app/Livewire/Project/Service/Configuration.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Service;use App\Actions\Docker\GetContainersStatus;use App\Models\Service;+use Exception;use Illuminate\Support\Facades\Auth;use Livewire\Component;@@ -71,9 +72,11 @@ class Configuration extends Component$application->restart();$this->dispatch('success', 'Service application restarted successfully.');}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function restartDatabase($id)@@ -84,9 +87,11 @@ class Configuration extends Component$database->restart();$this->dispatch('success', 'Service database restarted successfully.');}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function check_status()@@ -100,8 +105,10 @@ class Configuration extends Component$database->refresh();});$this->dispatch('$refresh');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Service/Database.php b/app/Livewire/Project/Service/Database.phpindex 9f02db05c8..88bedd3b4b 100644--- a/app/Livewire/Project/Service/Database.php+++ b/app/Livewire/Project/Service/Database.php@@ -6,6 +6,7 @@ use App\Actions\Database\StartDatabaseProxy;use App\Actions\Database\StopDatabaseProxy;use App\Models\ServiceDatabase;use Livewire\Component;+use Throwable;class Database extends Component{@@ -95,7 +96,7 @@ class Database extends Component$this->database->save();updateCompose($this->database);$this->dispatch('success', 'Database saved.');- } catch (\Throwable) {+ } catch (Throwable) {} finally {$this->dispatch('generateDockerCompose');}diff --git a/app/Livewire/Project/Service/EditCompose.php b/app/Livewire/Project/Service/EditCompose.phpindex dc043e65ad..3b8b7d1556 100644--- a/app/Livewire/Project/Service/EditCompose.php+++ b/app/Livewire/Project/Service/EditCompose.php@@ -31,12 +31,12 @@ class EditCompose extends Componentpublic function refreshEnvs(){- $this->service = Service::find($this->serviceId);+ $this->service = Service::query()->find($this->serviceId);}public function mount(){- $this->service = Service::find($this->serviceId);+ $this->service = Service::query()->find($this->serviceId);}public function saveEditedCompose()diff --git a/app/Livewire/Project/Service/EditDomain.php b/app/Livewire/Project/Service/EditDomain.phpindex e89aeda85f..dbc5ca2ff9 100644--- a/app/Livewire/Project/Service/EditDomain.php+++ b/app/Livewire/Project/Service/EditDomain.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Service;use App\Models\ServiceApplication;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class EditDomain extends Component{@@ -19,7 +20,7 @@ class EditDomain extends Componentpublic function mount(){- $this->application = ServiceApplication::find($this->applicationId);+ $this->application = ServiceApplication::query()->find($this->applicationId);}public function submit()@@ -43,13 +44,13 @@ class EditDomain extends ComponentupdateCompose($this->application);if (str($this->application->fqdn)->contains(',')) {$this->dispatch('warning', 'Some services do not support multiple domains, which can lead to problems and is NOT RECOMMENDED.<br><br>Only use multiple domains if you know what you are doing.');- } else {- ! $warning && $this->dispatch('success', 'Service saved.');+ } elseif (! $warning) {+ $this->dispatch('success', 'Service saved.');}$this->application->service->parse();$this->dispatch('refresh');$this->dispatch('configurationChanged');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$originalFqdn = $this->application->getOriginal('fqdn');if ($originalFqdn !== $this->application->fqdn) {$this->application->fqdn = $originalFqdn;@@ -57,6 +58,8 @@ class EditDomain extends Componentreturn handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Service/FileStorage.php b/app/Livewire/Project/Service/FileStorage.phpindex 4d070bc0cc..83b05acb15 100644--- a/app/Livewire/Project/Service/FileStorage.php+++ b/app/Livewire/Project/Service/FileStorage.php@@ -18,6 +18,7 @@ use App\Models\StandaloneRedis;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Component;+use Throwable;class FileStorage extends Component{@@ -61,11 +62,13 @@ class FileStorage extends Component$this->fileStorage->is_based_on_git = false;$this->fileStorage->save();$this->fileStorage->saveStorageOnServer();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refreshStorages');}++ return null;}public function convertToFile()@@ -79,21 +82,21 @@ class FileStorage extends Component}$this->fileStorage->save();$this->fileStorage->saveStorageOnServer();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refreshStorages');}++ return null;}public function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}try {@@ -107,11 +110,13 @@ class FileStorage extends Component}$this->fileStorage->delete();$this->dispatch('success', $message);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->dispatch('refreshStorages');}++ return null;}public function submit()@@ -125,12 +130,14 @@ class FileStorage extends Component$this->fileStorage->save();$this->fileStorage->saveStorageOnServer();$this->dispatch('success', 'File updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->fileStorage->setRawAttributes($original);$this->fileStorage->save();return handleError($e, $this);}++ return null;}public function instantSave()diff --git a/app/Livewire/Project/Service/Index.php b/app/Livewire/Project/Service/Index.phpindex ba4ebe2fca..38a2aad2d1 100644--- a/app/Livewire/Project/Service/Index.php+++ b/app/Livewire/Project/Service/Index.php@@ -7,6 +7,7 @@ use App\Models\ServiceApplication;use App\Models\ServiceDatabase;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class Index extends Component{@@ -45,9 +46,11 @@ class Index extends Component$this->serviceDatabase->getFilesFromServer();}$this->s3s = currentTeam()->s3s;- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function generateDockerCompose()diff --git a/app/Livewire/Project/Service/Navbar.php b/app/Livewire/Project/Service/Navbar.phpindex 22fc1c0d6b..0fc9207795 100644--- a/app/Livewire/Project/Service/Navbar.php+++ b/app/Livewire/Project/Service/Navbar.php@@ -10,6 +10,7 @@ use App\Models\Service;use Illuminate\Support\Facades\Auth;use Livewire\Component;use Spatie\Activitylog\Models\Activity;+use Throwable;class Navbar extends Component{@@ -70,14 +71,10 @@ class Navbar extends Componenttry {// TODO: This is a temporary solution. We need to refactor this.// We need to delete null bytes somehow.- $activity = Activity::where('properties->type_uuid', $this->service->uuid)->latest()->first();+ $activity = Activity::query()->where('properties->type_uuid', $this->service->uuid)->latest()->first();$status = data_get($activity, 'properties.status');- if ($status === 'queued' || $status === 'in_progress') {- $this->isDeploymentProgress = true;- } else {- $this->isDeploymentProgress = false;- }- } catch (\Throwable) {+ $this->isDeploymentProgress = $status === 'queued' || $status === 'in_progress';+ } catch (Throwable) {$this->isDeploymentProgress = false;}}diff --git a/app/Livewire/Project/Service/ServiceApplicationView.php b/app/Livewire/Project/Service/ServiceApplicationView.phpindex 8324ee645c..a3e417567b 100644--- a/app/Livewire/Project/Service/ServiceApplicationView.php+++ b/app/Livewire/Project/Service/ServiceApplicationView.php@@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Component;use Spatie\Url\Url;+use Throwable;class ServiceApplicationView extends Component{@@ -50,12 +51,10 @@ class ServiceApplicationView extends Componentpublic function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}try {@@ -63,7 +62,7 @@ class ServiceApplicationView extends Component$this->dispatch('success', 'Application deleted.');return redirect()->route('project.service.configuration', $this->parameters);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}@@ -94,11 +93,11 @@ class ServiceApplicationView extends ComponentupdateCompose($this->application);if (str($this->application->fqdn)->contains(',')) {$this->dispatch('warning', 'Some services do not support multiple domains, which can lead to problems and is NOT RECOMMENDED.<br><br>Only use multiple domains if you know what you are doing.');- } else {- ! $warning && $this->dispatch('success', 'Service saved.');+ } elseif (! $warning) {+ $this->dispatch('success', 'Service saved.');}$this->dispatch('generateDockerCompose');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$originalFqdn = $this->application->getOriginal('fqdn');if ($originalFqdn !== $this->application->fqdn) {$this->application->fqdn = $originalFqdn;@@ -106,6 +105,8 @@ class ServiceApplicationView extends Componentreturn handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Service/StackForm.php b/app/Livewire/Project/Service/StackForm.phpindex 2c751aa92a..2ee43cb578 100644--- a/app/Livewire/Project/Service/StackForm.php+++ b/app/Livewire/Project/Service/StackForm.php@@ -3,8 +3,10 @@namespace App\Livewire\Project\Service;use App\Models\Service;+use Exception;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class StackForm extends Component{@@ -78,7 +80,7 @@ class StackForm extends Component$this->validate();$isValid = validateComposeFile($this->service->docker_compose_raw, $this->service->server->id);if ($isValid !== 'OK') {- throw new \Exception("Invalid docker-compose file.\n$isValid");+ throw new Exception("Invalid docker-compose file.\n$isValid");}$this->service->save();$this->service->saveExtraFields($this->fields);@@ -87,7 +89,7 @@ class StackForm extends Component$this->service->saveComposeConfigs();$this->dispatch('refreshEnvs');$notify && $this->dispatch('success', 'Service saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {if (is_null($this->service->config_hash)) {@@ -96,6 +98,8 @@ class StackForm extends Component$this->dispatch('configurationChanged');}}++ return null;}public function render()diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.phpindex 4b64a8b5ef..5fc83058d9 100644--- a/app/Livewire/Project/Service/Storage.php+++ b/app/Livewire/Project/Service/Storage.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Service;use App\Models\LocalPersistentVolume;use Livewire\Component;+use Throwable;class Storage extends Component{@@ -42,7 +43,7 @@ class Storage extends Componentpublic function addNewVolume($data){try {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => $data['name'],'mount_path' => $data['mount_path'],'host_path' => $data['host_path'],@@ -53,9 +54,11 @@ class Storage extends Component$this->dispatch('success', 'Storage added successfully');$this->dispatch('clearAddStorage');$this->dispatch('refreshStorages');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Shared/Danger.php b/app/Livewire/Project/Shared/Danger.phpindex 7da48f9fb4..014bd21afa 100644--- a/app/Livewire/Project/Shared/Danger.php+++ b/app/Livewire/Project/Shared/Danger.php@@ -10,6 +10,7 @@ use App\Models\ServiceDatabase;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class Danger extends Component@@ -43,10 +44,10 @@ class Danger extends Componentif ($this->resource === null) {if (isset($parameters['service_uuid'])) {- $this->resource = Service::where('uuid', $parameters['service_uuid'])->first();+ $this->resource = Service::query()->where('uuid', $parameters['service_uuid'])->first();} elseif (isset($parameters['stack_service_uuid'])) {- $this->resource = ServiceApplication::where('uuid', $parameters['stack_service_uuid'])->first()- ?? ServiceDatabase::where('uuid', $parameters['stack_service_uuid'])->first();+ $this->resource = ServiceApplication::query()->where('uuid', $parameters['stack_service_uuid'])->first()+ ?? ServiceDatabase::query()->where('uuid', $parameters['stack_service_uuid'])->first();}}@@ -81,18 +82,16 @@ class Danger extends Componentpublic function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}if (! $this->resource) {$this->addError('resource', 'Resource not found.');- return;+ return null;}try {@@ -109,7 +108,7 @@ class Danger extends Component'project_uuid' => $this->projectUuid,'environment_uuid' => $this->environmentUuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Project/Shared/Destination.php b/app/Livewire/Project/Shared/Destination.phpindex 1759fe08ac..0096bc9896 100644--- a/app/Livewire/Project/Shared/Destination.php+++ b/app/Livewire/Project/Shared/Destination.php@@ -8,6 +8,7 @@ use App\Events\ApplicationStatusChanged;use App\Models\InstanceSettings;use App\Models\Server;use App\Models\StandaloneDocker;+use Exception;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;@@ -63,9 +64,11 @@ class Destination extends Component$server = Server::ownedByCurrentTeam()->findOrFail($serverId);StopApplicationOneServer::run($this->resource, $server);$this->refreshServers();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function redeploy(int $network_id, int $server_id)@@ -74,13 +77,13 @@ class Destination extends Componentif ($this->resource->additional_servers->count() > 0 && str($this->resource->docker_registry_image_name)->isEmpty()) {$this->dispatch('error', 'Failed to deploy.', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.<br>More information here: <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/multiple-servers">documentation</a>');- return;+ return null;}- $deployment_uuid = new Cuid2;+ $cuid2 = new Cuid2;$server = Server::ownedByCurrentTeam()->findOrFail($server_id);$destination = $server->standaloneDockers->where('id', $network_id)->firstOrFail();queue_application_deployment(- deployment_uuid: $deployment_uuid,+ deployment_uuid: $cuid2,application: $this->resource,server: $server,destination: $destination,@@ -91,10 +94,10 @@ class Destination extends Componentreturn redirect()->route('project.application.deployment.show', ['project_uuid' => data_get($this->resource, 'environment.project.uuid'),'application_uuid' => data_get($this->resource, 'uuid'),- 'deployment_uuid' => $deployment_uuid,+ 'deployment_uuid' => $cuid2,'environment_uuid' => data_get($this->resource, 'environment.uuid'),]);- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}}@@ -130,26 +133,26 @@ class Destination extends Componentpublic function removeServer(int $network_id, int $server_id, $password){try {- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}if ($this->resource->destination->server->id == $server_id && $this->resource->destination->id == $network_id) {$this->dispatch('error', 'You cannot remove this destination server.', 'You are trying to remove the main server.');- return;+ return null;}$server = Server::ownedByCurrentTeam()->findOrFail($server_id);StopApplicationOneServer::run($this->resource, $server);$this->resource->additional_networks()->detach($network_id, ['server_id' => $server_id]);$this->loadData();ApplicationStatusChanged::dispatch(data_get($this->resource, 'environment.project.team.id'));- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/All.php b/app/Livewire/Project/Shared/EnvironmentVariable/All.phpindex 80156bf65a..db9184ba4a 100644--- a/app/Livewire/Project/Shared/EnvironmentVariable/All.php+++ b/app/Livewire/Project/Shared/EnvironmentVariable/All.php@@ -2,8 +2,10 @@namespace App\Livewire\Project\Shared\EnvironmentVariable;+use App\Models\Application;use App\Models\EnvironmentVariable;use Livewire\Component;+use Throwable;class All extends Component{@@ -31,7 +33,7 @@ class All extends Component{$this->is_env_sorting_enabled = data_get($this->resource, 'settings.is_env_sorting_enabled', false);$this->resourceClass = get_class($this->resource);- $resourceWithPreviews = [\App\Models\Application::class];+ $resourceWithPreviews = [Application::class];$simpleDockerfile = filled(data_get($this->resource, 'dockerfile'));if (str($this->resourceClass)->contains($resourceWithPreviews) && ! $simpleDockerfile) {$this->showPreview = true;@@ -101,11 +103,13 @@ class All extends Component$this->updateOrder();$this->sortEnvironmentVariables();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->refreshEnvs();}++ return null;}private function updateOrder()@@ -167,17 +171,17 @@ class All extends Componentprivate function createEnvironmentVariable($data){- $environment = new EnvironmentVariable;- $environment->key = $data['key'];- $environment->value = $data['value'];- $environment->is_build_time = $data['is_build_time'] ?? false;- $environment->is_multiline = $data['is_multiline'] ?? false;- $environment->is_literal = $data['is_literal'] ?? false;- $environment->is_preview = $data['is_preview'] ?? false;- $environment->resourceable_id = $this->resource->id;- $environment->resourceable_type = $this->resource->getMorphClass();-- return $environment;+ $environmentVariable = new EnvironmentVariable;+ $environmentVariable->key = $data['key'];+ $environmentVariable->value = $data['value'];+ $environmentVariable->is_build_time = $data['is_build_time'] ?? false;+ $environmentVariable->is_multiline = $data['is_multiline'] ?? false;+ $environmentVariable->is_literal = $data['is_literal'] ?? false;+ $environmentVariable->is_preview = $data['is_preview'] ?? false;+ $environmentVariable->resourceable_id = $this->resource->id;+ $environmentVariable->resourceable_type = $this->resource->getMorphClass();++ return $environmentVariable;}private function deleteRemovedVariables($isPreview, $variables)diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php b/app/Livewire/Project/Shared/EnvironmentVariable/Show.phpindex 4b66bfdcb6..7d588a55b1 100644--- a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php+++ b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Shared\EnvironmentVariable;use App\Models\EnvironmentVariable as ModelsEnvironmentVariable;use App\Models\SharedEnvironmentVariable;+use Exception;use Livewire\Component;class Show extends Component@@ -60,7 +61,7 @@ class Show extends Componentpublic function mount(){$this->syncData();- if ($this->env->getMorphClass() === \App\Models\SharedEnvironmentVariable::class) {+ if ($this->env->getMorphClass() === SharedEnvironmentVariable::class) {$this->isSharedVariable = true;}$this->parameters = get_route_parameters();@@ -116,7 +117,7 @@ class Show extends Componentpublic function serialize(){data_forget($this->env, 'real_value');- if ($this->env->getMorphClass() === \App\Models\SharedEnvironmentVariable::class) {+ if ($this->env->getMorphClass() === SharedEnvironmentVariable::class) {data_forget($this->env, 'is_build_time');}}@@ -156,7 +157,7 @@ class Show extends Component$this->value = $oldValue;$this->dispatch('error', 'Required environment variable cannot be empty.');- return;+ return null;}$this->serialize();@@ -168,9 +169,11 @@ class Show extends Component$this->syncData(true);$this->dispatch('success', 'Environment variable updated.');$this->dispatch('envsUpdated');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function delete()@@ -179,8 +182,10 @@ class Show extends Component$this->env->delete();$this->dispatch('environmentVariableDeleted');$this->dispatch('success', 'Environment variable deleted successfully.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}}diff --git a/app/Livewire/Project/Shared/ExecuteContainerCommand.php b/app/Livewire/Project/Shared/ExecuteContainerCommand.phpindex d12d8e26a9..9b6610e99a 100644--- a/app/Livewire/Project/Shared/ExecuteContainerCommand.php+++ b/app/Livewire/Project/Shared/ExecuteContainerCommand.php@@ -6,8 +6,11 @@ use App\Models\Application;use App\Models\Server;use App\Models\Service;use Illuminate\Support\Collection;+use InvalidArgumentException;use Livewire\Attributes\On;use Livewire\Component;+use RuntimeException;+use Throwable;class ExecuteContainerCommand extends Component{@@ -43,7 +46,7 @@ class ExecuteContainerCommand extends Component$this->servers = collect();if (data_get($this->parameters, 'application_uuid')) {$this->type = 'application';- $this->resource = Application::where('uuid', $this->parameters['application_uuid'])->firstOrFail();+ $this->resource = Application::query()->where('uuid', $this->parameters['application_uuid'])->firstOrFail();if ($this->resource->destination->server->isFunctional()) {$this->servers = $this->servers->push($this->resource->destination->server);}@@ -66,14 +69,14 @@ class ExecuteContainerCommand extends Component$this->loadContainers();} elseif (data_get($this->parameters, 'service_uuid')) {$this->type = 'service';- $this->resource = Service::where('uuid', $this->parameters['service_uuid'])->firstOrFail();+ $this->resource = Service::query()->where('uuid', $this->parameters['service_uuid'])->firstOrFail();if ($this->resource->server->isFunctional()) {$this->servers = $this->servers->push($this->resource->server);}$this->loadContainers();} elseif (data_get($this->parameters, 'server_uuid')) {$this->type = 'server';- $this->resource = Server::where('uuid', $this->parameters['server_uuid'])->firstOrFail();+ $this->resource = Server::query()->where('uuid', $this->parameters['server_uuid'])->firstOrFail();$this->server = $this->resource;}}@@ -146,7 +149,7 @@ class ExecuteContainerCommand extends Component{try {if ($this->server->isForceDisabled()) {- throw new \RuntimeException('Server is disabled.');+ throw new RuntimeException('Server is disabled.');}$this->dispatch('send-terminal-command',@@ -154,9 +157,11 @@ class ExecuteContainerCommand extends Componentdata_get($this->server, 'name'),data_get($this->server, 'uuid'));- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}#[On('connectToContainer')]@@ -165,28 +170,28 @@ class ExecuteContainerCommand extends Componentif ($this->selected_container === 'default') {$this->dispatch('error', 'Please select a container.');- return;+ return null;}try {// Validate container name formatif (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $this->selected_container)) {- throw new \InvalidArgumentException('Invalid container name format');+ throw new InvalidArgumentException('Invalid container name format');}// Verify container exists in our allowed list$container = collect($this->containers)->firstWhere('container.Names', $this->selected_container);if (is_null($container)) {- throw new \RuntimeException('Container not found.');+ throw new RuntimeException('Container not found.');}// Verify server ownership and status$server = data_get($container, 'server');if (! $server || ! $server instanceof Server) {- throw new \RuntimeException('Invalid server configuration.');+ throw new RuntimeException('Invalid server configuration.');}if ($server->isForceDisabled()) {- throw new \RuntimeException('Server is disabled.');+ throw new RuntimeException('Server is disabled.');}// Additional ownership verification based on resource type@@ -194,11 +199,11 @@ class ExecuteContainerCommand extends Component'application' => $this->resource->destination->server,'database' => $this->resource->destination->server,'service' => $this->resource->server,- default => throw new \RuntimeException('Invalid resource type.')+ default => throw new RuntimeException('Invalid resource type.')};if ($server->id !== $resourceServer->id && ! $this->resource->additional_servers->contains('id', $server->id)) {- throw new \RuntimeException('Server ownership verification failed.');+ throw new RuntimeException('Server ownership verification failed.');}$this->dispatch(@@ -207,9 +212,11 @@ class ExecuteContainerCommand extends Componentdata_get($container, 'container.Names'),data_get($container, 'server.uuid'));- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Shared/GetLogs.php b/app/Livewire/Project/Shared/GetLogs.phpindex 43fd97c341..992bf6619d 100644--- a/app/Livewire/Project/Shared/GetLogs.php+++ b/app/Livewire/Project/Shared/GetLogs.php@@ -44,19 +44,15 @@ class GetLogs extends Componentpublic function mount(){if (! is_null($this->resource)) {- if ($this->resource->getMorphClass() === \App\Models\Application::class) {+ if ($this->resource->getMorphClass() === Application::class) {$this->showTimeStamps = $this->resource->settings->is_include_timestamps;+ } elseif ($this->servicesubtype) {+ $this->showTimeStamps = $this->servicesubtype->is_include_timestamps;} else {- if ($this->servicesubtype) {- $this->showTimeStamps = $this->servicesubtype->is_include_timestamps;- } else {- $this->showTimeStamps = $this->resource->is_include_timestamps;- }+ $this->showTimeStamps = $this->resource->is_include_timestamps;}- if ($this->resource?->getMorphClass() === \App\Models\Application::class) {- if (str($this->container)->contains('-pr-')) {- $this->pull_request = 'Pull Request: '.str($this->container)->afterLast('-pr-')->beforeLast('_')->value();- }+ if ($this->resource?->getMorphClass() === Application::class && str($this->container)->contains('-pr-')) {+ $this->pull_request = 'Pull Request: '.str($this->container)->afterLast('-pr-')->beforeLast('_')->value();}}}@@ -69,11 +65,11 @@ class GetLogs extends Componentpublic function instantSave(){if (! is_null($this->resource)) {- if ($this->resource->getMorphClass() === \App\Models\Application::class) {+ if ($this->resource->getMorphClass() === Application::class) {$this->resource->settings->is_include_timestamps = $this->showTimeStamps;$this->resource->settings->save();}- if ($this->resource->getMorphClass() === \App\Models\Service::class) {+ if ($this->resource->getMorphClass() === Service::class) {$serviceName = str($this->container)->beforeLast('-')->value();$subType = $this->resource->applications()->where('name', $serviceName)->first();if ($subType) {@@ -95,7 +91,7 @@ class GetLogs extends Componentif (! $this->server->isFunctional()) {return;}- if (! $refresh && ($this->resource?->getMorphClass() === \App\Models\Service::class || str($this->container)->contains('-pr-'))) {+ if (! $refresh && ($this->resource?->getMorphClass() === Service::class || str($this->container)->contains('-pr-'))) {return;}if ($this->numberOfLines <= 0 || is_null($this->numberOfLines)) {@@ -118,22 +114,20 @@ class GetLogs extends Component}$sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);}+ } elseif ($this->server->isSwarm()) {+ $command = "docker service logs -n {$this->numberOfLines} {$this->container}";+ if ($this->server->isNonRoot()) {+ $command = parseCommandsByLineForSudo(collect($command), $this->server);+ $command = $command[0];+ }+ $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);} else {- if ($this->server->isSwarm()) {- $command = "docker service logs -n {$this->numberOfLines} {$this->container}";- if ($this->server->isNonRoot()) {- $command = parseCommandsByLineForSudo(collect($command), $this->server);- $command = $command[0];- }- $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);- } else {- $command = "docker logs -n {$this->numberOfLines} {$this->container}";- if ($this->server->isNonRoot()) {- $command = parseCommandsByLineForSudo(collect($command), $this->server);- $command = $command[0];- }- $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);+ $command = "docker logs -n {$this->numberOfLines} {$this->container}";+ if ($this->server->isNonRoot()) {+ $command = parseCommandsByLineForSudo(collect($command), $this->server);+ $command = $command[0];}+ $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);}if ($refresh) {$this->outputs = '';diff --git a/app/Livewire/Project/Shared/HealthChecks.php b/app/Livewire/Project/Shared/HealthChecks.phpindex 83162e36a2..027869f70c 100644--- a/app/Livewire/Project/Shared/HealthChecks.php+++ b/app/Livewire/Project/Shared/HealthChecks.php@@ -3,6 +3,7 @@namespace App\Livewire\Project\Shared;use Livewire\Component;+use Throwable;class HealthChecks extends Component{@@ -37,9 +38,11 @@ class HealthChecks extends Component$this->validate();$this->resource->save();$this->dispatch('success', 'Health check updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Shared/Logs.php b/app/Livewire/Project/Shared/Logs.phpindex 12022b1eeb..acc5480a53 100644--- a/app/Livewire/Project/Shared/Logs.php+++ b/app/Livewire/Project/Shared/Logs.php@@ -12,6 +12,7 @@ use App\Models\StandaloneMongodb;use App\Models\StandaloneMysql;use App\Models\StandalonePostgresql;use App\Models\StandaloneRedis;+use Exception;use Illuminate\Support\Collection;use Livewire\Component;@@ -42,7 +43,7 @@ class Logs extends Componenttry {$server = $this->servers->firstWhere('id', $server_id);if (! $server->isFunctional()) {- return;+ return null;}if ($server->isSwarm()) {$containers = collect([@@ -54,9 +55,11 @@ class Logs extends Component$containers = getCurrentApplicationContainerStatus($server, $this->resource->id, includePullrequests: true);}$server->containers = $containers->sort();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function mount()@@ -68,7 +71,7 @@ class Logs extends Component$this->query = request()->query();if (data_get($this->parameters, 'application_uuid')) {$this->type = 'application';- $this->resource = Application::where('uuid', $this->parameters['application_uuid'])->firstOrFail();+ $this->resource = Application::query()->where('uuid', $this->parameters['application_uuid'])->firstOrFail();$this->status = $this->resource->status;if ($this->resource->destination->server->isFunctional()) {$this->servers = $this->servers->push($this->resource->destination->server);@@ -93,7 +96,7 @@ class Logs extends Component$this->containers->push($this->container);} elseif (data_get($this->parameters, 'service_uuid')) {$this->type = 'service';- $this->resource = Service::where('uuid', $this->parameters['service_uuid'])->firstOrFail();+ $this->resource = Service::query()->where('uuid', $this->parameters['service_uuid'])->firstOrFail();$this->resource->applications()->get()->each(function ($application) {$this->containers->push(data_get($application, 'name').'-'.data_get($this->resource, 'uuid'));});@@ -110,9 +113,11 @@ class Logs extends Componentreturn str_contains($container, $this->query['pull_request_id']);});}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Shared/Metrics.php b/app/Livewire/Project/Shared/Metrics.phpindex fdc35fc0fb..052da00f26 100644--- a/app/Livewire/Project/Shared/Metrics.php+++ b/app/Livewire/Project/Shared/Metrics.php@@ -3,6 +3,7 @@namespace App\Livewire\Project\Shared;use Livewire\Component;+use Throwable;class Metrics extends Component{@@ -39,9 +40,11 @@ class Metrics extends Component$this->dispatch("refreshChartData-{$this->chartId}-memory", ['seriesData' => $memoryMetrics,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function setInterval()diff --git a/app/Livewire/Project/Shared/ResourceLimits.php b/app/Livewire/Project/Shared/ResourceLimits.phpindex 608dfbf022..e7c03f4eeb 100644--- a/app/Livewire/Project/Shared/ResourceLimits.php+++ b/app/Livewire/Project/Shared/ResourceLimits.php@@ -3,6 +3,7 @@namespace App\Livewire\Project\Shared;use Livewire\Component;+use Throwable;class ResourceLimits extends Component{@@ -55,8 +56,10 @@ class ResourceLimits extends Component$this->validate();$this->resource->save();$this->dispatch('success', 'Resource limits updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Shared/ResourceOperations.php b/app/Livewire/Project/Shared/ResourceOperations.phpindex c6a32f0c7a..421e16deb7 100644--- a/app/Livewire/Project/Shared/ResourceOperations.php+++ b/app/Livewire/Project/Shared/ResourceOperations.php@@ -2,11 +2,21 @@namespace App\Livewire\Project\Shared;+use App\Models\Application;use App\Models\Environment;use App\Models\Project;+use App\Models\StandaloneClickhouse;use App\Models\StandaloneDocker;+use App\Models\StandaloneDragonfly;+use App\Models\StandaloneKeydb;+use App\Models\StandaloneMariadb;+use App\Models\StandaloneMongodb;+use App\Models\StandaloneMysql;+use App\Models\StandalonePostgresql;+use App\Models\StandaloneRedis;use App\Models\SwarmDocker;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class ResourceOperations extends Component@@ -32,18 +42,17 @@ class ResourceOperations extends Componentpublic function cloneTo($destination_id){- $new_destination = StandaloneDocker::find($destination_id);+ $new_destination = StandaloneDocker::query()->find($destination_id);if (! $new_destination) {- $new_destination = SwarmDocker::find($destination_id);+ $new_destination = SwarmDocker::query()->find($destination_id);}if (! $new_destination) {return $this->addError('destination_id', 'Destination not found.');}$uuid = (string) new Cuid2;$server = $new_destination->server;- if ($this->resource->getMorphClass() === \App\Models\Application::class) {+ if ($this->resource->getMorphClass() === Application::class) {$name = 'clone-of-'.str($this->resource->name)->limit(20).'-'.$uuid;-$new_resource = $this->resource->replicate()->fill(['uuid' => $uuid,'name' => $name,@@ -66,12 +75,12 @@ class ResourceOperations extends Component$newEnvironmentVariable->save();}$persistentVolumes = $this->resource->persistentStorages()->get();- foreach ($persistentVolumes as $volume) {- $volumeName = str($volume->name)->replace($this->resource->uuid, $new_resource->uuid)->value();- if ($volumeName === $volume->name) {- $volumeName = $new_resource->uuid.'-'.str($volume->name)->afterLast('-');+ foreach ($persistentVolumes as $persistentVolume) {+ $volumeName = str($persistentVolume->name)->replace($this->resource->uuid, $new_resource->uuid)->value();+ if ($volumeName === $persistentVolume->name) {+ $volumeName = $new_resource->uuid.'-'.str($persistentVolume->name)->afterLast('-');}- $newPersistentVolume = $volume->replicate()->fill([+ $newPersistentVolume = $persistentVolume->replicate()->fill(['name' => $volumeName,'resource_id' => $new_resource->id,]);@@ -84,16 +93,15 @@ class ResourceOperations extends Component]).'#resource-operations';return redirect()->to($route);- } elseif (- $this->resource->getMorphClass() === \App\Models\StandalonePostgresql::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneMongodb::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneMysql::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneMariadb::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneRedis::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneKeydb::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneDragonfly::class ||- $this->resource->getMorphClass() === \App\Models\StandaloneClickhouse::class- ) {+ }+ if ($this->resource->getMorphClass() === StandalonePostgresql::class ||+ $this->resource->getMorphClass() === StandaloneMongodb::class ||+ $this->resource->getMorphClass() === StandaloneMysql::class ||+ $this->resource->getMorphClass() === StandaloneMariadb::class ||+ $this->resource->getMorphClass() === StandaloneRedis::class ||+ $this->resource->getMorphClass() === StandaloneKeydb::class ||+ $this->resource->getMorphClass() === StandaloneDragonfly::class ||+ $this->resource->getMorphClass() === StandaloneClickhouse::class) {$uuid = (string) new Cuid2;$new_resource = $this->resource->replicate()->fill(['uuid' => $uuid,@@ -127,7 +135,8 @@ class ResourceOperations extends Component]).'#resource-operations';return redirect()->to($route);- } elseif ($this->resource->type() === 'service') {+ }+ if ($this->resource->type() === 'service') {$uuid = (string) new Cuid2;$new_resource = $this->resource->replicate()->fill(['uuid' => $uuid,@@ -154,12 +163,14 @@ class ResourceOperations extends Componentreturn redirect()->to($route);}++ return null;}public function moveTo($environment_id){try {- $new_environment = Environment::findOrFail($environment_id);+ $new_environment = Environment::query()->findOrFail($environment_id);$this->resource->update(['environment_id' => $environment_id,]);@@ -171,7 +182,8 @@ class ResourceOperations extends Component]).'#resource-operations';return redirect()->to($route);- } elseif (str($this->resource->type())->startsWith('standalone-')) {+ }+ if (str($this->resource->type())->startsWith('standalone-')) {$route = route('project.database.configuration', ['project_uuid' => $new_environment->project->uuid,'environment_uuid' => $new_environment->uuid,@@ -179,7 +191,8 @@ class ResourceOperations extends Component]).'#resource-operations';return redirect()->to($route);- } elseif ($this->resource->type() === 'service') {+ }+ if ($this->resource->type() === 'service') {$route = route('project.service.configuration', ['project_uuid' => $new_environment->project->uuid,'environment_uuid' => $new_environment->uuid,@@ -188,9 +201,11 @@ class ResourceOperations extends Componentreturn redirect()->to($route);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Project/Shared/ScheduledTask/Add.php b/app/Livewire/Project/Shared/ScheduledTask/Add.phpindex adfd59217e..0f378e39b2 100644--- a/app/Livewire/Project/Shared/ScheduledTask/Add.php+++ b/app/Livewire/Project/Shared/ScheduledTask/Add.php@@ -2,6 +2,7 @@namespace App\Livewire\Project\Shared\ScheduledTask;+use Exception;use Illuminate\Support\Collection;use Livewire\Component;@@ -53,12 +54,10 @@ class Add extends Componentif (! $isValid) {$this->dispatch('error', 'Invalid Cron / Human expression.');- return;+ return null;}- if (empty($this->container) || $this->container === 'null') {- if ($this->type === 'service') {- $this->container = $this->subServiceName;- }+ if (($this->container === null || $this->container === '' || $this->container === '0' || $this->container === 'null') && $this->type === 'service') {+ $this->container = $this->subServiceName;}$this->dispatch('saveScheduledTask', ['name' => $this->name,@@ -67,9 +66,11 @@ class Add extends Component'container' => $this->container,]);$this->clear();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function clear()diff --git a/app/Livewire/Project/Shared/ScheduledTask/All.php b/app/Livewire/Project/Shared/ScheduledTask/All.phpindex 6ab8426f39..11e7fcef60 100644--- a/app/Livewire/Project/Shared/ScheduledTask/All.php+++ b/app/Livewire/Project/Shared/ScheduledTask/All.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Shared\ScheduledTask;use App\Models\ScheduledTask;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class All extends Component{@@ -43,29 +44,31 @@ class All extends Componentpublic function submit($data){try {- $task = new ScheduledTask;- $task->name = $data['name'];- $task->command = $data['command'];- $task->frequency = $data['frequency'];- $task->container = $data['container'];- $task->team_id = currentTeam()->id;+ $scheduledTask = new ScheduledTask;+ $scheduledTask->name = $data['name'];+ $scheduledTask->command = $data['command'];+ $scheduledTask->frequency = $data['frequency'];+ $scheduledTask->container = $data['container'];+ $scheduledTask->team_id = currentTeam()->id;switch ($this->resource->type()) {case 'application':- $task->application_id = $this->resource->id;+ $scheduledTask->application_id = $this->resource->id;break;case 'standalone-postgresql':- $task->standalone_postgresql_id = $this->resource->id;+ $scheduledTask->standalone_postgresql_id = $this->resource->id;break;case 'service':- $task->service_id = $this->resource->id;+ $scheduledTask->service_id = $this->resource->id;break;}- $task->save();+ $scheduledTask->save();$this->refreshTasks();$this->dispatch('success', 'Scheduled task added.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Shared/ScheduledTask/Executions.php b/app/Livewire/Project/Shared/ScheduledTask/Executions.phpindex 74eac7132e..f0f6cf7753 100644--- a/app/Livewire/Project/Shared/ScheduledTask/Executions.php+++ b/app/Livewire/Project/Shared/ScheduledTask/Executions.php@@ -3,6 +3,9 @@namespace App\Livewire\Project\Shared\ScheduledTask;use App\Models\ScheduledTask;+use DateTime;+use DateTimeZone;+use Exception;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Auth;use Livewire\Attributes\Locked;@@ -28,7 +31,7 @@ class Executions extends Componentpublic $logsPerPage = 100;- public $selectedExecution = null;+ public $selectedExecution;public $isPollingActive = false;@@ -45,7 +48,7 @@ class Executions extends Component{try {$this->taskId = $taskId;- $this->task = ScheduledTask::findOrFail($taskId);+ $this->task = ScheduledTask::query()->findOrFail($taskId);$this->executions = $this->task->executions()->take(20)->get();$this->serverTimezone = data_get($this->task, 'application.destination.server.settings.server_timezone');if (! $this->serverTimezone) {@@ -54,9 +57,11 @@ class Executions extends Componentif (! $this->serverTimezone) {$this->serverTimezone = 'UTC';}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function refreshExecutions(): void@@ -124,7 +129,7 @@ class Executions extends Component{$execution = $this->executions->firstWhere('id', $executionId);if (! $execution) {- return;+ return null;}return response()->streamDownload(function () use ($execution) {@@ -145,11 +150,11 @@ class Executions extends Componentpublic function formatDateInServerTimezone($date){$serverTimezone = $this->serverTimezone;- $dateObj = new \DateTime($date);+ $dateObj = new DateTime($date);try {- $dateObj->setTimezone(new \DateTimeZone($serverTimezone));- } catch (\Exception) {- $dateObj->setTimezone(new \DateTimeZone('UTC'));+ $dateObj->setTimezone(new DateTimeZone($serverTimezone));+ } catch (Exception) {+ $dateObj->setTimezone(new DateTimeZone('UTC'));}return $dateObj->format('Y-m-d H:i:s T');diff --git a/app/Livewire/Project/Shared/ScheduledTask/Show.php b/app/Livewire/Project/Shared/ScheduledTask/Show.phpindex 0764ab3b96..5ea0e3cdc0 100644--- a/app/Livewire/Project/Shared/ScheduledTask/Show.php+++ b/app/Livewire/Project/Shared/ScheduledTask/Show.php@@ -6,6 +6,7 @@ use App\Jobs\ScheduledTaskJob;use App\Models\Application;use App\Models\ScheduledTask;use App\Models\Service;+use Exception;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;@@ -68,9 +69,11 @@ class Show extends Component$this->task = $this->resource->scheduled_tasks()->where('uuid', $task_uuid)->firstOrFail();$this->syncData();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function syncData(bool $toModel = false)@@ -98,9 +101,11 @@ class Show extends Component$this->syncData(true);$this->dispatch('success', 'Scheduled task updated.');$this->refreshTasks();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function submit()@@ -108,18 +113,22 @@ class Show extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Scheduled task updated.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function refreshTasks(){try {$this->task->refresh();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}public function delete()@@ -129,10 +138,10 @@ class Show extends Componentif ($this->type === 'application') {return redirect()->route('project.application.configuration', $this->parameters, $this->task->name);- } else {- return redirect()->route('project.service.configuration', $this->parameters, $this->task->name);}- } catch (\Exception $e) {++ return redirect()->route('project.service.configuration', $this->parameters, $this->task->name);+ } catch (Exception $e) {return handleError($e);}}@@ -142,8 +151,10 @@ class Show extends Componenttry {ScheduledTaskJob::dispatch($this->task);$this->dispatch('success', 'Scheduled task executed.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e);}++ return null;}}diff --git a/app/Livewire/Project/Shared/Storages/Add.php b/app/Livewire/Project/Shared/Storages/Add.phpindex 6e250bd908..5645b28c37 100644--- a/app/Livewire/Project/Shared/Storages/Add.php+++ b/app/Livewire/Project/Shared/Storages/Add.php@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Shared\Storages;use App\Models\Application;use App\Models\LocalFileVolume;use Livewire\Component;+use Throwable;class Add extends Component{@@ -63,7 +64,7 @@ class Add extends Component$this->parameters = get_route_parameters();if (data_get($this->parameters, 'application_uuid')) {$applicationUuid = $this->parameters['application_uuid'];- $application = Application::where('uuid', $applicationUuid)->first();+ $application = Application::query()->where('uuid', $applicationUuid)->first();if (! $application) {abort(404);}@@ -83,23 +84,23 @@ class Add extends Component]);$this->file_storage_path = trim($this->file_storage_path);$this->file_storage_path = str($this->file_storage_path)->start('/')->value();- if ($this->resource->getMorphClass() === \App\Models\Application::class) {+ if ($this->resource->getMorphClass() === Application::class) {$fs_path = application_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path;}- LocalFileVolume::create(- [- 'fs_path' => $fs_path,- 'mount_path' => $this->file_storage_path,- 'content' => $this->file_storage_content,- 'is_directory' => false,- 'resource_id' => $this->resource->id,- 'resource_type' => get_class($this->resource),- ],- );+ LocalFileVolume::query()->create([+ 'fs_path' => $fs_path,+ 'mount_path' => $this->file_storage_path,+ 'content' => $this->file_storage_content,+ 'is_directory' => false,+ 'resource_id' => $this->resource->id,+ 'resource_type' => get_class($this->resource),+ ]);$this->dispatch('refreshStorages');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submitFileStorageDirectory()@@ -113,19 +114,19 @@ class Add extends Component$this->file_storage_directory_source = str($this->file_storage_directory_source)->start('/')->value();$this->file_storage_directory_destination = trim($this->file_storage_directory_destination);$this->file_storage_directory_destination = str($this->file_storage_directory_destination)->start('/')->value();- LocalFileVolume::create(- [- 'fs_path' => $this->file_storage_directory_source,- 'mount_path' => $this->file_storage_directory_destination,- 'is_directory' => true,- 'resource_id' => $this->resource->id,- 'resource_type' => get_class($this->resource),- ],- );+ LocalFileVolume::query()->create([+ 'fs_path' => $this->file_storage_directory_source,+ 'mount_path' => $this->file_storage_directory_destination,+ 'is_directory' => true,+ 'resource_id' => $this->resource->id,+ 'resource_type' => get_class($this->resource),+ ]);$this->dispatch('refreshStorages');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submitPersistentVolume()@@ -142,9 +143,11 @@ class Add extends Component'mount_path' => $this->mount_path,'host_path' => $this->host_path,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function clear()diff --git a/app/Livewire/Project/Shared/Storages/Show.php b/app/Livewire/Project/Shared/Storages/Show.phpindex 54b1be3af5..0451a7f925 100644--- a/app/Livewire/Project/Shared/Storages/Show.php+++ b/app/Livewire/Project/Shared/Storages/Show.php@@ -41,12 +41,10 @@ class Show extends Componentpublic function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return;}$this->storage->delete();diff --git a/app/Livewire/Project/Shared/Tags.php b/app/Livewire/Project/Shared/Tags.phpindex 811859cb88..2b22feb2a1 100644--- a/app/Livewire/Project/Shared/Tags.php+++ b/app/Livewire/Project/Shared/Tags.php@@ -3,13 +3,14 @@namespace App\Livewire\Project\Shared;use App\Models\Tag;+use Exception;use Livewire\Attributes\Validate;use Livewire\Component;// Refactored ✅class Tags extends Component{- public $resource = null;+ public $resource;#[Validate('required|string|min:2')]public string $newTags;@@ -50,7 +51,7 @@ class Tags extends Component}$found = Tag::ownedByCurrentTeam()->where(['name' => $tag])->exists();if (! $found) {- $found = Tag::create([+ $found = Tag::query()->create(['name' => $tag,'team_id' => currentTeam()->id,]);@@ -58,9 +59,11 @@ class Tags extends Component$this->resource->tags()->attach($found->id);}$this->refresh();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function addTag(string $id, string $name)@@ -70,14 +73,16 @@ class Tags extends Componentif ($this->resource->tags()->where('id', $id)->exists()) {$this->dispatch('error', 'Duplicate tags.', "Tag <span class='dark:text-warning'>$name</span> already added.");- return;+ return null;}$this->resource->tags()->attach($id);$this->refresh();$this->dispatch('success', 'Tag added.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function deleteTag(string $id)@@ -90,9 +95,11 @@ class Tags extends Component}$this->refresh();$this->dispatch('success', 'Tag deleted.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function refresh()diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.phpindex d8f1012770..375500142e 100644--- a/app/Livewire/Project/Shared/Terminal.php+++ b/app/Livewire/Project/Shared/Terminal.php@@ -4,6 +4,7 @@ namespace App\Livewire\Project\Shared;use App\Helpers\SshMultiplexingHelper;use App\Models\Server;+use InvalidArgumentException;use Livewire\Attributes\On;use Livewire\Component;@@ -31,7 +32,7 @@ class Terminal extends Componentif ($isContainer) {// Validate container identifier format (alphanumeric, dashes, and underscores only)if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $identifier)) {- throw new \InvalidArgumentException('Invalid container identifier format');+ throw new InvalidArgumentException('Invalid container identifier format');}// Verify container exists and belongs to the user's teamdiff --git a/app/Livewire/Project/Shared/UploadConfig.php b/app/Livewire/Project/Shared/UploadConfig.phpindex 1b10f588b8..9ebe045e49 100644--- a/app/Livewire/Project/Shared/UploadConfig.php+++ b/app/Livewire/Project/Shared/UploadConfig.php@@ -3,6 +3,7 @@namespace App\Livewire\Project\Shared;use App\Models\Application;+use Exception;use Livewire\Component;class UploadConfig extends Component@@ -29,10 +30,10 @@ class UploadConfig extends Componentpublic function uploadConfig(){try {- $application = Application::findOrFail($this->applicationId);+ $application = Application::query()->findOrFail($this->applicationId);$application->setConfig($this->config);$this->dispatch('success', 'Application settings updated');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());return;diff --git a/app/Livewire/Project/Shared/Webhooks.php b/app/Livewire/Project/Shared/Webhooks.phpindex aab1fdc47c..f88169af2c 100644--- a/app/Livewire/Project/Shared/Webhooks.php+++ b/app/Livewire/Project/Shared/Webhooks.php@@ -2,6 +2,7 @@namespace App\Livewire\Project\Shared;+use Exception;use Livewire\Component;// Refactored ✅@@ -57,8 +58,10 @@ class Webhooks extends Component'manual_webhook_secret_gitea' => $this->giteaManualWebhookSecret,]);$this->dispatch('success', 'Secret Saved.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Project/Show.php b/app/Livewire/Project/Show.phpindex 886a20218f..4c2ed4b890 100644--- a/app/Livewire/Project/Show.php+++ b/app/Livewire/Project/Show.php@@ -6,6 +6,7 @@ use App\Models\Environment;use App\Models\Project;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class Show extends Component@@ -21,17 +22,19 @@ class Show extends Componentpublic function mount(string $project_uuid){try {- $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();- } catch (\Throwable $e) {+ $this->project = Project::query()->where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit(){try {$this->validate();- $environment = Environment::create([+ $environment = Environment::query()->create(['name' => $this->name,'project_id' => $this->project->id,'uuid' => (string) new Cuid2,@@ -41,9 +44,11 @@ class Show extends Component'project_uuid' => $this->project->uuid,'environment_uuid' => $environment->uuid,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {handleError($e, $this);}++ return null;}public function navigateToEnvironment($projectUuid, $environmentUuid)diff --git a/app/Livewire/Security/ApiTokens.php b/app/Livewire/Security/ApiTokens.phpindex 72684bdc63..ad0ad745cc 100644--- a/app/Livewire/Security/ApiTokens.php+++ b/app/Livewire/Security/ApiTokens.php@@ -3,6 +3,7 @@namespace App\Livewire\Security;use App\Models\InstanceSettings;+use Exception;use Livewire\Component;class ApiTokens extends Component@@ -39,10 +40,8 @@ class ApiTokens extends Component$this->permissions[] = 'read';} elseif ($permissionToUpdate == 'deploy') {$this->permissions = ['deploy'];- } else {- if (count($this->permissions) == 0) {- $this->permissions = ['read'];- }+ } elseif (count($this->permissions) == 0) {+ $this->permissions = ['read'];}sort($this->permissions);}@@ -56,9 +55,11 @@ class ApiTokens extends Component$token = auth()->user()->createToken($this->description, array_values($this->permissions));$this->getTokens();session()->flash('token', $token->plainTextToken);- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function revoke(int $id)@@ -67,8 +68,10 @@ class ApiTokens extends Component$token = auth()->user()->tokens()->where('id', $id)->firstOrFail();$token->delete();$this->getTokens();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Security/PrivateKey/Create.php b/app/Livewire/Security/PrivateKey/Create.phpindex 319cec1926..1e52906f5e 100644--- a/app/Livewire/Security/PrivateKey/Create.php+++ b/app/Livewire/Security/PrivateKey/Create.php@@ -4,6 +4,7 @@ namespace App\Livewire\Security\PrivateKey;use App\Models\PrivateKey;use Livewire\Component;+use Throwable;class Create extends Component{@@ -58,7 +59,7 @@ class Create extends Component]);return $this->redirectAfterCreation($privateKey);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Security/PrivateKey/Show.php b/app/Livewire/Security/PrivateKey/Show.phpindex b9195b5430..f21c4583bd 100644--- a/app/Livewire/Security/PrivateKey/Show.php+++ b/app/Livewire/Security/PrivateKey/Show.php@@ -3,7 +3,9 @@namespace App\Livewire\Security\PrivateKey;use App\Models\PrivateKey;+use Exception;use Livewire\Component;+use Throwable;class Show extends Component{@@ -28,7 +30,7 @@ class Show extends Component{try {$this->private_key = PrivateKey::ownedByCurrentTeam(['name', 'description', 'private_key', 'is_git_related'])->whereUuid(request()->private_key_uuid)->firstOrFail();- } catch (\Throwable) {+ } catch (Throwable) {abort(404);}}@@ -45,14 +47,16 @@ class Show extends Component{try {$this->private_key->safeDelete();- currentTeam()->privateKeys = PrivateKey::where('team_id', currentTeam()->id)->get();+ currentTeam()->privateKeys = PrivateKey::query()->where('team_id', currentTeam()->id)->get();return redirect()->route('security.private-key.index');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function changePrivateKey()@@ -63,8 +67,10 @@ class Show extends Component]);refresh_server_connection($this->private_key);$this->dispatch('success', 'Private key updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Server/Advanced.php b/app/Livewire/Server/Advanced.phpindex 577730f244..f09c219629 100644--- a/app/Livewire/Server/Advanced.php+++ b/app/Livewire/Server/Advanced.php@@ -4,8 +4,10 @@ namespace App\Livewire\Server;use App\Jobs\DockerCleanupJob;use App\Models\Server;+use Exception;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Advanced extends Component{@@ -46,9 +48,11 @@ class Advanced extends Component$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();$this->parameters = get_route_parameters();$this->syncData();- } catch (\Throwable) {+ } catch (Throwable) {return redirect()->route('server.show');}++ return null;}public function syncData(bool $toModel = false)@@ -83,9 +87,11 @@ class Advanced extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Server updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function manualCleanup()@@ -93,9 +99,11 @@ class Advanced extends Componenttry {DockerCleanupJob::dispatch($this->server, true);$this->dispatch('success', 'Manual cleanup job started. Depending on the amount of data, this might take a while.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -103,17 +111,19 @@ class Advanced extends Componenttry {if (! validate_cron_expression($this->dockerCleanupFrequency)) {$this->dockerCleanupFrequency = $this->server->settings->getOriginal('docker_cleanup_frequency');- throw new \Exception('Invalid Cron / Human expression for Docker Cleanup Frequency.');+ throw new Exception('Invalid Cron / Human expression for Docker Cleanup Frequency.');}if (! validate_cron_expression($this->serverDiskUsageCheckFrequency)) {$this->serverDiskUsageCheckFrequency = $this->server->settings->getOriginal('server_disk_usage_check_frequency');- throw new \Exception('Invalid Cron / Human expression for Disk Usage Check Frequency.');+ throw new Exception('Invalid Cron / Human expression for Disk Usage Check Frequency.');}$this->syncData(true);$this->dispatch('success', 'Server updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Charts.php b/app/Livewire/Server/Charts.phpindex d0db87f577..d322364855 100644--- a/app/Livewire/Server/Charts.php+++ b/app/Livewire/Server/Charts.php@@ -4,6 +4,7 @@ namespace App\Livewire\Server;use App\Models\Server;use Livewire\Component;+use Throwable;class Charts extends Component{@@ -23,9 +24,11 @@ class Charts extends Component{try {$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function pollData()@@ -49,9 +52,11 @@ class Charts extends Component$this->dispatch("refreshChartData-{$this->chartId}-memory", ['seriesData' => $memoryMetrics,]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function setInterval()diff --git a/app/Livewire/Server/CloudflareTunnels.php b/app/Livewire/Server/CloudflareTunnels.phpindex f69fc86557..247cab6c2b 100644--- a/app/Livewire/Server/CloudflareTunnels.php+++ b/app/Livewire/Server/CloudflareTunnels.php@@ -5,6 +5,7 @@ namespace App\Livewire\Server;use App\Models\Server;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class CloudflareTunnels extends Component{@@ -21,9 +22,11 @@ class CloudflareTunnels extends Componentreturn redirect()->route('server.show', ['server_uuid' => $server_uuid]);}$this->isCloudflareTunnelsEnabled = $this->server->settings->is_cloudflare_tunnel;- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -33,9 +36,11 @@ class CloudflareTunnels extends Component$this->server->settings->is_cloudflare_tunnel = $this->isCloudflareTunnelsEnabled;$this->server->settings->save();$this->dispatch('success', 'Server updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function manualCloudflareConfig()diff --git a/app/Livewire/Server/ConfigureCloudflareTunnels.php b/app/Livewire/Server/ConfigureCloudflareTunnels.phpindex f58d7b6be6..336fe7772a 100644--- a/app/Livewire/Server/ConfigureCloudflareTunnels.php+++ b/app/Livewire/Server/ConfigureCloudflareTunnels.php@@ -5,6 +5,7 @@ namespace App\Livewire\Server;use App\Actions\Server\ConfigureCloudflared;use App\Models\Server;use Livewire\Component;+use Throwable;class ConfigureCloudflareTunnels extends Component{@@ -22,9 +23,11 @@ class ConfigureCloudflareTunnels extends Component$server->settings->save();$this->dispatch('success', 'Cloudflare Tunnels configured successfully.');$this->dispatch('refreshServerShow');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -42,9 +45,11 @@ class ConfigureCloudflareTunnels extends Component$server->save();$server->settings->save();$this->dispatch('warning', 'Cloudflare Tunnels configuration started.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Delete.php b/app/Livewire/Server/Delete.phpindex b9e3944b54..bd1ee0901f 100644--- a/app/Livewire/Server/Delete.php+++ b/app/Livewire/Server/Delete.php@@ -9,6 +9,7 @@ use Illuminate\Foundation\Auth\Access\AuthorizesRequests;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Component;+use Throwable;class Delete extends Component{@@ -20,32 +21,32 @@ class Delete extends Component{try {$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function delete($password){- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}try {$this->authorize('delete', $this->server);if ($this->server->hasDefinedResources()) {$this->dispatch('error', 'Server has defined resources. Please delete them first.');- return;+ return null;}$this->server->delete();DeleteServer::dispatch($this->server);return redirect()->route('server.index');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Server/Destinations.php b/app/Livewire/Server/Destinations.phpindex dbab6e03f0..26fde971f3 100644--- a/app/Livewire/Server/Destinations.php+++ b/app/Livewire/Server/Destinations.php@@ -7,6 +7,7 @@ use App\Models\StandaloneDocker;use App\Models\SwarmDocker;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class Destinations extends Component{@@ -19,9 +20,11 @@ class Destinations extends Componenttry {$this->networks = collect();$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}private function createNetworkAndAttachToProxy()@@ -38,37 +41,31 @@ class Destinations extends Component$this->dispatch('error', 'Network already added to this server.');return;- } else {- SwarmDocker::create([- 'name' => $this->server->name.'-'.$name,- 'network' => $this->name,- 'server_id' => $this->server->id,- ]);}+ SwarmDocker::query()->create([+ 'name' => $this->server->name.'-'.$name,+ 'network' => $this->name,+ 'server_id' => $this->server->id,+ ]);} else {$found = $this->server->standaloneDockers()->where('network', $name)->first();if ($found) {$this->dispatch('error', 'Network already added to this server.');return;- } else {- StandaloneDocker::create([- 'name' => $this->server->name.'-'.$name,- 'network' => $name,- 'server_id' => $this->server->id,- ]);}+ StandaloneDocker::query()->create([+ 'name' => $this->server->name.'-'.$name,+ 'network' => $name,+ 'server_id' => $this->server->id,+ ]);$this->createNetworkAndAttachToProxy();}}public function scan(){- if ($this->server->isSwarm()) {- $alreadyAddedNetworks = $this->server->swarmDockers;- } else {- $alreadyAddedNetworks = $this->server->standaloneDockers;- }+ $alreadyAddedNetworks = $this->server->isSwarm() ? $this->server->swarmDockers : $this->server->standaloneDockers;$networks = instant_remote_process(['docker network ls --format "{{json .}}"'], $this->server, false);$this->networks = format_docker_command_output_to_json($networks)->filter(function ($network) {return $network['Name'] !== 'bridge' && $network['Name'] !== 'host' && $network['Name'] !== 'none';diff --git a/app/Livewire/Server/LogDrains.php b/app/Livewire/Server/LogDrains.phpindex edddfc7557..1bad68d712 100644--- a/app/Livewire/Server/LogDrains.php+++ b/app/Livewire/Server/LogDrains.php@@ -7,6 +7,7 @@ use App\Actions\Server\StopLogDrain;use App\Models\Server;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class LogDrains extends Component{@@ -44,9 +45,11 @@ class LogDrains extends Componenttry {$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function syncDataNewRelic(bool $toModel = false)@@ -104,18 +107,16 @@ class LogDrains extends Component$this->syncDataCustom($toModel);}$this->server->settings->save();+ } elseif ($type === 'newrelic') {+ $this->syncDataNewRelic($toModel);+ } elseif ($type === 'axiom') {+ $this->syncDataAxiom($toModel);+ } elseif ($type === 'custom') {+ $this->syncDataCustom($toModel);} else {- if ($type === 'newrelic') {- $this->syncDataNewRelic($toModel);- } elseif ($type === 'axiom') {- $this->syncDataAxiom($toModel);- } elseif ($type === 'custom') {- $this->syncDataCustom($toModel);- } else {- $this->syncDataNewRelic($toModel);- $this->syncDataAxiom($toModel);- $this->syncDataCustom($toModel);- }+ $this->syncDataNewRelic($toModel);+ $this->syncDataAxiom($toModel);+ $this->syncDataCustom($toModel);}}@@ -127,7 +128,7 @@ class LogDrains extends Component'logDrainNewRelicLicenseKey' => ['required'],'logDrainNewRelicBaseUri' => ['required', 'url'],]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isLogDrainNewRelicEnabled = false;throw $e;@@ -138,7 +139,7 @@ class LogDrains extends Component'logDrainAxiomDatasetName' => ['required'],'logDrainAxiomApiKey' => ['required'],]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isLogDrainAxiomEnabled = false;throw $e;@@ -149,7 +150,7 @@ class LogDrains extends Component'logDrainCustomConfig' => ['required'],'logDrainCustomConfigParser' => ['string', 'nullable'],]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->isLogDrainCustomEnabled = false;throw $e;@@ -168,9 +169,11 @@ class LogDrains extends ComponentStopLogDrain::run($this->server);$this->dispatch('success', 'Log drain service stopped.');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit(string $type)@@ -178,9 +181,11 @@ class LogDrains extends Componenttry {$this->syncData(true, $type);$this->dispatch('success', 'Settings saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/New/ByIp.php b/app/Livewire/Server/New/ByIp.phpindex 5f60c5db5e..5d5169ff82 100644--- a/app/Livewire/Server/New/ByIp.php+++ b/app/Livewire/Server/New/ByIp.php@@ -9,6 +9,7 @@ use Illuminate\Support\Collection;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class ByIp extends Component{@@ -52,7 +53,7 @@ class ByIp extends Componentpublic bool $is_swarm_worker = false;#[Validate('nullable|integer', as: 'Swarm Cluster')]- public $selected_swarm_cluster = null;+ public $selected_swarm_cluster;#[Validate('required|boolean', as: 'Build Server')]public bool $is_build_server = false;@@ -84,7 +85,7 @@ class ByIp extends Component{$this->validate();try {- if (Server::where('team_id', currentTeam()->id)+ if (Server::query()->where('team_id', currentTeam()->id)->where('ip', $this->ip)->exists()) {return $this->dispatch('error', 'This IP/Domain is already in use by another server in your team.');@@ -111,7 +112,7 @@ class ByIp extends Componentif ($this->is_build_server) {data_forget($payload, 'proxy');}- $server = Server::create($payload);+ $server = Server::query()->create($payload);$server->proxy->set('status', 'exited');$server->proxy->set('type', ProxyTypes::TRAEFIK->value);$server->save();@@ -126,7 +127,7 @@ class ByIp extends Component$server->settings->save();return redirect()->route('server.show', $server->uuid);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Server/PrivateKey/Show.php b/app/Livewire/Server/PrivateKey/Show.phpindex 64aa1884ba..614629d8d0 100644--- a/app/Livewire/Server/PrivateKey/Show.php+++ b/app/Livewire/Server/PrivateKey/Show.php@@ -4,7 +4,9 @@ namespace App\Livewire\Server\PrivateKey;use App\Models\PrivateKey;use App\Models\Server;+use Exception;use Livewire\Component;+use Throwable;class Show extends Component{@@ -19,9 +21,11 @@ class Show extends Componenttry {$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();$this->privateKeys = PrivateKey::ownedByCurrentTeam()->get()->where('is_git_related', false);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function setPrivateKey($privateKeyId)@@ -40,9 +44,9 @@ class Show extends Componentif ($uptime) {$this->dispatch('success', 'Private key updated successfully.');} else {- throw new \Exception($error);+ throw new Exception($error);}- } catch (\Exception $e) {+ } catch (Exception $e) {$this->server->update(['private_key_id' => $originalPrivateKeyId]);$this->server->validateConnection();$this->dispatch('error', $e->getMessage());@@ -58,11 +62,13 @@ class Show extends Component} else {$this->dispatch('error', 'Server is not reachable.<br><br>Check this <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/openssh">documentation</a> for further help.<br><br>Error: '.$error);- return;+ return null;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Proxy.php b/app/Livewire/Server/Proxy.phpindex 4e325c1ff6..97f0a76aa9 100644--- a/app/Livewire/Server/Proxy.php+++ b/app/Livewire/Server/Proxy.php@@ -6,6 +6,7 @@ use App\Actions\Proxy\CheckConfiguration;use App\Actions\Proxy\SaveConfiguration;use App\Models\Server;use Livewire\Component;+use Throwable;class Proxy extends Component{@@ -13,7 +14,7 @@ class Proxy extends Componentpublic ?string $selectedProxy = null;- public $proxy_settings = null;+ public $proxy_settings;public bool $redirect_enabled = true;@@ -50,9 +51,11 @@ class Proxy extends Component$this->server->changeProxy($proxy_type, async: false);$this->selectedProxy = $this->server->proxy->type;$this->dispatch('reloadWindow');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -61,9 +64,11 @@ class Proxy extends Component$this->validate();$this->server->settings->save();$this->dispatch('success', 'Settings saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSaveRedirect()@@ -73,9 +78,11 @@ class Proxy extends Component$this->server->save();$this->server->setupDefaultRedirect();$this->dispatch('success', 'Proxy configuration saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -86,9 +93,11 @@ class Proxy extends Component$this->server->save();$this->server->setupDefaultRedirect();$this->dispatch('success', 'Proxy configuration saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function reset_proxy_configuration()@@ -98,9 +107,11 @@ class Proxy extends ComponentSaveConfiguration::run($this->server, $this->proxy_settings);$this->server->save();$this->dispatch('success', 'Proxy configuration saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function loadProxyConfiguration()@@ -112,8 +123,10 @@ class Proxy extends Component} else {$this->dispatch('traefikDashboardAvailable', false);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Server/Proxy/Deploy.php b/app/Livewire/Server/Proxy/Deploy.phpindex 4f9d410923..6188f06f34 100644--- a/app/Livewire/Server/Proxy/Deploy.php+++ b/app/Livewire/Server/Proxy/Deploy.php@@ -10,6 +10,7 @@ use Carbon\Carbon;use Illuminate\Process\InvokedProcess;use Illuminate\Support\Facades\Process;use Livewire\Component;+use Throwable;class Deploy extends Component{@@ -38,11 +39,7 @@ class Deploy extends Componentpublic function mount(){- if ($this->server->id === 0) {- $this->serverIp = base_ip();- } else {- $this->serverIp = $this->server->ip;- }+ $this->serverIp = $this->server->id === 0 ? base_ip() : $this->server->ip;$this->currentRoute = request()->route()->getName();}@@ -67,9 +64,11 @@ class Deploy extends Componenttry {$this->stop();$this->dispatch('checkProxy');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function checkProxy()@@ -78,9 +77,11 @@ class Deploy extends ComponentCheckProxy::run($this->server, true);$this->dispatch('startProxyPolling');$this->dispatch('proxyChecked');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function startProxy()@@ -90,9 +91,11 @@ class Deploy extends Component$this->server->save();$activity = StartProxy::run($this->server, force: true);$this->dispatch('activityMonitor', $activity->id, ProxyStatusChanged::class);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function stop(bool $forceStop = true)@@ -114,7 +117,7 @@ class Deploy extends Component}$this->removeContainer($containerName);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);} finally {$this->server->proxy->force_stop = $forceStop;@@ -122,6 +125,8 @@ class Deploy extends Component$this->server->save();$this->dispatch('proxyStatusUpdated');}++ return null;}private function stopContainer(string $containerName, int $timeout): InvokedProcessdiff --git a/app/Livewire/Server/Proxy/DynamicConfigurations.php b/app/Livewire/Server/Proxy/DynamicConfigurations.phpindex 6277a24bd4..f01d666735 100644--- a/app/Livewire/Server/Proxy/DynamicConfigurations.php+++ b/app/Livewire/Server/Proxy/DynamicConfigurations.php@@ -5,6 +5,7 @@ namespace App\Livewire\Server\Proxy;use App\Models\Server;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class DynamicConfigurations extends Component{@@ -32,7 +33,7 @@ class DynamicConfigurations extends Component{$proxy_path = $this->server->proxyPath();$files = instant_remote_process(["mkdir -p $proxy_path/dynamic && ls -1 {$proxy_path}/dynamic"], $this->server);- $files = collect(explode("\n", $files))->filter(fn ($file) => ! empty($file));+ $files = collect(explode("\n", $files))->reject(fn ($file): bool => $file === '' || $file === '0');$files = $files->map(fn ($file) => trim($file));$files = $files->sort();$contents = collect([]);@@ -52,9 +53,11 @@ class DynamicConfigurations extends Componentif (is_null($this->server)) {return redirect()->route('server.index');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Proxy/Logs.php b/app/Livewire/Server/Proxy/Logs.phpindex 8e0f40c54e..e2578f1ea2 100644--- a/app/Livewire/Server/Proxy/Logs.php+++ b/app/Livewire/Server/Proxy/Logs.php@@ -4,6 +4,7 @@ namespace App\Livewire\Server\Proxy;use App\Models\Server;use Livewire\Component;+use Throwable;class Logs extends Component{@@ -19,9 +20,11 @@ class Logs extends Componentif (is_null($this->server)) {return redirect()->route('server.index');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Proxy/NewDynamicConfiguration.php b/app/Livewire/Server/Proxy/NewDynamicConfiguration.phpindex 2155f1e82d..096700d8e0 100644--- a/app/Livewire/Server/Proxy/NewDynamicConfiguration.php+++ b/app/Livewire/Server/Proxy/NewDynamicConfiguration.php@@ -6,6 +6,7 @@ use App\Enums\ProxyTypes;use App\Models\Server;use Livewire\Component;use Symfony\Component\Yaml\Yaml;+use Throwable;class NewDynamicConfiguration extends Component{@@ -53,7 +54,7 @@ class NewDynamicConfiguration extends Componentif ($this->fileName === 'coolify.yaml') {$this->dispatch('error', 'File name is reserved.');- return;+ return null;}} elseif ($proxy_type === 'CADDY') {if (! str($this->fileName)->endsWith('.caddy')) {@@ -67,7 +68,7 @@ class NewDynamicConfiguration extends Componentif ($exists == 1) {$this->dispatch('error', 'File already exists');- return;+ return null;}}if ($proxy_type === ProxyTypes::TRAEFIK->value) {@@ -85,9 +86,11 @@ class NewDynamicConfiguration extends Component$this->dispatch('loadDynamicConfigurations');$this->dispatch('dynamic-configuration-added');$this->dispatch('success', 'Dynamic configuration saved.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Proxy/Show.php b/app/Livewire/Server/Proxy/Show.phpindex 5ecb56a691..507cea7b02 100644--- a/app/Livewire/Server/Proxy/Show.php+++ b/app/Livewire/Server/Proxy/Show.php@@ -4,6 +4,7 @@ namespace App\Livewire\Server\Proxy;use App\Models\Server;use Livewire\Component;+use Throwable;class Show extends Component{@@ -23,9 +24,11 @@ class Show extends Component$this->parameters = get_route_parameters();try {$this->server = Server::ownedByCurrentTeam()->whereUuid(request()->server_uuid)->firstOrFail();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Proxy/Status.php b/app/Livewire/Server/Proxy/Status.phpindex f4f18381f8..5750a12bd4 100644--- a/app/Livewire/Server/Proxy/Status.php+++ b/app/Livewire/Server/Proxy/Status.php@@ -7,6 +7,7 @@ use App\Actions\Proxy\CheckProxy;use App\Actions\Proxy\StartProxy;use App\Models\Server;use Livewire\Component;+use Throwable;class Status extends Component{@@ -38,9 +39,11 @@ class Status extends Componentif ($this->numberOfPolls >= 10) {$this->polling = false;$this->numberOfPolls = 0;- $notification && $this->dispatch('error', 'Proxy is not running.');+ if ($notification) {+ $this->dispatch('error', 'Proxy is not running.');+ }- return;+ return null;}$this->numberOfPolls++;}@@ -51,17 +54,25 @@ class Status extends Component$this->dispatch('proxyStatusUpdated');if ($this->server->proxy->status === 'running') {$this->polling = false;- $notification && $this->dispatch('success', 'Proxy is running.');- } elseif ($this->server->proxy->status === 'exited' and ! $this->server->proxy->force_stop) {- $notification && $this->dispatch('error', 'Proxy has exited.');+ if ($notification) {+ $this->dispatch('success', 'Proxy is running.');+ }+ } elseif ($this->server->proxy->status === 'exited' && ! $this->server->proxy->force_stop) {+ if ($notification) {+ $this->dispatch('error', 'Proxy has exited.');+ }} elseif ($this->server->proxy->force_stop) {- $notification && $this->dispatch('error', 'Proxy is stopped manually.');- } else {- $notification && $this->dispatch('error', 'Proxy is not running.');+ if ($notification) {+ $this->dispatch('error', 'Proxy is stopped manually.');+ }+ } elseif ($notification) {+ $this->dispatch('error', 'Proxy is not running.');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function getProxyStatus()@@ -70,8 +81,10 @@ class Status extends ComponentGetContainersStatus::run($this->server);// dispatch_sync(new ContainerStatusJob($this->server));$this->dispatch('proxyStatusUpdated');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Server/Resources.php b/app/Livewire/Server/Resources.phpindex f549b43cbd..cf3eb6c2c1 100644--- a/app/Livewire/Server/Resources.php+++ b/app/Livewire/Server/Resources.php@@ -6,6 +6,7 @@ use App\Models\Server;use Illuminate\Foundation\Auth\Access\AuthorizesRequests;use Illuminate\Support\Collection;use Livewire\Component;+use Throwable;class Resources extends Component{@@ -65,9 +66,11 @@ class Resources extends Componenttry {$this->activeTab = 'managed';$this->containers = $this->server->refresh()->definedResources();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function loadUnmanagedContainers()@@ -75,9 +78,11 @@ class Resources extends Component$this->activeTab = 'unmanaged';try {$this->containers = $this->server->loadUnmanagedContainers();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function mount()@@ -90,9 +95,11 @@ class Resources extends Componentreturn redirect()->route('server.index');}$this->loadManagedContainers();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/Show.php b/app/Livewire/Server/Show.phpindex 6d267b9c89..4e36e0e5a1 100644--- a/app/Livewire/Server/Show.php+++ b/app/Livewire/Server/Show.php@@ -6,9 +6,11 @@ use App\Actions\Server\StartSentinel;use App\Actions\Server\StopSentinel;use App\Events\ServerReachabilityChanged;use App\Models\Server;+use Exception;use Livewire\Attributes\Computed;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Show extends Component{@@ -95,9 +97,11 @@ class Show extends Componenttry {$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();$this->syncData();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}#[Computed]@@ -114,12 +118,12 @@ class Show extends Componentif ($toModel) {$this->validate();- if (Server::where('team_id', currentTeam()->id)+ if (Server::query()->where('team_id', currentTeam()->id)->where('ip', $this->ip)->where('id', '!=', $this->server->id)->exists()) {$this->ip = $this->server->ip;- throw new \Exception('This IP/Domain is already in use by another server in your team.');+ throw new Exception('This IP/Domain is already in use by another server in your team.');}$this->server->name = $this->name;@@ -145,10 +149,9 @@ class Show extends Componentif (! validate_timezone($this->serverTimezone)) {$this->serverTimezone = config('app.timezone');- throw new \Exception('Invalid timezone.');- } else {- $this->server->settings->server_timezone = $this->serverTimezone;+ throw new Exception('Invalid timezone.');}+ $this->server->settings->server_timezone = $this->serverTimezone;$this->server->settings->save();} else {@@ -189,9 +192,11 @@ class Show extends Component$this->validationLogs = $this->server->validation_logs = null;$this->server->save();$this->dispatch('init', $install);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function checkLocalhostConnection()@@ -248,9 +253,11 @@ class Show extends Componenttry {$this->server->settings->generateSentinelToken();$this->dispatch('success', 'Token regenerated & Sentinel restarted.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -263,9 +270,11 @@ class Show extends Componenttry {$this->syncData(true);$this->dispatch('success', 'Server updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Server/ValidateAndInstall.php b/app/Livewire/Server/ValidateAndInstall.phpindex 791ef93501..1c73537a97 100644--- a/app/Livewire/Server/ValidateAndInstall.php+++ b/app/Livewire/Server/ValidateAndInstall.php@@ -5,7 +5,9 @@ namespace App\Livewire\Server;use App\Actions\Proxy\CheckProxy;use App\Actions\Proxy\StartProxy;use App\Models\Server;+use Exception;use Livewire\Component;+use Throwable;class ValidateAndInstall extends Component{@@ -17,19 +19,19 @@ class ValidateAndInstall extends Componentpublic bool $install = true;- public $uptime = null;+ public $uptime;- public $supported_os_type = null;+ public $supported_os_type;- public $docker_installed = null;+ public $docker_installed;- public $docker_compose_installed = null;+ public $docker_compose_installed;- public $docker_version = null;+ public $docker_version;public $proxy_started = false;- public $error = null;+ public $error;public bool $ask = false;@@ -73,14 +75,16 @@ class ValidateAndInstall extends Componentif ($proxy === 'OK') {$this->proxy_started = true;} else {- throw new \Exception('Proxy could not be started.');+ throw new Exception('Proxy could not be started.');}} else {$this->proxy_started = true;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function validateConnection()@@ -117,30 +121,28 @@ class ValidateAndInstall extends Component$this->docker_compose_installed = $this->server->validateDockerCompose();if (! $this->docker_installed || ! $this->docker_compose_installed) {if ($this->install) {- if ($this->number_of_tries == $this->max_tries) {+ if ($this->number_of_tries === $this->max_tries) {$this->error = 'Docker Engine could not be installed. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.';$this->server->update(['validation_logs' => $this->error,]);- return;- } else {- if ($this->number_of_tries <= $this->max_tries) {- $activity = $this->server->installDocker();- $this->number_of_tries++;- $this->dispatch('newActivityMonitor', $activity->id, 'init', $this->number_of_tries);- }-return;}- } else {- $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.';- $this->server->update([- 'validation_logs' => $this->error,- ]);+ if ($this->number_of_tries <= $this->max_tries) {+ $activity = $this->server->installDocker();+ $this->number_of_tries++;+ $this->dispatch('newActivityMonitor', $activity->id, 'init', $this->number_of_tries);+ }return;}+ $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.';+ $this->server->update([+ 'validation_logs' => $this->error,+ ]);++ return;}$this->dispatch('validateDockerVersion');}diff --git a/app/Livewire/Settings/Index.php b/app/Livewire/Settings/Index.phpindex 3d90024b7e..29dc61969d 100644--- a/app/Livewire/Settings/Index.php+++ b/app/Livewire/Settings/Index.php@@ -5,6 +5,7 @@ namespace App\Livewire\Settings;use App\Jobs\CheckForUpdatesJob;use App\Models\InstanceSettings;use App\Models\Server;+use Exception;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Livewire\Attributes\Computed;@@ -77,26 +78,27 @@ class Index extends Component{if (! isInstanceAdmin()) {return redirect()->route('dashboard');- } else {- $this->settings = instanceSettings();- $this->fqdn = $this->settings->fqdn;- $this->public_port_min = $this->settings->public_port_min;- $this->public_port_max = $this->settings->public_port_max;- $this->custom_dns_servers = $this->settings->custom_dns_servers;- $this->instance_name = $this->settings->instance_name;- $this->allowed_ips = $this->settings->allowed_ips;- $this->public_ipv4 = $this->settings->public_ipv4;- $this->public_ipv6 = $this->settings->public_ipv6;- $this->do_not_track = $this->settings->do_not_track;- $this->is_auto_update_enabled = $this->settings->is_auto_update_enabled;- $this->is_registration_enabled = $this->settings->is_registration_enabled;- $this->is_dns_validation_enabled = $this->settings->is_dns_validation_enabled;- $this->is_api_enabled = $this->settings->is_api_enabled;- $this->auto_update_frequency = $this->settings->auto_update_frequency;- $this->update_check_frequency = $this->settings->update_check_frequency;- $this->instance_timezone = $this->settings->instance_timezone;- $this->disable_two_step_confirmation = $this->settings->disable_two_step_confirmation;}+ $this->settings = instanceSettings();+ $this->fqdn = $this->settings->fqdn;+ $this->public_port_min = $this->settings->public_port_min;+ $this->public_port_max = $this->settings->public_port_max;+ $this->custom_dns_servers = $this->settings->custom_dns_servers;+ $this->instance_name = $this->settings->instance_name;+ $this->allowed_ips = $this->settings->allowed_ips;+ $this->public_ipv4 = $this->settings->public_ipv4;+ $this->public_ipv6 = $this->settings->public_ipv6;+ $this->do_not_track = $this->settings->do_not_track;+ $this->is_auto_update_enabled = $this->settings->is_auto_update_enabled;+ $this->is_registration_enabled = $this->settings->is_registration_enabled;+ $this->is_dns_validation_enabled = $this->settings->is_dns_validation_enabled;+ $this->is_api_enabled = $this->settings->is_api_enabled;+ $this->auto_update_frequency = $this->settings->auto_update_frequency;+ $this->update_check_frequency = $this->settings->update_check_frequency;+ $this->instance_timezone = $this->settings->instance_timezone;+ $this->disable_two_step_confirmation = $this->settings->disable_two_step_confirmation;++ return null;}#[Computed]@@ -144,46 +146,43 @@ class Index extends Component{try {$error_show = false;- $this->server = Server::findOrFail(0);+ $this->server = Server::query()->findOrFail(0);$this->resetErrorBag();if (! validate_timezone($this->instance_timezone)) {$this->instance_timezone = config('app.timezone');- throw new \Exception('Invalid timezone.');- } else {- $this->settings->instance_timezone = $this->instance_timezone;+ throw new Exception('Invalid timezone.');}+ $this->settings->instance_timezone = $this->instance_timezone;if ($this->settings->public_port_min > $this->settings->public_port_max) {$this->addError('settings.public_port_min', 'The minimum port must be lower than the maximum port.');- return;+ return null;}$this->validate();if ($this->is_auto_update_enabled && ! validate_cron_expression($this->auto_update_frequency)) {$this->dispatch('error', 'Invalid Cron / Human expression for Auto Update Frequency.');- if (empty($this->auto_update_frequency)) {+ if (! isset($this->auto_update_frequency) || ($this->auto_update_frequency === '' || $this->auto_update_frequency === '0')) {$this->auto_update_frequency = '0 0 * * *';}- return;+ return null;}if (! validate_cron_expression($this->update_check_frequency)) {$this->dispatch('error', 'Invalid Cron / Human expression for Update Check Frequency.');- if (empty($this->update_check_frequency)) {+ if (! isset($this->update_check_frequency) || ($this->update_check_frequency === '' || $this->update_check_frequency === '0')) {$this->update_check_frequency = '0 * * * *';}- return;+ return null;}- if ($this->settings->is_dns_validation_enabled && $this->settings->fqdn) {- if (! validate_dns_entry($this->settings->fqdn, $this->server)) {- $this->dispatch('error', "Validating DNS failed.<br><br>Make sure you have added the DNS records correctly.<br><br>{$this->settings->fqdn}->{$this->server->ip}<br><br>Check this <a target='_blank' class='underline dark:text-white' href='https://coolify.io/docs/knowledge-base/dns-configuration'>documentation</a> for further help.");- $error_show = true;- }+ if ($this->settings->is_dns_validation_enabled && $this->settings->fqdn && ! validate_dns_entry($this->settings->fqdn, $this->server)) {+ $this->dispatch('error', "Validating DNS failed.<br><br>Make sure you have added the DNS records correctly.<br><br>{$this->settings->fqdn}->{$this->server->ip}<br><br>Check this <a target='_blank' class='underline dark:text-white' href='https://coolify.io/docs/knowledge-base/dns-configuration'>documentation</a> for further help.");+ $error_show = true;}if ($this->settings->fqdn) {check_domain_usage(domain: $this->settings->fqdn);@@ -209,9 +208,11 @@ class Index extends Componentif (! $error_show) {$this->dispatch('success', 'Instance settings updated successfully!');}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function checkManually()diff --git a/app/Livewire/SettingsBackup.php b/app/Livewire/SettingsBackup.phpindex 1b0599ffee..275c0f4b0a 100644--- a/app/Livewire/SettingsBackup.php+++ b/app/Livewire/SettingsBackup.php@@ -6,7 +6,9 @@ use App\Models\InstanceSettings;use App\Models\S3Storage;use App\Models\ScheduledDatabaseBackup;use App\Models\Server;+use App\Models\StandaloneDocker;use App\Models\StandalonePostgresql;+use Exception;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;@@ -44,39 +46,40 @@ class SettingsBackup extends Component{if (! isInstanceAdmin()) {return redirect()->route('dashboard');- } else {- $settings = instanceSettings();- $this->database = StandalonePostgresql::whereName('coolify-db')->first();- $s3s = S3Storage::whereTeamId(0)->get() ?? [];- if ($this->database) {- $this->uuid = $this->database->uuid;- $this->name = $this->database->name;- $this->description = $this->database->description;- $this->postgres_user = $this->database->postgres_user;- $this->postgres_password = $this->database->postgres_password;-- if ($this->database->status !== 'running') {- $this->database->status = 'running';- $this->database->save();- }- $this->backup = $this->database->scheduledBackups->first();- $this->executions = $this->backup->executions;+ }+ $settings = instanceSettings();+ $this->database = StandalonePostgresql::whereName('coolify-db')->first();+ $s3s = S3Storage::whereTeamId(0)->get() ?? [];+ if ($this->database instanceof StandalonePostgresql) {+ $this->uuid = $this->database->uuid;+ $this->name = $this->database->name;+ $this->description = $this->database->description;+ $this->postgres_user = $this->database->postgres_user;+ $this->postgres_password = $this->database->postgres_password;++ if ($this->database->status !== 'running') {+ $this->database->status = 'running';+ $this->database->save();}- $this->settings = $settings;- $this->s3s = $s3s;+ $this->backup = $this->database->scheduledBackups->first();+ $this->executions = $this->backup->executions;}+ $this->settings = $settings;+ $this->s3s = $s3s;++ return null;}public function addCoolifyDatabase(){try {- $server = Server::findOrFail(0);+ $server = Server::query()->findOrFail(0);$out = instant_remote_process(['docker inspect coolify-db'], $server);$envs = format_docker_envs_to_json($out);$postgres_password = $envs['POSTGRES_PASSWORD'];$postgres_user = $envs['POSTGRES_USER'];$postgres_db = $envs['POSTGRES_DB'];- $this->database = StandalonePostgresql::create([+ $this->database = StandalonePostgresql::query()->create(['id' => 0,'name' => 'coolify-db','description' => 'Coolify database',@@ -84,16 +87,16 @@ class SettingsBackup extends Component'postgres_password' => $postgres_password,'postgres_db' => $postgres_db,'status' => 'running',- 'destination_type' => \App\Models\StandaloneDocker::class,+ 'destination_type' => StandaloneDocker::class,'destination_id' => 0,]);- $this->backup = ScheduledDatabaseBackup::create([+ $this->backup = ScheduledDatabaseBackup::query()->create(['id' => 0,'enabled' => true,'save_s3' => false,'frequency' => '0 0 * * *','database_id' => $this->database->id,- 'database_type' => \App\Models\StandalonePostgresql::class,+ 'database_type' => StandalonePostgresql::class,'team_id' => currentTeam()->id,]);$this->database->refresh();@@ -107,9 +110,11 @@ class SettingsBackup extends Component$this->postgres_password = $this->database->postgres_password;$this->executions = $this->backup->executions;- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()diff --git a/app/Livewire/SettingsEmail.php b/app/Livewire/SettingsEmail.phpindex 058f080e42..bbdc23034b 100644--- a/app/Livewire/SettingsEmail.php+++ b/app/Livewire/SettingsEmail.php@@ -5,10 +5,12 @@ namespace App\Livewire;use App\Models\InstanceSettings;use App\Models\Team;use App\Notifications\Test;+use Exception;use Illuminate\Support\Facades\RateLimiter;use Livewire\Attributes\Locked;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class SettingsEmail extends Component{@@ -65,6 +67,8 @@ class SettingsEmail extends Component$this->syncData();$this->team = auth()->user()->currentTeam();$this->testEmailAddress = auth()->user()->email;++ return null;}public function syncData(bool $toModel = false)@@ -106,9 +110,11 @@ class SettingsEmail extends Component$this->resetErrorBag();$this->syncData(true);$this->dispatch('success', 'Transactional email settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSave(string $type)@@ -122,7 +128,7 @@ class SettingsEmail extends Component$this->submitResend();}- } catch (\Throwable $e) {+ } catch (Throwable $e) {if ($type === 'SMTP') {$this->smtpEnabled = false;} elseif ($type === 'Resend') {@@ -131,6 +137,8 @@ class SettingsEmail extends Componentreturn handleError($e, $this);}++ return null;}public function submitSmtp()@@ -172,11 +180,13 @@ class SettingsEmail extends Component$this->settings->save();$this->dispatch('success', 'SMTP settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->smtpEnabled = false;return handleError($e);}++ return null;}public function submitResend()@@ -205,11 +215,13 @@ class SettingsEmail extends Component$this->settings->save();$this->dispatch('success', 'Resend settings updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->resendEnabled = false;return handleError($e);}++ return null;}public function sendTestEmail()@@ -233,10 +245,12 @@ class SettingsEmail extends Component);if (! $executed) {- throw new \Exception('Too many messages sent!');+ throw new Exception('Too many messages sent!');}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}}diff --git a/app/Livewire/SettingsOauth.php b/app/Livewire/SettingsOauth.phpindex e23f94a73b..01c76a459b 100644--- a/app/Livewire/SettingsOauth.php+++ b/app/Livewire/SettingsOauth.php@@ -3,6 +3,7 @@namespace App\Livewire;use App\Models\OauthSetting;+use Exception;use Livewire\Component;class SettingsOauth extends Component@@ -33,6 +34,8 @@ class SettingsOauth extends Componentreturn $carry;}, []);++ return null;}private function updateOauthSettings(?string $provider = null)@@ -41,7 +44,7 @@ class SettingsOauth extends Component$oauth = $this->oauth_settings_map[$provider];if (! $oauth->couldBeEnabled()) {$oauth->update(['enabled' => false]);- throw new \Exception('OAuth settings are not complete for '.$oauth->provider.'.<br/>Please fill in all required fields.');+ throw new Exception('OAuth settings are not complete for '.$oauth->provider.'.<br/>Please fill in all required fields.');}$oauth->save();$this->dispatch('success', 'OAuth settings for '.$oauth->provider.' updated successfully!');@@ -56,9 +59,11 @@ class SettingsOauth extends Component{try {$this->updateOauthSettings($provider);- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function submit()diff --git a/app/Livewire/SharedVariables/Environment/Show.php b/app/Livewire/SharedVariables/Environment/Show.phpindex e88ac5f135..4495375ace 100644--- a/app/Livewire/SharedVariables/Environment/Show.php+++ b/app/Livewire/SharedVariables/Environment/Show.php@@ -4,7 +4,9 @@ namespace App\Livewire\SharedVariables\Environment;use App\Models\Application;use App\Models\Project;+use Exception;use Livewire\Component;+use Throwable;class Show extends Component{@@ -23,7 +25,7 @@ class Show extends Componenttry {$found = $this->environment->environment_variables()->where('key', $data['key'])->first();if ($found) {- throw new \Exception('Variable already exists.');+ throw new Exception('Variable already exists.');}$this->environment->environment_variables()->create(['key' => $data['key'],@@ -34,9 +36,11 @@ class Show extends Component'team_id' => currentTeam()->id,]);$this->environment->refresh();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function mount()diff --git a/app/Livewire/SharedVariables/Project/Show.php b/app/Livewire/SharedVariables/Project/Show.phpindex 0171283c4a..79d217e655 100644--- a/app/Livewire/SharedVariables/Project/Show.php+++ b/app/Livewire/SharedVariables/Project/Show.php@@ -3,7 +3,9 @@namespace App\Livewire\SharedVariables\Project;use App\Models\Project;+use Exception;use Livewire\Component;+use Throwable;class Show extends Component{@@ -16,7 +18,7 @@ class Show extends Componenttry {$found = $this->project->environment_variables()->where('key', $data['key'])->first();if ($found) {- throw new \Exception('Variable already exists.');+ throw new Exception('Variable already exists.');}$this->project->environment_variables()->create(['key' => $data['key'],@@ -27,20 +29,24 @@ class Show extends Component'team_id' => currentTeam()->id,]);$this->project->refresh();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function mount(){$projectUuid = request()->route('project_uuid');$teamId = currentTeam()->id;- $project = Project::where('team_id', $teamId)->where('uuid', $projectUuid)->first();+ $project = Project::query()->where('team_id', $teamId)->where('uuid', $projectUuid)->first();if (! $project) {return redirect()->route('dashboard');}$this->project = $project;++ return null;}public function render()diff --git a/app/Livewire/SharedVariables/Team/Index.php b/app/Livewire/SharedVariables/Team/Index.phpindex a76ccf58a6..3de2b86faa 100644--- a/app/Livewire/SharedVariables/Team/Index.php+++ b/app/Livewire/SharedVariables/Team/Index.php@@ -3,7 +3,9 @@namespace App\Livewire\SharedVariables\Team;use App\Models\Team;+use Exception;use Livewire\Component;+use Throwable;class Index extends Component{@@ -16,7 +18,7 @@ class Index extends Componenttry {$found = $this->team->environment_variables()->where('key', $data['key'])->first();if ($found) {- throw new \Exception('Variable already exists.');+ throw new Exception('Variable already exists.');}$this->team->environment_variables()->create(['key' => $data['key'],@@ -27,9 +29,11 @@ class Index extends Component'team_id' => currentTeam()->id,]);$this->team->refresh();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function mount()diff --git a/app/Livewire/Source/Github/Change.php b/app/Livewire/Source/Github/Change.phpindex 8f4f02f70f..851212dc77 100644--- a/app/Livewire/Source/Github/Change.php+++ b/app/Livewire/Source/Github/Change.php@@ -5,11 +5,13 @@ namespace App\Livewire\Source\Github;use App\Jobs\GithubAppPermissionJob;use App\Models\GithubApp;use App\Models\PrivateKey;+use DateTimeImmutable;use Illuminate\Support\Facades\Http;use Lcobucci\JWT\Configuration;use Lcobucci\JWT\Signer\Key\InMemory;use Lcobucci\JWT\Signer\Rsa\Sha256;use Livewire\Component;+use Throwable;class Change extends Component{@@ -58,7 +60,7 @@ class Change extends Componentpublic function boot(){- if ($this->github_app) {+ if ($this->github_app instanceof GithubApp) {$this->github_app->makeVisible(['client_secret', 'webhook_secret']);}}@@ -151,9 +153,11 @@ class Change extends Component$this->webhook_endpoint = $this->ipv4;$this->is_system_wide = $this->github_app->is_system_wide;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function getGithubAppNameUpdatePath()@@ -179,8 +183,8 @@ class Change extends Component->issuedBy((string) $app_id)->permittedFor('https://api.github.com')->identifiedBy((string) $now)- ->issuedAt(new \DateTimeImmutable("@{$now}"))- ->expiresAt(new \DateTimeImmutable('@'.($now + 600)))+ ->issuedAt(new DateTimeImmutable("@{$now}"))+ ->expiresAt(new DateTimeImmutable('@'.($now + 600)))->getToken($configuration->signer(), $configuration->signingKey())->toString();}@@ -193,7 +197,7 @@ class Change extends Componentif (! $privateKey) {$this->dispatch('error', 'No private key found for this GitHub App.');- return;+ return null;}$jwt = $this->generateGithubJwt($privateKey->private_key, $this->github_app->app_id);@@ -222,9 +226,11 @@ class Change extends Component$error_message = $response->json()['message'] ?? 'Unknown error';$this->dispatch('error', "Failed to fetch GitHub App information: {$error_message}");}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function submit()@@ -247,9 +253,11 @@ class Change extends Component]);$this->github_app->save();$this->dispatch('success', 'Github App updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function instantSave()@@ -258,9 +266,11 @@ class Change extends Component$this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');$this->github_app->save();$this->dispatch('success', 'Github App updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function delete()@@ -270,12 +280,12 @@ class Change extends Component$this->dispatch('error', 'This source is being used by an application. Please delete all applications first.');$this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');- return;+ return null;}$this->github_app->delete();return redirect()->route('source.all');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Source/Github/Create.php b/app/Livewire/Source/Github/Create.phpindex 136d3525e0..0b6ede36f5 100644--- a/app/Livewire/Source/Github/Create.php+++ b/app/Livewire/Source/Github/Create.php@@ -4,6 +4,7 @@ namespace App\Livewire\Source\Github;use App\Models\GithubApp;use Livewire\Component;+use Throwable;class Create extends Component{@@ -50,13 +51,13 @@ class Create extends Componentif (isCloud()) {$payload['is_system_wide'] = $this->is_system_wide;}- $github_app = GithubApp::create($payload);+ $github_app = GithubApp::query()->create($payload);if (session('from')) {session(['from' => session('from') + ['source_id' => $github_app->id]]);}return redirect()->route('source.github.show', ['github_app_uuid' => $github_app->uuid]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Storage/Create.php b/app/Livewire/Storage/Create.phpindex c5250e1e3b..6e45b42114 100644--- a/app/Livewire/Storage/Create.php+++ b/app/Livewire/Storage/Create.php@@ -4,6 +4,7 @@ namespace App\Livewire\Storage;use App\Models\S3Storage;use Livewire\Component;+use Throwable;class Create extends Component{@@ -68,19 +69,17 @@ class Create extends Component$this->storage->key = $this->key;$this->storage->secret = $this->secret;$this->storage->bucket = $this->bucket;- if (empty($this->endpoint)) {- $this->storage->endpoint = "https://s3.{$this->region}.amazonaws.com";- } else {- $this->storage->endpoint = $this->endpoint;- }+ $this->storage->endpoint = ! isset($this->endpoint) || ($this->endpoint === '' || $this->endpoint === '0') ? "https://s3.{$this->region}.amazonaws.com" : $this->endpoint;$this->storage->team_id = currentTeam()->id;$this->storage->testConnection();$this->storage->save();return redirect()->route('storage.show', $this->storage->uuid);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->dispatch('error', 'Failed to create storage.', $e->getMessage());// return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Storage/Form.php b/app/Livewire/Storage/Form.phpindex 8ca0020c7b..2deecefdd9 100644--- a/app/Livewire/Storage/Form.php+++ b/app/Livewire/Storage/Form.php@@ -4,6 +4,7 @@ namespace App\Livewire\Storage;use App\Models\S3Storage;use Livewire\Component;+use Throwable;class Form extends Component{@@ -37,9 +38,11 @@ class Form extends Component$this->storage->testConnection(shouldSave: true);return $this->dispatch('success', 'Connection is working.', 'Tested with "ListObjectsV2" action.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->dispatch('error', 'Failed to create storage.', $e->getMessage());}++ return null;}public function delete()@@ -48,7 +51,7 @@ class Form extends Component$this->storage->delete();return redirect()->route('storage.index');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}@@ -58,8 +61,10 @@ class Form extends Component$this->validate();try {$this->test_s3_connection();- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Storage/Show.php b/app/Livewire/Storage/Show.phpindex bdea9a3b04..b473435c69 100644--- a/app/Livewire/Storage/Show.php+++ b/app/Livewire/Storage/Show.php@@ -7,7 +7,7 @@ use Livewire\Component;class Show extends Component{- public $storage = null;+ public $storage;public function mount(){diff --git a/app/Livewire/Subscription/Index.php b/app/Livewire/Subscription/Index.phpindex df450cf7ef..a6f6b19421 100644--- a/app/Livewire/Subscription/Index.php+++ b/app/Livewire/Subscription/Index.php@@ -25,13 +25,15 @@ class Index extends Component}$this->settings = instanceSettings();$this->alreadySubscribed = currentTeam()->subscription()->exists();++ return null;}public function stripeCustomerPortal(){$session = getStripeCustomerPortalSession(currentTeam());if (is_null($session)) {- return;+ return null;}return redirect($session->url);diff --git a/app/Livewire/Subscription/PricingPlans.php b/app/Livewire/Subscription/PricingPlans.phpindex 6b2d3fb364..c3099d70d8 100644--- a/app/Livewire/Subscription/PricingPlans.php+++ b/app/Livewire/Subscription/PricingPlans.php@@ -22,7 +22,7 @@ class PricingPlans extends Componentif (! $priceId) {$this->dispatch('error', 'Price ID not found! Please contact the administrator.');- return;+ return null;}$payload = ['allow_promotion_codes' => true,diff --git a/app/Livewire/Subscription/Show.php b/app/Livewire/Subscription/Show.phpindex 96258c64e0..e0c17af8ae 100644--- a/app/Livewire/Subscription/Show.php+++ b/app/Livewire/Subscription/Show.php@@ -17,6 +17,8 @@ class Show extends Componentif (! data_get(currentTeam(), 'subscription')) {return redirect()->route('subscription.index');}++ return null;}public function render()diff --git a/app/Livewire/SwitchTeam.php b/app/Livewire/SwitchTeam.phpindex 7629c95964..7d31dd5ab3 100644--- a/app/Livewire/SwitchTeam.php+++ b/app/Livewire/SwitchTeam.php@@ -22,11 +22,11 @@ class SwitchTeam extends Componentpublic function switch_to($team_id){if (! auth()->user()->teams->contains($team_id)) {- return;+ return null;}- $team_to_switch_to = Team::find($team_id);+ $team_to_switch_to = Team::query()->find($team_id);if (! $team_to_switch_to) {- return;+ return null;}refreshSession($team_to_switch_to);diff --git a/app/Livewire/Tags/Deployments.php b/app/Livewire/Tags/Deployments.phpindex e4afa5b606..932b0a4305 100644--- a/app/Livewire/Tags/Deployments.php+++ b/app/Livewire/Tags/Deployments.php@@ -3,6 +3,7 @@namespace App\Livewire\Tags;use App\Models\ApplicationDeploymentQueue;+use Exception;use Livewire\Component;class Deployments extends Component@@ -19,7 +20,7 @@ class Deployments extends Componentpublic function getDeployments(){try {- $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $this->resourceIds)->get([+ $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $this->resourceIds)->get(['id','application_id','application_name',@@ -30,8 +31,10 @@ class Deployments extends Component'status',])->sortBy('id')->groupBy('server_name')->toArray();$this->dispatch('deployments', $this->deploymentsPerTagPerServer);- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/Tags/Show.php b/app/Livewire/Tags/Show.phpindex fc5b133749..9955187c0a 100644--- a/app/Livewire/Tags/Show.php+++ b/app/Livewire/Tags/Show.php@@ -5,6 +5,7 @@ namespace App\Livewire\Tags;use App\Http\Controllers\Api\DeployController;use App\Models\ApplicationDeploymentQueue;use App\Models\Tag;+use Exception;use Illuminate\Support\Collection;use Livewire\Attributes\Locked;use Livewire\Attributes\Title;@@ -46,16 +47,18 @@ class Show extends Component$this->tag = $tag;$this->getDeployments();}- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function getDeployments(){try {$resource_ids = $this->applications->pluck('id');- $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $resource_ids)->get([+ $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $resource_ids)->get(['id','application_id','application_name',@@ -65,9 +68,11 @@ class Show extends Component'server_id','status',])->sortBy('id')->groupBy('server_name')->toArray();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function redeployAll()@@ -83,9 +88,11 @@ class Show extends Component$message->push($deploy->deploy_resource($resource));});$this->dispatch('success', 'Mass deployment started.');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Livewire/Team/AdminView.php b/app/Livewire/Team/AdminView.phpindex cfb47d9d83..58c46d51b2 100644--- a/app/Livewire/Team/AdminView.php+++ b/app/Livewire/Team/AdminView.php@@ -25,12 +25,14 @@ class AdminView extends Componentreturn redirect()->route('dashboard');}$this->getUsers();++ return null;}public function submitSearch(){if ($this->search !== '') {- $this->users = User::where(function ($query) {+ $this->users = User::query()->where(function ($query) {$query->where('name', 'like', "%{$this->search}%")->orWhere('email', 'like', "%{$this->search}%");})->get()->filter(function ($user) {@@ -43,7 +45,7 @@ class AdminView extends Componentpublic function getUsers(){- $users = User::where('id', '!=', auth()->id())->get();+ $users = User::query()->where('id', '!=', auth()->id())->get();if ($users->count() > $this->number_of_users_to_show) {$this->lots_of_users = true;$this->users = $users->take($this->number_of_users_to_show);@@ -77,24 +79,20 @@ class AdminView extends Componentif (! isInstanceAdmin()) {return redirect()->route('dashboard');}- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {- if (! Hash::check($password, Auth::user()->password)) {- $this->addError('password', 'The provided password is incorrect.');+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {+ $this->addError('password', 'The provided password is incorrect.');- return;- }+ return null;}if (! auth()->user()->isInstanceAdmin()) {return $this->dispatch('error', 'You are not authorized to delete users');}- $user = User::find($id);+ $user = User::query()->find($id);$teams = $user->teams;foreach ($teams as $team) {$user_alone_in_team = $team->members->count() === 1;- if ($team->id === 0) {- if ($user_alone_in_team) {- return $this->dispatch('error', 'User is alone in the root team, cannot delete');- }+ if ($team->id === 0 && $user_alone_in_team) {+ return $this->dispatch('error', 'User is alone in the root team, cannot delete');}if ($user_alone_in_team) {$this->finalizeDeletion($user, $team);@@ -110,26 +108,26 @@ class AdminView extends Component$team->members()->detach($user->id);continue;+ }+ $found_other_member_who_is_not_owner = $team->members->filter(function ($member) {+ return $member->pivot->role === 'member';+ })->first();+ if ($found_other_member_who_is_not_owner) {+ $found_other_member_who_is_not_owner->pivot->role = 'owner';+ $found_other_member_who_is_not_owner->pivot->save();+ $team->members()->detach($user->id);} else {- $found_other_member_who_is_not_owner = $team->members->filter(function ($member) {- return $member->pivot->role === 'member';- })->first();- if ($found_other_member_who_is_not_owner) {- $found_other_member_who_is_not_owner->pivot->role = 'owner';- $found_other_member_who_is_not_owner->pivot->save();- $team->members()->detach($user->id);- } else {- $this->finalizeDeletion($user, $team);- }-- continue;+ $this->finalizeDeletion($user, $team);}- } else {- $team->members()->detach($user->id);++ continue;}+ $team->members()->detach($user->id);}$user->delete();$this->getUsers();++ return null;}public function render()diff --git a/app/Livewire/Team/Create.php b/app/Livewire/Team/Create.phpindex f805d61222..f5069d92db 100644--- a/app/Livewire/Team/Create.php+++ b/app/Livewire/Team/Create.php@@ -5,6 +5,7 @@ namespace App\Livewire\Team;use App\Models\Team;use Livewire\Attributes\Validate;use Livewire\Component;+use Throwable;class Create extends Component{@@ -18,7 +19,7 @@ class Create extends Component{try {$this->validate();- $team = Team::create([+ $team = Team::query()->create(['name' => $this->name,'description' => $this->description,'personal_team' => false,@@ -27,7 +28,7 @@ class Create extends ComponentrefreshSession();return redirect()->route('team.index');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}}diff --git a/app/Livewire/Team/Index.php b/app/Livewire/Team/Index.phpindex 0972e7364f..0682d86aed 100644--- a/app/Livewire/Team/Index.php+++ b/app/Livewire/Team/Index.php@@ -7,6 +7,7 @@ use App\Models\TeamInvitation;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\DB;use Livewire\Component;+use Throwable;class Index extends Component{@@ -45,9 +46,11 @@ class Index extends Component$this->team->save();refreshSession();$this->dispatch('success', 'Team updated.');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function delete()diff --git a/app/Livewire/Team/Invitations.php b/app/Livewire/Team/Invitations.phpindex 93432efc86..9d3ea8736a 100644--- a/app/Livewire/Team/Invitations.php+++ b/app/Livewire/Team/Invitations.php@@ -3,6 +3,7 @@namespace App\Livewire\Team;use App\Models\TeamInvitation;+use Exception;use Livewire\Component;class Invitations extends Component@@ -18,9 +19,11 @@ class Invitations extends Component$initiation_found->delete();$this->refreshInvitations();$this->dispatch('success', 'Invitation revoked.');- } catch (\Exception) {+ } catch (Exception) {return $this->dispatch('error', 'Invitation not found.');}++ return null;}public function refreshInvitations()diff --git a/app/Livewire/Team/InviteLink.php b/app/Livewire/Team/InviteLink.phpindex 25f8a1ff51..50a7e302bb 100644--- a/app/Livewire/Team/InviteLink.php+++ b/app/Livewire/Team/InviteLink.php@@ -4,11 +4,13 @@ namespace App\Livewire\Team;use App\Models\TeamInvitation;use App\Models\User;+use Exception;use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Support\Facades\Crypt;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Str;use Livewire\Component;+use Throwable;use Visus\Cuid2\Cuid2;class InviteLink extends Component@@ -42,19 +44,19 @@ class InviteLink extends Componenttry {$this->validate();if (auth()->user()->role() === 'admin' && $this->role === 'owner') {- throw new \Exception('Admins cannot invite owners.');+ throw new Exception('Admins cannot invite owners.');}$member_emails = currentTeam()->members()->get()->pluck('email');if ($member_emails->contains($this->email)) {return handleError(livewire: $this, customErrorMessage: "$this->email is already a member of ".currentTeam()->name.'.');}- $uuid = new Cuid2(32);- $link = url('/').config('constants.invitation.link.base_url').$uuid;+ $cuid2 = new Cuid2(32);+ $link = url('/').config('constants.invitation.link.base_url').$cuid2;$user = User::whereEmail($this->email)->first();if (is_null($user)) {$password = Str::password();- $user = User::create([+ $user = User::query()->create(['name' => str($this->email)->before('@'),'email' => $this->email,'password' => Hash::make($password),@@ -68,36 +70,34 @@ class InviteLink extends Component$invitationValid = $invitation->isValid();if ($invitationValid) {return handleError(livewire: $this, customErrorMessage: "Pending invitation already exists for $this->email.");- } else {- $invitation->delete();}+ $invitation->delete();}- $invitation = TeamInvitation::firstOrCreate([+ $invitation = TeamInvitation::query()->firstOrCreate(['team_id' => currentTeam()->id,- 'uuid' => $uuid,+ 'uuid' => $cuid2,'email' => $this->email,'role' => $this->role,'link' => $link,'via' => $sendEmail ? 'email' : 'link',]);if ($sendEmail) {- $mail = new MailMessage;- $mail->view('emails.invitation-link', [+ $mailMessage = new MailMessage;+ $mailMessage->view('emails.invitation-link', ['team' => currentTeam()->name,'invitation_link' => $link,]);- $mail->subject('You have been invited to '.currentTeam()->name.' on '.config('app.name').'.');- send_user_an_email($mail, $this->email);+ $mailMessage->subject('You have been invited to '.currentTeam()->name.' on '.config('app.name').'.');+ send_user_an_email($mailMessage, $this->email);$this->dispatch('success', 'Invitation sent via email.');$this->dispatch('refreshInvitations');- return;- } else {- $this->dispatch('success', 'Invitation link generated.');- $this->dispatch('refreshInvitations');+ return null;}- } catch (\Throwable $e) {+ $this->dispatch('success', 'Invitation link generated.');+ $this->dispatch('refreshInvitations');+ } catch (Throwable $e) {$error_message = $e->getMessage();if ($e->getCode() === '23505') {$error_message = 'Invitation already sent.';@@ -105,5 +105,7 @@ class InviteLink extends Componentreturn handleError(error: $e, livewire: $this, customErrorMessage: $error_message);}++ return null;}}diff --git a/app/Livewire/Team/Member.php b/app/Livewire/Team/Member.phpindex 890d640a07..463d201546 100644--- a/app/Livewire/Team/Member.php+++ b/app/Livewire/Team/Member.php@@ -4,6 +4,7 @@ namespace App\Livewire\Team;use App\Enums\Role;use App\Models\User;+use Exception;use Illuminate\Support\Facades\Cache;use Livewire\Component;@@ -16,11 +17,11 @@ class Member extends Componenttry {if (Role::from(auth()->user()->role())->lt(Role::ADMIN)|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {- throw new \Exception('You are not authorized to perform this action.');+ throw new Exception('You are not authorized to perform this action.');}$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::ADMIN->value]);$this->dispatch('reloadWindow');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());}}@@ -30,11 +31,11 @@ class Member extends Componenttry {if (Role::from(auth()->user()->role())->lt(Role::OWNER)|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {- throw new \Exception('You are not authorized to perform this action.');+ throw new Exception('You are not authorized to perform this action.');}$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::OWNER->value]);$this->dispatch('reloadWindow');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());}}@@ -44,11 +45,11 @@ class Member extends Componenttry {if (Role::from(auth()->user()->role())->lt(Role::ADMIN)|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {- throw new \Exception('You are not authorized to perform this action.');+ throw new Exception('You are not authorized to perform this action.');}$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::MEMBER->value]);$this->dispatch('reloadWindow');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());}}@@ -58,7 +59,7 @@ class Member extends Componenttry {if (Role::from(auth()->user()->role())->lt(Role::ADMIN)|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {- throw new \Exception('You are not authorized to perform this action.');+ throw new Exception('You are not authorized to perform this action.');}$this->member->teams()->detach(currentTeam());Cache::forget("team:{$this->member->id}");@@ -66,7 +67,7 @@ class Member extends Componentreturn $this->member->teams()->first();});$this->dispatch('reloadWindow');- } catch (\Exception $e) {+ } catch (Exception $e) {$this->dispatch('error', $e->getMessage());}}diff --git a/app/Livewire/Team/Storage/Show.php b/app/Livewire/Team/Storage/Show.phpindex d3051afd42..f45c15c05b 100644--- a/app/Livewire/Team/Storage/Show.php+++ b/app/Livewire/Team/Storage/Show.php@@ -7,7 +7,7 @@ use Livewire\Component;class Show extends Component{- public $storage = null;+ public $storage;public function mount(){diff --git a/app/Livewire/Terminal/Index.php b/app/Livewire/Terminal/Index.phpindex a24a237c58..c087a5b03e 100644--- a/app/Livewire/Terminal/Index.php+++ b/app/Livewire/Terminal/Index.php@@ -3,6 +3,7 @@namespace App\Livewire\Terminal;use App\Models\Server;+use Exception;use Livewire\Attributes\On;use Livewire\Component;@@ -28,11 +29,13 @@ class Index extends Component{try {$this->containers = $this->getAllActiveContainers();- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);} finally {$this->isLoadingContainers = false;}++ return null;}private function getAllActiveContainers()@@ -43,8 +46,8 @@ class Index extends Component}return $server->loadAllContainers()->map(function ($container) use ($server) {- $state = data_get_str($container, 'State')->lower();- if ($state->contains('running')) {+ $stringable = data_get_str($container, 'State')->lower();+ if ($stringable->contains('running')) {return ['name' => data_get($container, 'Names'),'connection_name' => data_get($container, 'Names'),diff --git a/app/Livewire/Upgrade.php b/app/Livewire/Upgrade.phpindex e50085c64e..0bb3a548c3 100644--- a/app/Livewire/Upgrade.php+++ b/app/Livewire/Upgrade.php@@ -5,6 +5,7 @@ namespace App\Livewire;use App\Actions\Server\UpdateCoolify;use App\Models\InstanceSettings;use Livewire\Component;+use Throwable;class Upgrade extends Component{@@ -26,21 +27,25 @@ class Upgrade extends Componentif (isDev()) {$this->isUpgradeAvailable = true;}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}public function upgrade(){try {if ($this->updateInProgress) {- return;+ return null;}$this->updateInProgress = true;UpdateCoolify::run(manual_update: true);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e, $this);}++ return null;}}diff --git a/app/Livewire/VerifyEmail.php b/app/Livewire/VerifyEmail.phpindex fab3265b65..39aaa1f9cd 100644--- a/app/Livewire/VerifyEmail.php+++ b/app/Livewire/VerifyEmail.php@@ -3,6 +3,7 @@namespace App\Livewire;use DanHarrin\LivewireRateLimiting\WithRateLimiting;+use Exception;use Livewire\Component;class VerifyEmail extends Component@@ -15,9 +16,11 @@ class VerifyEmail extends Component$this->rateLimit(1, 300);auth()->user()->sendVerificationEmail();$this->dispatch('success', 'Email verification link sent!');- } catch (\Exception $e) {+ } catch (Exception $e) {return handleError($e, $this);}++ return null;}public function render()diff --git a/app/Models/Application.php b/app/Models/Application.phpindex 13f15468dc..5b99cfbd0d 100644--- a/app/Models/Application.php+++ b/app/Models/Application.php@@ -3,6 +3,7 @@namespace App\Models;use App\Enums\ApplicationDeploymentStatus;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Relations\HasMany;@@ -147,17 +148,15 @@ class Application extends BaseModelif ($application->isDirty('status')) {$payload['last_online_at'] = now();}- if ($application->isDirty('custom_nginx_configuration')) {- if ($application->custom_nginx_configuration === '') {- $payload['custom_nginx_configuration'] = null;- }+ if ($application->isDirty('custom_nginx_configuration') && $application->custom_nginx_configuration === '') {+ $payload['custom_nginx_configuration'] = null;}- if (count($payload) > 0) {+ if ($payload !== []) {$application->forceFill($payload);}});static::created(function ($application) {- ApplicationSetting::create([+ ApplicationSetting::query()->create(['application_id' => $application->id,]);$application->compose_parsing_version = self::$parserVersion;@@ -182,12 +181,12 @@ class Application extends BaseModelpublic static function ownedByCurrentTeamAPI(int $teamId){- return Application::whereRelation('environment.project.team', 'id', $teamId)->orderBy('name');+ return \App\Models\Application::query()->whereRelation('environment.project.team', 'id', $teamId)->orderBy('name');}public static function ownedByCurrentTeam(){- return Application::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');+ return \App\Models\Application::query()->whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');}public function getContainersToStop(bool $previewDeployments = false): array@@ -207,11 +206,11 @@ class Application extends BaseModel}$startTime = time();- while (count($processes) > 0) {+ while ($processes !== []) {$finishedProcesses = array_filter($processes, function ($process) {return ! $process->running();});- foreach ($finishedProcesses as $containerName => $process) {+ foreach (array_keys($finishedProcesses) as $containerName) {unset($processes[$containerName]);$this->removeContainer($containerName, $server);}@@ -252,17 +251,17 @@ class Application extends BaseModel}}- public function delete_volumes(?Collection $persistentStorages)+ public function delete_volumes(?Collection $collection){if ($this->build_pack === 'dockercompose') {$server = data_get($this, 'destination.server');instant_remote_process(["cd {$this->dirOnServer()} && docker compose down -v"], $server, false);} else {- if ($persistentStorages->count() === 0) {+ if ($collection->count() === 0) {return;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {+ foreach ($collection as $storage) {instant_remote_process(["docker volume rm -f $storage->name"], $server, false);}}@@ -289,20 +288,12 @@ class Application extends BaseModelpublic function is_public_repository(): bool{- if (data_get($this, 'source.is_public')) {- return true;- }-- return false;+ return (bool) data_get($this, 'source.is_public');}public function is_github_based(): bool{- if (data_get($this, 'source')) {- return true;- }-- return false;+ return (bool) data_get($this, 'source');}public function isForceHttpsEnabled()@@ -486,13 +477,12 @@ class Application extends BaseModelset: function ($value) {if (is_null($value) || $value === '') {return '/Dockerfile';- } else {- if ($value !== '/') {- return Str::start(Str::replaceEnd('/', '', $value), '/');- }-- return Str::start($value, '/');}+ if ($value !== '/') {+ return Str::start(Str::replaceEnd('/', '', $value), '/');+ }++ return Str::start($value, '/');});}@@ -503,13 +493,12 @@ class Application extends BaseModelset: function ($value) {if (is_null($value) || $value === '') {return '/docker-compose.yaml';- } else {- if ($value !== '/') {- return Str::start(Str::replaceEnd('/', '', $value), '/');- }-- return Str::start($value, '/');}+ if ($value !== '/') {+ return Str::start(Str::replaceEnd('/', '', $value), '/');+ }++ return Str::start($value, '/');});}@@ -580,37 +569,22 @@ class Application extends BaseModel{return Attribute::make(set: function ($value) {- if ($this->additional_servers->count() === 0) {- if (str($value)->contains('(')) {- $status = str($value)->before('(')->trim()->value();- $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';- } elseif (str($value)->contains(':')) {- $status = str($value)->before(':')->trim()->value();- $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';- } else {- $status = $value;- $health = 'unhealthy';- }-- return "$status:$health";+ if (str($value)->contains('(')) {+ $status = str($value)->before('(')->trim()->value();+ $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';+ } elseif (str($value)->contains(':')) {+ $status = str($value)->before(':')->trim()->value();+ $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';} else {- if (str($value)->contains('(')) {- $status = str($value)->before('(')->trim()->value();- $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';- } elseif (str($value)->contains(':')) {- $status = str($value)->before(':')->trim()->value();- $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';- } else {- $status = $value;- $health = 'unhealthy';- }-- return "$status:$health";+ $status = $value;+ $health = 'unhealthy';}++ return "$status:$health";},get: function ($value) {if ($this->additional_servers->count() === 0) {- //running (healthy)+ // running (healthy)if (str($value)->contains('(')) {$status = str($value)->before('(')->trim()->value();$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';@@ -623,25 +597,24 @@ class Application extends BaseModel}return "$status:$health";- } else {- $complex_status = null;- $complex_health = null;- $complex_status = $main_server_status = str($value)->before(':')->value();- $complex_health = $main_server_health = str($value)->after(':')->value() ?? 'unhealthy';- $additional_servers_status = $this->additional_servers->pluck('pivot.status');- foreach ($additional_servers_status as $status) {- $server_status = str($status)->before(':')->value();- $server_health = str($status)->after(':')->value() ?? 'unhealthy';- if ($main_server_status !== $server_status) {- $complex_status = 'degraded';- }- if ($main_server_health !== $server_health) {- $complex_health = 'unhealthy';- }+ }+ $complex_status = null;+ $complex_health = null;+ $complex_status = $main_server_status = str($value)->before(':')->value();+ $complex_health = $main_server_health = str($value)->after(':')->value() ?? 'unhealthy';+ $additional_servers_status = $this->additional_servers->pluck('pivot.status');+ foreach ($additional_servers_status as $status) {+ $server_status = str($status)->before(':')->value();+ $server_health = str($status)->after(':')->value() ?? 'unhealthy';+ if ($main_server_status !== $server_status) {+ $complex_status = 'degraded';+ }+ if ($main_server_health !== $server_health) {+ $complex_health = 'unhealthy';}-- return "$complex_status:$complex_health";}++ return "$complex_status:$complex_health";},);}@@ -790,27 +763,24 @@ class Application extends BaseModelpublic function isDeploymentInprogress(){- $deployments = ApplicationDeploymentQueue::where('application_id', $this->id)->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS, ApplicationDeploymentStatus::QUEUED])->count();- if ($deployments > 0) {- return true;- }+ $deployments = ApplicationDeploymentQueue::query()->where('application_id', $this->id)->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS, ApplicationDeploymentStatus::QUEUED])->count();- return false;+ return $deployments > 0;}public function get_last_successful_deployment(){- return ApplicationDeploymentQueue::where('application_id', $this->id)->where('status', ApplicationDeploymentStatus::FINISHED)->where('pull_request_id', 0)->orderBy('created_at', 'desc')->first();+ return ApplicationDeploymentQueue::query()->where('application_id', $this->id)->where('status', ApplicationDeploymentStatus::FINISHED)->where('pull_request_id', 0)->orderBy('created_at', 'desc')->first();}public function get_last_days_deployments(){- return ApplicationDeploymentQueue::where('application_id', $this->id)->where('created_at', '>=', now()->subDays(7))->orderBy('created_at', 'desc')->get();+ return ApplicationDeploymentQueue::query()->where('application_id', $this->id)->where('created_at', '>=', now()->subDays(7))->orderBy('created_at', 'desc')->get();}public function deployments(int $skip = 0, int $take = 10){- $deployments = ApplicationDeploymentQueue::where('application_id', $this->id)->orderBy('created_at', 'desc');+ $deployments = ApplicationDeploymentQueue::query()->where('application_id', $this->id)->orderBy('created_at', 'desc');$count = $deployments->count();$deployments = $deployments->skip($skip)->take($take)->get();@@ -822,25 +792,17 @@ class Application extends BaseModelpublic function get_deployment(string $deployment_uuid){- return Activity::where('subject_id', $this->id)->where('properties->type_uuid', '=', $deployment_uuid)->first();+ return Activity::query()->where('subject_id', $this->id)->where('properties->type_uuid', '=', $deployment_uuid)->first();}public function isDeployable(): bool{- if ($this->settings->is_auto_deploy_enabled) {- return true;- }-- return false;+ return (bool) $this->settings->is_auto_deploy_enabled;}public function isPRDeployable(): bool{- if ($this->settings->is_preview_deployments_enabled) {- return true;- }-- return false;+ return (bool) $this->settings->is_preview_deployments_enabled;}public function deploymentType()@@ -850,21 +812,17 @@ class Application extends BaseModel}if (data_get($this, 'private_key_id')) {return 'deploy_key';- } elseif (data_get($this, 'source')) {+ }+ if (data_get($this, 'source')) {return 'source';- } else {- return 'other';}- throw new \Exception('No deployment type found');++ return 'other';}public function could_set_build_commands(): bool{- if ($this->build_pack === 'nixpacks') {- return true;- }-- return false;+ return $this->build_pack === 'nixpacks';}public function git_based(): bool@@ -872,20 +830,13 @@ class Application extends BaseModelif ($this->dockerfile) {return false;}- if ($this->build_pack === 'dockerimage') {- return false;- }- return true;+ return $this->build_pack !== 'dockerimage';}public function isHealthcheckDisabled(): bool{- if (data_get($this, 'health_check_enabled') === false) {- return true;- }-- return false;+ return data_get($this, 'health_check_enabled') === false;}public function workdir()@@ -918,14 +869,13 @@ class Application extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function customRepository()@@ -957,7 +907,7 @@ class Application extends BaseModel$git_clone_command = "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git submodule update --init --recursive";}if ($this->settings->is_git_lfs_enabled) {- $git_clone_command = "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git lfs pull";+ return "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git lfs pull";}return $git_clone_command;@@ -973,7 +923,7 @@ class Application extends BaseModel'is_accessible' => true,'error' => null,];- } catch (\RuntimeException $ex) {+ } catch (RuntimeException $ex) {return ['is_accessible' => false,'error' => $ex->getMessage(),@@ -1077,6 +1027,8 @@ class Application extends BaseModel'fullRepoUrl' => $fullRepoUrl,];}++ return null;}public function generateGitImportCommands(string $deployment_uuid, int $pull_request_id = 0, ?string $git_type = null, bool $exec_in_docker = true, bool $only_checkout = false, ?string $custom_base_dir = null, ?string $commit = null)@@ -1098,7 +1050,7 @@ class Application extends BaseModel$source_html_url_host = $url['host'];$source_html_url_scheme = $url['scheme'];- if ($this->source->getMorphClass() === \App\Models\GithubApp::class) {+ if ($this->source->getMorphClass() === GithubApp::class) {if ($this->source->is_public) {$fullRepoUrl = "{$this->source->html_url}/{$customRepository}";$git_clone_command = "{$git_clone_command} {$this->source->html_url}/{$customRepository} {$baseDir}";@@ -1255,14 +1207,16 @@ class Application extends BaseModel'fullRepoUrl' => $fullRepoUrl,];}++ return null;}public function oldRawParser(){try {$yaml = Yaml::parse($this->docker_compose_raw);- } catch (\Exception $e) {- throw new \Exception($e->getMessage());+ } catch (Exception $e) {+ throw new Exception($e->getMessage(), $e->getCode(), $e);}$services = data_get($yaml, 'services');@@ -1270,24 +1224,27 @@ class Application extends BaseModel$services = collect($services)->map(function ($service) use ($commands) {$serviceVolumes = collect(data_get($service, 'volumes', []));if ($serviceVolumes->count() > 0) {- foreach ($serviceVolumes as $volume) {+ foreach ($serviceVolumes as $serviceVolume) {$workdir = $this->workdir();$type = null;$source = null;- if (is_string($volume)) {- $source = str($volume)->before(':');+ if (is_string($serviceVolume)) {+ $source = str($serviceVolume)->before(':');if ($source->startsWith('./') || $source->startsWith('/') || $source->startsWith('~')) {$type = str('bind');}- } elseif (is_array($volume)) {- $type = data_get_str($volume, 'type');- $source = data_get_str($volume, 'source');+ } elseif (is_array($serviceVolume)) {+ $type = data_get_str($serviceVolume, 'type');+ $source = data_get_str($serviceVolume, 'source');}if ($type?->value() === 'bind') {if ($source->value() === '/var/run/docker.sock') {continue;}- if ($source->value() === '/tmp' || $source->value() === '/tmp/') {+ if ($source->value() === '/tmp') {+ continue;+ }+ if ($source->value() === '/tmp/') {continue;}if ($source->startsWith('.')) {@@ -1322,27 +1279,28 @@ class Application extends BaseModel{if ((int) $this->compose_parsing_version >= 3) {return newParser($this, $pull_request_id, $preview_id);- } elseif ($this->docker_compose_raw) {+ }+ if ($this->docker_compose_raw) {return parseDockerComposeFile(resource: $this, isNew: false, pull_request_id: $pull_request_id, preview_id: $preview_id);- } else {- return collect([]);}++ return collect([]);}public function loadComposeFile($isInit = false){$initialDockerComposeLocation = $this->docker_compose_location;if ($isInit && $this->docker_compose_raw) {- return;+ return null;}- $uuid = new Cuid2;- ['commands' => $cloneCommand] = $this->generateGitImportCommands(deployment_uuid: $uuid, only_checkout: true, exec_in_docker: false, custom_base_dir: '.');+ $cuid2 = new Cuid2;+ ['commands' => $cloneCommand] = $this->generateGitImportCommands(deployment_uuid: $cuid2, only_checkout: true, exec_in_docker: false, custom_base_dir: '.');$workdir = rtrim($this->base_directory, '/');$composeFile = $this->docker_compose_location;$fileList = collect([".$workdir$composeFile"]);- $gitRemoteStatus = $this->getGitRemoteStatus(deployment_uuid: $uuid);+ $gitRemoteStatus = $this->getGitRemoteStatus(deployment_uuid: $cuid2);if (! $gitRemoteStatus['is_accessible']) {- throw new \RuntimeException("Failed to read Git source:\n\n{$gitRemoteStatus['error']}");+ throw new RuntimeException("Failed to read Git source:\n\n{$gitRemoteStatus['error']}");}$getGitVersion = instant_remote_process(['git --version'], $this->destination->server, false);$gitVersion = str($getGitVersion)->explode(' ')->last();@@ -1353,7 +1311,7 @@ class Application extends BaseModel$paths = collect();$currentPath = '';foreach ($parts as $part) {- $currentPath .= ($currentPath ? '/' : '').$part;+ $currentPath .= ($currentPath !== '' && $currentPath !== '0' ? '/' : '').$part;if (str($currentPath)->isNotEmpty()) {$paths->push($currentPath);}@@ -1362,9 +1320,9 @@ class Application extends BaseModelreturn $paths;})->flatten()->unique()->values();$commands = collect([- "rm -rf /tmp/{$uuid}",- "mkdir -p /tmp/{$uuid}",- "cd /tmp/{$uuid}",+ "rm -rf /tmp/{$cuid2}",+ "mkdir -p /tmp/{$cuid2}",+ "cd /tmp/{$cuid2}",$cloneCommand,'git sparse-checkout init',"git sparse-checkout set {$fileList->implode(' ')}",@@ -1373,9 +1331,9 @@ class Application extends BaseModel]);} else {$commands = collect([- "rm -rf /tmp/{$uuid}",- "mkdir -p /tmp/{$uuid}",- "cd /tmp/{$uuid}",+ "rm -rf /tmp/{$cuid2}",+ "mkdir -p /tmp/{$cuid2}",+ "cd /tmp/{$cuid2}",$cloneCommand,'git sparse-checkout init --cone',"git sparse-checkout set {$fileList->implode(' ')}",@@ -1385,22 +1343,22 @@ class Application extends BaseModel}try {$composeFileContent = instant_remote_process($commands, $this->destination->server);- } catch (\Exception $e) {+ } catch (Exception $e) {if (str($e->getMessage())->contains('No such file')) {- throw new \RuntimeException("Docker Compose file not found at: $workdir$composeFile<br><br>Check if you used the right extension (.yaml or .yml) in the compose file name.");+ throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile<br><br>Check if you used the right extension (.yaml or .yml) in the compose file name.", $e->getCode(), $e);}if (str($e->getMessage())->contains('fatal: repository') && str($e->getMessage())->contains('does not exist')) {if ($this->deploymentType() === 'deploy_key') {- throw new \RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.');+ throw new RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.', $e->getCode(), $e);}- throw new \RuntimeException('Repository does not exist. Please check your repository URL and try again.');+ throw new RuntimeException('Repository does not exist. Please check your repository URL and try again.', $e->getCode(), $e);}- throw new \RuntimeException($e->getMessage());+ throw new RuntimeException($e->getMessage(), $e->getCode(), $e);} finally {$this->docker_compose_location = $initialDockerComposeLocation;$this->save();$commands = collect([- "rm -rf /tmp/{$uuid}",+ "rm -rf /tmp/{$cuid2}",]);instant_remote_process($commands, $this->destination->server, false);}@@ -1416,11 +1374,7 @@ class Application extends BaseModel$json = $json->filter(function ($value, $key) use ($diff) {return ! in_array($key, $diff);});- if ($json) {- $this->docker_compose_domains = json_encode($json);- } else {- $this->docker_compose_domains = null;- }+ $this->docker_compose_domains = $json ? json_encode($json) : null;$this->save();}@@ -1428,16 +1382,15 @@ class Application extends BaseModel'parsedServices' => $parsedServices,'initialDockerComposeLocation' => $this->docker_compose_location,];- } else {- throw new \RuntimeException("Docker Compose file not found at: $workdir$composeFile<br><br>Check if you used the right extension (.yaml or .yml) in the compose file name.");}+ throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile<br><br>Check if you used the right extension (.yaml or .yml) in the compose file name.");}- public function parseContainerLabels(?ApplicationPreview $preview = null)+ public function parseContainerLabels(?ApplicationPreview $applicationPreview = null){$customLabels = data_get($this, 'custom_labels');if (! $customLabels) {- return;+ return null;}if (base64_encode(base64_decode($customLabels, true)) !== $customLabels) {$this->custom_labels = str($customLabels)->replace(',', "\n");@@ -1445,7 +1398,7 @@ class Application extends BaseModel}$customLabels = base64_decode($this->custom_labels);if (mb_detect_encoding($customLabels, 'ASCII', true) === false) {- $customLabels = str(implode('|coolify|', generateLabelsApplication($this, $preview)))->replace('|coolify|', "\n");+ $customLabels = str(implode('|coolify|', generateLabelsApplication($this, $applicationPreview)))->replace('|coolify|', "\n");}$this->custom_labels = base64_encode($customLabels);$this->save();@@ -1519,7 +1472,7 @@ class Application extends BaseModelif (isset($healthcheckCommand) && str_contains($trimmedLine, '\\')) {$healthcheckCommand .= ' '.trim($trimmedLine, '\\ ');}- if (isset($healthcheckCommand) && ! str_contains($trimmedLine, '\\') && ! empty($healthcheckCommand)) {+ if (isset($healthcheckCommand) && ! str_contains($trimmedLine, '\\') && ($healthcheckCommand !== '' && $healthcheckCommand !== '0')) {$healthcheckCommand .= ' '.$trimmedLine;break;}@@ -1569,8 +1522,8 @@ class Application extends BaseModel$template = $this->preview_url_template;$host = $url->getHost();$schema = $url->getScheme();- $random = new Cuid2;- $preview_fqdn = str_replace('{{random}}', $random, $template);+ $cuid2 = new Cuid2;+ $preview_fqdn = str_replace('{{random}}', $cuid2, $template);$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);$preview_fqdn = str_replace('{{pr_id}}', $pull_request_id, $preview_fqdn);$preview_fqdn = "$schema://$preview_fqdn";@@ -1583,7 +1536,7 @@ class Application extends BaseModelpublic static function getDomainsByUuid(string $uuid): array{- $application = self::where('uuid', $uuid)->first();+ $application = self::query()->where('uuid', $uuid)->first();if ($application) {return $application->fqdns;@@ -1605,7 +1558,7 @@ class Application extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -1614,6 +1567,8 @@ class Application extends BaseModelreturn $parsedCollection->toArray();}++ return null;}public function getMemoryMetrics(int $mins = 5)@@ -1629,7 +1584,7 @@ class Application extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -1638,12 +1593,14 @@ class Application extends BaseModelreturn $parsedCollection->toArray();}++ return null;}public function generateConfig($is_json = false){$config = collect([]);- if ($this->build_pack = 'nixpacks') {+ if (($this->build_pack = 'nixpacks') !== '') {$config = collect(['build_pack' => 'nixpacks','docker_registry_image_name' => $this->docker_registry_image_name,@@ -1677,7 +1634,7 @@ class Application extends BaseModel'config' => 'required|json',]);if ($validator->fails()) {- throw new \Exception('Invalid JSON format');+ throw new Exception('Invalid JSON format');}$config = json_decode($config, true);@@ -1689,7 +1646,7 @@ class Application extends BaseModel'config.settings.is_static' => 'required|boolean',]);if ($deepValidator->fails()) {- throw new \Exception('Invalid data');+ throw new Exception('Invalid data');}$config = $deepValidator->validated()['config'];@@ -1698,8 +1655,8 @@ class Application extends BaseModeldata_forget($config, 'settings');$this->update($config);$this->settings()->update($settings);- } catch (\Exception $e) {- throw new \Exception('Failed to update application settings');+ } catch (Exception $e) {+ throw new Exception('Failed to update application settings', $e->getCode(), $e);}}}diff --git a/app/Models/ApplicationDeploymentQueue.php b/app/Models/ApplicationDeploymentQueue.phpindex c261c30c65..6029d08011 100644--- a/app/Models/ApplicationDeploymentQueue.php+++ b/app/Models/ApplicationDeploymentQueue.php@@ -43,14 +43,14 @@ class ApplicationDeploymentQueue extends Modelpublic function application(): Attribute{return Attribute::make(- get: fn () => Application::find($this->application_id),+ get: fn () => Application::query()->find($this->application_id),);}public function server(): Attribute{return Attribute::make(- get: fn () => Server::find($this->server_id),+ get: fn () => Server::query()->find($this->server_id),);}diff --git a/app/Models/ApplicationPreview.php b/app/Models/ApplicationPreview.phpindex bf2bf05bf1..c06c32937f 100644--- a/app/Models/ApplicationPreview.php+++ b/app/Models/ApplicationPreview.php@@ -37,7 +37,7 @@ class ApplicationPreview extends BaseModelpublic static function findPreviewByApplicationAndPullId(int $application_id, int $pull_request_id){- return self::where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();+ return self::query()->where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();}public function isRunning()diff --git a/app/Models/DiscordNotificationSettings.php b/app/Models/DiscordNotificationSettings.phpindex 619393ddc0..edd3921909 100644--- a/app/Models/DiscordNotificationSettings.php+++ b/app/Models/DiscordNotificationSettings.php@@ -30,23 +30,6 @@ class DiscordNotificationSettings extends Model'server_unreachable_discord_notifications',];- protected $casts = [- 'discord_enabled' => 'boolean',- 'discord_webhook_url' => 'encrypted',-- 'deployment_success_discord_notifications' => 'boolean',- 'deployment_failure_discord_notifications' => 'boolean',- 'status_change_discord_notifications' => 'boolean',- 'backup_success_discord_notifications' => 'boolean',- 'backup_failure_discord_notifications' => 'boolean',- 'scheduled_task_success_discord_notifications' => 'boolean',- 'scheduled_task_failure_discord_notifications' => 'boolean',- 'docker_cleanup_discord_notifications' => 'boolean',- 'server_disk_usage_discord_notifications' => 'boolean',- 'server_reachable_discord_notifications' => 'boolean',- 'server_unreachable_discord_notifications' => 'boolean',- ];-public function team(){return $this->belongsTo(Team::class);@@ -56,4 +39,24 @@ class DiscordNotificationSettings extends Model{return $this->discord_enabled;}++ protected function casts(): array+ {+ return [+ 'discord_enabled' => 'boolean',+ 'discord_webhook_url' => 'encrypted',++ 'deployment_success_discord_notifications' => 'boolean',+ 'deployment_failure_discord_notifications' => 'boolean',+ 'status_change_discord_notifications' => 'boolean',+ 'backup_success_discord_notifications' => 'boolean',+ 'backup_failure_discord_notifications' => 'boolean',+ 'scheduled_task_success_discord_notifications' => 'boolean',+ 'scheduled_task_failure_discord_notifications' => 'boolean',+ 'docker_cleanup_discord_notifications' => 'boolean',+ 'server_disk_usage_discord_notifications' => 'boolean',+ 'server_reachable_discord_notifications' => 'boolean',+ 'server_unreachable_discord_notifications' => 'boolean',+ ];+ }}diff --git a/app/Models/EmailNotificationSettings.php b/app/Models/EmailNotificationSettings.phpindex ae118986fc..65e459e79d 100644--- a/app/Models/EmailNotificationSettings.php+++ b/app/Models/EmailNotificationSettings.php@@ -37,32 +37,6 @@ class EmailNotificationSettings extends Model'server_disk_usage_email_notifications',];- protected $casts = [- 'smtp_enabled' => 'boolean',- 'smtp_from_address' => 'encrypted',- 'smtp_from_name' => 'encrypted',- 'smtp_recipients' => 'encrypted',- 'smtp_host' => 'encrypted',- 'smtp_port' => 'integer',- 'smtp_username' => 'encrypted',- 'smtp_password' => 'encrypted',- 'smtp_timeout' => 'integer',-- 'resend_enabled' => 'boolean',- 'resend_api_key' => 'encrypted',-- 'use_instance_email_settings' => 'boolean',-- 'deployment_success_email_notifications' => 'boolean',- 'deployment_failure_email_notifications' => 'boolean',- 'status_change_email_notifications' => 'boolean',- 'backup_success_email_notifications' => 'boolean',- 'backup_failure_email_notifications' => 'boolean',- 'scheduled_task_success_email_notifications' => 'boolean',- 'scheduled_task_failure_email_notifications' => 'boolean',- 'server_disk_usage_email_notifications' => 'boolean',- ];-public function team(){return $this->belongsTo(Team::class);@@ -76,4 +50,33 @@ class EmailNotificationSettings extends Modelreturn $this->smtp_enabled || $this->resend_enabled || $this->use_instance_email_settings;}++ protected function casts(): array+ {+ return [+ 'smtp_enabled' => 'boolean',+ 'smtp_from_address' => 'encrypted',+ 'smtp_from_name' => 'encrypted',+ 'smtp_recipients' => 'encrypted',+ 'smtp_host' => 'encrypted',+ 'smtp_port' => 'integer',+ 'smtp_username' => 'encrypted',+ 'smtp_password' => 'encrypted',+ 'smtp_timeout' => 'integer',++ 'resend_enabled' => 'boolean',+ 'resend_api_key' => 'encrypted',++ 'use_instance_email_settings' => 'boolean',++ 'deployment_success_email_notifications' => 'boolean',+ 'deployment_failure_email_notifications' => 'boolean',+ 'status_change_email_notifications' => 'boolean',+ 'backup_success_email_notifications' => 'boolean',+ 'backup_failure_email_notifications' => 'boolean',+ 'scheduled_task_success_email_notifications' => 'boolean',+ 'scheduled_task_failure_email_notifications' => 'boolean',+ 'server_disk_usage_email_notifications' => 'boolean',+ ];+ }}diff --git a/app/Models/EnvironmentVariable.php b/app/Models/EnvironmentVariable.phpindex 507ff0d7e2..2dd4019700 100644--- a/app/Models/EnvironmentVariable.php+++ b/app/Models/EnvironmentVariable.php@@ -55,30 +55,30 @@ class EnvironmentVariable extends Model}});- static::created(function (EnvironmentVariable $environment_variable) {- if ($environment_variable->resourceable_type === Application::class && ! $environment_variable->is_preview) {- $found = ModelsEnvironmentVariable::where('key', $environment_variable->key)+ static::created(function (EnvironmentVariable $environmentVariable) {+ if ($environmentVariable->resourceable_type === Application::class && ! $environmentVariable->is_preview) {+ $found = ModelsEnvironmentVariable::where('key', $environmentVariable->key)->where('resourceable_type', Application::class)- ->where('resourceable_id', $environment_variable->resourceable_id)+ ->where('resourceable_id', $environmentVariable->resourceable_id)->where('is_preview', true)->first();if (! $found) {- $application = Application::find($environment_variable->resourceable_id);+ $application = Application::query()->find($environmentVariable->resourceable_id);if ($application && $application->build_pack !== 'dockerfile') {ModelsEnvironmentVariable::create([- 'key' => $environment_variable->key,- 'value' => $environment_variable->value,- 'is_build_time' => $environment_variable->is_build_time,- 'is_multiline' => $environment_variable->is_multiline ?? false,+ 'key' => $environmentVariable->key,+ 'value' => $environmentVariable->value,+ 'is_build_time' => $environmentVariable->is_build_time,+ 'is_multiline' => $environmentVariable->is_multiline ?? false,'resourceable_type' => Application::class,- 'resourceable_id' => $environment_variable->resourceable_id,+ 'resourceable_id' => $environmentVariable->resourceable_id,'is_preview' => true,]);}}}- $environment_variable->update([+ $environmentVariable->update(['version' => config('constants.coolify.version'),]);});@@ -143,18 +143,15 @@ class EnvironmentVariable extends Modelreturn Attribute::make(get: function () {$type = str($this->value)->after('{{')->before('.')->value;- if (str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}')) {- return true;- }- return false;+ return str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}');});}private function get_real_environment_variables(?string $environment_variable = null, $resource = null){- if ((is_null($environment_variable) && $environment_variable === '') || is_null($resource)) {+ if (is_null($resource)) {return null;}$environment_variable = trim($environment_variable);@@ -162,12 +159,12 @@ class EnvironmentVariable extends Modelif ($sharedEnvsFound->isEmpty()) {return $environment_variable;}- foreach ($sharedEnvsFound as $sharedEnv) {- $type = str($sharedEnv)->match('/(.*?)\./');+ foreach ($sharedEnvsFound as $sharedEnvFound) {+ $type = str($sharedEnvFound)->match('/(.*?)\./');if (! collect(SHARED_VARIABLE_TYPES)->contains($type)) {continue;}- $variable = str($sharedEnv)->match('/\.(.*)/');+ $variable = str($sharedEnvFound)->match('/\.(.*)/');if ($type->value() === 'environment') {$id = $resource->environment->id;} elseif ($type->value() === 'project') {@@ -178,9 +175,9 @@ class EnvironmentVariable extends Modelif (is_null($id)) {continue;}- $environment_variable_found = SharedEnvironmentVariable::where('type', $type)->where('key', $variable)->where('team_id', $resource->team()->id)->where("{$type}_id", $id)->first();+ $environment_variable_found = SharedEnvironmentVariable::query()->where('type', $type)->where('key', $variable)->where('team_id', $resource->team()->id)->where("{$type}_id", $id)->first();if ($environment_variable_found) {- $environment_variable = str($environment_variable)->replace("{{{$sharedEnv}}}", $environment_variable_found->value);+ $environment_variable = str($environment_variable)->replace("{{{$sharedEnvFound}}}", $environment_variable_found->value);}}diff --git a/app/Models/GithubApp.php b/app/Models/GithubApp.phpindex 0b0e93b128..f21597dfdd 100644--- a/app/Models/GithubApp.php+++ b/app/Models/GithubApp.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;class GithubApp extends BaseModel@@ -10,11 +11,6 @@ class GithubApp extends BaseModelprotected $appends = ['type'];- protected $casts = [- 'is_public' => 'boolean',- 'type' => 'string',- ];-protected $hidden = ['client_secret','webhook_secret',@@ -22,12 +18,12 @@ class GithubApp extends BaseModelprotected static function booted(): void{- static::deleting(function (GithubApp $github_app) {- $applications_count = Application::where('source_id', $github_app->id)->count();+ static::deleting(function (GithubApp $githubApp) {+ $applications_count = Application::query()->where('source_id', $githubApp->id)->count();if ($applications_count > 0) {- throw new \Exception('You cannot delete this GitHub App because it is in use by '.$applications_count.' application(s). Delete them first.');+ throw new Exception('You cannot delete this GitHub App because it is in use by '.$applications_count.' application(s). Delete them first.');}- $github_app->privateKey()->delete();+ $githubApp->privateKey()->delete();});}@@ -71,4 +67,12 @@ class GithubApp extends BaseModel},);}++ protected function casts(): array+ {+ return [+ 'is_public' => 'boolean',+ 'type' => 'string',+ ];+ }}diff --git a/app/Models/InstanceSettings.php b/app/Models/InstanceSettings.phpindex 5b89bb401c..58b243567c 100644--- a/app/Models/InstanceSettings.php+++ b/app/Models/InstanceSettings.php@@ -15,32 +15,11 @@ class InstanceSettings extends Model implements SendsEmailprotected $guarded = [];- protected $casts = [- 'smtp_enabled' => 'boolean',- 'smtp_from_address' => 'encrypted',- 'smtp_from_name' => 'encrypted',- 'smtp_recipients' => 'encrypted',- 'smtp_host' => 'encrypted',- 'smtp_port' => 'integer',- 'smtp_username' => 'encrypted',- 'smtp_password' => 'encrypted',- 'smtp_timeout' => 'integer',-- 'resend_enabled' => 'boolean',- 'resend_api_key' => 'encrypted',-- 'allowed_ip_ranges' => 'array',- 'is_auto_update_enabled' => 'boolean',- 'auto_update_frequency' => 'string',- 'update_check_frequency' => 'string',- 'sentinel_token' => 'encrypted',- ];-protected static function booted(): void{static::updated(function ($settings) {if ($settings->isDirty('helper_version')) {- Server::chunkById(100, function ($servers) {+ Server::query()->chunkById(100, function ($servers) {foreach ($servers as $server) {PullHelperImageJob::dispatch($server);}@@ -89,7 +68,7 @@ class InstanceSettings extends Model implements SendsEmailpublic static function get(){- return InstanceSettings::findOrFail(0);+ return \App\Models\InstanceSettings::query()->findOrFail(0);}public function getRecipients($notification)@@ -124,4 +103,27 @@ class InstanceSettings extends Model implements SendsEmail// }// );// }+ protected function casts(): array+ {+ return [+ 'smtp_enabled' => 'boolean',+ 'smtp_from_address' => 'encrypted',+ 'smtp_from_name' => 'encrypted',+ 'smtp_recipients' => 'encrypted',+ 'smtp_host' => 'encrypted',+ 'smtp_port' => 'integer',+ 'smtp_username' => 'encrypted',+ 'smtp_password' => 'encrypted',+ 'smtp_timeout' => 'integer',++ 'resend_enabled' => 'boolean',+ 'resend_api_key' => 'encrypted',++ 'allowed_ip_ranges' => 'array',+ 'is_auto_update_enabled' => 'boolean',+ 'auto_update_frequency' => 'string',+ 'update_check_frequency' => 'string',+ 'sentinel_token' => 'encrypted',+ ];+ }}diff --git a/app/Models/LocalFileVolume.php b/app/Models/LocalFileVolume.phpindex 2c223be779..c5b5a0870f 100644--- a/app/Models/LocalFileVolume.php+++ b/app/Models/LocalFileVolume.php@@ -3,6 +3,8 @@namespace App\Models;use App\Events\FileStorageChanged;+use App\Jobs\ServerStorageSaveJob;+use Exception;use Illuminate\Database\Eloquent\Factories\HasFactory;class LocalFileVolume extends BaseModel@@ -13,9 +15,9 @@ class LocalFileVolume extends BaseModelprotected static function booted(){- static::created(function (LocalFileVolume $fileVolume) {- $fileVolume->load(['service']);- dispatch(new \App\Jobs\ServerStorageSaveJob($fileVolume));+ static::created(function (LocalFileVolume $localFileVolume) {+ $localFileVolume->load(['service']);+ dispatch(new ServerStorageSaveJob($localFileVolume));});}@@ -35,7 +37,7 @@ class LocalFileVolume extends BaseModel$workdir = $this->resource->workdir();$server = $this->resource->destination->server;}- $commands = collect([]);+ collect([]);$path = data_get_str($this, 'fs_path');if ($path->startsWith('.')) {$path = $path->after('.');@@ -80,6 +82,8 @@ class LocalFileVolume extends BaseModelif ($commands->count() > 0) {return instant_remote_process($commands, $server);}++ return null;}public function saveStorageOnServer()@@ -118,12 +122,13 @@ class LocalFileVolume extends BaseModel$this->content = $content;$this->save();FileStorageChanged::dispatch(data_get($server, 'team_id'));- throw new \Exception('The following file is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory.');- } elseif ($isDir === 'OK' && ! $this->is_directory) {+ throw new Exception('The following file is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory.');+ }+ if ($isDir === 'OK' && ! $this->is_directory) {if ($path === '/' || $path === '.' || $path === '..' || $path === '' || str($path)->isEmpty() || is_null($path)) {$this->is_directory = true;$this->save();- throw new \Exception('The following file is a directory on the server, but you are trying to mark it as a file. <br><br>Please delete the directory on the server or mark it as directory.');+ throw new Exception('The following file is a directory on the server, but you are trying to mark it as a file. <br><br>Please delete the directory on the server or mark it as directory.');}instant_remote_process(["rm -fr $path",diff --git a/app/Models/LocalPersistentVolume.php b/app/Models/LocalPersistentVolume.phpindex 68e476365a..b3ed3c2441 100644--- a/app/Models/LocalPersistentVolume.php+++ b/app/Models/LocalPersistentVolume.php@@ -49,9 +49,9 @@ class LocalPersistentVolume extends Modelset: function (?string $value) {if ($value) {return str($value)->trim()->start('/')->value;- } else {- return $value;}++ return $value;});}diff --git a/app/Models/OauthSetting.php b/app/Models/OauthSetting.phpindex 3d82e89f29..eb72d862c4 100644--- a/app/Models/OauthSetting.php+++ b/app/Models/OauthSetting.php@@ -16,8 +16,8 @@ class OauthSetting extends Modelprotected function clientSecret(): Attribute{return Attribute::make(- get: fn (?string $value) => empty($value) ? null : Crypt::decryptString($value),- set: fn (?string $value) => empty($value) ? null : Crypt::encryptString($value),+ get: fn (?string $value) => $value === null || $value === '' || $value === '0' ? null : Crypt::decryptString($value),+ set: fn (?string $value) => $value === null || $value === '' || $value === '0' ? null : Crypt::encryptString($value),);}diff --git a/app/Models/PrivateKey.php b/app/Models/PrivateKey.phpindex 80015d87f8..228fb16218 100644--- a/app/Models/PrivateKey.php+++ b/app/Models/PrivateKey.php@@ -3,10 +3,12 @@namespace App\Models;use DanHarrin\LivewireRateLimiting\WithRateLimiting;+use Exception;use Illuminate\Support\Facades\Storage;use Illuminate\Validation\ValidationException;use OpenApi\Attributes as OA;use phpseclib3\Crypt\PublicKeyLoader;+use Throwable;#[OA\Schema(description: 'Private Key model',@@ -36,10 +38,6 @@ class PrivateKey extends BaseModel'fingerprint',];- protected $casts = [- 'private_key' => 'encrypted',- ];-protected static function booted(){static::saving(function ($key) {@@ -82,7 +80,7 @@ class PrivateKey extends BaseModelPublicKeyLoader::load($privateKey);return true;- } catch (\Throwable $e) {+ } catch (Throwable $e) {return false;}}@@ -111,8 +109,8 @@ class PrivateKey extends BaseModel'private_key' => $keyPair['private'],'public_key' => $keyPair['public'],];- } catch (\Throwable $e) {- throw new \Exception("Failed to generate new {$type} key: ".$e->getMessage());+ } catch (Throwable $e) {+ throw new Exception("Failed to generate new {$type} key: ".$e->getMessage(), $e->getCode(), $e);}}@@ -122,7 +120,7 @@ class PrivateKey extends BaseModel$key = PublicKeyLoader::load($privateKey);return $key->getPublicKey()->toString('OpenSSH', ['comment' => '']);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return null;}}@@ -187,10 +185,17 @@ class PrivateKey extends BaseModelpublic function isInUse(){- return $this->servers()->exists()- || $this->applications()->exists()- || $this->githubApps()->exists()- || $this->gitlabApps()->exists();+ if ($this->servers()->exists()) {+ return true;+ }+ if ($this->applications()->exists()) {+ return true;+ }+ if ($this->githubApps()->exists()) {+ return true;+ }++ return (bool) $this->gitlabApps()->exists();}public function safeDelete()@@ -211,22 +216,22 @@ class PrivateKey extends BaseModel$publicKey = $key->getPublicKey();return $publicKey->getFingerprint('sha256');- } catch (\Throwable $e) {+ } catch (Throwable $e) {return null;}}private static function fingerprintExists($fingerprint, $excludeId = null){- $query = self::query()+ $builder = self::query()->where('fingerprint', $fingerprint)->where('id', '!=', $excludeId);if (currentTeam()) {- $query->where('team_id', currentTeam()->id);+ $builder->where('team_id', currentTeam()->id);}- return $query->exists();+ return $builder->exists();}public static function cleanupUnusedKeys()@@ -235,4 +240,11 @@ class PrivateKey extends BaseModel$privateKey->safeDelete();});}++ protected function casts(): array+ {+ return [+ 'private_key' => 'encrypted',+ ];+ }}diff --git a/app/Models/Project.php b/app/Models/Project.phpindex 3b50b9b33e..d47da2b23c 100644--- a/app/Models/Project.php+++ b/app/Models/Project.php@@ -33,10 +33,10 @@ class Project extends BaseModelprotected static function booted(){static::created(function ($project) {- ProjectSetting::create([+ ProjectSetting::query()->create(['project_id' => $project->id,]);- Environment::create([+ Environment::query()->create(['name' => 'production','project_id' => $project->id,'uuid' => (string) new Cuid2,diff --git a/app/Models/PushoverNotificationSettings.php b/app/Models/PushoverNotificationSettings.phpindex e3191dcc34..4179057d6f 100644--- a/app/Models/PushoverNotificationSettings.php+++ b/app/Models/PushoverNotificationSettings.php@@ -31,24 +31,6 @@ class PushoverNotificationSettings extends Model'server_unreachable_pushover_notifications',];- protected $casts = [- 'pushover_enabled' => 'boolean',- 'pushover_user_key' => 'encrypted',- 'pushover_api_token' => 'encrypted',-- 'deployment_success_pushover_notifications' => 'boolean',- 'deployment_failure_pushover_notifications' => 'boolean',- 'status_change_pushover_notifications' => 'boolean',- 'backup_success_pushover_notifications' => 'boolean',- 'backup_failure_pushover_notifications' => 'boolean',- 'scheduled_task_success_pushover_notifications' => 'boolean',- 'scheduled_task_failure_pushover_notifications' => 'boolean',- 'docker_cleanup_pushover_notifications' => 'boolean',- 'server_disk_usage_pushover_notifications' => 'boolean',- 'server_reachable_pushover_notifications' => 'boolean',- 'server_unreachable_pushover_notifications' => 'boolean',- ];-public function team(){return $this->belongsTo(Team::class);@@ -58,4 +40,25 @@ class PushoverNotificationSettings extends Model{return $this->pushover_enabled;}++ protected function casts(): array+ {+ return [+ 'pushover_enabled' => 'boolean',+ 'pushover_user_key' => 'encrypted',+ 'pushover_api_token' => 'encrypted',++ 'deployment_success_pushover_notifications' => 'boolean',+ 'deployment_failure_pushover_notifications' => 'boolean',+ 'status_change_pushover_notifications' => 'boolean',+ 'backup_success_pushover_notifications' => 'boolean',+ 'backup_failure_pushover_notifications' => 'boolean',+ 'scheduled_task_success_pushover_notifications' => 'boolean',+ 'scheduled_task_failure_pushover_notifications' => 'boolean',+ 'docker_cleanup_pushover_notifications' => 'boolean',+ 'server_disk_usage_pushover_notifications' => 'boolean',+ 'server_reachable_pushover_notifications' => 'boolean',+ 'server_unreachable_pushover_notifications' => 'boolean',+ ];+ }}diff --git a/app/Models/S3Storage.php b/app/Models/S3Storage.phpindex f1247e6f74..c87b7f200a 100644--- a/app/Models/S3Storage.php+++ b/app/Models/S3Storage.php@@ -5,6 +5,7 @@ namespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Support\Facades\Storage;+use Throwable;class S3Storage extends BaseModel{@@ -12,12 +13,6 @@ class S3Storage extends BaseModelprotected $guarded = [];- protected $casts = [- 'is_usable' => 'boolean',- 'key' => 'encrypted',- 'secret' => 'encrypted',- ];-public static function ownedByCurrentTeam(array $select = ['*']){$selectArray = collect($select)->concat(['id']);@@ -57,12 +52,12 @@ class S3Storage extends BaseModelStorage::disk('custom-s3')->files();$this->unusable_email_sent = false;$this->is_usable = true;- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->is_usable = false;if ($this->unusable_email_sent === false && is_transactional_emails_enabled()) {- $mail = new MailMessage;- $mail->subject('Coolify: S3 Storage Connection Error');- $mail->view('emails.s3-connection-error', ['name' => $this->name, 'reason' => $e->getMessage(), 'url' => route('storage.show', ['storage_uuid' => $this->uuid])]);+ $mailMessage = new MailMessage;+ $mailMessage->subject('Coolify: S3 Storage Connection Error');+ $mailMessage->view('emails.s3-connection-error', ['name' => $this->name, 'reason' => $e->getMessage(), 'url' => route('storage.show', ['storage_uuid' => $this->uuid])]);$users = collect([]);$members = $this->team->members()->get();foreach ($members as $user) {@@ -71,7 +66,7 @@ class S3Storage extends BaseModel}}foreach ($users as $user) {- send_user_an_email($mail, $user->email);+ send_user_an_email($mailMessage, $user->email);}$this->unusable_email_sent = true;}@@ -83,4 +78,13 @@ class S3Storage extends BaseModel}}}++ protected function casts(): array+ {+ return [+ 'is_usable' => 'boolean',+ 'key' => 'encrypted',+ 'secret' => 'encrypted',+ ];+ }}diff --git a/app/Models/Server.php b/app/Models/Server.phpindex 8d11e23a93..484760096e 100644--- a/app/Models/Server.php+++ b/app/Models/Server.php@@ -10,6 +10,7 @@ use App\Events\ServerReachabilityChanged;use App\Jobs\CheckAndStartSentinelJob;use App\Notifications\Server\Reachable;use App\Notifications\Server\Unreachable;+use Exception;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -19,11 +20,13 @@ use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Stringable;+use Log;use OpenApi\Attributes as OA;use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;use Spatie\SchemalessAttributes\SchemalessAttributesTrait;use Spatie\Url\Url;use Symfony\Component\Yaml\Yaml;+use Throwable;#[OA\Schema(description: 'Server model',@@ -72,39 +75,37 @@ class Server extends BaseModel}});static::created(function ($server) {- ServerSetting::create([+ ServerSetting::query()->create(['server_id' => $server->id,]);if ($server->id === 0) {if ($server->isSwarm()) {- SwarmDocker::create([+ SwarmDocker::query()->create(['id' => 0,'name' => 'coolify','network' => 'coolify-overlay','server_id' => $server->id,]);} else {- StandaloneDocker::create([+ StandaloneDocker::query()->create(['id' => 0,'name' => 'coolify','network' => 'coolify','server_id' => $server->id,]);}+ } elseif ($server->isSwarm()) {+ SwarmDocker::query()->create([+ 'name' => 'coolify-overlay',+ 'network' => 'coolify-overlay',+ 'server_id' => $server->id,+ ]);} else {- if ($server->isSwarm()) {- SwarmDocker::create([- 'name' => 'coolify-overlay',- 'network' => 'coolify-overlay',- 'server_id' => $server->id,- ]);- } else {- StandaloneDocker::create([- 'name' => 'coolify',- 'network' => 'coolify',- 'server_id' => $server->id,- ]);- }+ StandaloneDocker::query()->create([+ 'name' => 'coolify',+ 'network' => 'coolify',+ 'server_id' => $server->id,+ ]);}if (! isset($server->proxy->redirect_enabled)) {$server->proxy->redirect_enabled = true;@@ -124,17 +125,6 @@ class Server extends BaseModel});}- protected $casts = [- 'proxy' => SchemalessAttributes::class,- 'logdrain_axiom_api_key' => 'encrypted',- 'logdrain_newrelic_license_key' => 'encrypted',- 'delete_unused_volumes' => 'boolean',- 'delete_unused_networks' => 'boolean',- 'unreachable_notification_sent' => 'boolean',- 'is_build_server' => 'boolean',- 'force_disabled' => 'boolean',- ];-protected $schemalessAttributes = ['proxy',];@@ -202,10 +192,8 @@ class Server extends BaseModel$proxy_type = $this->proxyType();$redirect_enabled = $this->proxy->redirect_enabled ?? true;$redirect_url = $this->proxy->redirect_url;- if (isDev()) {- if ($proxy_type === ProxyTypes::CADDY->value) {- $dynamic_conf_path = '/data/coolify/proxy/caddy/dynamic';- }+ if (isDev() && $proxy_type === ProxyTypes::CADDY->value) {+ $dynamic_conf_path = '/data/coolify/proxy/caddy/dynamic';}if ($proxy_type === ProxyTypes::TRAEFIK->value) {$default_redirect_file = "$dynamic_conf_path/default_redirect_503.yaml";@@ -223,15 +211,11 @@ class Server extends BaseModelinstant_remote_process(["rm -f $default_redirect_file"], $this);} else {if ($proxy_type === ProxyTypes::CADDY->value) {- if (filled($redirect_url)) {- $conf = ":80, :443 {+ $conf = filled($redirect_url) ? ":80, :443 {redir $redirect_url-}";- } else {- $conf = ':80, :443 {+}" : ':80, :443 {respond 503}';- }} elseif ($proxy_type === ProxyTypes::TRAEFIK->value) {$dynamic_conf = ['http' => [@@ -474,17 +458,9 @@ $schema://$host {if ($proxyType === ProxyTypes::TRAEFIK->value) {// Do nothing} elseif ($proxyType === ProxyTypes::CADDY->value) {- if (isDev()) {- $proxy_path = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/caddy';- } else {- $proxy_path = $proxy_path.'/caddy';- }+ $proxy_path = isDev() ? '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/caddy' : $proxy_path.'/caddy';} elseif ($proxyType === ProxyTypes::NGINX->value) {- if (isDev()) {- $proxy_path = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/nginx';- } else {- $proxy_path = $proxy_path.'/nginx';- }+ $proxy_path = isDev() ? '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/nginx' : $proxy_path.'/nginx';}return $proxy_path;@@ -545,7 +521,7 @@ $schema://$host {{$wait = $this->settings->sentinel_push_interval_seconds * 3;if ($wait < 120) {- $wait = 120;+ return 120;}return $wait;@@ -587,7 +563,7 @@ $schema://$host {if ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$cpu = json_decode($cpu, true);@@ -595,6 +571,8 @@ $schema://$host {return [(int) $metric['time'], (float) $metric['percent']];});}++ return null;}public function getMemoryMetrics(int $mins = 5)@@ -608,7 +586,7 @@ $schema://$host {if ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$memory = json_decode($memory, true);$parsedCollection = collect($memory)->map(function ($metric) {@@ -619,6 +597,8 @@ $schema://$host {return $parsedCollection->toArray();}++ return null;}public function getDiskUsage(): ?string@@ -661,11 +641,11 @@ $schema://$host {$containerReplicates = instant_remote_process(["docker service ls --format '{{json .}}'"], $this, false);if ($containerReplicates) {$containerReplicates = format_docker_command_output_to_json($containerReplicates);- foreach ($containerReplicates as $containerReplica) {- $name = data_get($containerReplica, 'Name');- $containers = $containers->map(function ($container) use ($name, $containerReplica) {+ foreach ($containerReplicates as $containerReplicate) {+ $name = data_get($containerReplicate, 'Name');+ $containers = $containers->map(function ($container) use ($name, $containerReplicate) {if (data_get($container, 'Spec.Name') === $name) {- $replicas = data_get($containerReplica, 'Replicas');+ $replicas = data_get($containerReplicate, 'Replicas');$running = str($replicas)->explode('/')[0];$total = str($replicas)->explode('/')[1];if ($running === $total) {@@ -737,9 +717,9 @@ $schema://$host {$containers = $containers->filter();return collect($containers);- } else {- return collect([]);}++ return collect([]);}public function hasDefinedResources()@@ -747,11 +727,8 @@ $schema://$host {$applications = $this->applications()->count() > 0;$databases = $this->databases()->count() > 0;$services = $this->services()->count() > 0;- if ($applications || $databases || $services) {- return true;- }- return false;+ return $applications || $databases || $services;}public function databases()@@ -781,7 +758,7 @@ $schema://$host {$additionalApplicationIds = collect($additionalApplicationIds)->map(function ($item) {return $item->application_id;});- Application::whereIn('id', $additionalApplicationIds)->get()->each(function ($application) use ($applications) {+ Application::query()->whereIn('id', $additionalApplicationIds)->get()->each(function ($application) use ($applications) {$applications->push($application);});@@ -799,7 +776,7 @@ $schema://$host {{return $this->previews()->filter(function ($preview) {$applicationId = data_get($preview, 'application_id');- $application = Application::find($applicationId);+ $application = Application::query()->find($applicationId);if (! $application) {return false;}@@ -901,11 +878,7 @@ $schema://$host {public function isProxyShouldRun(){// TODO: Do we need "|| $this->proxy->force_stop" here?- if ($this->proxyType() === ProxyTypes::NONE->value || $this->isBuildServer()) {- return false;- }-- return true;+ return $this->proxyType() !== ProxyTypes::NONE->value && ! $this->isBuildServer();}public function skipServer()@@ -913,11 +886,8 @@ $schema://$host {if ($this->ip === '1.2.3.4') {return true;}- if ($this->settings->force_disabled === true) {- return true;- }- return false;+ return $this->settings->force_disabled === true;}public function isFunctional()@@ -941,8 +911,8 @@ $schema://$host {$os_release = instant_remote_process(['cat /etc/os-release'], $this);$releaseLines = collect(explode("\n", $os_release));$collectedData = collect([]);- foreach ($releaseLines as $line) {- $item = str($line)->trim();+ foreach ($releaseLines as $releaseLine) {+ $item = str($releaseLine)->trim();$collectedData->put($item->before('=')->value(), $item->after('=')->lower()->replace('"', '')->value());}$ID = data_get($collectedData, 'ID');@@ -956,10 +926,10 @@ $schema://$host {if ($supported->count() === 1) {// ray('supported');return str($supported->first());- } else {- // ray('not supported');- return false;}++ // ray('not supported');+ return false;}public function isSwarm()@@ -982,11 +952,8 @@ $schema://$host {if ($this->status() === false) {return false;}- if ($this->isFunctional() === false) {- return false;- }- return true;+ return $this->isFunctional() !== false;}public function status(): bool@@ -1026,19 +993,19 @@ $schema://$host {$unreachableNotificationSent = (bool) $this->unreachable_notification_sent;$isReachable = (bool) $this->settings->is_reachable;- \Log::debug('Server reachability check', [+ Log::debug('Server reachability check', ['server_id' => $this->id,'is_reachable' => $isReachable,'notification_sent' => $unreachableNotificationSent,'unreachable_count' => $this->unreachable_count,]);- if ($isReachable === true) {+ if ($isReachable) {$this->unreachable_count = 0;$this->save();- if ($unreachableNotificationSent === true) {- \Log::debug('Server is now reachable, sending notification', [+ if ($unreachableNotificationSent) {+ Log::debug('Server is now reachable, sending notification', ['server_id' => $this->id,]);$this->sendReachableNotification();@@ -1048,7 +1015,7 @@ $schema://$host {}$this->increment('unreachable_count');- \Log::debug('Incremented unreachable count', [+ Log::debug('Incremented unreachable count', ['server_id' => $this->id,'new_count' => $this->unreachable_count,]);@@ -1056,7 +1023,7 @@ $schema://$host {if ($this->unreachable_count === 1) {$this->settings->is_reachable = true;$this->settings->save();- \Log::debug('First unreachable attempt, marking as reachable', [+ Log::debug('First unreachable attempt, marking as reachable', ['server_id' => $this->id,]);@@ -1067,7 +1034,7 @@ $schema://$host {$failedChecks = 0;for ($i = 0; $i < 3; $i++) {$status = $this->serverStatus();- \Log::debug('Additional reachability check', [+ Log::debug('Additional reachability check', ['server_id' => $this->id,'attempt' => $i + 1,'status' => $status,@@ -1079,7 +1046,7 @@ $schema://$host {}if ($failedChecks === 3 && ! $unreachableNotificationSent) {- \Log::debug('Server confirmed unreachable after 3 attempts, sending notification', [+ Log::debug('Server confirmed unreachable after 3 attempts, sending notification', ['server_id' => $this->id,]);$this->sendUnreachableNotification();@@ -1119,7 +1086,7 @@ $schema://$host {}return ['uptime' => true, 'error' => null];- } catch (\Throwable $e) {+ } catch (Throwable $e) {if ($justCheckingNewKey) {return ['uptime' => false, 'error' => 'This key is not valid for this server.'];}@@ -1145,18 +1112,18 @@ $schema://$host {$this->settings->is_usable = false;$this->settings->save();if ($throwError) {- throw new \Exception('Server is not usable. Docker Engine is not installed.');+ throw new Exception('Server is not usable. Docker Engine is not installed.');}return false;}try {instant_remote_process(['docker version'], $this);- } catch (\Throwable $e) {+ } catch (Throwable $e) {$this->settings->is_usable = false;$this->settings->save();if ($throwError) {- throw new \Exception('Server is not usable. Docker Engine is not running.');+ throw new Exception('Server is not usable. Docker Engine is not running.', $e->getCode(), $e);}return false;@@ -1175,7 +1142,7 @@ $schema://$host {$this->settings->is_usable = false;$this->settings->save();if ($throwError) {- throw new \Exception('Server is not usable. Docker Compose is not installed.');+ throw new Exception('Server is not usable. Docker Compose is not installed.');}return false;@@ -1191,9 +1158,7 @@ $schema://$host {$swarmStatus = instant_remote_process(['docker info|grep -i swarm'], $this, false);$swarmStatus = str($swarmStatus)->trim()->after(':')->trim();if ($swarmStatus === 'inactive') {- throw new \Exception('Docker Swarm is not initiated. Please join the server to a swarm before continuing.');-- return false;+ throw new Exception('Docker Swarm is not initiated. Please join the server to a swarm before continuing.');}$this->settings->is_usable = true;$this->settings->save();@@ -1225,13 +1190,13 @@ $schema://$host {public function validateCoolifyNetwork($isSwarm = false, $isBuildServer = false){if ($isBuildServer) {- return;+ return null;}if ($isSwarm) {return instant_remote_process(['docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true'], $this, false);- } else {- return instant_remote_process(['docker network create coolify --attachable >/dev/null 2>&1 || true'], $this, false);}++ return instant_remote_process(['docker network create coolify --attachable >/dev/null 2>&1 || true'], $this, false);}public function isNonRoot()@@ -1260,7 +1225,7 @@ $schema://$host {public function updateWithPrivateKey(array $data, ?PrivateKey $privateKey = null){$this->update($data);- if ($privateKey) {+ if ($privateKey instanceof PrivateKey) {$this->privateKey()->associate($privateKey);$this->save();}@@ -1290,9 +1255,11 @@ $schema://$host {} else {StartSentinel::run($this, true);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {return handleError($e);}++ return null;}public function url()@@ -1322,7 +1289,21 @@ $schema://$host {}}} else {- throw new \Exception('Invalid proxy type.');+ throw new Exception('Invalid proxy type.');}}++ protected function casts(): array+ {+ return [+ 'proxy' => SchemalessAttributes::class,+ 'logdrain_axiom_api_key' => 'encrypted',+ 'logdrain_newrelic_license_key' => 'encrypted',+ 'delete_unused_volumes' => 'boolean',+ 'delete_unused_networks' => 'boolean',+ 'unreachable_notification_sent' => 'boolean',+ 'is_build_server' => 'boolean',+ 'force_disabled' => 'boolean',+ ];+ }}diff --git a/app/Models/ServerSetting.php b/app/Models/ServerSetting.phpindex f4b776cca0..1b54e0ea5f 100644--- a/app/Models/ServerSetting.php+++ b/app/Models/ServerSetting.php@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Facades\Log;use OpenApi\Attributes as OA;+use Throwable;#[OA\Schema(description: 'Server Settings model',@@ -53,14 +54,6 @@ class ServerSetting extends Model{protected $guarded = [];- protected $casts = [- 'force_docker_cleanup' => 'boolean',- 'docker_cleanup_threshold' => 'integer',- 'sentinel_token' => 'encrypted',- 'is_reachable' => 'boolean',- 'is_usable' => 'boolean',- ];-protected static function booted(){static::creating(function ($setting) {@@ -71,7 +64,7 @@ class ServerSetting extends Modelif (str($setting->sentinel_custom_url)->isEmpty()) {$setting->generateSentinelUrl(save: false, ignoreEvent: true);}- } catch (\Throwable $e) {+ } catch (Throwable $e) {Log::error('Error creating server setting: '.$e->getMessage());}});@@ -148,4 +141,15 @@ class ServerSetting extends Model});}++ protected function casts(): array+ {+ return [+ 'force_docker_cleanup' => 'boolean',+ 'docker_cleanup_threshold' => 'integer',+ 'sentinel_token' => 'encrypted',+ 'is_reachable' => 'boolean',+ 'is_usable' => 'boolean',+ ];+ }}diff --git a/app/Models/Service.php b/app/Models/Service.phpindex 1df579802d..c01e74bcb7 100644--- a/app/Models/Service.php+++ b/app/Models/Service.php@@ -84,14 +84,13 @@ class Service extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}protected function serverStatus(): Attribute@@ -135,7 +134,7 @@ class Service extends BaseModelpublic static function ownedByCurrentTeam(){- return Service::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');+ return \App\Models\Service::query()->whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');}public function getContainersToStop(): array@@ -161,7 +160,7 @@ class Service extends BaseModel}$startTime = time();- while (count($processes) > 0) {+ while ($processes !== []) {$finishedProcesses = array_filter($processes, function ($process) {return ! $process->running();});@@ -231,11 +230,7 @@ class Service extends BaseModelcontinue;}if ($status->startsWith('running')) {- if ($complexStatus === 'exited') {- $complexStatus = 'degraded';- } else {- $complexStatus = 'running';- }+ $complexStatus = $complexStatus === 'exited' ? 'degraded' : 'running';} elseif ($status->startsWith('restarting')) {$complexStatus = 'degraded';} elseif ($status->startsWith('exited')) {@@ -260,11 +255,7 @@ class Service extends BaseModelcontinue;}if ($status->startsWith('running')) {- if ($complexStatus === 'exited') {- $complexStatus = 'degraded';- } else {- $complexStatus = 'running';- }+ $complexStatus = $complexStatus === 'exited' ? 'degraded' : 'running';} elseif ($status->startsWith('restarting')) {$complexStatus = 'degraded';} elseif ($status->startsWith('exited')) {@@ -1287,12 +1278,10 @@ class Service extends BaseModel$real_value = $env->real_value;if ($env->version === '4.0.0-beta.239') {$real_value = $env->real_value;+ } elseif ($env->is_literal || $env->is_multiline) {+ $real_value = '\''.$real_value.'\'';} else {- if ($env->is_literal || $env->is_multiline) {- $real_value = '\''.$real_value.'\'';- } else {- $real_value = escapeEnvVariables($env->real_value);- }+ $real_value = escapeEnvVariables($env->real_value);}$commands[] = "echo \"{$env->key}={$real_value}\" >> .env";}@@ -1307,11 +1296,12 @@ class Service extends BaseModel{if ((int) $this->compose_parsing_version >= 3) {return newParser($this);- } elseif ($this->docker_compose_raw) {+ }+ if ($this->docker_compose_raw) {return parseDockerComposeFile($this, $isNew);- } else {- return collect([]);}++ return collect([]);}public function networks()diff --git a/app/Models/ServiceApplication.php b/app/Models/ServiceApplication.phpindex 5cafc90422..f5c1e5f145 100644--- a/app/Models/ServiceApplication.php+++ b/app/Models/ServiceApplication.php@@ -34,12 +34,12 @@ class ServiceApplication extends BaseModelpublic static function ownedByCurrentTeamAPI(int $teamId){- return ServiceApplication::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');+ return \App\Models\ServiceApplication::query()->whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');}public static function ownedByCurrentTeam(){- return ServiceApplication::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');+ return \App\Models\ServiceApplication::query()->whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');}public function isRunning()diff --git a/app/Models/ServiceDatabase.php b/app/Models/ServiceDatabase.phpindex 5fdd52637f..88b637cd53 100644--- a/app/Models/ServiceDatabase.php+++ b/app/Models/ServiceDatabase.php@@ -26,12 +26,12 @@ class ServiceDatabase extends BaseModelpublic static function ownedByCurrentTeamAPI(int $teamId){- return ServiceDatabase::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');+ return \App\Models\ServiceDatabase::query()->whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');}public static function ownedByCurrentTeam(){- return ServiceDatabase::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');+ return \App\Models\ServiceDatabase::query()->whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');}public function restart()@@ -133,10 +133,19 @@ class ServiceDatabase extends BaseModelpublic function isBackupSolutionAvailable(){- return str($this->databaseType())->contains('mysql') ||- str($this->databaseType())->contains('postgres') ||- str($this->databaseType())->contains('postgis') ||- str($this->databaseType())->contains('mariadb') ||- str($this->databaseType())->contains('mongodb');+ if (str($this->databaseType())->contains('mysql')) {+ return true;+ }+ if (str($this->databaseType())->contains('postgres')) {+ return true;+ }+ if (str($this->databaseType())->contains('postgis')) {+ return true;+ }+ if (str($this->databaseType())->contains('mariadb')) {+ return true;+ }++ return (bool) str($this->databaseType())->contains('mongodb');}}diff --git a/app/Models/SharedEnvironmentVariable.php b/app/Models/SharedEnvironmentVariable.phpindex aab8b87350..453ff0c948 100644--- a/app/Models/SharedEnvironmentVariable.php+++ b/app/Models/SharedEnvironmentVariable.php@@ -8,8 +8,11 @@ class SharedEnvironmentVariable extends Model{protected $guarded = [];- protected $casts = [- 'key' => 'string',- 'value' => 'encrypted',- ];+ protected function casts(): array+ {+ return [+ 'key' => 'string',+ 'value' => 'encrypted',+ ];+ }}diff --git a/app/Models/SlackNotificationSettings.php b/app/Models/SlackNotificationSettings.phpindex 48153f2ea8..f14c527f4c 100644--- a/app/Models/SlackNotificationSettings.php+++ b/app/Models/SlackNotificationSettings.php@@ -30,23 +30,6 @@ class SlackNotificationSettings extends Model'server_unreachable_slack_notifications',];- protected $casts = [- 'slack_enabled' => 'boolean',- 'slack_webhook_url' => 'encrypted',-- 'deployment_success_slack_notifications' => 'boolean',- 'deployment_failure_slack_notifications' => 'boolean',- 'status_change_slack_notifications' => 'boolean',- 'backup_success_slack_notifications' => 'boolean',- 'backup_failure_slack_notifications' => 'boolean',- 'scheduled_task_success_slack_notifications' => 'boolean',- 'scheduled_task_failure_slack_notifications' => 'boolean',- 'docker_cleanup_slack_notifications' => 'boolean',- 'server_disk_usage_slack_notifications' => 'boolean',- 'server_reachable_slack_notifications' => 'boolean',- 'server_unreachable_slack_notifications' => 'boolean',- ];-public function team(){return $this->belongsTo(Team::class);@@ -56,4 +39,24 @@ class SlackNotificationSettings extends Model{return $this->slack_enabled;}++ protected function casts(): array+ {+ return [+ 'slack_enabled' => 'boolean',+ 'slack_webhook_url' => 'encrypted',++ 'deployment_success_slack_notifications' => 'boolean',+ 'deployment_failure_slack_notifications' => 'boolean',+ 'status_change_slack_notifications' => 'boolean',+ 'backup_success_slack_notifications' => 'boolean',+ 'backup_failure_slack_notifications' => 'boolean',+ 'scheduled_task_success_slack_notifications' => 'boolean',+ 'scheduled_task_failure_slack_notifications' => 'boolean',+ 'docker_cleanup_slack_notifications' => 'boolean',+ 'server_disk_usage_slack_notifications' => 'boolean',+ 'server_reachable_slack_notifications' => 'boolean',+ 'server_unreachable_slack_notifications' => 'boolean',+ ];+ }}diff --git a/app/Models/StandaloneClickhouse.php b/app/Models/StandaloneClickhouse.phpindex 60198115da..5bd23068e1 100644--- a/app/Models/StandaloneClickhouse.php+++ b/app/Models/StandaloneClickhouse.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,14 +16,10 @@ class StandaloneClickhouse extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];- protected $casts = [- 'clickhouse_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'clickhouse-data-'.$database->uuid,'mount_path' => '/bitnami/clickhouse','host_path' => null,@@ -69,14 +66,13 @@ class StandaloneClickhouse extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -109,8 +105,8 @@ class StandaloneClickhouse extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -283,7 +279,7 @@ class StandaloneClickhouse extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -305,7 +301,7 @@ class StandaloneClickhouse extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -319,4 +315,11 @@ class StandaloneClickhouse extends BaseModel{return false;}++ protected function casts(): array+ {+ return [+ 'clickhouse_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandaloneDocker.php b/app/Models/StandaloneDocker.phpindex 1ef6ff587a..3beb20d6ec 100644--- a/app/Models/StandaloneDocker.php+++ b/app/Models/StandaloneDocker.php@@ -74,6 +74,10 @@ class StandaloneDocker extends BaseModelpublic function attachedTo(){- return $this->applications?->count() > 0 || $this->databases()->count() > 0;+ if ($this->applications?->count() > 0) {+ return true;+ }++ return $this->databases()->count() > 0;}}diff --git a/app/Models/StandaloneDragonfly.php b/app/Models/StandaloneDragonfly.phpindex 3c1127d8de..d659e0a1bb 100644--- a/app/Models/StandaloneDragonfly.php+++ b/app/Models/StandaloneDragonfly.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,14 +16,10 @@ class StandaloneDragonfly extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];- protected $casts = [- 'dragonfly_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'dragonfly-data-'.$database->uuid,'mount_path' => '/data','host_path' => null,@@ -69,14 +66,13 @@ class StandaloneDragonfly extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -109,8 +105,8 @@ class StandaloneDragonfly extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -277,7 +273,7 @@ class StandaloneDragonfly extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -299,7 +295,7 @@ class StandaloneDragonfly extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -319,4 +315,11 @@ class StandaloneDragonfly extends BaseModelreturn $this->morphMany(EnvironmentVariable::class, 'resourceable')->orderBy('key', 'asc');}++ protected function casts(): array+ {+ return [+ 'dragonfly_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandaloneKeydb.php b/app/Models/StandaloneKeydb.phpindex ebf1c22e95..2754fa40f7 100644--- a/app/Models/StandaloneKeydb.php+++ b/app/Models/StandaloneKeydb.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,14 +16,10 @@ class StandaloneKeydb extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'server_status'];- protected $casts = [- 'keydb_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'keydb-data-'.$database->uuid,'mount_path' => '/data','host_path' => null,@@ -69,14 +66,13 @@ class StandaloneKeydb extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -109,8 +105,8 @@ class StandaloneKeydb extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -277,7 +273,7 @@ class StandaloneKeydb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -299,7 +295,7 @@ class StandaloneKeydb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -319,4 +315,11 @@ class StandaloneKeydb extends BaseModelreturn $this->morphMany(EnvironmentVariable::class, 'resourceable')->orderBy('key', 'asc');}++ protected function casts(): array+ {+ return [+ 'keydb_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandaloneMariadb.php b/app/Models/StandaloneMariadb.phpindex 004ead4d95..cdb1932717 100644--- a/app/Models/StandaloneMariadb.php+++ b/app/Models/StandaloneMariadb.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,14 +16,10 @@ class StandaloneMariadb extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];- protected $casts = [- 'mariadb_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'mariadb-data-'.$database->uuid,'mount_path' => '/var/lib/mysql','host_path' => null,@@ -69,14 +66,13 @@ class StandaloneMariadb extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -109,8 +105,8 @@ class StandaloneMariadb extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -283,7 +279,7 @@ class StandaloneMariadb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -305,7 +301,7 @@ class StandaloneMariadb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -319,4 +315,11 @@ class StandaloneMariadb extends BaseModel{return true;}++ protected function casts(): array+ {+ return [+ 'mariadb_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandaloneMongodb.php b/app/Models/StandaloneMongodb.phpindex aba0f6123e..76c618f804 100644--- a/app/Models/StandaloneMongodb.php+++ b/app/Models/StandaloneMongodb.php@@ -2,10 +2,12 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\SoftDeletes;+use Throwable;class StandaloneMongodb extends BaseModel{@@ -18,7 +20,7 @@ class StandaloneMongodb extends BaseModelprotected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'mongodb-configdb-'.$database->uuid,'mount_path' => '/data/configdb','host_path' => null,@@ -26,7 +28,7 @@ class StandaloneMongodb extends BaseModel'resource_type' => $database->getMorphClass(),'is_readonly' => true,]);- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'mongodb-db-'.$database->uuid,'mount_path' => '/data/db','host_path' => null,@@ -73,14 +75,13 @@ class StandaloneMongodb extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -113,8 +114,8 @@ class StandaloneMongodb extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -196,7 +197,7 @@ class StandaloneMongodb extends BaseModelget: function ($value) {try {return decrypt($value);- } catch (\Throwable $th) {+ } catch (Throwable $th) {$this->mongo_initdb_root_password = encrypt($value);$this->save();@@ -297,7 +298,7 @@ class StandaloneMongodb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -319,7 +320,7 @@ class StandaloneMongodb extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {diff --git a/app/Models/StandaloneMysql.php b/app/Models/StandaloneMysql.phpindex 9ae0fdcaeb..32cc016cfe 100644--- a/app/Models/StandaloneMysql.php+++ b/app/Models/StandaloneMysql.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,15 +16,10 @@ class StandaloneMysql extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];- protected $casts = [- 'mysql_password' => 'encrypted',- 'mysql_root_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'mysql-data-'.$database->uuid,'mount_path' => '/var/lib/mysql','host_path' => null,@@ -70,14 +66,13 @@ class StandaloneMysql extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -110,8 +105,8 @@ class StandaloneMysql extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -278,7 +273,7 @@ class StandaloneMysql extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -300,7 +295,7 @@ class StandaloneMysql extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -320,4 +315,12 @@ class StandaloneMysql extends BaseModelreturn $this->morphMany(EnvironmentVariable::class, 'resourceable')->orderBy('key', 'asc');}++ protected function casts(): array+ {+ return [+ 'mysql_password' => 'encrypted',+ 'mysql_root_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandalonePostgresql.php b/app/Models/StandalonePostgresql.phpindex dd92ae7c91..1117848231 100644--- a/app/Models/StandalonePostgresql.php+++ b/app/Models/StandalonePostgresql.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,15 +16,10 @@ class StandalonePostgresql extends BaseModelprotected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];- protected $casts = [- 'init_scripts' => 'array',- 'postgres_password' => 'encrypted',- ];-protected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'postgres-data-'.$database->uuid,'mount_path' => '/var/lib/postgresql/data','host_path' => null,@@ -74,8 +70,8 @@ class StandalonePostgresql extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -95,14 +91,13 @@ class StandalonePostgresql extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -283,7 +278,7 @@ class StandalonePostgresql extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -305,7 +300,7 @@ class StandalonePostgresql extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -320,4 +315,12 @@ class StandalonePostgresql extends BaseModelreturn $this->morphMany(EnvironmentVariable::class, 'resourceable')->orderBy('key', 'asc');}++ protected function casts(): array+ {+ return [+ 'init_scripts' => 'array',+ 'postgres_password' => 'encrypted',+ ];+ }}diff --git a/app/Models/StandaloneRedis.php b/app/Models/StandaloneRedis.phpindex ed5cf98708..5ca849c987 100644--- a/app/Models/StandaloneRedis.php+++ b/app/Models/StandaloneRedis.php@@ -2,6 +2,7 @@namespace App\Models;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -18,7 +19,7 @@ class StandaloneRedis extends BaseModelprotected static function booted(){static::created(function ($database) {- LocalPersistentVolume::create([+ LocalPersistentVolume::query()->create(['name' => 'redis-data-'.$database->uuid,'mount_path' => '/data','host_path' => null,@@ -65,14 +66,13 @@ class StandaloneRedis extends BaseModel}if ($oldConfigHash === $newConfigHash) {return false;- } else {- if ($save) {- $this->config_hash = $newConfigHash;- $this->save();- }-- return true;}+ if ($save) {+ $this->config_hash = $newConfigHash;+ $this->save();+ }++ return true;}public function isRunning()@@ -105,8 +105,8 @@ class StandaloneRedis extends BaseModelreturn;}$server = data_get($this, 'destination.server');- foreach ($persistentStorages as $storage) {- instant_remote_process(["docker volume rm -f $storage->name"], $server, false);+ foreach ($persistentStorages as $persistentStorage) {+ instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);}}@@ -288,7 +288,7 @@ class StandaloneRedis extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {@@ -310,7 +310,7 @@ class StandaloneRedis extends BaseModelif ($error === 'Unauthorized') {$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';}- throw new \Exception($error);+ throw new Exception($error);}$metrics = json_decode($metrics, true);$parsedCollection = collect($metrics)->map(function ($metric) {diff --git a/app/Models/Subscription.php b/app/Models/Subscription.phpindex 1bd84a6647..a50e39a27a 100644--- a/app/Models/Subscription.php+++ b/app/Models/Subscription.php@@ -19,7 +19,7 @@ class Subscription extends Modelif (! $this->stripe_plan_id) {return 'zero';}- $subscription = Subscription::where('id', $this->id)->first();+ $subscription = \App\Models\Subscription::query()->where('id', $this->id)->first();if (! $subscription) {return null;}diff --git a/app/Models/SwarmDocker.php b/app/Models/SwarmDocker.phpindex e0fe349c71..99993aba69 100644--- a/app/Models/SwarmDocker.php+++ b/app/Models/SwarmDocker.php@@ -77,6 +77,10 @@ class SwarmDocker extends BaseModelpublic function attachedTo(){- return $this->applications?->count() > 0 || $this->databases()->count() > 0;+ if ($this->applications?->count() > 0) {+ return true;+ }++ return $this->databases()->count() > 0;}}diff --git a/app/Models/Team.php b/app/Models/Team.phpindex 8651df3c8b..9915918b2d 100644--- a/app/Models/Team.php+++ b/app/Models/Team.php@@ -8,6 +8,7 @@ use App\Notifications\Channels\SendsEmail;use App\Notifications\Channels\SendsPushover;use App\Notifications\Channels\SendsSlack;use App\Traits\HasNotificationSettings;+use Exception;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Model;use Illuminate\Notifications\Notifiable;@@ -40,10 +41,6 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senprotected $guarded = [];- protected $casts = [- 'personal_team' => 'boolean',- ];-protected static function booted(){static::created(function ($team) {@@ -56,7 +53,7 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senstatic::saving(function ($team) {if (auth()->user()?->isMember()) {- throw new \Exception('You are not allowed to update this team.');+ throw new Exception('You are not allowed to update this team.');}});@@ -95,11 +92,7 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senpublic function serverOverflow(){- if ($this->serverLimit() < $this->servers->count()) {- return true;- }-- return false;+ return $this->serverLimit() < $this->servers->count();}public static function serverLimit()@@ -107,7 +100,7 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senif (currentTeam()->id === 0 && isDev()) {return 9999999;}- $team = Team::find(currentTeam()->id);+ $team = \App\Models\Team::query()->find(currentTeam()->id);if (! $team) {return 0;}@@ -169,12 +162,20 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senif (isCloud()) {return true;}+ if ($this->getNotificationSettings('email')?->isEnabled()) {+ return true;+ }+ if ($this->getNotificationSettings('discord')?->isEnabled()) {+ return true;+ }+ if ($this->getNotificationSettings('slack')?->isEnabled()) {+ return true;+ }+ if ($this->getNotificationSettings('telegram')?->isEnabled()) {+ return true;+ }- return $this->getNotificationSettings('email')?->isEnabled() ||- $this->getNotificationSettings('discord')?->isEnabled() ||- $this->getNotificationSettings('slack')?->isEnabled() ||- $this->getNotificationSettings('telegram')?->isEnabled() ||- $this->getNotificationSettings('pushover')?->isEnabled();+ return (bool) $this->getNotificationSettings('pushover')?->isEnabled();}public function subscriptionEnded()@@ -222,11 +223,7 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Senpublic function isEmpty(){- if ($this->projects()->count() === 0 && $this->servers()->count() === 0 && $this->privateKeys()->count() === 0 && $this->sources()->count() === 0) {- return true;- }-- return false;+ return $this->projects()->count() === 0 && $this->servers()->count() === 0 && $this->privateKeys()->count() === 0 && $this->sources()->count() === 0;}public function projects()@@ -282,4 +279,11 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Sen{return $this->hasOne(PushoverNotificationSettings::class);}++ protected function casts(): array+ {+ return [+ 'personal_team' => 'boolean',+ ];+ }}diff --git a/app/Models/TeamInvitation.php b/app/Models/TeamInvitation.phpindex bc1a90d586..b64b356bd0 100644--- a/app/Models/TeamInvitation.php+++ b/app/Models/TeamInvitation.php@@ -31,10 +31,9 @@ class TeamInvitation extends Model$diff = $createdAt->diffInDays(now());if ($diff <= config('constants.invitation.link.expiration_days')) {return true;- } else {- $this->delete();-- return false;}+ $this->delete();++ return false;}}diff --git a/app/Models/TelegramNotificationSettings.php b/app/Models/TelegramNotificationSettings.phpindex 78bd841bd4..ec83327aed 100644--- a/app/Models/TelegramNotificationSettings.php+++ b/app/Models/TelegramNotificationSettings.php@@ -43,36 +43,6 @@ class TelegramNotificationSettings extends Model'telegram_notifications_server_unreachable_thread_id',];- protected $casts = [- 'telegram_enabled' => 'boolean',- 'telegram_token' => 'encrypted',- 'telegram_chat_id' => 'encrypted',-- 'deployment_success_telegram_notifications' => 'boolean',- 'deployment_failure_telegram_notifications' => 'boolean',- 'status_change_telegram_notifications' => 'boolean',- 'backup_success_telegram_notifications' => 'boolean',- 'backup_failure_telegram_notifications' => 'boolean',- 'scheduled_task_success_telegram_notifications' => 'boolean',- 'scheduled_task_failure_telegram_notifications' => 'boolean',- 'docker_cleanup_telegram_notifications' => 'boolean',- 'server_disk_usage_telegram_notifications' => 'boolean',- 'server_reachable_telegram_notifications' => 'boolean',- 'server_unreachable_telegram_notifications' => 'boolean',-- 'telegram_notifications_deployment_success_thread_id' => 'encrypted',- 'telegram_notifications_deployment_failure_thread_id' => 'encrypted',- 'telegram_notifications_status_change_thread_id' => 'encrypted',- 'telegram_notifications_backup_success_thread_id' => 'encrypted',- 'telegram_notifications_backup_failure_thread_id' => 'encrypted',- 'telegram_notifications_scheduled_task_success_thread_id' => 'encrypted',- 'telegram_notifications_scheduled_task_failure_thread_id' => 'encrypted',- 'telegram_notifications_docker_cleanup_thread_id' => 'encrypted',- 'telegram_notifications_server_disk_usage_thread_id' => 'encrypted',- 'telegram_notifications_server_reachable_thread_id' => 'encrypted',- 'telegram_notifications_server_unreachable_thread_id' => 'encrypted',- ];-public function team(){return $this->belongsTo(Team::class);@@ -82,4 +52,37 @@ class TelegramNotificationSettings extends Model{return $this->telegram_enabled;}++ protected function casts(): array+ {+ return [+ 'telegram_enabled' => 'boolean',+ 'telegram_token' => 'encrypted',+ 'telegram_chat_id' => 'encrypted',++ 'deployment_success_telegram_notifications' => 'boolean',+ 'deployment_failure_telegram_notifications' => 'boolean',+ 'status_change_telegram_notifications' => 'boolean',+ 'backup_success_telegram_notifications' => 'boolean',+ 'backup_failure_telegram_notifications' => 'boolean',+ 'scheduled_task_success_telegram_notifications' => 'boolean',+ 'scheduled_task_failure_telegram_notifications' => 'boolean',+ 'docker_cleanup_telegram_notifications' => 'boolean',+ 'server_disk_usage_telegram_notifications' => 'boolean',+ 'server_reachable_telegram_notifications' => 'boolean',+ 'server_unreachable_telegram_notifications' => 'boolean',++ 'telegram_notifications_deployment_success_thread_id' => 'encrypted',+ 'telegram_notifications_deployment_failure_thread_id' => 'encrypted',+ 'telegram_notifications_status_change_thread_id' => 'encrypted',+ 'telegram_notifications_backup_success_thread_id' => 'encrypted',+ 'telegram_notifications_backup_failure_thread_id' => 'encrypted',+ 'telegram_notifications_scheduled_task_success_thread_id' => 'encrypted',+ 'telegram_notifications_scheduled_task_failure_thread_id' => 'encrypted',+ 'telegram_notifications_docker_cleanup_thread_id' => 'encrypted',+ 'telegram_notifications_server_disk_usage_thread_id' => 'encrypted',+ 'telegram_notifications_server_reachable_thread_id' => 'encrypted',+ 'telegram_notifications_server_unreachable_thread_id' => 'encrypted',+ ];+ }}diff --git a/app/Models/User.php b/app/Models/User.phpindex 7c23631c36..054a647fba 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -48,12 +48,6 @@ class User extends Authenticatable implements SendsEmail'two_factor_secret',];- protected $casts = [- 'email_verified_at' => 'datetime',- 'force_password_reset' => 'boolean',- 'show_boarding' => 'boolean',- ];-protected static function boot(){parent::boot();@@ -67,7 +61,7 @@ class User extends Authenticatable implements SendsEmail$team['id'] = 0;$team['name'] = 'Root Team';}- $new_team = Team::create($team);+ $new_team = Team::query()->create($team);$user->teams()->attach($new_team, ['role' => 'owner']);});}@@ -83,7 +77,7 @@ class User extends Authenticatable implements SendsEmail$team['id'] = 0;$team['name'] = 'Root Team';}- $new_team = Team::create($team);+ $new_team = Team::query()->create($team);$this->teams()->attach($new_team, ['role' => 'owner']);return $new_team;@@ -98,7 +92,7 @@ class User extends Authenticatable implements SendsEmailhash('crc32b', $tokenEntropy));- $token = $this->tokens()->create([+ $personalAccessToken = $this->tokens()->create(['name' => $name,'token' => hash('sha256', $plainTextToken),'abilities' => $abilities,@@ -106,7 +100,7 @@ class User extends Authenticatable implements SendsEmail'team_id' => session('currentTeam')->id,]);- return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);+ return new NewAccessToken($personalAccessToken, $personalAccessToken->getKey().'|'.$plainTextToken);}public function teams()@@ -121,7 +115,7 @@ class User extends Authenticatable implements SendsEmailpublic function sendVerificationEmail(){- $mail = new MailMessage;+ $mailMessage = new MailMessage;$url = Url::temporarySignedRoute('verify.verify',Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),@@ -130,11 +124,11 @@ class User extends Authenticatable implements SendsEmail'hash' => sha1($this->getEmailForVerification()),]);- $mail->view('emails.email-verification', [+ $mailMessage->view('emails.email-verification', ['url' => $url,]);- $mail->subject('Coolify: Verify your email.');- send_user_an_email($mail, $this->email);+ $mailMessage->subject('Coolify: Verify your email.');+ send_user_an_email($mailMessage, $this->email);}public function sendPasswordResetNotification($token): void@@ -144,7 +138,11 @@ class User extends Authenticatable implements SendsEmailpublic function isAdmin(){- return $this->role() === 'admin' || $this->role() === 'owner';+ if ($this->role() === 'admin') {+ return true;+ }++ return $this->role() === 'owner';}public function isOwner()@@ -181,11 +179,7 @@ class User extends Authenticatable implements SendsEmail{$found_root_team = Auth::user()->teams->filter(function ($team) {if ($team->id == 0) {- if (! Auth::user()->isAdmin()) {- return false;- }-- return true;+ return (bool) Auth::user()->isAdmin();}return false;@@ -201,7 +195,7 @@ class User extends Authenticatable implements SendsEmailreturn Auth::user()->teams[0];}- return Team::find(session('currentTeam')->id);+ return Team::query()->find(session('currentTeam')->id);});}@@ -221,4 +215,13 @@ class User extends Authenticatable implements SendsEmailreturn data_get($user, 'pivot.role');}++ protected function casts(): array+ {+ return [+ 'email_verified_at' => 'datetime',+ 'force_password_reset' => 'boolean',+ 'show_boarding' => 'boolean',+ ];+ }}diff --git a/app/Models/Webhook.php b/app/Models/Webhook.phpindex 8e2b629558..f4d7c3de98 100644--- a/app/Models/Webhook.php+++ b/app/Models/Webhook.php@@ -8,8 +8,11 @@ class Webhook extends Model{protected $guarded = [];- protected $casts = [- 'type' => 'string',- 'payload' => 'encrypted',- ];+ protected function casts(): array+ {+ return [+ 'type' => 'string',+ 'payload' => 'encrypted',+ ];+ }}diff --git a/app/Notifications/Application/DeploymentFailed.php b/app/Notifications/Application/DeploymentFailed.phpindex 0c09b1dbd0..37760d086a 100644--- a/app/Notifications/Application/DeploymentFailed.php+++ b/app/Notifications/Application/DeploymentFailed.php@@ -30,12 +30,12 @@ class DeploymentFailed extends CustomEmailNotificationpublic ?string $fqdn = null;- public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)+ public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $applicationPreview = null){$this->onQueue('high');$this->application = $application;$this->deployment_uuid = $deployment_uuid;- $this->preview = $preview;+ $this->preview = $applicationPreview;$this->application_name = data_get($application, 'name');$this->project_uuid = data_get($application, 'environment.project.uuid');$this->environment_uuid = data_get($application, 'environment.uuid');@@ -54,28 +54,28 @@ class DeploymentFailed extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;+ $mailMessage = new MailMessage;$pull_request_id = data_get($this->preview, 'pull_request_id', 0);$fqdn = $this->fqdn;if ($pull_request_id === 0) {- $mail->subject('Coolify: Deployment failed of '.$this->application_name.'.');+ $mailMessage->subject('Coolify: Deployment failed of '.$this->application_name.'.');} else {$fqdn = $this->preview->fqdn;- $mail->subject('Coolify: Deployment failed of pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.'.');+ $mailMessage->subject('Coolify: Deployment failed of pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.'.');}- $mail->view('emails.application-deployment-failed', [+ $mailMessage->view('emails.application-deployment-failed', ['name' => $this->application_name,'fqdn' => $fqdn,'deployment_url' => $this->deployment_url,'pull_request_id' => data_get($this->preview, 'pull_request_id', 0),]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$message = new DiscordMessage(title: ':cross_mark: Deployment failed',description: 'Pull request: '.$this->preview->pull_request_id,@@ -92,22 +92,16 @@ class DeploymentFailed extends CustomEmailNotification$message->addField('Domain', $this->fqdn, true);}} else {- if ($this->fqdn) {- $description = '[Open application]('.$this->fqdn.')';- } else {- $description = '';- }+ $description = $this->fqdn ? '[Open application]('.$this->fqdn.')' : '';$message = new DiscordMessage(title: ':cross_mark: Deployment failed',description: $description,color: DiscordMessage::errorColor(),isCritical: true,);-$message->addField('Project', data_get($this->application, 'environment.project.name'), true);$message->addField('Environment', $this->environment_name, true);$message->addField('Name', $this->application_name, true);-$message->addField('Deployment Logs', '[Link]('.$this->deployment_url.')');}@@ -116,7 +110,7 @@ class DeploymentFailed extends CustomEmailNotificationpublic function toTelegram(): array{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$message = 'Coolify: Pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.' ('.$this->preview->fqdn.') deployment failed: ';} else {$message = 'Coolify: Deployment failed of '.$this->application_name.' ('.$this->fqdn.'): ';@@ -136,7 +130,7 @@ class DeploymentFailed extends CustomEmailNotificationpublic function toPushover(): PushoverMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$title = "Pull request #{$this->preview->pull_request_id} deployment failed";$message = "Pull request deployment failed for {$this->application_name}";} else {@@ -161,7 +155,7 @@ class DeploymentFailed extends CustomEmailNotificationpublic function toSlack(): SlackMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$title = "Pull request #{$this->preview->pull_request_id} deployment failed";$description = "Pull request deployment failed for {$this->application_name}";if ($this->preview->fqdn) {diff --git a/app/Notifications/Application/DeploymentSuccess.php b/app/Notifications/Application/DeploymentSuccess.phpindex e1067e9bc4..1632988451 100644--- a/app/Notifications/Application/DeploymentSuccess.php+++ b/app/Notifications/Application/DeploymentSuccess.php@@ -30,12 +30,12 @@ class DeploymentSuccess extends CustomEmailNotificationpublic ?string $fqdn;- public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)+ public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $applicationPreview = null){$this->onQueue('high');$this->application = $application;$this->deployment_uuid = $deployment_uuid;- $this->preview = $preview;+ $this->preview = $applicationPreview;$this->application_name = data_get($application, 'name');$this->project_uuid = data_get($application, 'environment.project.uuid');$this->environment_uuid = data_get($application, 'environment.uuid');@@ -54,28 +54,28 @@ class DeploymentSuccess extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;+ $mailMessage = new MailMessage;$pull_request_id = data_get($this->preview, 'pull_request_id', 0);$fqdn = $this->fqdn;if ($pull_request_id === 0) {- $mail->subject("Coolify: New version is deployed of {$this->application_name}");+ $mailMessage->subject("Coolify: New version is deployed of {$this->application_name}");} else {$fqdn = $this->preview->fqdn;- $mail->subject("Coolify: Pull request #{$pull_request_id} of {$this->application_name} deployed successfully");+ $mailMessage->subject("Coolify: Pull request #{$pull_request_id} of {$this->application_name} deployed successfully");}- $mail->view('emails.application-deployment-success', [+ $mailMessage->view('emails.application-deployment-success', ['name' => $this->application_name,'fqdn' => $fqdn,'deployment_url' => $this->deployment_url,'pull_request_id' => $pull_request_id,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$message = new DiscordMessage(title: ':white_check_mark: Preview deployment successful',description: 'Pull request: '.$this->preview->pull_request_id,@@ -91,11 +91,7 @@ class DeploymentSuccess extends CustomEmailNotification$message->addField('Name', $this->application_name, true);$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');} else {- if ($this->fqdn) {- $description = '[Open application]('.$this->fqdn.')';- } else {- $description = '';- }+ $description = $this->fqdn ? '[Open application]('.$this->fqdn.')' : '';$message = new DiscordMessage(title: ':white_check_mark: New version successfully deployed',description: $description,@@ -104,7 +100,6 @@ class DeploymentSuccess extends CustomEmailNotification$message->addField('Project', data_get($this->application, 'environment.project.name'), true);$message->addField('Environment', $this->environment_name, true);$message->addField('Name', $this->application_name, true);-$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');}@@ -113,7 +108,7 @@ class DeploymentSuccess extends CustomEmailNotificationpublic function toTelegram(): array{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$message = 'Coolify: New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';if ($this->preview->fqdn) {$buttons[] = [@@ -145,7 +140,7 @@ class DeploymentSuccess extends CustomEmailNotificationpublic function toPushover(): PushoverMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";$message = 'New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';if ($this->preview->fqdn) {@@ -181,7 +176,7 @@ class DeploymentSuccess extends CustomEmailNotificationpublic function toSlack(): SlackMessage{- if ($this->preview) {+ if ($this->preview instanceof ApplicationPreview) {$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";$description = "New version successfully deployed for {$this->application_name}";if ($this->preview->fqdn) {diff --git a/app/Notifications/Application/StatusChanged.php b/app/Notifications/Application/StatusChanged.phpindex 669f6e5842..d9fa18e401 100644--- a/app/Notifications/Application/StatusChanged.php+++ b/app/Notifications/Application/StatusChanged.php@@ -23,18 +23,18 @@ class StatusChanged extends CustomEmailNotificationpublic ?string $fqdn;- public function __construct(public Application $resource)+ public function __construct(public Application $application){$this->onQueue('high');- $this->resource_name = data_get($resource, 'name');- $this->project_uuid = data_get($resource, 'environment.project.uuid');- $this->environment_uuid = data_get($resource, 'environment.uuid');- $this->environment_name = data_get($resource, 'environment.name');- $this->fqdn = data_get($resource, 'fqdn', null);+ $this->resource_name = data_get($application, 'name');+ $this->project_uuid = data_get($application, 'environment.project.uuid');+ $this->environment_uuid = data_get($application, 'environment.uuid');+ $this->environment_name = data_get($application, 'environment.name');+ $this->fqdn = data_get($application, 'fqdn', null);if (str($this->fqdn)->explode(',')->count() > 1) {$this->fqdn = str($this->fqdn)->explode(',')->first();}- $this->resource_url = base_url()."/project/{$this->project_uuid}/environments/{$this->environment_uuid}/application/{$this->resource->uuid}";+ $this->resource_url = base_url()."/project/{$this->project_uuid}/environments/{$this->environment_uuid}/application/{$this->application->uuid}";}public function via(object $notifiable): array@@ -44,16 +44,16 @@ class StatusChanged extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;+ $mailMessage = new MailMessage;$fqdn = $this->fqdn;- $mail->subject("Coolify: {$this->resource_name} has been stopped");- $mail->view('emails.application-status-changes', [+ $mailMessage->subject("Coolify: {$this->resource_name} has been stopped");+ $mailMessage->view('emails.application-status-changes', ['name' => $this->resource_name,'fqdn' => $fqdn,'resource_url' => $this->resource_url,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage@@ -103,7 +103,7 @@ class StatusChanged extends CustomEmailNotification$title = 'Application stopped';$description = "{$this->resource_name} has been stopped";- $description .= "\n\n**Project:** ".data_get($this->resource, 'environment.project.name');+ $description .= "\n\n**Project:** ".data_get($this->application, 'environment.project.name');$description .= "\n**Environment:** {$this->environment_name}";$description .= "\n**Application URL:** {$this->resource_url}";diff --git a/app/Notifications/Channels/DiscordChannel.php b/app/Notifications/Channels/DiscordChannel.phpindex 362006d8ec..cf3613df00 100644--- a/app/Notifications/Channels/DiscordChannel.php+++ b/app/Notifications/Channels/DiscordChannel.php@@ -10,11 +10,11 @@ class DiscordChannel/*** Send the given notification.*/- public function send(SendsDiscord $notifiable, Notification $notification): void+ public function send(SendsDiscord $sendsDiscord, Notification $notification): void{$message = $notification->toDiscord();- $discordSettings = $notifiable->discordNotificationSettings;+ $discordSettings = $sendsDiscord->discordNotificationSettings;if (! $discordSettings || ! $discordSettings->isEnabled() || ! $discordSettings->discord_webhook_url) {return;diff --git a/app/Notifications/Channels/EmailChannel.php b/app/Notifications/Channels/EmailChannel.phpindex 6ffe5c4d79..1289e2b572 100644--- a/app/Notifications/Channels/EmailChannel.php+++ b/app/Notifications/Channels/EmailChannel.php@@ -9,16 +9,16 @@ use Illuminate\Support\Facades\Mail;class EmailChannel{- public function send(SendsEmail $notifiable, Notification $notification): void+ public function send(SendsEmail $sendsEmail, Notification $notification): void{try {- $this->bootConfigs($notifiable);- $recipients = $notifiable->getRecipients($notification);+ $this->bootConfigs($sendsEmail);+ $recipients = $sendsEmail->getRecipients($notification);if (count($recipients) === 0) {throw new Exception('No email recipients found');}- $mailMessage = $notification->toMail($notifiable);+ $mailMessage = $notification->toMail($sendsEmail);Mail::send([],[],diff --git a/app/Notifications/Channels/PushoverChannel.php b/app/Notifications/Channels/PushoverChannel.phpindex 3d3728d01f..663db4aa77 100644--- a/app/Notifications/Channels/PushoverChannel.php+++ b/app/Notifications/Channels/PushoverChannel.php@@ -7,10 +7,10 @@ use Illuminate\Notifications\Notification;class PushoverChannel{- public function send(SendsPushover $notifiable, Notification $notification): void+ public function send(SendsPushover $sendsPushover, Notification $notification): void{$message = $notification->toPushover();- $pushoverSettings = $notifiable->pushoverNotificationSettings;+ $pushoverSettings = $sendsPushover->pushoverNotificationSettings;if (! $pushoverSettings || ! $pushoverSettings->isEnabled() || ! $pushoverSettings->pushover_user_key || ! $pushoverSettings->pushover_api_token) {return;diff --git a/app/Notifications/Channels/SlackChannel.php b/app/Notifications/Channels/SlackChannel.phpindex cddb7a5611..f85de5c826 100644--- a/app/Notifications/Channels/SlackChannel.php+++ b/app/Notifications/Channels/SlackChannel.php@@ -10,10 +10,10 @@ class SlackChannel/*** Send the given notification.*/- public function send(SendsSlack $notifiable, Notification $notification): void+ public function send(SendsSlack $sendsSlack, Notification $notification): void{$message = $notification->toSlack();- $slackSettings = $notifiable->slackNotificationSettings;+ $slackSettings = $sendsSlack->slackNotificationSettings;if (! $slackSettings || ! $slackSettings->isEnabled() || ! $slackSettings->slack_webhook_url) {return;diff --git a/app/Notifications/Channels/TelegramChannel.php b/app/Notifications/Channels/TelegramChannel.phpindex ea4ab71715..43f8fc4233 100644--- a/app/Notifications/Channels/TelegramChannel.php+++ b/app/Notifications/Channels/TelegramChannel.php@@ -3,6 +3,20 @@namespace App\Notifications\Channels;use App\Jobs\SendMessageToTelegramJob;+use App\Notifications\Application\DeploymentFailed;+use App\Notifications\Application\DeploymentSuccess;+use App\Notifications\Application\StatusChanged;+use App\Notifications\Container\ContainerRestarted;+use App\Notifications\Container\ContainerStopped;+use App\Notifications\Database\BackupFailed;+use App\Notifications\Database\BackupSuccess;+use App\Notifications\ScheduledTask\TaskFailed;+use App\Notifications\ScheduledTask\TaskSuccess;+use App\Notifications\Server\DockerCleanupFailed;+use App\Notifications\Server\DockerCleanupSuccess;+use App\Notifications\Server\HighDiskUsage;+use App\Notifications\Server\Reachable;+use App\Notifications\Server\Unreachable;class TelegramChannel{@@ -17,23 +31,23 @@ class TelegramChannel$chatId = $settings->telegram_chat_id;$threadId = match (get_class($notification)) {- \App\Notifications\Application\DeploymentSuccess::class => $settings->telegram_notifications_deployment_success_thread_id,- \App\Notifications\Application\DeploymentFailed::class => $settings->telegram_notifications_deployment_failure_thread_id,- \App\Notifications\Application\StatusChanged::class,- \App\Notifications\Container\ContainerRestarted::class,- \App\Notifications\Container\ContainerStopped::class => $settings->telegram_notifications_status_change_thread_id,-- \App\Notifications\Database\BackupSuccess::class => $settings->telegram_notifications_backup_success_thread_id,- \App\Notifications\Database\BackupFailed::class => $settings->telegram_notifications_backup_failure_thread_id,-- \App\Notifications\ScheduledTask\TaskSuccess::class => $settings->telegram_notifications_scheduled_task_success_thread_id,- \App\Notifications\ScheduledTask\TaskFailed::class => $settings->telegram_notifications_scheduled_task_failure_thread_id,-- \App\Notifications\Server\DockerCleanupSuccess::class => $settings->telegram_notifications_docker_cleanup_success_thread_id,- \App\Notifications\Server\DockerCleanupFailed::class => $settings->telegram_notifications_docker_cleanup_failure_thread_id,- \App\Notifications\Server\HighDiskUsage::class => $settings->telegram_notifications_server_disk_usage_thread_id,- \App\Notifications\Server\Unreachable::class => $settings->telegram_notifications_server_unreachable_thread_id,- \App\Notifications\Server\Reachable::class => $settings->telegram_notifications_server_reachable_thread_id,+ DeploymentSuccess::class => $settings->telegram_notifications_deployment_success_thread_id,+ DeploymentFailed::class => $settings->telegram_notifications_deployment_failure_thread_id,+ StatusChanged::class,+ ContainerRestarted::class,+ ContainerStopped::class => $settings->telegram_notifications_status_change_thread_id,++ BackupSuccess::class => $settings->telegram_notifications_backup_success_thread_id,+ BackupFailed::class => $settings->telegram_notifications_backup_failure_thread_id,++ TaskSuccess::class => $settings->telegram_notifications_scheduled_task_success_thread_id,+ TaskFailed::class => $settings->telegram_notifications_scheduled_task_failure_thread_id,++ DockerCleanupSuccess::class => $settings->telegram_notifications_docker_cleanup_success_thread_id,+ DockerCleanupFailed::class => $settings->telegram_notifications_docker_cleanup_failure_thread_id,+ HighDiskUsage::class => $settings->telegram_notifications_server_disk_usage_thread_id,+ Unreachable::class => $settings->telegram_notifications_server_unreachable_thread_id,+ Reachable::class => $settings->telegram_notifications_server_reachable_thread_id,default => null,};diff --git a/app/Notifications/Channels/TransactionalEmailChannel.php b/app/Notifications/Channels/TransactionalEmailChannel.phpindex 7617802313..91bfaa8b67 100644--- a/app/Notifications/Channels/TransactionalEmailChannel.php+++ b/app/Notifications/Channels/TransactionalEmailChannel.php@@ -10,18 +10,18 @@ use Illuminate\Support\Facades\Mail;class TransactionalEmailChannel{- public function send(User $notifiable, Notification $notification): void+ public function send(User $user, Notification $notification): void{$settings = instanceSettings();if (! data_get($settings, 'smtp_enabled') && ! data_get($settings, 'resend_enabled')) {return;}- $email = $notifiable->email;+ $email = $user->email;if (! $email) {return;}$this->bootConfigs();- $mailMessage = $notification->toMail($notifiable);+ $mailMessage = $notification->toMail($user);Mail::send([],[],diff --git a/app/Notifications/Container/ContainerRestarted.php b/app/Notifications/Container/ContainerRestarted.phpindex 68fc6b019d..91fdc9e2ba 100644--- a/app/Notifications/Container/ContainerRestarted.php+++ b/app/Notifications/Container/ContainerRestarted.php@@ -23,30 +23,30 @@ class ContainerRestarted extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}");- $mail->view('emails.container-restarted', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}");+ $mailMessage->view('emails.container-restarted', ['containerName' => $this->name,'serverName' => $this->server->name,'url' => $this->url,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':warning: Resource restarted',description: "{$this->name} has been restarted automatically on {$this->server->name}.",color: DiscordMessage::infoColor(),);if ($this->url) {- $message->addField('Resource', '[Link]('.$this->url.')');+ $discordMessage->addField('Resource', '[Link]('.$this->url.')');}- return $message;+ return $discordMessage;}public function toTelegram(): arraydiff --git a/app/Notifications/Container/ContainerStopped.php b/app/Notifications/Container/ContainerStopped.phpindex 49aea196d4..01955651f1 100644--- a/app/Notifications/Container/ContainerStopped.php+++ b/app/Notifications/Container/ContainerStopped.php@@ -23,30 +23,30 @@ class ContainerStopped extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: A resource has been stopped unexpectedly on {$this->server->name}");- $mail->view('emails.container-stopped', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: A resource has been stopped unexpectedly on {$this->server->name}");+ $mailMessage->view('emails.container-stopped', ['containerName' => $this->name,'serverName' => $this->server->name,'url' => $this->url,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: Resource stopped',description: "{$this->name} has been stopped unexpectedly on {$this->server->name}.",color: DiscordMessage::errorColor(),);if ($this->url) {- $message->addField('Resource', '[Link]('.$this->url.')');+ $discordMessage->addField('Resource', '[Link]('.$this->url.')');}- return $message;+ return $discordMessage;}public function toTelegram(): array@@ -87,7 +87,6 @@ class ContainerStopped extends CustomEmailNotification);}-public function toSlack(): SlackMessage{$title = 'Resource stopped';diff --git a/app/Notifications/Database/BackupFailed.php b/app/Notifications/Database/BackupFailed.phpindex 6dcb705839..4229c95582 100644--- a/app/Notifications/Database/BackupFailed.php+++ b/app/Notifications/Database/BackupFailed.php@@ -15,11 +15,11 @@ class BackupFailed extends CustomEmailNotificationpublic string $frequency;- public function __construct(ScheduledDatabaseBackup $backup, public $database, public $output, public $database_name)+ public function __construct(ScheduledDatabaseBackup $scheduledDatabaseBackup, public $database, public $output, public $database_name){$this->onQueue('high');$this->name = $database->name;- $this->frequency = $backup->frequency;+ $this->frequency = $scheduledDatabaseBackup->frequency;}public function via(object $notifiable): array@@ -29,31 +29,31 @@ class BackupFailed extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: [ACTION REQUIRED] Database Backup FAILED for {$this->database->name}");- $mail->view('emails.backup-failed', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: [ACTION REQUIRED] Database Backup FAILED for {$this->database->name}");+ $mailMessage->view('emails.backup-failed', ['name' => $this->name,'database_name' => $this->database_name,'frequency' => $this->frequency,'output' => $this->output,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: Database backup failed',description: "Database backup for {$this->name} (db:{$this->database_name}) has FAILED.",color: DiscordMessage::errorColor(),isCritical: true,);- $message->addField('Frequency', $this->frequency, true);- $message->addField('Output', $this->output);+ $discordMessage->addField('Frequency', $this->frequency, true);+ $discordMessage->addField('Output', $this->output);- return $message;+ return $discordMessage;}public function toTelegram(): arraydiff --git a/app/Notifications/Database/BackupSuccess.php b/app/Notifications/Database/BackupSuccess.phpindex 4c3e8e060d..8696d52fc4 100644--- a/app/Notifications/Database/BackupSuccess.php+++ b/app/Notifications/Database/BackupSuccess.php@@ -15,12 +15,12 @@ class BackupSuccess extends CustomEmailNotificationpublic string $frequency;- public function __construct(ScheduledDatabaseBackup $backup, public $database, public $database_name)+ public function __construct(ScheduledDatabaseBackup $scheduledDatabaseBackup, public $database, public $database_name){$this->onQueue('high');$this->name = $database->name;- $this->frequency = $backup->frequency;+ $this->frequency = $scheduledDatabaseBackup->frequency;}public function via(object $notifiable): array@@ -30,28 +30,28 @@ class BackupSuccess extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Backup successfully done for {$this->database->name}");- $mail->view('emails.backup-success', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Backup successfully done for {$this->database->name}");+ $mailMessage->view('emails.backup-success', ['name' => $this->name,'database_name' => $this->database_name,'frequency' => $this->frequency,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':white_check_mark: Database backup successful',description: "Database backup for {$this->name} (db:{$this->database_name}) was successful.",color: DiscordMessage::successColor(),);- $message->addField('Frequency', $this->frequency, true);+ $discordMessage->addField('Frequency', $this->frequency, true);- return $message;+ return $discordMessage;}public function toTelegram(): array@@ -63,7 +63,6 @@ class BackupSuccess extends CustomEmailNotification];}-public function toPushover(): PushoverMessage{return new PushoverMessage(@@ -73,7 +72,6 @@ class BackupSuccess extends CustomEmailNotification);}-public function toSlack(): SlackMessage{$title = 'Database backup successful';diff --git a/app/Notifications/ScheduledTask/TaskFailed.php b/app/Notifications/ScheduledTask/TaskFailed.phpindex c4d92f2135..9d43808c68 100644--- a/app/Notifications/ScheduledTask/TaskFailed.php+++ b/app/Notifications/ScheduledTask/TaskFailed.php@@ -13,13 +13,13 @@ class TaskFailed extends CustomEmailNotification{public ?string $url = null;- public function __construct(public ScheduledTask $task, public string $output)+ public function __construct(public ScheduledTask $scheduledTask, public string $output){$this->onQueue('high');- if ($task->application) {- $this->url = $task->application->taskLink($task->uuid);- } elseif ($task->service) {- $this->url = $task->service->taskLink($task->uuid);+ if ($scheduledTask->application) {+ $this->url = $scheduledTask->application->taskLink($scheduledTask->uuid);+ } elseif ($scheduledTask->service) {+ $this->url = $scheduledTask->service->taskLink($scheduledTask->uuid);}}@@ -30,39 +30,39 @@ class TaskFailed extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: [ACTION REQUIRED] Scheduled task ({$this->task->name}) failed.");- $mail->view('emails.scheduled-task-failed', [- 'task' => $this->task,+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: [ACTION REQUIRED] Scheduled task ({$this->scheduledTask->name}) failed.");+ $mailMessage->view('emails.scheduled-task-failed', [+ 'task' => $this->scheduledTask,'url' => $this->url,'output' => $this->output,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: Scheduled task failed',- description: "Scheduled task ({$this->task->name}) failed.",+ description: "Scheduled task ({$this->scheduledTask->name}) failed.",color: DiscordMessage::errorColor(),);if ($this->url) {- $message->addField('Scheduled task', '[Link]('.$this->url.')');+ $discordMessage->addField('Scheduled task', '[Link]('.$this->url.')');}- return $message;+ return $discordMessage;}public function toTelegram(): array{- $message = "Coolify: Scheduled task ({$this->task->name}) failed with output: {$this->output}";+ $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) failed with output: {$this->output}";if ($this->url) {$buttons[] = ['text' => 'Open task in Coolify',- 'url' => (string) $this->url,+ 'url' => $this->url,];}@@ -73,9 +73,9 @@ class TaskFailed extends CustomEmailNotificationpublic function toPushover(): PushoverMessage{- $message = "Scheduled task ({$this->task->name}) failed<br/>";+ $message = "Scheduled task ({$this->scheduledTask->name}) failed<br/>";- if ($this->output) {+ if ($this->output !== '' && $this->output !== '0') {$message .= "<br/><b>Error Output:</b>{$this->output}";}@@ -83,7 +83,7 @@ class TaskFailed extends CustomEmailNotificationif ($this->url) {$buttons[] = ['text' => 'Open task in Coolify',- 'url' => (string) $this->url,+ 'url' => $this->url,];}@@ -98,9 +98,9 @@ class TaskFailed extends CustomEmailNotificationpublic function toSlack(): SlackMessage{$title = 'Scheduled task failed';- $description = "Scheduled task ({$this->task->name}) failed.";+ $description = "Scheduled task ({$this->scheduledTask->name}) failed.";- if ($this->output) {+ if ($this->output !== '' && $this->output !== '0') {$description .= "\n\n**Error Output:**\n{$this->output}";}diff --git a/app/Notifications/ScheduledTask/TaskSuccess.php b/app/Notifications/ScheduledTask/TaskSuccess.phpindex 5d4154e7ab..4b55a389f0 100644--- a/app/Notifications/ScheduledTask/TaskSuccess.php+++ b/app/Notifications/ScheduledTask/TaskSuccess.php@@ -13,13 +13,13 @@ class TaskSuccess extends CustomEmailNotification{public ?string $url = null;- public function __construct(public ScheduledTask $task, public string $output)+ public function __construct(public ScheduledTask $scheduledTask, public string $output){$this->onQueue('high');- if ($task->application) {- $this->url = $task->application->taskLink($task->uuid);- } elseif ($task->service) {- $this->url = $task->service->taskLink($task->uuid);+ if ($scheduledTask->application) {+ $this->url = $scheduledTask->application->taskLink($scheduledTask->uuid);+ } elseif ($scheduledTask->service) {+ $this->url = $scheduledTask->service->taskLink($scheduledTask->uuid);}}@@ -30,39 +30,39 @@ class TaskSuccess extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Scheduled task ({$this->task->name}) succeeded.");- $mail->view('emails.scheduled-task-success', [- 'task' => $this->task,+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.");+ $mailMessage->view('emails.scheduled-task-success', [+ 'task' => $this->scheduledTask,'url' => $this->url,'output' => $this->output,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':white_check_mark: Scheduled task succeeded',- description: "Scheduled task ({$this->task->name}) succeeded.",+ description: "Scheduled task ({$this->scheduledTask->name}) succeeded.",color: DiscordMessage::successColor(),);if ($this->url) {- $message->addField('Scheduled task', '[Link]('.$this->url.')');+ $discordMessage->addField('Scheduled task', '[Link]('.$this->url.')');}- return $message;+ return $discordMessage;}public function toTelegram(): array{- $message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";+ $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.";if ($this->url) {$buttons[] = ['text' => 'Open task in Coolify',- 'url' => (string) $this->url,+ 'url' => $this->url,];}@@ -73,12 +73,12 @@ class TaskSuccess extends CustomEmailNotificationpublic function toPushover(): PushoverMessage{- $message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";+ $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.";$buttons = [];if ($this->url) {$buttons[] = ['text' => 'Open task in Coolify',- 'url' => (string) $this->url,+ 'url' => $this->url,];}@@ -93,7 +93,7 @@ class TaskSuccess extends CustomEmailNotificationpublic function toSlack(): SlackMessage{$title = 'Scheduled task succeeded';- $description = "Scheduled task ({$this->task->name}) succeeded.";+ $description = "Scheduled task ({$this->scheduledTask->name}) succeeded.";if ($this->url) {$description .= "\n\n**Task URL:** {$this->url}";diff --git a/app/Notifications/Server/DockerCleanupFailed.php b/app/Notifications/Server/DockerCleanupFailed.phpindex 0291eed19d..ab6485dfce 100644--- a/app/Notifications/Server/DockerCleanupFailed.php+++ b/app/Notifications/Server/DockerCleanupFailed.php@@ -23,14 +23,14 @@ class DockerCleanupFailed extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}");- $mail->view('emails.docker-cleanup-failed', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}");+ $mailMessage->view('emails.docker-cleanup-failed', ['name' => $this->server->name,'text' => $this->message,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessagediff --git a/app/Notifications/Server/DockerCleanupSuccess.php b/app/Notifications/Server/DockerCleanupSuccess.phpindex 1a652d1890..be0fb6dc68 100644--- a/app/Notifications/Server/DockerCleanupSuccess.php+++ b/app/Notifications/Server/DockerCleanupSuccess.php@@ -23,14 +23,14 @@ class DockerCleanupSuccess extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Docker cleanup job succeeded on {$this->server->name}");- $mail->view('emails.docker-cleanup-success', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Docker cleanup job succeeded on {$this->server->name}");+ $mailMessage->view('emails.docker-cleanup-success', ['name' => $this->server->name,'text' => $this->message,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessagediff --git a/app/Notifications/Server/ForceDisabled.php b/app/Notifications/Server/ForceDisabled.phpindex 7a1f7bcbf7..3b1a1187b2 100644--- a/app/Notifications/Server/ForceDisabled.php+++ b/app/Notifications/Server/ForceDisabled.php@@ -23,26 +23,26 @@ class ForceDisabled extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Server ({$this->server->name}) disabled because it is not paid!");- $mail->view('emails.server-force-disabled', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Server ({$this->server->name}) disabled because it is not paid!");+ $mailMessage->view('emails.server-force-disabled', ['name' => $this->server->name,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: Server disabled',description: "Server ({$this->server->name}) disabled because it is not paid!",color: DiscordMessage::errorColor(),);- $message->addField('Please update your subscription to enable the server again!', '[Link](https://app.coolify.io/subscriptions)');+ $discordMessage->addField('Please update your subscription to enable the server again!', '[Link](https://app.coolify.io/subscriptions)');- return $message;+ return $discordMessage;}public function toTelegram(): arraydiff --git a/app/Notifications/Server/ForceEnabled.php b/app/Notifications/Server/ForceEnabled.phpindex 36dad3c60f..dea66d3db0 100644--- a/app/Notifications/Server/ForceEnabled.php+++ b/app/Notifications/Server/ForceEnabled.php@@ -23,13 +23,13 @@ class ForceEnabled extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Server ({$this->server->name}) enabled again!");- $mail->view('emails.server-force-enabled', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Server ({$this->server->name}) enabled again!");+ $mailMessage->view('emails.server-force-enabled', ['name' => $this->server->name,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessagediff --git a/app/Notifications/Server/HighDiskUsage.php b/app/Notifications/Server/HighDiskUsage.phpindex aea9abd031..805c730eb1 100644--- a/app/Notifications/Server/HighDiskUsage.php+++ b/app/Notifications/Server/HighDiskUsage.php@@ -23,32 +23,32 @@ class HighDiskUsage extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Server ({$this->server->name}) high disk usage detected!");- $mail->view('emails.high-disk-usage', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Server ({$this->server->name}) high disk usage detected!");+ $mailMessage->view('emails.high-disk-usage', ['name' => $this->server->name,'disk_usage' => $this->disk_usage,'threshold' => $this->server_disk_usage_notification_threshold,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: High disk usage detected',description: "Server '{$this->server->name}' high disk usage detected!",color: DiscordMessage::errorColor(),isCritical: true,);- $message->addField('Disk usage', "{$this->disk_usage}%", true);- $message->addField('Threshold', "{$this->server_disk_usage_notification_threshold}%", true);- $message->addField('What to do?', '[Link](https://coolify.io/docs/knowledge-base/server/automated-cleanup)', true);- $message->addField('Change Settings', '[Threshold]('.base_url().'/server/'.$this->server->uuid.'#advanced) | [Notification]('.base_url().'/notifications/discord)');+ $discordMessage->addField('Disk usage', "{$this->disk_usage}%", true);+ $discordMessage->addField('Threshold', "{$this->server_disk_usage_notification_threshold}%", true);+ $discordMessage->addField('What to do?', '[Link](https://coolify.io/docs/knowledge-base/server/automated-cleanup)', true);+ $discordMessage->addField('Change Settings', '[Threshold]('.base_url().'/server/'.$this->server->uuid.'#advanced) | [Notification]('.base_url().'/notifications/discord)');- return $message;+ return $discordMessage;}public function toTelegram(): array@@ -65,8 +65,8 @@ class HighDiskUsage extends CustomEmailNotificationlevel: 'warning',message: "Server '{$this->server->name}' high disk usage detected!<br/><br/><b>Disk usage:</b> {$this->disk_usage}%.<br/><b>Threshold:</b> {$this->server_disk_usage_notification_threshold}%.<br/>Please cleanup your disk to prevent data-loss.",buttons: [- 'Change settings' => base_url().'/server/'.$this->server->uuid."#advanced",- 'Tips for cleanup' => "https://coolify.io/docs/knowledge-base/server/automated-cleanup",+ 'Change settings' => base_url().'/server/'.$this->server->uuid.'#advanced',+ 'Tips for cleanup' => 'https://coolify.io/docs/knowledge-base/server/automated-cleanup',],);}diff --git a/app/Notifications/Server/Reachable.php b/app/Notifications/Server/Reachable.phpindex e03aef6b79..357d40823f 100644--- a/app/Notifications/Server/Reachable.php+++ b/app/Notifications/Server/Reachable.php@@ -32,13 +32,13 @@ class Reachable extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Server ({$this->server->name}) revived.");- $mail->view('emails.server-revived', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Server ({$this->server->name}) revived.");+ $mailMessage->view('emails.server-revived', ['name' => $this->server->name,]);- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessagediff --git a/app/Notifications/Server/Unreachable.php b/app/Notifications/Server/Unreachable.phpindex fe90cc6105..2a2351c0be 100644--- a/app/Notifications/Server/Unreachable.php+++ b/app/Notifications/Server/Unreachable.php@@ -32,26 +32,26 @@ class Unreachable extends CustomEmailNotificationpublic function toMail(): ?MailMessage{- $mail = new MailMessage;- $mail->subject("Coolify: Your server ({$this->server->name}) is unreachable.");- $mail->view('emails.server-lost-connection', [+ $mailMessage = new MailMessage;+ $mailMessage->subject("Coolify: Your server ({$this->server->name}) is unreachable.");+ $mailMessage->view('emails.server-lost-connection', ['name' => $this->server->name,]);- return $mail;+ return $mailMessage;}public function toDiscord(): ?DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':cross_mark: Server unreachable',description: "Your server '{$this->server->name}' is unreachable.",color: DiscordMessage::errorColor(),);- $message->addField('IMPORTANT', 'We automatically try to revive your server and turn on all automations & integrations.');+ $discordMessage->addField('IMPORTANT', 'We automatically try to revive your server and turn on all automations & integrations.');- return $message;+ return $discordMessage;}public function toTelegram(): ?arraydiff --git a/app/Notifications/Test.php b/app/Notifications/Test.phpindex 65971a0eee..91625ee6e7 100644--- a/app/Notifications/Test.php+++ b/app/Notifications/Test.php@@ -4,9 +4,9 @@ namespace App\Notifications;use App\Notifications\Channels\DiscordChannel;use App\Notifications\Channels\EmailChannel;+use App\Notifications\Channels\PushoverChannel;use App\Notifications\Channels\SlackChannel;use App\Notifications\Channels\TelegramChannel;-use App\Notifications\Channels\PushoverChannel;use App\Notifications\Dto\DiscordMessage;use App\Notifications\Dto\PushoverMessage;use App\Notifications\Dto\SlackMessage;@@ -30,7 +30,7 @@ class Test extends Notification implements ShouldQueuepublic function via(object $notifiable): array{if ($this->channel) {- $channels = match ($this->channel) {+ return match ($this->channel) {'email' => [EmailChannel::class],'discord' => [DiscordChannel::class],'telegram' => [TelegramChannel::class],@@ -38,11 +38,9 @@ class Test extends Notification implements ShouldQueue'pushover' => [PushoverChannel::class],default => [],};- } else {- $channels = $notifiable->getEnabledChannels('test');}- return $channels;+ return $notifiable->getEnabledChannels('test');}public function middleware(object $notifiable, string $channel)@@ -55,24 +53,24 @@ class Test extends Notification implements ShouldQueuepublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject('Coolify: Test Email');- $mail->view('emails.test');+ $mailMessage = new MailMessage;+ $mailMessage->subject('Coolify: Test Email');+ $mailMessage->view('emails.test');- return $mail;+ return $mailMessage;}public function toDiscord(): DiscordMessage{- $message = new DiscordMessage(+ $discordMessage = new DiscordMessage(title: ':white_check_mark: Test Success',description: 'This is a test Discord notification from Coolify. :cross_mark: :warning: :information_source:',color: DiscordMessage::successColor(),);- $message->addField(name: 'Dashboard', value: '[Link]('.base_url().')', inline: true);+ $discordMessage->addField(name: 'Dashboard', value: '[Link]('.base_url().')', inline: true);- return $message;+ return $discordMessage;}public function toTelegram(): arraydiff --git a/app/Notifications/TransactionalEmails/InvitationLink.php b/app/Notifications/TransactionalEmails/InvitationLink.phpindex 30ace99dcb..5bf143434a 100644--- a/app/Notifications/TransactionalEmails/InvitationLink.php+++ b/app/Notifications/TransactionalEmails/InvitationLink.php@@ -24,16 +24,16 @@ class InvitationLink extends CustomEmailNotificationpublic function toMail(): MailMessage{$invitation = TeamInvitation::whereEmail($this->user->email)->first();- $invitation_team = Team::find($invitation->team->id);+ $invitation_team = Team::query()->find($invitation->team->id);- $mail = new MailMessage;- $mail->subject('Coolify: Invitation for '.$invitation_team->name);- $mail->view('emails.invitation-link', [+ $mailMessage = new MailMessage;+ $mailMessage->subject('Coolify: Invitation for '.$invitation_team->name);+ $mailMessage->view('emails.invitation-link', ['team' => $invitation_team->name,'email' => $this->user->email,'invitation_link' => $invitation->link,]);- return $mail;+ return $mailMessage;}}diff --git a/app/Notifications/TransactionalEmails/ResetPassword.php b/app/Notifications/TransactionalEmails/ResetPassword.phpindex 3938a8da79..ffb66940ff 100644--- a/app/Notifications/TransactionalEmails/ResetPassword.php+++ b/app/Notifications/TransactionalEmails/ResetPassword.php@@ -3,6 +3,7 @@namespace App\Notifications\TransactionalEmails;use App\Models\InstanceSettings;+use Exception;use Illuminate\Notifications\Messages\MailMessage;use Illuminate\Notifications\Notification;@@ -36,7 +37,7 @@ class ResetPassword extends Notification{$type = set_transanctional_email_settings();if (! $type) {- throw new \Exception('No email settings found.');+ throw new Exception('No email settings found.');}return ['mail'];@@ -53,11 +54,11 @@ class ResetPassword extends Notificationprotected function buildMailMessage($url){- $mail = new MailMessage;- $mail->subject('Coolify: Reset Password');- $mail->view('emails.reset-password', ['url' => $url, 'count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]);+ $mailMessage = new MailMessage;+ $mailMessage->subject('Coolify: Reset Password');+ $mailMessage->view('emails.reset-password', ['url' => $url, 'count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]);- return $mail;+ return $mailMessage;}protected function resetUrl($notifiable)diff --git a/app/Notifications/TransactionalEmails/Test.php b/app/Notifications/TransactionalEmails/Test.phpindex eeb32a2545..96b1c8be49 100644--- a/app/Notifications/TransactionalEmails/Test.php+++ b/app/Notifications/TransactionalEmails/Test.php@@ -20,10 +20,10 @@ class Test extends CustomEmailNotificationpublic function toMail(): MailMessage{- $mail = new MailMessage;- $mail->subject('Coolify: Test Email');- $mail->view('emails.test');+ $mailMessage = new MailMessage;+ $mailMessage->subject('Coolify: Test Email');+ $mailMessage->view('emails.test');- return $mail;+ return $mailMessage;}}diff --git a/app/Policies/ApplicationPolicy.php b/app/Policies/ApplicationPolicy.phpindex 05fc289b8b..e7fed03b13 100644--- a/app/Policies/ApplicationPolicy.php+++ b/app/Policies/ApplicationPolicy.php@@ -44,11 +44,7 @@ class ApplicationPolicy*/public function delete(User $user, Application $application): bool{- if ($user->isAdmin()) {- return true;- }-- return false;+ return (bool) $user->isAdmin();}/**diff --git a/app/Policies/ServicePolicy.php b/app/Policies/ServicePolicy.phpindex 51a6d81168..5a764a25c4 100644--- a/app/Policies/ServicePolicy.php+++ b/app/Policies/ServicePolicy.php@@ -44,11 +44,7 @@ class ServicePolicy*/public function delete(User $user, Service $service): bool{- if ($user->isAdmin()) {- return true;- }-- return false;+ return (bool) $user->isAdmin();}/**@@ -64,19 +60,11 @@ class ServicePolicy*/public function forceDelete(User $user, Service $service): bool{- if ($user->isAdmin()) {- return true;- }-- return false;+ return (bool) $user->isAdmin();}public function stop(User $user, Service $service): bool{- if ($user->isAdmin()) {- return true;- }-- return false;+ return (bool) $user->isAdmin();}}diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex 2ce94201ca..d1b5b99b0b 100644--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -8,29 +8,32 @@ use Illuminate\Support\Facades\Http;use Illuminate\Support\ServiceProvider;use Illuminate\Validation\Rules\Password;use Laravel\Sanctum\Sanctum;+use Laravel\Telescope\TelescopeServiceProvider;+use SocialiteProviders\Authentik\Provider;+use SocialiteProviders\Manager\SocialiteWasCalled;class AppServiceProvider extends ServiceProvider{public function register(): void{if ($this->app->environment('local')) {- $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);+ $this->app->register(TelescopeServiceProvider::class);}}public function boot(): void{- Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {- $event->extendSocialite('authentik', \SocialiteProviders\Authentik\Provider::class);+ Event::listen(function (SocialiteWasCalled $socialiteWasCalled) {+ $socialiteWasCalled->extendSocialite('authentik', Provider::class);});Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);Password::defaults(function () {- $rule = Password::min(8);+ $password = Password::min(8);return $this->app->isProduction()- ? $rule->mixedCase()->letters()->numbers()->symbols()- : $rule;+ ? $password->mixedCase()->letters()->numbers()->symbols()+ : $password;});Http::macro('github', function (string $api_url, ?string $github_access_token = null) {@@ -40,11 +43,11 @@ class AppServiceProvider extends ServiceProvider'Accept' => 'application/vnd.github.v3+json','Authorization' => "Bearer $github_access_token",])->baseUrl($api_url);- } else {- return Http::withHeaders([- 'Accept' => 'application/vnd.github.v3+json',- ])->baseUrl($api_url);}++ return Http::withHeaders([+ 'Accept' => 'application/vnd.github.v3+json',+ ])->baseUrl($api_url);});}}diff --git a/app/Providers/DuskServiceProvider.php b/app/Providers/DuskServiceProvider.phpindex 07e0e8709f..02c06d4dc3 100644--- a/app/Providers/DuskServiceProvider.php+++ b/app/Providers/DuskServiceProvider.php@@ -3,6 +3,7 @@namespace App\Providers;use Illuminate\Support\ServiceProvider;+use Laravel\Dusk\Browser;class DuskServiceProvider extends ServiceProvider{@@ -11,7 +12,7 @@ class DuskServiceProvider extends ServiceProvider*/public function boot(): void{- \Laravel\Dusk\Browser::macro('loginWithRootUser', function () {+ Browser::macro('loginWithRootUser', function () {return $this->visit('/login')->type('email', '[email protected]')->type('password', 'password')diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.phpindex ed27a158a1..960d0794ee 100644--- a/app/Providers/FortifyServiceProvider.php+++ b/app/Providers/FortifyServiceProvider.php@@ -8,6 +8,7 @@ use App\Actions\Fortify\UpdateUserPassword;use App\Actions\Fortify\UpdateUserProfileInformation;use App\Models\OauthSetting;use App\Models\User;+use Illuminate\Auth\Events\Login;use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Http\Request;use Illuminate\Support\Facades\Hash;@@ -44,7 +45,7 @@ class FortifyServiceProvider extends ServiceProvider{Fortify::createUsersUsing(CreateNewUser::class);Fortify::registerView(function () {- $isFirstUser = User::count() === 0;+ $isFirstUser = User::query()->count() === 0;$settings = instanceSettings();if (! $settings->is_registration_enabled) {@@ -58,14 +59,14 @@ class FortifyServiceProvider extends ServiceProviderFortify::loginView(function () {$settings = instanceSettings();- $enabled_oauth_providers = OauthSetting::where('enabled', true)->get();- $users = User::count();+ $enabled_oauth_providers = OauthSetting::query()->where('enabled', true)->get();+ $users = User::query()->count();if ($users == 0) {// If there are no users, redirect to registrationreturn redirect()->route('register');}- return view('auth.login', [+ return view(Login::class, ['is_registration_enabled' => $settings->is_registration_enabled,'enabled_oauth_providers' => $enabled_oauth_providers,]);@@ -73,7 +74,7 @@ class FortifyServiceProvider extends ServiceProviderFortify::authenticateUsing(function (Request $request) {$email = strtolower($request->email);- $user = User::where('email', $email)->with('teams')->first();+ $user = User::query()->where('email', $email)->with('teams')->first();if ($user &&Hash::check($request->password, $user->password)diff --git a/app/Providers/HorizonServiceProvider.php b/app/Providers/HorizonServiceProvider.phpindex 2e2b79a597..55f949ae34 100644--- a/app/Providers/HorizonServiceProvider.php+++ b/app/Providers/HorizonServiceProvider.php@@ -31,11 +31,9 @@ class HorizonServiceProvider extends HorizonApplicationServiceProviderprotected function gate(): void{Gate::define('viewHorizon', function ($user) {- $root_user = User::find(0);+ $root_user = User::query()->find(0);- return in_array($user->email, [- $root_user->email,- ]);+ return $user->email == $root_user->email;});}}diff --git a/app/Providers/TelescopeServiceProvider.php b/app/Providers/TelescopeServiceProvider.phpindex b7a3366314..1e185251e5 100644--- a/app/Providers/TelescopeServiceProvider.php+++ b/app/Providers/TelescopeServiceProvider.php@@ -21,13 +21,24 @@ class TelescopeServiceProvider extends TelescopeApplicationServiceProvider$isLocal = $this->app->environment('local');- Telescope::filter(function (IncomingEntry $entry) use ($isLocal) {- return $isLocal ||- $entry->isReportableException() ||- $entry->isFailedRequest() ||- $entry->isFailedJob() ||- $entry->isScheduledTask() ||- $entry->hasMonitoredTag();+ Telescope::filter(function (IncomingEntry $incomingEntry) use ($isLocal) {+ if ($isLocal) {+ return true;+ }+ if ($incomingEntry->isReportableException()) {+ return true;+ }+ if ($incomingEntry->isFailedRequest()) {+ return true;+ }+ if ($incomingEntry->isFailedJob()) {+ return true;+ }+ if ($incomingEntry->isScheduledTask()) {+ return true;+ }++ return $incomingEntry->hasMonitoredTag();});}@@ -57,11 +68,9 @@ class TelescopeServiceProvider extends TelescopeApplicationServiceProviderprotected function gate(): void{Gate::define('viewTelescope', function ($user) {- $root_user = User::find(0);+ $root_user = User::query()->find(0);- return in_array($user->email, [- $root_user->email,- ]);+ return $user->email == $root_user->email;});}}diff --git a/app/Traits/ExecuteRemoteCommand.php b/app/Traits/ExecuteRemoteCommand.phpindex f8ccee9db7..5b5f6c37a4 100644--- a/app/Traits/ExecuteRemoteCommand.php+++ b/app/Traits/ExecuteRemoteCommand.php@@ -8,6 +8,7 @@ use App\Models\Server;use Carbon\Carbon;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Process;+use RuntimeException;trait ExecuteRemoteCommand{@@ -18,18 +19,14 @@ trait ExecuteRemoteCommandpublic function execute_remote_command(...$commands){static::$batch_counter++;- if ($commands instanceof Collection) {- $commandsText = $commands;- } else {- $commandsText = collect($commands);- }+ $commandsText = $commands instanceof Collection ? $commands : collect($commands);if ($this->server instanceof Server === false) {- throw new \RuntimeException('Server is not set or is not an instance of Server model');+ throw new RuntimeException('Server is not set or is not an instance of Server model');}$commandsText->each(function ($single_command) {- $command = data_get($single_command, 'command') ?? $single_command[0] ?? null;+ $command = data_get($single_command, 'command', $single_command[0] ?? null);if ($command === null) {- throw new \RuntimeException('Command is not set');+ throw new RuntimeException('Command is not set');}$hidden = data_get($single_command, 'hidden', false);$customType = data_get($single_command, 'type');@@ -44,7 +41,7 @@ trait ExecuteRemoteCommand}}$remote_command = SshMultiplexingHelper::generateSshCommand($this->server, $command);- $process = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {+ $invokedProcess = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {$output = str($output)->trim();if ($output->startsWith('╔')) {$output = "\n".$output;@@ -80,16 +77,14 @@ trait ExecuteRemoteCommand}});$this->application_deployment_queue->update([- 'current_process_id' => $process->id(),+ 'current_process_id' => $invokedProcess->id(),]);- $process_result = $process->wait();- if ($process_result->exitCode() !== 0) {- if (! $ignore_errors) {- $this->application_deployment_queue->status = ApplicationDeploymentStatus::FAILED->value;- $this->application_deployment_queue->save();- throw new \RuntimeException($process_result->errorOutput());- }+ $processResult = $invokedProcess->wait();+ if ($processResult->exitCode() !== 0 && ! $ignore_errors) {+ $this->application_deployment_queue->status = ApplicationDeploymentStatus::FAILED->value;+ $this->application_deployment_queue->save();+ throw new RuntimeException($processResult->errorOutput());}});}diff --git a/app/Traits/SaveFromRedirect.php b/app/Traits/SaveFromRedirect.phpindex 166c16a4bc..189e08d253 100644--- a/app/Traits/SaveFromRedirect.php+++ b/app/Traits/SaveFromRedirect.php@@ -6,19 +6,19 @@ use Illuminate\Support\Collection;trait SaveFromRedirect{- public function saveFromRedirect(string $route, ?Collection $parameters = null)+ public function saveFromRedirect(string $route, ?Collection $collection = null){session()->forget('from');- if (! $parameters || $parameters->count() === 0) {- $parameters = $this->parameters;+ if (! $collection || $collection->count() === 0) {+ $collection = $this->parameters;}- $parameters = collect($parameters) ?? collect([]);+ $collection = collect($collection) ?? collect([]);$queries = collect($this->query) ?? collect([]);- $parameters = $parameters->merge($queries);+ $collection = $collection->merge($queries);session(['from' => ['back' => $this->currentRoute,'route' => $route,- 'parameters' => $parameters,+ 'parameters' => $collection,]]);return redirect()->route($route);diff --git a/app/View/Components/Forms/Input.php b/app/View/Components/Forms/Input.phpindex 7283ef20f8..e08459e89f 100644--- a/app/View/Components/Forms/Input.php+++ b/app/View/Components/Forms/Input.php@@ -36,7 +36,7 @@ class Input extends Component$this->name = $this->id;}if ($this->type === 'password') {- $this->defaultClass = $this->defaultClass.' pr-[2.8rem]';+ $this->defaultClass .= ' pr-[2.8rem]';}// $this->label = Str::title($this->label);diff --git a/app/View/Components/Services/Links.php b/app/View/Components/Services/Links.phpindex 0497aebae2..c14832b451 100644--- a/app/View/Components/Services/Links.php+++ b/app/View/Components/Services/Links.php@@ -33,11 +33,7 @@ class Links extends Componentif ($application->ports) {$portsCollection = collect(str($application->ports)->explode(','));$portsCollection->map(function ($port) {- if (str($port)->contains(':')) {- $hostPort = str($port)->before(':');- } else {- $hostPort = $port;- }+ $hostPort = str($port)->contains(':') ? str($port)->before(':') : $port;$this->links->push(base_url(withPort: false).":{$hostPort}");});}diff --git a/config/app.php b/config/app.phpindex 371ac44ecc..a8b28a6c87 100644--- a/config/app.php+++ b/config/app.php@@ -1,6 +1,34 @@<?php+use App\Providers\AppServiceProvider;+use App\Providers\EventServiceProvider;+use App\Providers\FortifyServiceProvider;+use App\Providers\HorizonServiceProvider;+use App\Providers\RouteServiceProvider;+use Illuminate\Auth\AuthServiceProvider;+use Illuminate\Auth\Passwords\PasswordResetServiceProvider;+use Illuminate\Broadcasting\BroadcastServiceProvider;+use Illuminate\Bus\BusServiceProvider;+use Illuminate\Cache\CacheServiceProvider;+use Illuminate\Cookie\CookieServiceProvider;+use Illuminate\Database\DatabaseServiceProvider;+use Illuminate\Encryption\EncryptionServiceProvider;+use Illuminate\Filesystem\FilesystemServiceProvider;+use Illuminate\Foundation\Providers\ConsoleSupportServiceProvider;+use Illuminate\Foundation\Providers\FoundationServiceProvider;+use Illuminate\Hashing\HashServiceProvider;+use Illuminate\Mail\MailServiceProvider;+use Illuminate\Notifications\NotificationServiceProvider;+use Illuminate\Pagination\PaginationServiceProvider;+use Illuminate\Pipeline\PipelineServiceProvider;+use Illuminate\Queue\QueueServiceProvider;+use Illuminate\Redis\RedisServiceProvider;+use Illuminate\Session\SessionServiceProvider;use Illuminate\Support\Facades\Facade;+use Illuminate\Translation\TranslationServiceProvider;+use Illuminate\Validation\ValidationServiceProvider;+use Illuminate\View\ViewServiceProvider;+use SocialiteProviders\Manager\ServiceProvider;return [@@ -161,44 +189,44 @@ return [/** Laravel Framework Service Providers...*/- Illuminate\Auth\AuthServiceProvider::class,- Illuminate\Broadcasting\BroadcastServiceProvider::class,- Illuminate\Bus\BusServiceProvider::class,- Illuminate\Cache\CacheServiceProvider::class,- Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,- Illuminate\Cookie\CookieServiceProvider::class,- Illuminate\Database\DatabaseServiceProvider::class,- Illuminate\Encryption\EncryptionServiceProvider::class,- Illuminate\Filesystem\FilesystemServiceProvider::class,- Illuminate\Foundation\Providers\FoundationServiceProvider::class,- Illuminate\Hashing\HashServiceProvider::class,- Illuminate\Mail\MailServiceProvider::class,- Illuminate\Notifications\NotificationServiceProvider::class,- Illuminate\Pagination\PaginationServiceProvider::class,- Illuminate\Pipeline\PipelineServiceProvider::class,- Illuminate\Queue\QueueServiceProvider::class,- Illuminate\Redis\RedisServiceProvider::class,- Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,- Illuminate\Session\SessionServiceProvider::class,- Illuminate\Translation\TranslationServiceProvider::class,- Illuminate\Validation\ValidationServiceProvider::class,- Illuminate\View\ViewServiceProvider::class,+ AuthServiceProvider::class,+ BroadcastServiceProvider::class,+ BusServiceProvider::class,+ CacheServiceProvider::class,+ ConsoleSupportServiceProvider::class,+ CookieServiceProvider::class,+ DatabaseServiceProvider::class,+ EncryptionServiceProvider::class,+ FilesystemServiceProvider::class,+ FoundationServiceProvider::class,+ HashServiceProvider::class,+ MailServiceProvider::class,+ NotificationServiceProvider::class,+ PaginationServiceProvider::class,+ PipelineServiceProvider::class,+ QueueServiceProvider::class,+ RedisServiceProvider::class,+ PasswordResetServiceProvider::class,+ SessionServiceProvider::class,+ TranslationServiceProvider::class,+ ValidationServiceProvider::class,+ ViewServiceProvider::class,/** Package Service Providers...*/- \SocialiteProviders\Manager\ServiceProvider::class,+ ServiceProvider::class,/** Application Service Providers...*/- App\Providers\AppServiceProvider::class,- App\Providers\FortifyServiceProvider::class,+ AppServiceProvider::class,+ FortifyServiceProvider::class,App\Providers\AuthServiceProvider::class,App\Providers\BroadcastServiceProvider::class,- App\Providers\EventServiceProvider::class,- App\Providers\HorizonServiceProvider::class,- App\Providers\RouteServiceProvider::class,+ EventServiceProvider::class,+ HorizonServiceProvider::class,+ RouteServiceProvider::class,],/*diff --git a/config/auth.php b/config/auth.phpindex 83c36c0d3a..63ddf7f5b4 100644--- a/config/auth.php+++ b/config/auth.php@@ -1,5 +1,7 @@<?php+use App\Models\User;+return [/*@@ -62,7 +64,7 @@ return ['providers' => ['users' => ['driver' => 'eloquent',- 'model' => App\Models\User::class,+ 'model' => User::class,],// 'users' => [diff --git a/config/sanctum.php b/config/sanctum.phpindex f1e5fc0e51..5dfd3f266a 100644--- a/config/sanctum.php+++ b/config/sanctum.php@@ -1,5 +1,8 @@<?php+use Illuminate\Cookie\Middleware\EncryptCookies;+use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;+use Laravel\Sanctum\Http\Middleware\AuthenticateSession;use Laravel\Sanctum\Sanctum;return [@@ -60,9 +63,9 @@ return [*/'middleware' => [- 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,- 'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,- 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,+ 'authenticate_session' => AuthenticateSession::class,+ 'encrypt_cookies' => EncryptCookies::class,+ 'validate_csrf_token' => ValidateCsrfToken::class,],];diff --git a/config/telescope.php b/config/telescope.phpindex c940bec8a8..85589ee755 100644--- a/config/telescope.php+++ b/config/telescope.php@@ -1,7 +1,24 @@<?phpuse Laravel\Telescope\Http\Middleware\Authorize;-use Laravel\Telescope\Watchers;+use Laravel\Telescope\Watchers\BatchWatcher;+use Laravel\Telescope\Watchers\CacheWatcher;+use Laravel\Telescope\Watchers\ClientRequestWatcher;+use Laravel\Telescope\Watchers\CommandWatcher;+use Laravel\Telescope\Watchers\DumpWatcher;+use Laravel\Telescope\Watchers\EventWatcher;+use Laravel\Telescope\Watchers\ExceptionWatcher;+use Laravel\Telescope\Watchers\GateWatcher;+use Laravel\Telescope\Watchers\JobWatcher;+use Laravel\Telescope\Watchers\LogWatcher;+use Laravel\Telescope\Watchers\MailWatcher;+use Laravel\Telescope\Watchers\ModelWatcher;+use Laravel\Telescope\Watchers\NotificationWatcher;+use Laravel\Telescope\Watchers\QueryWatcher;+use Laravel\Telescope\Watchers\RedisWatcher;+use Laravel\Telescope\Watchers\RequestWatcher;+use Laravel\Telescope\Watchers\ScheduleWatcher;+use Laravel\Telescope\Watchers\ViewWatcher;return [@@ -133,73 +150,73 @@ return [*/'watchers' => [- Watchers\BatchWatcher::class => env('TELESCOPE_BATCH_WATCHER', true),+ BatchWatcher::class => env('TELESCOPE_BATCH_WATCHER', true),- Watchers\CacheWatcher::class => [+ CacheWatcher::class => ['enabled' => env('TELESCOPE_CACHE_WATCHER', true),'hidden' => [],],- Watchers\ClientRequestWatcher::class => env('TELESCOPE_CLIENT_REQUEST_WATCHER', true),+ ClientRequestWatcher::class => env('TELESCOPE_CLIENT_REQUEST_WATCHER', true),- Watchers\CommandWatcher::class => [+ CommandWatcher::class => ['enabled' => env('TELESCOPE_COMMAND_WATCHER', true),'ignore' => [],],- Watchers\DumpWatcher::class => [+ DumpWatcher::class => ['enabled' => env('TELESCOPE_DUMP_WATCHER', true),'always' => env('TELESCOPE_DUMP_WATCHER_ALWAYS', false),],- Watchers\EventWatcher::class => [+ EventWatcher::class => ['enabled' => env('TELESCOPE_EVENT_WATCHER', true),'ignore' => [],],- Watchers\ExceptionWatcher::class => env('TELESCOPE_EXCEPTION_WATCHER', true),+ ExceptionWatcher::class => env('TELESCOPE_EXCEPTION_WATCHER', true),- Watchers\GateWatcher::class => [+ GateWatcher::class => ['enabled' => env('TELESCOPE_GATE_WATCHER', true),'ignore_abilities' => [],'ignore_packages' => true,'ignore_paths' => [],],- Watchers\JobWatcher::class => env('TELESCOPE_JOB_WATCHER', true),+ JobWatcher::class => env('TELESCOPE_JOB_WATCHER', true),- Watchers\LogWatcher::class => [+ LogWatcher::class => ['enabled' => env('TELESCOPE_LOG_WATCHER', true),'level' => 'error',],- Watchers\MailWatcher::class => env('TELESCOPE_MAIL_WATCHER', true),+ MailWatcher::class => env('TELESCOPE_MAIL_WATCHER', true),- Watchers\ModelWatcher::class => [+ ModelWatcher::class => ['enabled' => env('TELESCOPE_MODEL_WATCHER', true),'events' => ['eloquent.*'],'hydrations' => true,],- Watchers\NotificationWatcher::class => env('TELESCOPE_NOTIFICATION_WATCHER', true),+ NotificationWatcher::class => env('TELESCOPE_NOTIFICATION_WATCHER', true),- Watchers\QueryWatcher::class => [+ QueryWatcher::class => ['enabled' => env('TELESCOPE_QUERY_WATCHER', true),'ignore_packages' => true,'ignore_paths' => [],'slow' => 100,],- Watchers\RedisWatcher::class => env('TELESCOPE_REDIS_WATCHER', true),+ RedisWatcher::class => env('TELESCOPE_REDIS_WATCHER', true),- Watchers\RequestWatcher::class => [+ RequestWatcher::class => ['enabled' => env('TELESCOPE_REQUEST_WATCHER', true),'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64),'ignore_http_methods' => [],'ignore_status_codes' => [],],- Watchers\ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),- Watchers\ViewWatcher::class => env('TELESCOPE_VIEW_WATCHER', true),+ ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),+ ViewWatcher::class => env('TELESCOPE_VIEW_WATCHER', true),],];diff --git a/rector.php b/rector.phpindex cffbb9f536..94e1a99f3f 100644--- a/rector.php+++ b/rector.php@@ -11,7 +11,6 @@ return RectorConfig::configure()__DIR__.'/app',__DIR__.'/routes',__DIR__.'/config',-])->withSets([LaravelLevelSetList::UP_TO_LARAVEL_110,@@ -24,11 +23,13 @@ return RectorConfig::configure()->withRules([TypedPropertyFromStrictConstructorRector::class,])+ ->withImportNames(+ removeUnusedImports: true,+ )->withPreparedSets(deadCode: true,codeQuality: true,naming: true,privatization: true,earlyReturn: true,-);diff --git a/routes/api.php b/routes/api.phpindex c3f7a8f269..84722c61b3 100644--- a/routes/api.php+++ b/routes/api.php@@ -141,7 +141,7 @@ Route::group([$decrypted = decrypt($naked_token);$decrypted_token = json_decode($decrypted, true);$server_uuid = data_get($decrypted_token, 'server_uuid');- $server = Server::where('uuid', $server_uuid)->first();+ $server = Server::query()->where('uuid', $server_uuid)->first();if (! $server) {return response()->json(['message' => 'Server not found'], 404);}diff --git a/routes/channels.php b/routes/channels.phpindex f75c30d0f1..72a8c2c9a0 100644--- a/routes/channels.php+++ b/routes/channels.php@@ -16,17 +16,9 @@ use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Broadcast;Broadcast::channel('team.{teamId}', function (User $user, int $teamId) {- if ($user->teams->pluck('id')->contains($teamId)) {- return true;- }-- return false;+ return (bool) $user->teams->pluck('id')->contains($teamId);});Broadcast::channel('user.{userId}', function (User $user) {- if ($user->id === Auth::id()) {- return true;- }-- return false;+ return $user->id === Auth::id();});diff --git a/routes/web.php b/routes/web.phpindex ec49239415..0050796b69 100644--- a/routes/web.php+++ b/routes/web.php@@ -72,6 +72,7 @@ use App\Livewire\Team\Member\Index as TeamMemberIndex;use App\Livewire\Terminal\Index as TerminalIndex;use App\Models\GitlabApp;use App\Models\ScheduledDatabaseBackupExecution;+use App\Models\ServiceDatabase;use App\Providers\RouteServiceProvider;use Illuminate\Http\Request;use Illuminate\Support\Facades\Route;@@ -295,7 +296,7 @@ Route::middleware(['auth'])->group(function () {return response()->json(['message' => 'Team not found.'], 404);}$exeuctionId = request()->route('executionId');- $execution = ScheduledDatabaseBackupExecution::where('id', $exeuctionId)->firstOrFail();+ $execution = ScheduledDatabaseBackupExecution::query()->where('id', $exeuctionId)->firstOrFail();$execution_team_id = $execution->scheduledDatabaseBackup->database->team()?->id;if ($team->id !== 0) {if (is_null($execution_team_id)) {@@ -309,7 +310,7 @@ Route::middleware(['auth'])->group(function () {}}$filename = data_get($execution, 'filename');- if ($execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {+ if ($execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class) {$server = $execution->scheduledDatabaseBackup->database->service->destination->server;} else {$server = $execution->scheduledDatabaseBackup->database->destination->server;@@ -329,7 +330,7 @@ Route::middleware(['auth'])->group(function () {}return new StreamedResponse(function () use ($disk, $filename) {- if (ob_get_level()) {+ if (ob_get_level() !== 0) {ob_end_clean();}$stream = $disk->readStream($filename);@@ -346,7 +347,7 @@ Route::middleware(['auth'])->group(function () {'Content-Type' => 'application/octet-stream','Content-Disposition' => 'attachment; filename="'.basename($filename).'"',]);- } catch (\Throwable $e) {+ } catch (Throwable $e) {return response()->json(['message' => $e->getMessage()], 500);}})->name('download.backup');