repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/ForcePasswordReset.php
app/Livewire/ForcePasswordReset.php
<?php namespace App\Livewire; use DanHarrin\LivewireRateLimiting\WithRateLimiting; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules\Password; use Livewire\Component; class ForcePasswordReset extends Component { use WithRateLimiting; public string $email; public string $password; public string $password_confirmation; public function rules(): array { return [ 'email' => ['required', 'email'], 'password' => ['required', Password::defaults(), 'confirmed'], ]; } public function mount() { if (auth()->user()->force_password_reset === false) { return redirect()->route('dashboard'); } $this->email = auth()->user()->email; } public function render() { return view('livewire.force-password-reset')->layout('layouts.simple'); } public function submit() { if (auth()->user()->force_password_reset === false) { return redirect()->route('dashboard'); } try { $this->rateLimit(10); $this->validate(); $firstLogin = auth()->user()->created_at == auth()->user()->updated_at; auth()->user()->forceFill([ 'password' => Hash::make($this->password), 'force_password_reset' => false, ])->save(); if ($firstLogin) { send_internal_notification('First login for '.auth()->user()->email); } return redirect()->route('dashboard'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/SettingsDropdown.php
app/Livewire/SettingsDropdown.php
<?php namespace App\Livewire; use App\Jobs\PullChangelog; use App\Services\ChangelogService; use Illuminate\Support\Facades\Auth; use Livewire\Component; class SettingsDropdown extends Component { public $showWhatsNewModal = false; public function getUnreadCountProperty() { return Auth::user()->getUnreadChangelogCount(); } public function getEntriesProperty() { $user = Auth::user(); return app(ChangelogService::class)->getEntriesForUser($user); } public function getCurrentVersionProperty() { return 'v'.config('constants.coolify.version'); } public function openWhatsNewModal() { $this->showWhatsNewModal = true; } public function closeWhatsNewModal() { $this->showWhatsNewModal = false; } public function markAsRead($identifier) { app(ChangelogService::class)->markAsReadForUser($identifier, Auth::user()); } public function markAllAsRead() { app(ChangelogService::class)->markAllAsReadForUser(Auth::user()); } public function manualFetchChangelog() { if (! isDev()) { return; } try { PullChangelog::dispatch(); $this->dispatch('success', 'Changelog fetch initiated! Check back in a few moments.'); } catch (\Throwable $e) { $this->dispatch('error', 'Failed to fetch changelog: '.$e->getMessage()); } } public function render() { return view('livewire.settings-dropdown', [ 'entries' => $this->entries, 'unreadCount' => $this->unreadCount, 'currentVersion' => $this->currentVersion, ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/DeleteEnvironment.php
app/Livewire/Project/DeleteEnvironment.php
<?php namespace App\Livewire\Project; use App\Models\Environment; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class DeleteEnvironment extends Component { use AuthorizesRequests; public int $environment_id; public bool $disabled = false; public string $environmentName = ''; public array $parameters; public function mount() { try { $this->environmentName = Environment::findOrFail($this->environment_id)->name; $this->parameters = get_route_parameters(); } catch (\Exception $e) { return handleError($e, $this); } } public function delete() { $this->validate([ 'environment_id' => 'required|int', ]); $environment = Environment::findOrFail($this->environment_id); $this->authorize('delete', $environment); if ($environment->isEmpty()) { $environment->delete(); return redirectRoute($this, 'project.show', ['project_uuid' => $this->parameters['project_uuid']]); } return $this->dispatch('error', "<strong>Environment {$environment->name}</strong> has defined resources, please delete them first."); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/DeleteProject.php
app/Livewire/Project/DeleteProject.php
<?php namespace App\Livewire\Project; use App\Models\Project; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class DeleteProject extends Component { use AuthorizesRequests; public array $parameters; public int $project_id; public bool $disabled = false; public string $projectName = ''; public function mount() { $this->parameters = get_route_parameters(); $this->projectName = Project::findOrFail($this->project_id)->name; } public function delete() { $this->validate([ 'project_id' => 'required|int', ]); $project = Project::findOrFail($this->project_id); $this->authorize('delete', $project); if ($project->isEmpty()) { $project->delete(); return redirectRoute($this, 'project.index'); } return $this->dispatch('error', "<strong>Project {$project->name}</strong> has resources defined, please delete them first."); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/CloneMe.php
app/Livewire/Project/CloneMe.php
<?php namespace App\Livewire\Project; use App\Actions\Database\StartDatabase; use App\Actions\Database\StopDatabase; use App\Actions\Service\StartService; use App\Actions\Service\StopService; use App\Jobs\VolumeCloneJob; use App\Models\Environment; use App\Models\Project; use App\Models\Server; use App\Support\ValidationPatterns; use Livewire\Component; use Visus\Cuid2\Cuid2; class CloneMe extends Component { public string $project_uuid; public string $environment_uuid; public int $project_id; public Project $project; public $environments; public $servers; public ?Environment $environment = null; public ?int $selectedServer = null; public ?int $selectedDestination = null; public ?Server $server = null; public $resources = []; public string $newName = ''; public bool $cloneVolumeData = false; protected function messages(): array { return array_merge([ 'selectedServer' => 'Please select a server.', 'selectedDestination' => 'Please select a server & destination.', 'newName.required' => 'Please enter a name for the new project or environment.', ], ValidationPatterns::nameMessages()); } public function mount($project_uuid) { $this->project_uuid = $project_uuid; $this->project = Project::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() ->get() ->reject(fn ($server) => $server->isBuildServer()); $this->newName = str($this->project->name.'-clone-'.(string) new Cuid2)->slug(); } public function toggleVolumeCloning(bool $value) { $this->cloneVolumeData = $value; } public function render() { return view('livewire.project.clone-me'); } public function selectServer($server_id, $destination_id) { if ($server_id == $this->selectedServer && $destination_id == $this->selectedDestination) { $this->selectedServer = null; $this->selectedDestination = null; $this->server = null; return; } $this->selectedServer = $server_id; $this->selectedDestination = $destination_id; $this->server = $this->servers->where('id', $server_id)->first(); } public function clone(string $type) { try { $this->validate([ 'selectedDestination' => 'required', 'newName' => ValidationPatterns::nameRules(), ]); if ($type === 'project') { $foundProject = Project::where('name', $this->newName)->first(); if ($foundProject) { throw new \Exception('Project with the same name already exists.'); } $project = Project::create([ 'name' => $this->newName, 'team_id' => currentTeam()->id, 'description' => $this->project->description.' (clone)', ]); if ($this->environment->name !== 'production') { $project->environments()->create([ 'name' => $this->environment->name, 'uuid' => (string) new Cuid2, ]); } $environment = $project->environments->where('name', $this->environment->name)->first(); } else { $foundEnv = $this->project->environments()->where('name', $this->newName)->first(); if ($foundEnv) { throw new \Exception('Environment with the same name already exists.'); } $project = $this->project; $environment = $this->project->environments()->create([ 'name' => $this->newName, 'uuid' => (string) new Cuid2, ]); } $applications = $this->environment->applications; $databases = $this->environment->databases(); $services = $this->environment->services; foreach ($applications as $application) { $selectedDestination = $this->servers->flatMap(fn ($server) => $server->destinations())->where('id', $this->selectedDestination)->first(); clone_application($application, $selectedDestination, [ 'environment_id' => $environment->id, ], $this->cloneVolumeData); } foreach ($databases as $database) { $uuid = (string) new Cuid2; $newDatabase = $database->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'status' => 'exited', 'started_at' => null, 'environment_id' => $environment->id, 'destination_id' => $this->selectedDestination, ]); $newDatabase->save(); $tags = $database->tags; foreach ($tags as $tag) { $newDatabase->tags()->attach($tag->id); } $newDatabase->persistentStorages()->delete(); $persistentVolumes = $database->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $originalName = $volume->name; $newName = ''; if (str_starts_with($originalName, 'postgres-data-')) { $newName = 'postgres-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'mysql-data-')) { $newName = 'mysql-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'redis-data-')) { $newName = 'redis-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'clickhouse-data-')) { $newName = 'clickhouse-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'mariadb-data-')) { $newName = 'mariadb-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'mongodb-data-')) { $newName = 'mongodb-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'keydb-data-')) { $newName = 'keydb-data-'.$newDatabase->uuid; } elseif (str_starts_with($originalName, 'dragonfly-data-')) { $newName = 'dragonfly-data-'.$newDatabase->uuid; } else { if (str_starts_with($volume->name, $database->uuid)) { $newName = str($volume->name)->replace($database->uuid, $newDatabase->uuid); } else { $newName = $newDatabase->uuid.'-'.$volume->name; } } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $newDatabase->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopDatabase::dispatch($database); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $database->destination->server; $targetServer = $newDatabase->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartDatabase::dispatch($database); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } $fileStorages = $database->fileStorages()->get(); foreach ($fileStorages as $storage) { $newStorage = $storage->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resource_id' => $newDatabase->id, ]); $newStorage->save(); } $scheduledBackups = $database->scheduledBackups()->get(); foreach ($scheduledBackups as $backup) { $uuid = (string) new Cuid2; $newBackup = $backup->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'database_id' => $newDatabase->id, 'database_type' => $newDatabase->getMorphClass(), 'team_id' => currentTeam()->id, ]); $newBackup->save(); } $environmentVaribles = $database->environment_variables()->get(); foreach ($environmentVaribles as $environmentVarible) { $payload = []; $payload['resourceable_id'] = $newDatabase->id; $payload['resourceable_type'] = $newDatabase->getMorphClass(); $newEnvironmentVariable = $environmentVarible->replicate([ 'id', 'created_at', 'updated_at', ])->fill($payload); $newEnvironmentVariable->save(); } } foreach ($services as $service) { $uuid = (string) new Cuid2; $newService = $service->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'environment_id' => $environment->id, 'destination_id' => $this->selectedDestination, ]); $newService->save(); $tags = $service->tags; foreach ($tags as $tag) { $newService->tags()->attach($tag->id); } $scheduledTasks = $service->scheduled_tasks()->get(); foreach ($scheduledTasks as $task) { $newTask = $task->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => (string) new Cuid2, 'service_id' => $newService->id, 'team_id' => currentTeam()->id, ]); $newTask->save(); } $environmentVariables = $service->environment_variables()->get(); foreach ($environmentVariables as $environmentVariable) { $newEnvironmentVariable = $environmentVariable->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resourceable_id' => $newService->id, 'resourceable_type' => $newService->getMorphClass(), ]); $newEnvironmentVariable->save(); } foreach ($newService->applications() as $application) { $application->update([ 'status' => 'exited', ]); $persistentVolumes = $application->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $newName = ''; if (str_starts_with($volume->name, $application->uuid)) { $newName = str($volume->name)->replace($application->uuid, $application->uuid); } else { $newName = $application->uuid.'-'.$volume->name; } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $application->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopService::dispatch($application); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $application->service->destination->server; $targetServer = $newService->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartService::dispatch($application); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } $fileStorages = $application->fileStorages()->get(); foreach ($fileStorages as $storage) { $newStorage = $storage->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resource_id' => $application->id, ]); $newStorage->save(); } } foreach ($newService->databases() as $database) { $database->update([ 'status' => 'exited', ]); $persistentVolumes = $database->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $newName = ''; if (str_starts_with($volume->name, $database->uuid)) { $newName = str($volume->name)->replace($database->uuid, $database->uuid); } else { $newName = $database->uuid.'-'.$volume->name; } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $database->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopService::dispatch($database->service); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $database->service->destination->server; $targetServer = $newService->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartService::dispatch($database->service); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } $fileStorages = $database->fileStorages()->get(); foreach ($fileStorages as $storage) { $newStorage = $storage->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resource_id' => $database->id, ]); $newStorage->save(); } $scheduledBackups = $database->scheduledBackups()->get(); foreach ($scheduledBackups as $backup) { $uuid = (string) new Cuid2; $newBackup = $backup->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'database_id' => $database->id, 'database_type' => $database->getMorphClass(), 'team_id' => currentTeam()->id, ]); $newBackup->save(); } } $newService->parse(); } } catch (\Exception $e) { handleError($e, $this); return; } finally { if (! isset($e)) { return redirect()->route('project.resource.index', [ 'project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, ]); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Show.php
app/Livewire/Project/Show.php
<?php namespace App\Livewire\Project; use App\Models\Environment; use App\Models\Project; use App\Support\ValidationPatterns; use Livewire\Component; use Visus\Cuid2\Cuid2; class Show extends Component { public Project $project; public string $name; public ?string $description = null; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return ValidationPatterns::combinedMessages(); } public function mount(string $project_uuid) { try { $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail(); } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->validate(); $environment = Environment::create([ 'name' => $this->name, 'project_id' => $this->project->id, 'uuid' => (string) new Cuid2, ]); return redirectRoute($this, 'project.resource.index', [ 'project_uuid' => $this->project->uuid, 'environment_uuid' => $environment->uuid, ]); } catch (\Throwable $e) { handleError($e, $this); } } public function navigateToEnvironment($projectUuid, $environmentUuid) { return redirectRoute($this, 'project.resource.index', [ 'project_uuid' => $projectUuid, 'environment_uuid' => $environmentUuid, ]); } public function render() { return view('livewire.project.show'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/EnvironmentEdit.php
app/Livewire/Project/EnvironmentEdit.php
<?php namespace App\Livewire\Project; use App\Models\Application; use App\Models\Project; use App\Support\ValidationPatterns; use Livewire\Attributes\Locked; use Livewire\Component; class EnvironmentEdit extends Component { public Project $project; public Application $application; #[Locked] public $environment; public string $name; public ?string $description = null; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return ValidationPatterns::combinedMessages(); } public function mount(string $project_uuid, string $environment_uuid) { try { $this->project = Project::ownedByCurrentTeam()->where('uuid', $project_uuid)->firstOrFail(); $this->environment = $this->project->environments()->where('uuid', $environment_uuid)->firstOrFail(); $this->syncData(); } catch (\Throwable $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->environment->update([ 'name' => $this->name, 'description' => $this->description, ]); } else { $this->name = $this->environment->name; $this->description = $this->environment->description; } } public function submit() { try { $this->syncData(true); redirectRoute($this, 'project.environment.edit', [ 'environment_uuid' => $this->environment->uuid, 'project_uuid' => $this->project->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.environment-edit'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Edit.php
app/Livewire/Project/Edit.php
<?php namespace App\Livewire\Project; use App\Models\Project; use App\Support\ValidationPatterns; use Livewire\Component; class Edit extends Component { public Project $project; public string $name; public ?string $description = null; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return ValidationPatterns::combinedMessages(); } public function mount(string $project_uuid) { try { $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail(); $this->syncData(); } catch (\Throwable $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->project->update([ 'name' => $this->name, 'description' => $this->description, ]); } else { $this->name = $this->project->name; $this->description = $this->project->description; } } public function submit() { try { $this->syncData(true); $this->dispatch('success', 'Project updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/AddEmpty.php
app/Livewire/Project/AddEmpty.php
<?php namespace App\Livewire\Project; use App\Models\Project; use App\Support\ValidationPatterns; use Livewire\Component; use Visus\Cuid2\Cuid2; class AddEmpty extends Component { public string $name; public string $description = ''; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return ValidationPatterns::combinedMessages(); } public function submit() { try { $this->validate(); $project = Project::create([ 'name' => $this->name, 'description' => $this->description, 'team_id' => currentTeam()->id, 'uuid' => (string) new Cuid2, ]); $productionEnvironment = $project->environments()->where('name', 'production')->first(); return redirect()->route('project.resource.index', [ 'project_uuid' => $project->uuid, 'environment_uuid' => $productionEnvironment->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Index.php
app/Livewire/Project/Index.php
<?php namespace App\Livewire\Project; use App\Models\PrivateKey; use App\Models\Project; use App\Models\Server; use Livewire\Component; class Index extends Component { public $projects; public $servers; public $private_keys; public function mount() { $this->private_keys = PrivateKey::ownedByCurrentTeamCached(); $this->projects = Project::ownedByCurrentTeamCached(); $this->servers = Server::ownedByCurrentTeamCached(); } public function render() { return view('livewire.project.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
<?php namespace App\Livewire\Project\New; use App\Models\Application; use App\Models\GithubApp; use App\Models\GitlabApp; use App\Models\PrivateKey; use App\Models\Project; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use App\Rules\ValidGitBranch; use App\Rules\ValidGitRepositoryUrl; use Illuminate\Support\Str; use Livewire\Component; use Spatie\Url\Url; class GithubPrivateRepositoryDeployKey extends Component { public $current_step = 'private_keys'; public $parameters; public $query; public $private_keys = []; public int $private_key_id; public int $port = 3000; public string $type; public bool $is_static = false; public ?string $publish_directory = null; // In case of docker compose public ?string $base_directory = null; public ?string $docker_compose_location = '/docker-compose.yaml'; // End of docker compose public string $repository_url; public string $branch; public $build_pack = 'nixpacks'; public bool $show_is_static = true; private object $repository_url_parsed; private GithubApp|GitlabApp|string $git_source = 'other'; private ?string $git_host = null; private ?string $git_repository = null; protected $rules = [ 'repository_url' => ['required', 'string'], 'branch' => ['required', 'string'], 'port' => 'required|numeric', 'is_static' => 'required|boolean', 'publish_directory' => 'nullable|string', 'build_pack' => 'required|string', ]; protected function rules() { return [ 'repository_url' => ['required', 'string', new ValidGitRepositoryUrl], 'branch' => ['required', 'string', new ValidGitBranch], 'port' => 'required|numeric', 'is_static' => 'required|boolean', 'publish_directory' => 'nullable|string', 'build_pack' => 'required|string', ]; } protected $validationAttributes = [ 'repository_url' => 'Repository', 'branch' => 'Branch', 'port' => 'Port', 'is_static' => 'Is static', 'publish_directory' => 'Publish directory', 'build_pack' => 'Build pack', ]; public function mount() { if (isDev()) { $this->repository_url = 'https://github.com/coollabsio/coolify-examples/tree/v4.x'; } $this->parameters = get_route_parameters(); $this->query = request()->query(); if (isDev()) { $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->get(); } else { $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->where('id', '!=', 0)->get(); } } public function updatedBuildPack() { if ($this->build_pack === 'nixpacks') { $this->show_is_static = true; $this->port = 3000; } elseif ($this->build_pack === 'static') { $this->show_is_static = false; $this->is_static = false; $this->port = 80; } else { $this->show_is_static = false; $this->is_static = false; } } public function instantSave() { if ($this->is_static) { $this->port = 80; $this->publish_directory = '/dist'; } else { $this->port = 3000; $this->publish_directory = null; } } public function setPrivateKey($private_key_id) { $this->private_key_id = $private_key_id; $this->current_step = 'repository'; } public function submit() { $this->validate(); try { $destination_uuid = $this->query['destination']; $destination = StandaloneDocker::where('uuid', $destination_uuid)->first(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $this->get_git_source(); // Note: git_repository has already been validated and transformed in get_git_source() // It may now be in SSH format (git@host:repo.git) which is valid for deploy keys $project = Project::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 = [ 'name' => generate_random_name(), 'git_repository' => $this->git_repository, 'git_branch' => $this->branch, 'build_pack' => $this->build_pack, 'ports_exposes' => $this->port, 'publish_directory' => $this->publish_directory, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'private_key_id' => $this->private_key_id, ]; } else { $application_init = [ 'name' => generate_random_name(), 'git_repository' => $this->git_repository, 'git_branch' => $this->branch, 'build_pack' => $this->build_pack, 'ports_exposes' => $this->port, 'publish_directory' => $this->publish_directory, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'private_key_id' => $this->private_key_id, 'source_id' => $this->git_source->id, 'source_type' => $this->git_source->getMorphClass(), ]; } if ($this->build_pack === 'dockerfile' || $this->build_pack === 'dockerimage') { $application_init['health_check_enabled'] = false; } if ($this->build_pack === 'dockercompose') { $application_init['docker_compose_location'] = $this->docker_compose_location; $application_init['base_directory'] = $this->base_directory; } $application = Application::create($application_init); $application->settings->is_static = $this->is_static; $application->settings->save(); $fqdn = generateUrl(server: $destination->server, random: $application->uuid); $application->fqdn = $fqdn; $application->name = generate_random_name($application->uuid); $application->save(); return redirect()->route('project.application.configuration', [ 'application_uuid' => $application->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } private function get_git_source() { // Validate repository URL before parsing $validator = validator(['repository_url' => $this->repository_url], [ 'repository_url' => ['required', 'string', new ValidGitRepositoryUrl], ]); if ($validator->fails()) { throw new \RuntimeException('Invalid repository URL: '.$validator->errors()->first('repository_url')); } $this->repository_url_parsed = Url::fromString($this->repository_url); $this->git_host = $this->repository_url_parsed->getHost(); $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(); return; } if (str($this->repository_url)->startsWith('http')) { $this->git_host = $this->repository_url_parsed->getHost(); $this->git_repository = $this->repository_url_parsed->getSegment(1).'/'.$this->repository_url_parsed->getSegment(2); // Convert to SSH format for deploy key usage $this->git_repository = Str::finish("git@$this->git_host:$this->git_repository", '.git'); } else { // If it's already in SSH format, just use it as-is $this->git_repository = $this->repository_url; } $this->git_source = 'other'; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/DockerImage.php
app/Livewire/Project/New/DockerImage.php
<?php namespace App\Livewire\Project\New; use App\Models\Application; use App\Models\Project; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use App\Services\DockerImageParser; use Livewire\Component; use Visus\Cuid2\Cuid2; class DockerImage extends Component { public string $imageName = ''; public string $imageTag = ''; public string $imageSha256 = ''; public array $parameters; public array $query; public function mount() { $this->parameters = get_route_parameters(); $this->query = request()->query(); } /** * Auto-parse image name when user pastes a complete Docker image reference * Examples: * - nginx:stable-alpine3.21-perl@sha256:4e272eef... * - ghcr.io/user/app:v1.2.3 * - nginx@sha256:abc123... */ public function updatedImageName(): void { if (empty($this->imageName)) { return; } // Don't auto-parse if user has already manually filled tag or sha256 fields if (! empty($this->imageTag) || ! empty($this->imageSha256)) { return; } // Only auto-parse if the image name contains a tag (:) or digest (@) if (! str_contains($this->imageName, ':') && ! str_contains($this->imageName, '@')) { return; } try { $parser = new DockerImageParser; $parser->parse($this->imageName); // Extract the base image name (without tag/digest) $baseImageName = $parser->getFullImageNameWithoutTag(); // Only update if parsing resulted in different base name // This prevents unnecessary updates when user types just the name if ($baseImageName !== $this->imageName) { if ($parser->isImageHash()) { // It's a SHA256 digest (takes priority over tag) $this->imageSha256 = $parser->getTag(); $this->imageTag = ''; } elseif ($parser->getTag() !== 'latest' || str_contains($this->imageName, ':')) { // It's a regular tag (only set if not default 'latest' or explicitly specified) $this->imageTag = $parser->getTag(); $this->imageSha256 = ''; } // Update imageName to just the base name $this->imageName = $baseImageName; } } catch (\Exception $e) { // If parsing fails, leave the image name as-is // User will see validation error on submit } } public function submit() { $this->validate([ 'imageName' => ['required', 'string'], 'imageTag' => ['nullable', 'string', 'regex:/^[a-z0-9][a-z0-9._-]*$/i'], 'imageSha256' => ['nullable', 'string', 'regex:/^[a-f0-9]{64}$/i'], ]); // Validate that either tag or sha256 is provided, but not both if ($this->imageTag && $this->imageSha256) { $this->addError('imageTag', 'Provide either a tag or SHA256 digest, not both.'); $this->addError('imageSha256', 'Provide either a tag or SHA256 digest, not both.'); return; } // Build the full Docker image string if ($this->imageSha256) { // Strip 'sha256:' prefix if user pasted it $sha256Hash = preg_replace('/^sha256:/i', '', trim($this->imageSha256)); $dockerImage = $this->imageName.'@sha256:'.$sha256Hash; } elseif ($this->imageTag) { $dockerImage = $this->imageName.':'.$this->imageTag; } else { $dockerImage = $this->imageName.':latest'; } // Parse using DockerImageParser to normalize the image reference $parser = new DockerImageParser; $parser->parse($dockerImage); $destination_uuid = $this->query['destination']; $destination = StandaloneDocker::where('uuid', $destination_uuid)->first(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $project = Project::where('uuid', $this->parameters['project_uuid'])->first(); $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first(); // Append @sha256 to image name if using digest and not already present $imageName = $parser->getFullImageNameWithoutTag(); if ($parser->isImageHash() && ! str_ends_with($imageName, '@sha256')) { $imageName .= '@sha256'; } // Determine the image tag based on whether it's a hash or regular tag $imageTag = $parser->isImageHash() ? 'sha256-'.$parser->getTag() : $parser->getTag(); $application = Application::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' => $imageName, 'docker_registry_image_tag' => $imageTag, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'health_check_enabled' => false, ]); $fqdn = generateUrl(server: $destination->server, random: $application->uuid); $application->update([ 'name' => 'docker-image-'.$application->uuid, 'fqdn' => $fqdn, ]); return redirectRoute($this, 'project.application.configuration', [ 'application_uuid' => $application->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } public function render() { return view('livewire.project.new.docker-image'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/GithubPrivateRepository.php
app/Livewire/Project/New/GithubPrivateRepository.php
<?php namespace App\Livewire\Project\New; use App\Models\Application; use App\Models\GithubApp; use App\Models\Project; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use App\Rules\ValidGitBranch; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Route; use Livewire\Component; class GithubPrivateRepository extends Component { public $current_step = 'github_apps'; public $github_apps; public GithubApp $github_app; public $parameters; public $currentRoute; public $query; public $type; public int $selected_repository_id; public int $selected_github_app_id; public string $selected_repository_owner; public string $selected_repository_repo; public string $selected_branch_name = 'main'; public string $token; public $repositories; public int $total_repositories_count = 0; public $branches; public int $total_branches_count = 0; public int $port = 3000; public bool $is_static = false; public ?string $publish_directory = null; // In case of docker compose public ?string $base_directory = '/'; public ?string $docker_compose_location = '/docker-compose.yaml'; // End of docker compose protected int $page = 1; public $build_pack = 'nixpacks'; public bool $show_is_static = true; public function mount() { $this->currentRoute = Route::currentRouteName(); $this->parameters = get_route_parameters(); $this->query = request()->query(); $this->repositories = $this->branches = collect(); $this->github_apps = GithubApp::private(); } public function updatedBuildPack() { if ($this->build_pack === 'nixpacks') { $this->show_is_static = true; $this->port = 3000; } elseif ($this->build_pack === 'static') { $this->show_is_static = false; $this->is_static = false; $this->port = 80; } else { $this->show_is_static = false; $this->is_static = false; } } public function loadRepositories($github_app_id) { $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->token = generateGithubInstallationToken($this->github_app); $repositories = loadRepositoryByPage($this->github_app, $this->token, $this->page); $this->total_repositories_count = $repositories['total_count']; $this->repositories = $this->repositories->concat(collect($repositories['repositories'])); if ($this->repositories->count() < $this->total_repositories_count) { while ($this->repositories->count() < $this->total_repositories_count) { $this->page++; $repositories = loadRepositoryByPage($this->github_app, $this->token, $this->page); $this->total_repositories_count = $repositories['total_count']; $this->repositories = $this->repositories->concat(collect($repositories['repositories'])); } } $this->repositories = $this->repositories->sortBy('name'); if ($this->repositories->count() > 0) { $this->selected_repository_id = data_get($this->repositories->first(), 'id'); } $this->current_step = 'repository'; } public function loadBranches() { $this->selected_repository_owner = $this->repositories->where('id', $this->selected_repository_id)->first()['owner']['login']; $this->selected_repository_repo = $this->repositories->where('id', $this->selected_repository_id)->first()['name']; $this->branches = collect(); $this->page = 1; $this->loadBranchByPage(); if ($this->total_branches_count === 100) { while ($this->total_branches_count === 100) { $this->page++; $this->loadBranchByPage(); } } $this->branches = sortBranchesByPriority($this->branches); $this->selected_branch_name = data_get($this->branches, '0.name', 'main'); } protected function loadBranchByPage() { $response = Http::GitHub($this->github_app->api_url, $this->token) ->timeout(20) ->retry(3, 200, throw: false) ->get("/repos/{$this->selected_repository_owner}/{$this->selected_repository_repo}/branches", [ 'per_page' => 100, 'page' => $this->page, ]); $json = $response->json(); if ($response->status() !== 200) { return $this->dispatch('error', $json['message']); } $this->total_branches_count = count($json); $this->branches = $this->branches->concat(collect($json)); } public function submit() { try { // Validate git repository parts and branch $validator = validator([ 'selected_repository_owner' => $this->selected_repository_owner, 'selected_repository_repo' => $this->selected_repository_repo, 'selected_branch_name' => $this->selected_branch_name, ], [ 'selected_repository_owner' => 'required|string|regex:/^[a-zA-Z0-9\-_]+$/', 'selected_repository_repo' => 'required|string|regex:/^[a-zA-Z0-9\-_\.]+$/', 'selected_branch_name' => ['required', 'string', new ValidGitBranch], ]); if ($validator->fails()) { throw new \RuntimeException('Invalid repository data: '.$validator->errors()->first()); } $destination_uuid = $this->query['destination']; $destination = StandaloneDocker::where('uuid', $destination_uuid)->first(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $project = Project::where('uuid', $this->parameters['project_uuid'])->first(); $environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first(); $application = Application::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' => str($this->selected_repository_owner)->trim()->toString().'/'.str($this->selected_repository_repo)->trim()->toString(), 'git_branch' => str($this->selected_branch_name)->trim()->toString(), 'build_pack' => $this->build_pack, 'ports_exposes' => $this->port, 'publish_directory' => $this->publish_directory, 'base_directory' => $this->base_directory, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'source_id' => $this->github_app->id, 'source_type' => $this->github_app->getMorphClass(), ]); $application->settings->is_static = $this->is_static; $application->settings->save(); if ($this->build_pack === 'dockerfile' || $this->build_pack === 'dockerimage') { $application->health_check_enabled = false; } if ($this->build_pack === 'dockercompose') { $application['docker_compose_location'] = $this->docker_compose_location; } $fqdn = generateUrl(server: $destination->server, random: $application->uuid); $application->fqdn = $fqdn; $application->name = generate_application_name($this->selected_repository_owner.'/'.$this->selected_repository_repo, $this->selected_branch_name, $application->uuid); $application->save(); return redirect()->route('project.application.configuration', [ 'application_uuid' => $application->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSave() { if ($this->is_static) { $this->port = 80; $this->publish_directory = '/dist'; } else { $this->port = 3000; $this->publish_directory = null; } $this->dispatch('success', 'Application settings updated!'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/DockerCompose.php
app/Livewire/Project/New/DockerCompose.php
<?php namespace App\Livewire\Project\New; use App\Models\EnvironmentVariable; use App\Models\Project; use App\Models\Service; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use Livewire\Component; use Symfony\Component\Yaml\Yaml; class DockerCompose extends Component { public string $dockerComposeRaw = ''; public string $envFile = ''; public array $parameters; public array $query; public function mount() { $this->parameters = get_route_parameters(); $this->query = request()->query(); if (isDev()) { $this->dockerComposeRaw = file_get_contents(base_path('templates/test-database-detection.yaml')); } } public function submit() { $server_id = $this->query['server_id']; try { $this->validate([ 'dockerComposeRaw' => 'required', ]); $this->dockerComposeRaw = Yaml::dump(Yaml::parse($this->dockerComposeRaw), 10, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK); // Validate for command injection BEFORE saving to database validateDockerComposeForInjection($this->dockerComposeRaw); $project = Project::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(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $service = Service::create([ 'docker_compose_raw' => $this->dockerComposeRaw, 'environment_id' => $environment->id, 'server_id' => (int) $server_id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, ]); $variables = parseEnvFormatToArray($this->envFile); foreach ($variables as $key => $variable) { EnvironmentVariable::create([ 'key' => $key, 'value' => $variable, 'is_preview' => false, 'resourceable_id' => $service->id, 'resourceable_type' => $service->getMorphClass(), ]); } $service->parse(isNew: true); // Apply service-specific application prerequisites applyServiceApplicationPrerequisites($service); return redirect()->route('project.service.configuration', [ 'service_uuid' => $service->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/SimpleDockerfile.php
app/Livewire/Project/New/SimpleDockerfile.php
<?php namespace App\Livewire\Project\New; use App\Models\Application; use App\Models\GithubApp; use App\Models\Project; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use Livewire\Component; use Visus\Cuid2\Cuid2; class SimpleDockerfile extends Component { public string $dockerfile = ''; public array $parameters; public array $query; public function mount() { $this->parameters = get_route_parameters(); $this->query = request()->query(); if (isDev()) { $this->dockerfile = 'FROM nginx EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] '; } } public function submit() { $this->validate([ 'dockerfile' => 'required', ]); $destination_uuid = $this->query['destination']; $destination = StandaloneDocker::where('uuid', $destination_uuid)->first(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $project = Project::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([ 'name' => 'dockerfile-'.new Cuid2, 'repository_project_id' => 0, 'git_repository' => 'coollabsio/coolify', 'git_branch' => 'main', 'build_pack' => 'dockerfile', 'dockerfile' => $this->dockerfile, 'ports_exposes' => $port, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'health_check_enabled' => false, 'source_id' => 0, 'source_type' => GithubApp::class, ]); $fqdn = generateUrl(server: $destination->server, random: $application->uuid); $application->update([ 'name' => 'dockerfile-'.$application->uuid, 'fqdn' => $fqdn, ]); $application->parseHealthcheckFromDockerfile(dockerfile: $this->dockerfile, isInit: true); return redirect()->route('project.application.configuration', [ 'application_uuid' => $application->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/EmptyProject.php
app/Livewire/Project/New/EmptyProject.php
<?php namespace App\Livewire\Project\New; use App\Models\Project; use Livewire\Component; use Visus\Cuid2\Cuid2; class EmptyProject extends Component { public function createEmptyProject() { $project = Project::create([ 'name' => generate_random_name(), 'team_id' => currentTeam()->id, 'uuid' => (string) new Cuid2, ]); return redirectRoute($this, 'project.show', ['project_uuid' => $project->uuid, 'environment_uuid' => $project->environments->first()->uuid]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/Select.php
app/Livewire/Project/New/Select.php
<?php namespace App\Livewire\Project\New; use App\Models\Project; use App\Models\Server; use Illuminate\Support\Collection; use Livewire\Component; class Select extends Component { public $current_step = 'type'; public ?Server $server = null; public string $type; public string $server_id; public string $destination_uuid; public Collection|null|Server $allServers; public Collection|null|Server $servers; public bool $onlyBuildServerAvailable = false; public ?Collection $standaloneDockers; public ?Collection $swarmDockers; public array $parameters; public Collection|array $services = []; public Collection|array $allServices = []; public bool $isDatabase = false; public bool $includeSwarm = true; public bool $loadingServices = true; public bool $loading = false; public $environments = []; public ?string $selectedEnvironment = null; public string $postgresql_type = 'postgres:16-alpine'; public ?string $existingPostgresqlUrl = null; protected $queryString = [ 'server_id', 'type' => ['except' => ''], 'destination_uuid' => ['except' => '', 'as' => 'destination'], ]; public function mount() { try { $this->parameters = get_route_parameters(); if (isDev()) { $this->existingPostgresqlUrl = 'postgres://coolify:password@coolify-db:5432'; } $projectUuid = data_get($this->parameters, 'project_uuid'); $project = Project::whereUuid($projectUuid)->firstOrFail(); $this->environments = $project->environments; $this->selectedEnvironment = $this->environments->where('uuid', data_get($this->parameters, 'environment_uuid'))->firstOrFail()->name; // Check if we have all required params for PostgreSQL type selection // This handles navigation from global search $queryType = request()->query('type'); $queryServerId = request()->query('server_id'); $queryDestination = request()->query('destination'); if ($queryType === 'postgresql' && $queryServerId !== null && $queryDestination) { $this->type = $queryType; $this->server_id = $queryServerId; $this->destination_uuid = $queryDestination; $this->server = Server::find($queryServerId); $this->current_step = 'select-postgresql-type'; } } catch (\Exception $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.new.select'); } public function updatedSelectedEnvironment() { $environmentUuid = $this->environments->where('name', $this->selectedEnvironment)->first()->uuid; return redirect()->route('project.resource.create', [ 'project_uuid' => $this->parameters['project_uuid'], 'environment_uuid' => $environmentUuid, ]); } public function loadServices() { $services = get_service_templates(); $services = collect($services)->map(function ($service, $key) { $default_logo = 'images/default.webp'; $logo = data_get($service, 'logo', $default_logo); $local_logo_path = public_path($logo); return [ 'name' => str($key)->headline(), 'logo' => asset($logo), 'logo_github_url' => file_exists($local_logo_path) ? 'https://raw.githubusercontent.com/coollabsio/coolify/refs/heads/main/public/'.$logo : asset($default_logo), ] + (array) $service; })->all(); // Extract unique categories from services $categories = collect($services) ->pluck('category') ->filter() ->unique() ->map(function ($category) { // Handle multiple categories separated by comma if (str_contains($category, ',')) { return collect(explode(',', $category))->map(fn ($cat) => trim($cat)); } return [$category]; }) ->flatten() ->unique() ->map(function ($category) { // Format common acronyms to uppercase $acronyms = ['ai', 'api', 'ci', 'cd', 'cms', 'crm', 'erp', 'iot', 'vpn', 'vps', 'dns', 'ssl', 'tls', 'ssh', 'ftp', 'http', 'https', 'smtp', 'imap', 'pop3', 'sql', 'nosql', 'json', 'xml', 'yaml', 'csv', 'pdf', 'sms', 'mfa', '2fa', 'oauth', 'saml', 'jwt', 'rest', 'soap', 'grpc', 'graphql', 'websocket', 'webrtc', 'p2p', 'b2b', 'b2c', 'seo', 'sem', 'ppc', 'roi', 'kpi', 'ui', 'ux', 'ide', 'sdk', 'api', 'cli', 'gui', 'cdn', 'ddos', 'dos', 'xss', 'csrf', 'sqli', 'rce', 'lfi', 'rfi', 'ssrf', 'xxe', 'idor', 'owasp', 'gdpr', 'hipaa', 'pci', 'dss', 'iso', 'nist', 'cve', 'cwe', 'cvss']; $lower = strtolower($category); if (in_array($lower, $acronyms)) { return strtoupper($category); } return $category; }) ->sort(SORT_NATURAL | SORT_FLAG_CASE) ->values() ->all(); $gitBasedApplications = [ [ 'id' => 'public', 'name' => 'Public Repository', 'description' => 'You can deploy any kind of public repositories from the supported git providers.', 'logo' => asset('svgs/git.svg'), ], [ 'id' => 'private-gh-app', 'name' => 'Private Repository (with GitHub App)', 'description' => 'You can deploy public & private repositories through your GitHub Apps.', 'logo' => asset('svgs/github.svg'), ], [ 'id' => 'private-deploy-key', 'name' => 'Private Repository (with Deploy Key)', 'description' => 'You can deploy private repositories with a deploy key.', 'logo' => asset('svgs/git.svg'), ], ]; $dockerBasedApplications = [ [ 'id' => 'dockerfile', 'name' => 'Dockerfile', 'description' => 'You can deploy a simple Dockerfile, without Git.', 'logo' => asset('svgs/docker.svg'), ], [ 'id' => 'docker-compose-empty', 'name' => 'Docker Compose Empty', 'description' => 'You can deploy complex application easily with Docker Compose, without Git.', 'logo' => asset('svgs/docker.svg'), ], [ 'id' => 'docker-image', 'name' => 'Docker Image', 'description' => 'You can deploy an existing Docker Image from any Registry, without Git.', 'logo' => asset('svgs/docker.svg'), ], ]; $databases = [ [ 'id' => 'postgresql', 'name' => 'PostgreSQL', 'description' => 'PostgreSQL is an object-relational database known for its robustness, advanced features, and strong standards compliance.', 'logo' => '<svg class="w-[4.5rem] h-[4.5rem] p-2 transition-all duration-200 bg-black/10 dark:bg-white/10" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><path fill="#currentColor" d="M85.988 76.075c.632-5.262.443-6.034 4.362-5.182l.995.088c3.014.137 6.957-.485 9.272-1.561 4.986-2.313 7.942-6.177 3.026-5.162-11.215 2.313-11.986-1.483-11.986-1.483C103.5 45.204 108.451 22.9 104.178 17.44 92.524 2.548 72.35 9.59 72.012 9.773l-.108.021c-2.216-.461-4.695-.735-7.481-.78-5.075-.083-8.926 1.331-11.847 3.546 0 0-35.989-14.827-34.315 18.646.356 7.121 10.207 53.882 21.956 39.758 4.294-5.164 8.444-9.531 8.444-9.531 2.061 1.369 4.528 2.067 7.116 1.816l.2-.17c-.062.641-.035 1.268.081 2.01-3.027 3.383-2.137 3.977-8.189 5.222-6.122 1.262-2.525 3.508-.178 4.095 2.848.713 9.433 1.722 13.884-4.509l-.177.711c1.188.95 1.107 6.827 1.275 11.026.168 4.199.45 8.117 1.306 10.429.856 2.31 1.866 8.261 9.819 6.557 6.646-1.426 11.727-3.476 12.19-22.545"/><path fill="#currentColor" d="M71.208 102.77c-3.518 0-5.808-1.36-7.2-2.674-2.1-1.981-2.933-4.534-3.43-6.059l-.215-.637c-1.002-2.705-1.341-6.599-1.542-11.613a199.25 199.25 0 01-.075-2.352c-.017-.601-.038-1.355-.068-2.146a15.157 15.157 0 01-3.997 1.264c-2.48.424-5.146.286-7.926-.409-1.961-.49-3.999-1.506-5.16-3.076-3.385 2.965-6.614 2.562-8.373 1.976-3.103-1.035-5.88-3.942-8.491-8.89-1.859-3.523-3.658-8.115-5.347-13.646-2.94-9.633-4.808-19.779-4.974-23.109-.522-10.427 2.284-17.883 8.34-22.16 9.555-6.749 24.03-2.781 29.307-.979 3.545-2.137 7.716-3.178 12.43-3.102 2.532.041 4.942.264 7.181.662 2.335-.734 6.949-1.788 12.23-1.723 9.73.116 17.793 3.908 23.316 10.966 3.941 5.036 1.993 15.61.48 21.466-2.127 8.235-5.856 16.996-10.436 24.622 1.244.009 3.045-.141 5.607-.669 5.054-1.044 6.531 1.666 6.932 2.879 1.607 4.867-5.378 8.544-7.557 9.555-2.792 1.297-7.343 2.086-11.071 1.915l-.163-.011-.979-.086-.097.816-.093.799c-.25 9.664-1.631 15.784-4.472 19.829-2.977 4.239-7.116 5.428-10.761 6.209a16.146 16.146 0 01-3.396.383zm-7.402-35.174c2.271 1.817 2.47 5.236 2.647 11.626.022.797.043 1.552.071 2.257.086 2.134.287 7.132 1.069 9.244.111.298.21.602.314.922.872 2.672 1.31 4.011 5.081 3.203 3.167-.678 4.794-1.287 6.068-3.101 1.852-2.638 2.888-7.941 3.078-15.767l3.852.094-3.826-.459.112-.955c.367-3.148.631-5.424 2.736-6.928 1.688-1.207 3.613-1.09 5.146-.814-1.684-1.271-2.15-2.765-2.274-3.377l-.321-1.582.902-1.34c5.2-7.716 9.489-17.199 11.767-26.018 2.34-9.062 1.626-13.875.913-14.785-9.446-12.071-25.829-7.088-27.539-6.521l-.29.156-1.45.271-.743-.154c-2.047-.425-4.321-.66-6.76-.7-3.831-.064-6.921.841-9.455 2.764l-1.758 1.333-2.041-.841c-4.358-1.782-17.162-5.365-23.918-.58-3.75 2.656-5.458 7.861-5.078 15.47.125 2.512 1.833 12.021 4.647 21.245 3.891 12.746 7.427 16.979 8.903 17.472.257.087.926-.433 1.591-1.231 4.326-5.203 8.44-9.54 8.613-9.723l2.231-2.347 2.697 1.792c1.087.723 2.286 1.132 3.518 1.209l6.433-5.486-.932 9.51c-.021.214-.031.504.053 1.044l.28 1.803-1.213 1.358-.14.157 3.534 1.632 1.482-1.853z"/><path fill="#336791" d="M103.646 64.258c-11.216 2.313-11.987-1.484-11.987-1.484 11.842-17.571 16.792-39.876 12.52-45.335C92.524 2.547 72.35 9.59 72.013 9.773l-.109.019c-2.216-.459-4.695-.733-7.482-.778-5.075-.083-8.925 1.33-11.846 3.545 0 0-35.99-14.826-34.316 18.647.356 7.121 10.207 53.882 21.956 39.758 4.294-5.164 8.443-9.531 8.443-9.531 2.061 1.369 4.528 2.067 7.115 1.816l.201-.17c-.062.641-.034 1.268.08 2.01-3.026 3.383-2.138 3.977-8.188 5.222-6.123 1.262-2.526 3.508-.177 4.095 2.847.713 9.433 1.722 13.883-4.509l-.178.711c1.186.95 2.019 6.179 1.879 10.919s-.233 7.994.702 10.536c.935 2.541 1.866 8.261 9.82 6.557 6.646-1.425 10.09-5.116 10.57-11.272.34-4.377 1.109-3.73 1.158-7.644l.618-1.853c.711-5.934.113-7.848 4.208-6.957l.995.087c3.014.138 6.958-.485 9.273-1.561 4.986-2.314 7.943-6.177 3.028-5.162z"/><path fill="#fff" d="M71.61 100.394c-6.631.001-8.731-5.25-9.591-7.397-1.257-3.146-1.529-15.358-1.249-25.373a1.286 1.286 0 012.57.072c-.323 11.551.136 22.018 1.066 24.346 1.453 3.632 3.656 6.809 9.887 5.475 5.915-1.269 8.13-3.512 9.116-9.23.758-4.389 2.254-16.874 2.438-19.338a1.285 1.285 0 012.563.191c-.192 2.564-1.682 15.026-2.469 19.584-1.165 6.755-4.176 9.819-11.11 11.306a15.462 15.462 0 01-3.221.364zM35.659 74.749a5.343 5.343 0 01-1.704-.281c-4.307-1.437-8.409-8.451-12.193-20.849-2.88-9.438-4.705-19.288-4.865-22.489-.475-9.49 1.97-16.205 7.265-19.957 10.476-7.423 28.1-.354 28.845-.05a1.285 1.285 0 01-.972 2.379v.001c-.17-.07-17.07-6.84-26.392-.229-4.528 3.211-6.607 9.175-6.18 17.729.135 2.696 1.84 12.311 4.757 21.867 3.378 11.067 7.223 18.052 10.548 19.16.521.175 2.109.704 4.381-2.026 4.272-5.14 8.197-9.242 8.236-9.283a1.286 1.286 0 011.856 1.778c-.039.04-3.904 4.081-8.116 9.148-1.995 2.398-3.908 3.102-5.466 3.102zm55.92-10.829a1.284 1.284 0 01-1.065-2.004c11.971-17.764 16.173-39.227 12.574-43.825-4.53-5.788-10.927-8.812-19.012-8.985-5.987-.13-10.746 1.399-11.523 1.666l-.195.079c-.782.246-1.382-.183-1.608-.684a1.29 1.29 0 01.508-1.631l.346-.142-.017.005.018-.006c1.321-.483 6.152-1.933 12.137-1.864 8.947.094 16.337 3.545 21.371 9.977 2.382 3.044 2.387 10.057.015 19.24-2.418 9.362-6.968 19.425-12.482 27.607a1.282 1.282 0 01-1.067.567zm.611 8.223c-2.044 0-3.876-.287-4.973-.945-1.128-.675-1.343-1.594-1.371-2.081-.308-5.404 2.674-6.345 4.195-6.774-.212-.32-.514-.697-.825-1.086-.887-1.108-2.101-2.626-3.037-4.896-.146-.354-.606-1.179-1.138-2.133-2.883-5.169-8.881-15.926-5.028-21.435 1.784-2.549 5.334-3.552 10.566-2.992-1.539-4.689-8.869-19.358-26.259-19.643-5.231-.088-9.521 1.521-12.744 4.775-7.217 7.289-6.955 20.477-6.952 20.608a1.284 1.284 0 11-2.569.067c-.016-.585-.286-14.424 7.695-22.484 3.735-3.772 8.651-5.634 14.612-5.537C75.49 7.77 82.651 13.426 86.7 18.14c4.412 5.136 6.576 10.802 6.754 12.692.133 1.406-.876 1.688-1.08 1.729l-.463.011c-5.135-.822-8.429-.252-9.791 1.695-2.931 4.188 2.743 14.363 5.166 18.709.619 1.108 1.065 1.909 1.269 2.404.796 1.93 1.834 3.227 2.668 4.269.733.917 1.369 1.711 1.597 2.645.105.185 1.603 2.399 10.488.565 2.227-.459 3.562-.066 3.97 1.168.803 2.429-3.702 5.261-6.196 6.42-2.238 1.039-5.805 1.696-8.892 1.696zm-3.781-3.238c.281.285 1.691.775 4.612.65 2.596-.112 5.335-.677 6.979-1.439 2.102-.976 3.504-2.067 4.231-2.812l-.404.074c-5.681 1.173-9.699 1.017-11.942-.465a4.821 4.821 0 01-.435-.323c-.243.096-.468.159-.628.204-1.273.357-2.589.726-2.413 4.111zm-36.697 7.179c-1.411 0-2.896-.191-4.413-.572-1.571-.393-4.221-1.576-4.18-3.519.045-2.181 3.216-2.835 4.411-3.081 4.312-.888 4.593-1.244 5.941-2.955.393-.499.882-1.12 1.548-1.865.99-1.107 2.072-1.669 3.216-1.669.796 0 1.45.271 1.881.449 1.376.57 2.524 1.948 2.996 3.598.426 1.488.223 2.92-.572 4.032-2.608 3.653-6.352 5.582-10.828 5.582zm-5.817-3.98c.388.299 1.164.699 2.027.916 1.314.328 2.588.495 3.79.495 3.662 0 6.601-1.517 8.737-4.506.445-.624.312-1.415.193-1.832-.25-.872-.87-1.665-1.509-1.931-.347-.144-.634-.254-.898-.254-.142 0-.573 0-1.3.813-.614.686-1.055 1.246-1.446 1.741-1.678 2.131-2.447 2.854-7.441 3.883-1.218.252-1.843.506-2.153.675zm9.882-5.928a1.286 1.286 0 01-1.269-1.09 6.026 6.026 0 01-.064-.644c-3.274-.062-6.432-1.466-8.829-3.968-3.031-3.163-4.411-7.545-3.785-12.022.68-4.862.426-9.154.289-11.46a25.514 25.514 0 01-.063-1.425c.002-.406.01-1.485 3.615-3.312 1.282-.65 3.853-1.784 6.661-2.075 4.654-.48 7.721 1.592 8.639 5.836 2.478 11.46.196 16.529-1.47 20.23-.311.688-.604 1.34-.838 1.97l-.207.557c-.88 2.36-1.641 4.399-1.407 5.923a1.287 1.287 0 01-1.075 1.466l-.197.014zM44.634 35.922l.051.918c.142 2.395.406 6.853-.31 11.969-.516 3.692.612 7.297 3.095 9.888 1.962 2.048 4.546 3.178 7.201 3.178h.055c.298-1.253.791-2.575 1.322-4l.206-.553c.265-.712.575-1.401.903-2.13 1.604-3.564 3.6-8 1.301-18.633-.456-2.105-1.56-3.324-3.375-3.726-3.728-.824-9.283 1.98-10.449 3.089zm7.756-.545c-.064.454.833 1.667 2.001 1.829 1.167.163 2.166-.785 2.229-1.239.063-.455-.833-.955-2.002-1.118-1.167-.163-2.166.073-2.228.528zm2.27 2.277l-.328-.023c-.725-.101-1.458-.558-1.959-1.223-.176-.233-.464-.687-.407-1.091.082-.593.804-.947 1.933-.947.253 0 .515.019.78.055.616.086 1.189.264 1.612.5.733.41.787.866.754 1.103-.091.653-1.133 1.626-2.385 1.626zm-1.844-2.201c.037.28.73 1.205 1.634 1.33l.209.015c.834 0 1.458-.657 1.531-.872-.077-.146-.613-.511-1.631-.651a4.72 4.72 0 00-.661-.048c-.652-.001-1.001.146-1.082.226zm35.121-1.003c.063.455-.832 1.668-2.001 1.83-1.168.162-2.167-.785-2.231-1.24-.062-.454.834-.955 2.002-1.117 1.168-.164 2.166.074 2.23.527zm-2.27 2.062c-1.125 0-2.094-.875-2.174-1.442-.092-.681 1.029-1.199 2.185-1.359.254-.036.506-.054.749-.054.997 0 1.657.293 1.723.764.043.306-.191.777-.595 1.201-.266.28-.826.765-1.588.87l-.3.02zm.759-2.427c-.223 0-.455.017-.69.049-1.162.161-1.853.628-1.82.878.039.274.78 1.072 1.75 1.072l.239-.017c.634-.089 1.11-.502 1.337-.741.356-.375.498-.727.481-.848-.021-.157-.449-.393-1.297-.393zm3.194 26.453a1.285 1.285 0 01-1.067-2c2.736-4.087 2.235-8.256 1.751-12.286-.207-1.718-.42-3.493-.364-5.198.056-1.753.278-3.199.494-4.599.255-1.657.496-3.224.396-5.082a1.286 1.286 0 012.567-.138c.114 2.124-.159 3.896-.423 5.611-.204 1.323-.415 2.691-.466 4.29-.049 1.509.144 3.112.348 4.808.516 4.287 1.099 9.146-2.167 14.023-.248.37-.655.571-1.069.571z"/><path fill="#currentColor" d="M2.835 103.184a26.23 26.23 0 014.343-.338c2.235 0 3.874.52 4.914 1.456.962.832 1.534 2.106 1.534 3.667 0 1.586-.469 2.834-1.353 3.744-1.196 1.274-3.146 1.924-5.356 1.924-.676 0-1.3-.026-1.819-.156v7.021H2.835v-17.318zm2.263 8.45c.494.13 1.118.182 1.872.182 2.729 0 4.394-1.326 4.394-3.744 0-2.314-1.638-3.432-4.134-3.432-.988 0-1.742.078-2.132.182v6.812zm22.23 2.47c0 4.654-3.225 6.683-6.267 6.683-3.406 0-6.032-2.496-6.032-6.475 0-4.212 2.756-6.682 6.24-6.682 3.615-.001 6.059 2.626 6.059 6.474zm-9.984.13c0 2.756 1.586 4.836 3.822 4.836 2.184 0 3.821-2.054 3.821-4.888 0-2.132-1.065-4.836-3.77-4.836s-3.873 2.496-3.873 4.888zm12.557 3.926c.676.442 1.872.91 3.016.91 1.664 0 2.444-.832 2.444-1.872 0-1.092-.649-1.69-2.34-2.314-2.262-.806-3.328-2.054-3.328-3.562 0-2.028 1.638-3.692 4.342-3.692 1.274 0 2.393.364 3.095.78l-.572 1.664a4.897 4.897 0 00-2.574-.728c-1.352 0-2.106.78-2.106 1.716 0 1.04.755 1.508 2.393 2.132 2.184.832 3.302 1.924 3.302 3.796 0 2.21-1.716 3.77-4.706 3.77-1.378 0-2.652-.338-3.536-.858l.57-1.742zm13.365-13.859v3.614h3.275v1.742h-3.275v6.786c0 1.56.441 2.444 1.716 2.444a5.09 5.09 0 001.326-.156l.104 1.716c-.441.182-1.144.312-2.027.312-1.066 0-1.925-.338-2.471-.962-.649-.676-.884-1.794-.884-3.276v-6.864h-1.95v-1.742h1.95v-3.016l2.236-.598zm16.536 3.615c-.053.91-.104 1.924-.104 3.458v7.306c0 2.886-.572 4.654-1.794 5.747-1.222 1.144-2.99 1.508-4.576 1.508-1.508 0-3.172-.364-4.187-1.04l.572-1.742c.832.52 2.132.988 3.692.988 2.34 0 4.056-1.222 4.056-4.394v-1.404h-.052c-.702 1.17-2.054 2.106-4.004 2.106-3.12 0-5.356-2.652-5.356-6.137 0-4.264 2.782-6.682 5.668-6.682 2.185 0 3.381 1.144 3.927 2.184h.052l.104-1.898h2.002zm-2.366 4.966c0-.39-.026-.728-.13-1.04-.416-1.326-1.534-2.418-3.198-2.418-2.185 0-3.744 1.846-3.744 4.758 0 2.47 1.248 4.524 3.718 4.524 1.404 0 2.678-.884 3.172-2.34.13-.39.183-.832.183-1.222v-2.262zm5.901-1.04c0-1.482-.026-2.756-.104-3.926h2.003l.077 2.47h.104c.572-1.69 1.95-2.756 3.484-2.756.26 0 .441.026.649.078v2.158a3.428 3.428 0 00-.779-.078c-1.612 0-2.757 1.222-3.068 2.938a6.44 6.44 0 00-.104 1.066v6.708h-2.262v-8.658zm9.517 2.782c.052 3.094 2.027 4.368 4.315 4.368 1.639 0 2.626-.286 3.484-.65l.39 1.638c-.806.364-2.184.78-4.186.78-3.874 0-6.188-2.548-6.188-6.344 0-3.796 2.236-6.787 5.902-6.787 4.108 0 5.2 3.614 5.2 5.928 0 .468-.052.832-.078 1.066h-8.839zm6.708-1.638c.025-1.456-.599-3.718-3.172-3.718-2.314 0-3.328 2.132-3.511 3.718h6.683z"/><path fill="#currentColor" d="M84.371 117.744a8.016 8.016 0 004.056 1.144c2.314 0 3.666-1.222 3.666-2.99 0-1.638-.936-2.574-3.302-3.484-2.86-1.014-4.628-2.496-4.628-4.966 0-2.73 2.262-4.758 5.668-4.758 1.794 0 3.094.416 3.874.858l-.624 1.846a6.98 6.98 0 00-3.328-.832c-2.392 0-3.302 1.43-3.302 2.626 0 1.638 1.065 2.444 3.484 3.38 2.964 1.145 4.472 2.574 4.472 5.148 0 2.704-2.002 5.044-6.136 5.044-1.69 0-3.536-.494-4.473-1.118l.573-1.898zm27.586 5.33a94.846 94.846 0 01-6.708-2.028c-.364-.13-.728-.26-1.066-.26-4.16-.156-7.722-3.224-7.722-8.866 0-5.616 3.432-9.23 8.164-9.23 4.758 0 7.853 3.692 7.853 8.866 0 4.498-2.08 7.384-4.992 8.398v.104c1.742.442 3.64.858 5.122 1.118l-.651 1.898zm-1.872-11.414c0-3.51-1.819-7.125-5.538-7.125-3.822 0-5.694 3.536-5.668 7.333-.026 3.718 2.028 7.072 5.564 7.072 3.615 0 5.642-3.276 5.642-7.28zm5.329-8.684h2.263v15.626h7.488v1.898h-9.751v-17.524z"/></svg> ', ], [ 'id' => 'mysql', 'name' => 'MySQL', 'description' => 'MySQL is an open-source relational database management system. ', 'logo' => '<svg class="w-[4.5rem] h-[4.5rem] p-2 transition-all duration-200 bg-black/10 dark:bg-white/10" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"> <path fill="currentColor" d="M0 91.313h4.242V74.566l6.566 14.598c.773 1.77 1.832 2.391 3.914 2.391s3.098-.621 3.871-2.391l6.566-14.598v16.746h4.242V74.594c0-1.633-.652-2.422-2-2.828-3.223-1.004-5.383-.137-6.363 2.039l-6.441 14.41-6.238-14.41c-.937-2.176-3.14-3.043-6.359-2.039-1.348.406-2 1.195-2 2.828zM32.93 77.68h4.238v9.227c-.039.5.16 1.676 2.484 1.715h9.223V77.633h4.25c.02 0-.008 14.984-.008 15.047.023 3.695-4.582 4.496-6.707 4.559H33.02v-2.852l13.414-.004c2.73-.285 2.406-1.645 2.406-2.098v-1.113h-9.012c-4.195-.039-6.863-1.871-6.898-3.977-.004-.191.09-9.422 0-9.516zm0 0" /> <path fill="currentColor" d="M56.391 91.313h12.195c1.426 0 2.813-.301 3.914-.816 1.836-.84 2.73-1.984 2.73-3.48v-3.098c0-1.223-1.016-2.367-3.016-3.125-1.059-.41-2.367-.625-3.629-.625h-5.141c-1.711 0-2.527-.516-2.73-1.656-.039-.137-.039-.246-.039-.383V76.2c0-.109 0-.219.039-.355.203-.867.652-1.113 2.16-1.25l.41-.027h12.109v-2.824H63.488c-1.711 0-2.609.109-3.426.352-2.527.789-3.629 2.039-3.629 4.215v2.473c0 1.902 2.16 3.535 5.789 3.914l1.223.055h4.406c.164 0 .324 0 .449.027 1.344.109 1.914.355 2.324.844.211.195.332.473.324.758v2.477c0 .297-.203.68-.609 1.004-.367.328-.98.543-1.793.598l-.449.027H56.391zm45.297-4.922c0 2.91 2.164 4.539 6.523 4.867l1.227.055h11.051v-2.828h-11.133c-2.488 0-3.426-.625-3.426-2.121V71.738h-4.238V86.39zm-23.75.148V76.457c0-2.559 1.801-4.113 5.355-4.602a7.976 7.976 0 0 1 1.145-.082h8.047c.41 0 .777.027 1.188.082 3.555.488 5.352 2.043 5.352 4.602v10.082c0 2.078-.762 3.188-2.523 3.914l4.18 3.77h-4.926l-3.379-3.051-3.402.215H84.44a9.23 9.23 0 0 1-2.492-.352c-2.699-.734-4.008-2.152-4.008-4.496zm4.578-.246c0 .137.039.273.082.438.246 1.172 1.348 1.824 3.023 1.824h3.852l-3.539-3.195h4.926l3.086 2.789c.57-.305.941-.766 1.074-1.363.039-.137.039-.273.039-.41v-9.668c0-.109 0-.246-.039-.383-.246-1.09-1.348-1.715-2.984-1.715h-6.414c-1.879 0-3.105.816-3.105 2.098zm0 0" /> <path fill="#00618A" d="M124.219 67.047c-2.605-.07-4.598.172-6.301.891-.484.203-1.258.207-1.336.813.266.281.309.699.52 1.039.406.66 1.094 1.539 1.707 2l2.074 1.484c1.273.777 2.699 1.223 3.93 2 .723.461 1.441 1.039 2.148 1.559.348.254.582.656 1.039.816v-.074c-.238-.305-.301-.723-.52-1.039l-.965-.965c-.941-1.25-2.137-2.348-3.41-3.262-1.016-.727-3.281-1.711-3.707-2.891l-.074-.074c.719-.078 1.563-.34 2.223-.516 1.117-.301 2.113-.223 3.262-.52l1.559-.449v-.293c-.582-.598-.996-1.387-1.633-1.93-1.656-1.41-3.469-2.824-5.336-4.004-1.035-.652-2.312-1.074-3.41-1.629-.367-.187-1.016-.281-1.262-.594-.574-.734-.887-1.664-1.332-2.52l-2.668-5.633c-.562-1.285-.93-2.555-1.633-3.707-3.363-5.535-6.988-8.875-12.602-12.156-1.191-.699-2.633-.973-4.148-1.332l-2.449-.148c-.496-.211-1.012-.82-1.48-1.113-1.859-1.176-6.629-3.73-8.008-.371-.867 2.121 1.301 4.191 2.078 5.266.543.754 1.242 1.598 1.629 2.445.258.555.301 1.113.52 1.703.539 1.453 1.008 3.031 1.707 4.375.352.68.738 1.395 1.184 2 .273.371.742.539.816 1.113-.457.641-.484 1.633-.742 2.445-1.16 3.652-.723 8.191.965 10.898.516.828 1.734 2.609 3.41 1.926 1.465-.598 1.137-2.445 1.555-4.078.098-.367.039-.641.223-.887v.074l1.336 2.668c.988 1.59 2.738 3.25 4.223 4.371.773.582 1.379 1.59 2.375 1.93V68.6h-.074c-.195-.297-.496-.422-.742-.664-.582-.57-1.227-1.277-1.703-1.93-1.352-1.832-2.547-3.84-3.633-5.93-.52-.996-.973-2.098-1.41-3.113-.168-.391-.164-.984-.516-1.184-.48.742-1.187 1.344-1.559 2.223-.594 1.402-.668 3.117-.891 4.891l-.148.074c-1.031-.25-1.395-1.312-1.777-2.223-.973-2.305-1.152-6.02-.297-8.672.219-.687 1.219-2.852.813-3.484-.191-.633-.828-1-1.184-1.484a11.7 11.7 0 0 1-1.187-2.074c-.793-1.801-1.164-3.816-2-5.633-.398-.871-1.074-1.75-1.629-2.523-.617-.855-1.305-1.484-1.781-2.52-.168-.367-.398-.957-.148-1.336.078-.254.195-.359.445-.441.43-.332 1.629.109 2.074.293 1.191.496 2.184.965 3.191 1.633.48.32.969.941 1.555 1.113h.668c1.043.238 2.211.07 3.188.367 1.723.523 3.27 1.34 4.668 2.227 4.273 2.695 7.766 6.535 10.156 11.117.387.738.551 1.441.891 2.223.684 1.578 1.543 3.203 2.223 4.746s1.34 3.094 2.297 4.375c.504.672 2.453 1.031 3.336 1.406.621.262 1.637.535 2.223.891 1.125.676 2.211 1.48 3.266 2.223.523.375 2.141 1.188 2.223 1.855zM91.082 38.805a5.26 5.26 0 0 0-1.332.148v.074h.074c.258.535.715.879 1.035 1.336l.742 1.555.074-.07c.461-.324.668-.844.668-1.633-.187-.195-.211-.437-.371-.668-.211-.309-.621-.48-.891-.742zm0 0" /> </svg>', ], [ 'id' => 'mariadb', 'name' => 'MariaDB', 'description' => 'MariaDB is a community-developed, commercially supported fork of the MySQL relational database management system, intended to remain free and open-source.', 'logo' => '<svg class="w-[4.5rem] h-[4.5rem] p-2 transition-all duration-200 bg-black/10 dark:bg-white/10" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><path fill="currentColor" d="M127.434 12.182a1.727 1.727 0 0 0-1.174-.392c-1.168 0-2.68.793-3.495 1.218l-.322.165a11.095 11.095 0 0 1-4.365 1.1c-1.554.049-2.892.14-4.635.322-10.327 1.06-14.933 8.975-19.37 16.63-2.416 4.164-4.91 8.489-8.33 11.793a22.472 22.472 0 0 1-2.252 1.913c-3.54 2.631-7.985 4.51-11.443 5.84-3.329 1.273-6.964 2.417-10.474 3.524-3.219 1.012-6.255 1.97-9.048 3.008a96.902 96.902 0 0 1-3.275 1.14c-2.545.825-4.378 1.458-7.06 3.304a45.386 45.386 0 0 0-2.804 2.066 29.585 29.585 0 0 0-5.597 5.894 34.802 34.802 0 0 1-4.701 5.642c-.566.554-1.57.826-3.074.826-1.76 0-3.895-.363-6.154-.747-2.33-.413-4.738-.805-6.803-.805-1.677 0-2.962.273-3.92.826 0 0-1.617.942-2.298 2.16l.67.302a13.718 13.718 0 0 1 2.859 2.065 14.342 14.342 0 0 0 2.973 2.115 2.553 2.553 0 0 1 .918.582c-.281.413-.694.946-1.129 1.516-2.384 3.119-3.774 5.09-2.977 6.163a2.507 2.507 0 0 0 1.239.28c5.196 0 7.989-1.35 11.52-3.06 1.024-.495 2.066-1.004 3.305-1.528 2.065-.896 4.288-2.325 6.647-3.838 3.084-2.01 6.31-4.076 9.442-5.072a25.734 25.734 0 0 1 7.943-1.115c3.305 0 6.783.441 10.138.872 2.499.322 5.089.652 7.63.805.986.057 1.9.086 2.787.086a32.307 32.307 0 0 0 3.557-.185l.284-.1c1.781-1.094 2.617-3.444 3.425-5.717.52-1.462.96-2.775 1.652-3.61a1.054 1.054 0 0 1 .132-.11.166.166 0 0 1 .202.032v.066c-.412 8.885-3.99 14.527-7.608 19.543l-2.416 2.59s3.383 0 5.307-.744c7.024-2.099 12.324-6.725 16.181-14.103a60.185 60.185 0 0 0 2.549-5.82c.065-.165.673-.47.616.384-.021.252-.038.533-.059.827 0 .173 0 .35-.033.528-.1 1.24-.392 3.859-.392 3.859l2.169-1.162c5.229-3.304 9.26-9.97 12.318-20.343 1.272-4.321 2.205-8.613 3.027-12.392.983-4.545 1.83-8.44 2.801-9.952 1.524-2.37 3.85-3.973 6.101-5.53.306-.211.616-.414.917-.637 2.83-1.986 5.643-4.279 6.263-8.555v-.095c.45-3.189.07-4.002-.364-4.373zm-7.283 103.727h-10.327V97.92h9.315c3.56 0 6.952.67 6.902 4.66 0 2.813-1.747 3.59-3.589 3.886 2.615.224 4.188 1.892 4.188 4.586.017 4.035-3.523 4.858-6.489 4.858zm-.772-10.14c3.565 0 4.362-1.372 4.362-3.115 0-2.619-1.595-3.214-4.362-3.214h-7.402v6.328zm.099 1.52h-7.501v7.1h7.823c2.194 0 4.511-.723 4.511-3.486 0-3.19-2.665-3.615-4.833-3.615zm-31.497-9.37h8.125c6.828 0 10.24 3.764 10.19 8.994.05 5.436-3.716 8.997-9.591 8.997H87.98zm2.242 1.596v14.825h6.197c5.432 0 7.501-3.665 7.501-7.477 0-4.309-2.59-7.348-7.5-7.348zm-10.838 5.357v-2.095h3.404v13.132h-3.392v-2.114c-.896 1.52-2.739 2.391-4.982 2.391-4.684 0-7.303-3.305-7.303-7.105 0-3.664 2.479-6.609 6.804-6.609 2.454.029 4.498.855 5.469 2.4zm-8.675 4.387c0 2.416 1.52 4.485 4.462 4.485 2.841 0 4.386-2.02 4.386-4.411 0-2.392-1.599-4.436-4.544-4.436-2.828 0-4.3 2.04-4.3 4.362zm-10.013-9.947a1.722 1.722 0 0 1 1.818-1.768 1.788 1.788 0 0 1 1.847 1.821 1.714 1.714 0 0 1-1.847 1.744 1.743 1.743 0 0 1-1.818-1.797zm.15 3.465h3.39v9.596c0 .595.125 1.02.62 1.02a3.657 3.657 0 0 0 .648-.073l.525 2.478a5.931 5.931 0 0 1-2.242.414c-1.421 0-2.942-.414-2.942-3.64zM52.15 115.91h-3.386v-13.132h3.386v2.942a5.197 5.197 0 0 1 4.735-3.218 6.13 6.13 0 0 1 2.119.347l-.723 2.479a7.435 7.435 0 0 0-1.793-.249c-2.445 0-4.338 1.843-4.338 4.545zm-11.037-11.037v-2.095h3.392v13.132h-3.392v-2.114c-.896 1.52-2.738 2.391-4.982 2.391-4.688 0-7.303-3.305-7.303-7.105 0-3.664 2.479-6.609 6.804-6.609 2.466.029 4.51.855 5.481 2.4zm-8.675 4.387c0 2.416 1.52 4.485 4.462 4.485 2.838 0 4.383-2.02 4.383-4.411 0-2.391-1.595-4.436-4.544-4.436-2.826 0-4.296 2.04-4.296 4.362zm-9.24-11.34 4.651 17.99h-3.51L21.24 102.95 15.4 115.91h-2.965l-5.808-12.883-3.19 12.883H0l4.61-17.99h3.04l6.28 13.93 6.253-13.93z"/></svg>', ], [ 'id' => 'redis', 'name' => 'Redis', 'description' => 'Redis is a source-available, in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.', 'logo' => '<svg class="w-[4.5rem] h-[4.5rem] p-2 transition-all duration-200 bg-black/10 dark:bg-white/10" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><path d="M21.4 97.6c0 1.8-1.5 3.5-3.5 3.5-1.5 0-2.8.4-4 1.3-1.3.8-2.2 1.9-3 3.2-1.6 2.1-2.4 4.6-2.7 5.5v12.5c0 1.9-1.6 3.5-3.6 3.5-1.9 0-3.5-1.6-3.5-3.5v-26c0-1.9 1.6-3.4 3.5-3.4 2 0 3.6 1.5 3.6 3.4v.5c.4-.5.9-1 1.4-1.3 2.2-1.4 5-2.6 8.3-2.6 2 0 3.5 1.5 3.5 3.4zm-1.9 13c.1-9 7-16.5 16.1-16.5 8.6 0 15.3 6.4 15.9 15.3v.3c0 .1 0 .5-.1.6-.2 1.6-1.6 2.6-3.4 2.6H27c.3 1.5 1.1 3.2 2.2 4.3 1.4 1.6 4 2.8 6.3 3 2.4.2 5.2-.4 6.8-1.6 1.4-1.4 4.1-1.3 4.9-.2.9.9 1.5 2.9 0 4.3-3.2 3-7.1 4.3-11.8 4.3-8.9 0-15.9-7.5-15.9-16.4zm7.1-3.2h18.6c-.7-2.6-4-6.5-9.7-7-5.6.2-8.3 4.3-8.9 7zm58.3 16.1c0 1.9-1.6 3.6-3.6 3.6-1.8 0-3.2-1.3-3.5-2.8-2.5 1.7-5.7 2.8-9 2.8-8.9 0-16-7.5-16-16.4 0-9 7.1-16.5 16-16.5 3.2 0 6.4 1.1 8.8 2.8V84.5c0-1.9 1.6-3.6 3.6-3.6s3.6 1.6 3.6 3.6v26.2l.1 12.8zm-16-22.2c-2.4 0-4.5 1-6.2 2.7-1.6 1.6-2.6 4-2.6 6.6 0 2.5 1 4.9 2.6 6.5 1.6 1.7 3.8 2.7 6.2 2.7 2.4 0 4.5-1 6.2-2.7 1.6-1.6 2.6-4 2.6-6.5 0-2.6-1-5-2.6-6.6-1.6-1.7-3.7-2.7-6.2-2.7zm28.6-15.4c0 2-1.5 3.6-3.6 3.6-2 0-3.6-1.6-3.6-3.6v-1.4c0-2 1.6-3.6 3.6-3.6s3.6 1.6 3.6 3.6v1.4zm0 11.9v25.7c0 2-1.5 3.6-3.6 3.6-2 0-3.6-1.6-3.6-3.6V97.8c0-2.1 1.6-3.6 3.6-3.6 2.1 0 3.6 1.5 3.6 3.6zm4.5 19.8c1.2-1.6 3.5-1.8 4.9-.5 1.7 1.4 4.7 3 7.2 2.9 1.8 0 3.4-.6 4.5-1.3.9-.8 1.2-1.4 1.2-2 0-.3-.1-.5-.2-.7-.1-.2-.3-.5-.9-.8-.9-.7-2.9-1.4-5.3-1.8h-.1c-2-.4-4-.9-5.7-1.7-1.8-.9-3.4-2-4.5-3.8-.7-1.2-1.1-2.6-1.1-4.1 0-3 1.7-5.6 3.9-7.2 2.3-1.6 5.1-2.4 8.1-2.4 4.5 0 7.8 2.2 9.9 3.6 1.6 1.1 2 3.2 1.1 4.9-1.1 1.6-3.2 2-4.9.9-2.1-1.4-4-2.4-6.1-2.4-1.6 0-3.1.5-4 1.2-.9.6-1.1 1.2-1.1 1.5 0 .3 0 .3.1.5.1.1.3.4.7.7.9.6 2.6 1.2 4.8 1.6l.1.1h.1c2.2.4 4.2 1 6.1 1.9 1.8.8 3.6 2 4.7 3.9.8 1.3 1.3 2.8 1.3 4.3 0 3.2-1.8 5.9-4.1 7.6-2.4 1.6-5.3 2.6-8.6 2.6-5.1-.1-9.1-2.4-11.7-4.5-1.4-1.3-1.6-3.5-.4-5z" fill="#currentColor"/><path fill="#A41E11" d="M106.9 62.7c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8-4.4-2.1-31.7-13.1-36.7-15.5-2.5-1.2-3.8-2.2-3.8-3.1v-9.4s35.6-7.8 41.4-9.8c5.8-2.1 7.8-2.1 12.6-.3 4.9 1.8 34.2 7.1 39 8.8v9.3c.1.9-1 1.9-3.5 3.2z"/><path fill="#D82C20" d="M106.9 53.3c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8C53.5 68 26.2 57 21.2 54.6c-4.9-2.4-5-4-.2-5.9 4.8-1.9 32.1-12.6 37.8-14.6 5.8-2.1 7.8-2.1 12.6-.3 4.9 1.8 30.5 12 35.3 13.7 5 1.8 5.2 3.2.2 5.8z"/><path fill="#A41E11" d="M106.9 47.4c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8-4.4-2.1-31.7-13.2-36.7-15.5-2.5-1.2-3.8-2.2-3.8-3.1v-9.4s35.6-7.8 41.4-9.8c5.8-2.1 7.8-2.1 12.6-.3 4.9 1.8 34.2 7.1 39 8.8v9.3c.1.9-1 1.9-3.5 3.2z"/><path fill="#D82C20" d="M106.9 38c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8-4.3-2.1-31.7-13.1-36.6-15.5-4.9-2.4-5-4-.2-5.9 4.8-1.9 32.1-12.6 37.8-14.6 5.8-2.1 7.8-2.1 12.6-.3 4.9 1.8 30.5 12 35.3 13.7 4.9 1.7 5.1 3.2.1 5.8z"/><path fill="#A41E11" d="M106.9 31.5c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8-4.3-2.1-31.7-13.1-36.6-15.5-2.5-1.2-3.8-2.2-3.8-3.1v-9.4s35.6-7.8 41.4-9.8c5.8-2.1 7.8-2.1 12.6-.3 4.9 1.8 34.2 7.1 39 8.8v9.3c0 .8-1.1 1.9-3.6 3.2z"/><path fill="#D82C20" d="M106.9 22.1c-5 2.6-30.7 13.2-36.2 16-5.5 2.9-8.5 2.8-12.8.8-4.3-2.1-31.7-13.1-36.6-15.5s-5-4-.2-5.9c4.8-1.9 32.1-12.6 37.8-14.6C64.7.8 66.7.8 71.5 2.6c4.9 1.8 30.5 12 35.3 13.7 4.9 1.7 5.1 3.2.1 5.8z"/><path fill="#fff" d="M76.2 13l-8.1.8-1.8 4.4-2.9-4.9-9.3-.8L61 10l-2-3.8 6.5 2.5 6.1-2-1.7 4zM65.8 34.1l-15-6.3 21.6-3.3z"/><ellipse fill="#fff" cx="45" cy="19.9" rx="11.5" ry="4.5"/><path fill="#7A0C00" d="M85.7 14.2l12.8 5-12.8 5.1z"/><path fill="#AD2115" d="M71.6 19.8l14.1-5.6v10.1l-1.3.5z"/></svg>', ], [ 'id' => 'keydb', 'name' => 'KeyDB', 'description' => 'KeyDB is a database that offers high performance, low latency, and scalability for various data structures and workloads.',
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
true
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/New/PublicGitRepository.php
app/Livewire/Project/New/PublicGitRepository.php
<?php namespace App\Livewire\Project\New; use App\Models\Application; use App\Models\GithubApp; use App\Models\GitlabApp; use App\Models\Project; use App\Models\Service; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use App\Rules\ValidGitBranch; use App\Rules\ValidGitRepositoryUrl; use Carbon\Carbon; use Livewire\Component; use Spatie\Url\Url; class PublicGitRepository extends Component { public string $repository_url; public int $port = 3000; public string $type; public $parameters; public $query; public bool $branchFound = false; public string $selectedBranch = 'main'; public bool $isStatic = false; public bool $checkCoolifyConfig = true; public ?string $publish_directory = null; // In case of docker compose public string $base_directory = '/'; public ?string $docker_compose_location = '/docker-compose.yaml'; // End of docker compose public string $git_branch = 'main'; public int $rate_limit_remaining = 0; public $rate_limit_reset = 0; private object $repository_url_parsed; public GithubApp|GitlabApp|string $git_source = 'other'; public string $git_host; public string $git_repository; public $build_pack = 'nixpacks'; public bool $show_is_static = true; public bool $new_compose_services = false; protected $rules = [ 'repository_url' => ['required', 'string'], 'port' => 'required|numeric', 'isStatic' => 'required|boolean', 'publish_directory' => 'nullable|string', 'build_pack' => 'required|string', 'base_directory' => 'nullable|string', 'docker_compose_location' => 'nullable|string', ]; protected function rules() { return [ 'repository_url' => ['required', 'string', new ValidGitRepositoryUrl], 'port' => 'required|numeric', 'isStatic' => 'required|boolean', 'publish_directory' => 'nullable|string', 'build_pack' => 'required|string', 'base_directory' => 'nullable|string', 'docker_compose_location' => 'nullable|string', 'git_branch' => ['required', 'string', new ValidGitBranch], ]; } protected $validationAttributes = [ 'repository_url' => 'repository', 'port' => 'port', 'isStatic' => 'static', 'publish_directory' => 'publish directory', 'build_pack' => 'build pack', 'base_directory' => 'base directory', 'docker_compose_location' => 'docker compose location', ]; public function mount() { if (isDev()) { $this->repository_url = 'https://github.com/coollabsio/coolify-examples/tree/v4.x'; $this->port = 3000; } $this->parameters = get_route_parameters(); $this->query = request()->query(); } public function updatedBuildPack() { if ($this->build_pack === 'nixpacks') { $this->show_is_static = true; $this->port = 3000; } elseif ($this->build_pack === 'static') { $this->show_is_static = false; $this->isStatic = false; $this->port = 80; } else { $this->show_is_static = false; $this->isStatic = false; } } public function instantSave() { if ($this->isStatic) { $this->port = 80; $this->publish_directory = '/dist'; } else { $this->port = 3000; $this->publish_directory = null; } $this->dispatch('success', 'Application settings updated!'); } public function loadBranch() { try { // Validate repository URL $validator = validator(['repository_url' => $this->repository_url], [ 'repository_url' => ['required', 'string', new ValidGitRepositoryUrl], ]); if ($validator->fails()) { throw new \RuntimeException('Invalid repository URL: '.$validator->errors()->first('repository_url')); } if (str($this->repository_url)->startsWith('git@')) { $github_instance = str($this->repository_url)->after('git@')->before(':'); $repository = str($this->repository_url)->after(':')->before('.git'); $this->repository_url = 'https://'.str($github_instance).'/'.$repository; } if ( (str($this->repository_url)->startsWith('https://') || str($this->repository_url)->startsWith('http://')) && ! str($this->repository_url)->endsWith('.git') && (! str($this->repository_url)->contains('github.com') || ! str($this->repository_url)->contains('git.sr.ht')) && ! str($this->repository_url)->contains('tangled') ) { $this->repository_url = $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) { return handleError($e, $this); } try { $this->branchFound = false; $this->getGitSource(); $this->getBranch(); if (str($this->repository_url)->contains('tangled')) { $this->git_branch = 'master'; } $this->selectedBranch = $this->git_branch; } catch (\Throwable $e) { if ($this->rate_limit_remaining == 0) { $this->selectedBranch = $this->git_branch; $this->branchFound = true; return; } if (! $this->branchFound && $this->git_branch === 'main') { try { $this->git_branch = 'master'; $this->getBranch(); } catch (\Throwable $e) { return handleError($e, $this); } } else { return handleError($e, $this); } } } private function getGitSource() { $this->git_branch = 'main'; $this->base_directory = '/'; // Validate repository URL before parsing $validator = validator(['repository_url' => $this->repository_url], [ 'repository_url' => ['required', 'string', new ValidGitRepositoryUrl], ]); if ($validator->fails()) { throw new \RuntimeException('Invalid repository URL: '.$validator->errors()->first('repository_url')); } $this->repository_url_parsed = Url::fromString($this->repository_url); $this->git_host = $this->repository_url_parsed->getHost(); $this->git_repository = $this->repository_url_parsed->getSegment(1).'/'.$this->repository_url_parsed->getSegment(2); if ($this->repository_url_parsed->getSegment(3) === 'tree') { $path = str($this->repository_url_parsed->getPath())->trim('/'); $this->git_branch = str($path)->after('tree/')->before('/')->value(); $this->base_directory = str($path)->after($this->git_branch)->after('/')->value(); if (filled($this->base_directory)) { $this->base_directory = '/'.$this->base_directory; } else { $this->base_directory = '/'; } } else { $this->git_branch = 'main'; } if ($this->git_host === 'github.com') { $this->git_source = GithubApp::where('name', 'Public GitHub')->first(); return; } $this->git_repository = $this->repository_url; $this->git_source = 'other'; } private function getBranch() { if ($this->git_source === 'other') { $this->branchFound = true; return; } if ($this->git_source->getMorphClass() === \App\Models\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; } } public function submit() { try { $this->validate(); // Additional validation for git repository and branch if ($this->git_source === 'other') { // For 'other' sources, git_repository contains the full URL $validator = validator(['git_repository' => $this->git_repository], [ 'git_repository' => ['required', 'string', new ValidGitRepositoryUrl], ]); if ($validator->fails()) { throw new \RuntimeException('Invalid repository URL: '.$validator->errors()->first('git_repository')); } } $branchValidator = validator(['git_branch' => $this->git_branch], [ 'git_branch' => ['required', 'string', new ValidGitBranch], ]); if ($branchValidator->fails()) { throw new \RuntimeException('Invalid branch: '.$branchValidator->errors()->first('git_branch')); } $destination_uuid = $this->query['destination']; $project_uuid = $this->parameters['project_uuid']; $environment_uuid = $this->parameters['environment_uuid']; $destination = StandaloneDocker::where('uuid', $destination_uuid)->first(); if (! $destination) { $destination = SwarmDocker::where('uuid', $destination_uuid)->first(); } if (! $destination) { throw new \Exception('Destination not found. What?!'); } $destination_class = $destination->getMorphClass(); $project = Project::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) { $server = $destination->server; $new_service = [ 'name' => 'service'.str()->random(10), 'docker_compose_raw' => 'coolify', 'environment_id' => $environment->id, 'server_id' => $server->id, ]; if ($this->git_source === 'other') { $new_service['git_repository'] = $this->git_repository; $new_service['git_branch'] = $this->git_branch; } else { $new_service['git_repository'] = $this->git_repository; $new_service['git_branch'] = $this->git_branch; $new_service['source_id'] = $this->git_source->id; $new_service['source_type'] = $this->git_source->getMorphClass(); } $service = Service::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 = [ 'name' => generate_random_name(), 'git_repository' => $this->git_repository, 'git_branch' => $this->git_branch, 'ports_exposes' => $this->port, 'publish_directory' => $this->publish_directory, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'build_pack' => $this->build_pack, 'base_directory' => $this->base_directory, ]; } else { $application_init = [ 'name' => generate_application_name($this->git_repository, $this->git_branch), 'git_repository' => $this->git_repository, 'git_branch' => $this->git_branch, 'ports_exposes' => $this->port, 'publish_directory' => $this->publish_directory, 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination_class, 'source_id' => $this->git_source->id, 'source_type' => $this->git_source->getMorphClass(), 'build_pack' => $this->build_pack, 'base_directory' => $this->base_directory, ]; } if ($this->build_pack === 'dockerfile' || $this->build_pack === 'dockerimage') { $application_init['health_check_enabled'] = false; } if ($this->build_pack === 'dockercompose') { $application_init['docker_compose_location'] = $this->docker_compose_location; $application_init['base_directory'] = $this->base_directory; } $application = Application::create($application_init); $application->settings->is_static = $this->isStatic; $application->settings->save(); $fqdn = generateUrl(server: $destination->server, random: $application->uuid); $application->fqdn = $fqdn; $application->save(); if ($this->checkCoolifyConfig) { // $config = loadConfigFromGit($this->repository_url, $this->git_branch, $this->base_directory, $this->query['server_id'], auth()->user()->currentTeam()->id); // if ($config) { // $application->setConfig($config); // } } return redirect()->route('project.application.configuration', [ 'application_uuid' => $application->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Swarm.php
app/Livewire/Project/Application/Swarm.php
<?php namespace App\Livewire\Project\Application; use App\Models\Application; use Livewire\Attributes\Validate; use Livewire\Component; class Swarm extends Component { public Application $application; #[Validate('required')] public int $swarmReplicas; #[Validate(['nullable'])] public ?string $swarmPlacementConstraints = null; #[Validate('required')] public bool $isSwarmOnlyWorkerNodes; public function mount() { try { $this->syncData(); } catch (\Throwable $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->application->swarm_replicas = $this->swarmReplicas; $this->application->swarm_placement_constraints = $this->swarmPlacementConstraints ? base64_encode($this->swarmPlacementConstraints) : null; $this->application->settings->is_swarm_only_worker_nodes = $this->isSwarmOnlyWorkerNodes; $this->application->save(); $this->application->settings->save(); } else { $this->swarmReplicas = $this->application->swarm_replicas; if ($this->application->swarm_placement_constraints) { $this->swarmPlacementConstraints = base64_decode($this->application->swarm_placement_constraints); } else { $this->swarmPlacementConstraints = null; } $this->isSwarmOnlyWorkerNodes = $this->application->settings->is_swarm_only_worker_nodes; } } public function instantSave() { try { $this->syncData(true); $this->dispatch('success', 'Swarm settings updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->syncData(true); $this->dispatch('success', 'Swarm settings updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.application.swarm'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Heading.php
app/Livewire/Project/Application/Heading.php
<?php namespace App\Livewire\Project\Application; use App\Actions\Application\StopApplication; use App\Actions\Docker\GetContainersStatus; use App\Models\Application; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; use Visus\Cuid2\Cuid2; class Heading extends Component { use AuthorizesRequests; public Application $application; public ?string $lastDeploymentInfo = null; public ?string $lastDeploymentLink = null; public array $parameters; protected string $deploymentUuid; public bool $docker_cleanup = true; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceStatusChanged" => 'checkStatus', "echo-private:team.{$teamId},ServiceChecked" => '$refresh', 'compose_loaded' => '$refresh', 'update_links' => '$refresh', ]; } public function mount() { $this->parameters = [ 'project_uuid' => $this->application->project()->uuid, 'environment_uuid' => $this->application->environment->uuid, 'application_uuid' => $this->application->uuid, ]; $lastDeployment = $this->application->get_last_successful_deployment(); $this->lastDeploymentInfo = data_get_str($lastDeployment, 'commit')->limit(7).' '.data_get($lastDeployment, 'commit_message'); $this->lastDeploymentLink = $this->application->gitCommitLink(data_get($lastDeployment, 'commit')); } public function checkStatus() { if ($this->application->destination->server->isFunctional()) { GetContainersStatus::dispatch($this->application->destination->server); } else { $this->dispatch('error', 'Server is not functional.'); } } public function manualCheckStatus() { $this->checkStatus(); } public function force_deploy_without_cache() { $this->authorize('deploy', $this->application); $this->deploy(force_rebuild: true); } public function deploy(bool $force_rebuild = false) { $this->authorize('deploy', $this->application); if ($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; } 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; } 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; } 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; } $this->setDeploymentUuid(); $result = queue_application_deployment( application: $this->application, deployment_uuid: $this->deploymentUuid, force_rebuild: $force_rebuild, ); if ($result['status'] === 'queue_full') { $this->dispatch('error', 'Deployment queue full', $result['message']); return; } if ($result['status'] === 'skipped') { $this->dispatch('error', 'Deployment skipped', $result['message']); return; } return $this->redirectRoute('project.application.deployment.show', [ 'project_uuid' => $this->parameters['project_uuid'], 'application_uuid' => $this->parameters['application_uuid'], 'deployment_uuid' => $this->deploymentUuid, 'environment_uuid' => $this->parameters['environment_uuid'], ], navigate: false); } protected function setDeploymentUuid() { $this->deploymentUuid = new Cuid2; $this->parameters['deployment_uuid'] = $this->deploymentUuid; } public function stop() { $this->authorize('deploy', $this->application); $this->dispatch('info', 'Gracefully stopping application.<br/>It could take a while depending on the application.'); StopApplication::dispatch($this->application, false, $this->docker_cleanup); } public function restart() { $this->authorize('deploy', $this->application); 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; } $this->setDeploymentUuid(); $result = queue_application_deployment( application: $this->application, deployment_uuid: $this->deploymentUuid, restart_only: true, ); if ($result['status'] === 'queue_full') { $this->dispatch('error', 'Deployment queue full', $result['message']); return; } if ($result['status'] === 'skipped') { $this->dispatch('success', 'Deployment skipped', $result['message']); return; } return $this->redirectRoute('project.application.deployment.show', [ 'project_uuid' => $this->parameters['project_uuid'], 'application_uuid' => $this->parameters['application_uuid'], 'deployment_uuid' => $this->deploymentUuid, 'environment_uuid' => $this->parameters['environment_uuid'], ], navigate: false); } public function render() { return view('livewire.project.application.heading', [ 'checkboxes' => [ ['id' => 'docker_cleanup', 'label' => __('resource.docker_cleanup')], ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Advanced.php
app/Livewire/Project/Application/Advanced.php
<?php namespace App\Livewire\Project\Application; use App\Models\Application; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; class Advanced extends Component { use AuthorizesRequests; public Application $application; #[Validate(['boolean'])] public bool $isForceHttpsEnabled = false; #[Validate(['boolean'])] public bool $isGitSubmodulesEnabled = false; #[Validate(['boolean'])] public bool $isGitLfsEnabled = false; #[Validate(['boolean'])] public bool $isGitShallowCloneEnabled = false; #[Validate(['boolean'])] public bool $isPreviewDeploymentsEnabled = false; #[Validate(['boolean'])] public bool $isPrDeploymentsPublicEnabled = false; #[Validate(['boolean'])] public bool $isAutoDeployEnabled = true; #[Validate(['boolean'])] public bool $disableBuildCache = false; #[Validate(['boolean'])] public bool $injectBuildArgsToDockerfile = true; #[Validate(['boolean'])] public bool $includeSourceCommitInBuild = false; #[Validate(['boolean'])] public bool $isLogDrainEnabled = false; #[Validate(['boolean'])] public bool $isGpuEnabled = false; #[Validate(['string'])] public string $gpuDriver = ''; #[Validate(['string', 'nullable'])] public ?string $gpuCount = null; #[Validate(['string', 'nullable'])] public ?string $gpuDeviceIds = null; #[Validate(['string', 'nullable'])] public ?string $gpuOptions = null; #[Validate(['boolean'])] public bool $isBuildServerEnabled = false; #[Validate(['boolean'])] public bool $isConsistentContainerNameEnabled = false; #[Validate(['string', 'nullable'])] public ?string $customInternalName = null; #[Validate(['boolean'])] public bool $isGzipEnabled = true; #[Validate(['boolean'])] public bool $isStripprefixEnabled = true; #[Validate(['boolean'])] public bool $isRawComposeDeploymentEnabled = false; #[Validate(['boolean'])] public bool $isConnectToDockerNetworkEnabled = false; public function mount() { try { $this->syncData(); } catch (\Throwable $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->application->settings->is_force_https_enabled = $this->isForceHttpsEnabled; $this->application->settings->is_git_submodules_enabled = $this->isGitSubmodulesEnabled; $this->application->settings->is_git_lfs_enabled = $this->isGitLfsEnabled; $this->application->settings->is_git_shallow_clone_enabled = $this->isGitShallowCloneEnabled; $this->application->settings->is_preview_deployments_enabled = $this->isPreviewDeploymentsEnabled; $this->application->settings->is_pr_deployments_public_enabled = $this->isPrDeploymentsPublicEnabled; $this->application->settings->is_auto_deploy_enabled = $this->isAutoDeployEnabled; $this->application->settings->is_log_drain_enabled = $this->isLogDrainEnabled; $this->application->settings->is_gpu_enabled = $this->isGpuEnabled; $this->application->settings->gpu_driver = $this->gpuDriver; $this->application->settings->gpu_count = $this->gpuCount; $this->application->settings->gpu_device_ids = $this->gpuDeviceIds; $this->application->settings->gpu_options = $this->gpuOptions; $this->application->settings->is_build_server_enabled = $this->isBuildServerEnabled; $this->application->settings->is_consistent_container_name_enabled = $this->isConsistentContainerNameEnabled; $this->application->settings->custom_internal_name = $this->customInternalName; $this->application->settings->is_gzip_enabled = $this->isGzipEnabled; $this->application->settings->is_stripprefix_enabled = $this->isStripprefixEnabled; $this->application->settings->is_raw_compose_deployment_enabled = $this->isRawComposeDeploymentEnabled; $this->application->settings->connect_to_docker_network = $this->isConnectToDockerNetworkEnabled; $this->application->settings->disable_build_cache = $this->disableBuildCache; $this->application->settings->inject_build_args_to_dockerfile = $this->injectBuildArgsToDockerfile; $this->application->settings->include_source_commit_in_build = $this->includeSourceCommitInBuild; $this->application->settings->save(); } else { $this->isForceHttpsEnabled = $this->application->isForceHttpsEnabled(); $this->isGzipEnabled = $this->application->isGzipEnabled(); $this->isStripprefixEnabled = $this->application->isStripprefixEnabled(); $this->isLogDrainEnabled = $this->application->isLogDrainEnabled(); $this->isGitSubmodulesEnabled = $this->application->settings->is_git_submodules_enabled; $this->isGitLfsEnabled = $this->application->settings->is_git_lfs_enabled; $this->isGitShallowCloneEnabled = $this->application->settings->is_git_shallow_clone_enabled ?? false; $this->isPreviewDeploymentsEnabled = $this->application->settings->is_preview_deployments_enabled; $this->isPrDeploymentsPublicEnabled = $this->application->settings->is_pr_deployments_public_enabled ?? false; $this->isAutoDeployEnabled = $this->application->settings->is_auto_deploy_enabled; $this->isGpuEnabled = $this->application->settings->is_gpu_enabled; $this->gpuDriver = $this->application->settings->gpu_driver; $this->gpuCount = $this->application->settings->gpu_count; $this->gpuDeviceIds = $this->application->settings->gpu_device_ids; $this->gpuOptions = $this->application->settings->gpu_options; $this->isBuildServerEnabled = $this->application->settings->is_build_server_enabled; $this->isConsistentContainerNameEnabled = $this->application->settings->is_consistent_container_name_enabled; $this->customInternalName = $this->application->settings->custom_internal_name; $this->isRawComposeDeploymentEnabled = $this->application->settings->is_raw_compose_deployment_enabled; $this->isConnectToDockerNetworkEnabled = $this->application->settings->connect_to_docker_network; $this->disableBuildCache = $this->application->settings->disable_build_cache; $this->injectBuildArgsToDockerfile = $this->application->settings->inject_build_args_to_dockerfile ?? true; $this->includeSourceCommitInBuild = $this->application->settings->include_source_commit_in_build ?? false; } } private function resetDefaultLabels() { if ($this->application->settings->is_container_label_readonly_enabled === false) { return; } $customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); $this->application->custom_labels = base64_encode($customLabels); $this->application->save(); } public function instantSave() { try { $this->authorize('update', $this->application); $reset = false; 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->application->isForceHttpsEnabled() !== $this->isForceHttpsEnabled || $this->application->isGzipEnabled() !== $this->isGzipEnabled || $this->application->isStripprefixEnabled() !== $this->isStripprefixEnabled ) { $reset = true; } if ($this->application->settings->is_raw_compose_deployment_enabled) { $this->application->oldRawParser(); } else { $this->application->parse(); } $this->syncData(true); if ($reset) { $this->resetDefaultLabels(); } $this->dispatch('success', 'Settings saved.'); $this->dispatch('configurationChanged'); } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->application); if ($this->gpuCount && $this->gpuDeviceIds) { $this->dispatch('error', 'You cannot set both GPU count and GPU device IDs.'); $this->gpuCount = null; $this->gpuDeviceIds = null; $this->syncData(true); return; } $this->syncData(true); $this->dispatch('success', 'Settings saved.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function saveCustomName() { try { $this->authorize('update', $this->application); if (str($this->customInternalName)->isNotEmpty()) { $this->customInternalName = str($this->customInternalName)->slug()->value(); } else { $this->customInternalName = null; } if (is_null($this->customInternalName)) { $this->syncData(true); $this->dispatch('success', 'Custom name saved.'); return; } $customInternalName = $this->customInternalName; $server = $this->application->destination->server; $allApplications = $server->applications(); $foundSameInternalName = $allApplications->filter(function ($application) { return $application->id !== $this->application->id && $application->settings->custom_internal_name === $this->customInternalName; }); if ($foundSameInternalName->isNotEmpty()) { $this->dispatch('error', 'This custom container name is already in use by another application on this server.'); $this->customInternalName = $customInternalName; $this->syncData(true); return; } $this->syncData(true); $this->dispatch('success', 'Custom name saved.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.application.advanced'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/DeploymentNavbar.php
app/Livewire/Project/Application/DeploymentNavbar.php
<?php namespace App\Livewire\Project\Application; use App\Enums\ApplicationDeploymentStatus; use App\Models\Application; use App\Models\ApplicationDeploymentQueue; use App\Models\Server; use Illuminate\Support\Carbon; use Livewire\Component; class DeploymentNavbar extends Component { public ApplicationDeploymentQueue $application_deployment_queue; public Application $application; public Server $server; public bool $is_debug_enabled = false; protected $listeners = ['deploymentFinished']; public function mount() { $this->application = Application::ownedByCurrentTeam()->find($this->application_deployment_queue->application_id); $this->server = $this->application->destination->server; $this->is_debug_enabled = $this->application->settings->is_debug_enabled; } public function deploymentFinished() { $this->application_deployment_queue->refresh(); } public function show_debug() { $this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled; $this->application->settings->save(); $this->is_debug_enabled = $this->application->settings->is_debug_enabled; $this->dispatch('refreshQueue'); } public function force_start() { try { force_start_deployment($this->application_deployment_queue); } catch (\Throwable $e) { return handleError($e, $this); } } public function copyLogsToClipboard(): string { $logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR); if (! $logs) { return ''; } $markdown = "# Deployment Logs\n\n"; $markdown .= "```\n"; foreach ($logs as $log) { if (isset($log['output'])) { $markdown .= $log['output']."\n"; } } $markdown .= "```\n"; return $markdown; } public function cancel() { $deployment_uuid = $this->application_deployment_queue->deployment_uuid; $kill_command = "docker rm -f {$deployment_uuid}"; $build_server_id = $this->application_deployment_queue->build_server_id ?? $this->application->destination->server_id; $server_id = $this->application_deployment_queue->server_id ?? $this->application->destination->server_id; // First, mark the deployment as cancelled to prevent further processing $this->application_deployment_queue->update([ 'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value, ]); try { if ($this->application->settings->is_build_server_enabled) { $server = Server::ownedByCurrentTeam()->find($build_server_id); } else { $server = Server::ownedByCurrentTeam()->find($server_id); } // Add cancellation log entry if ($this->application_deployment_queue->logs) { $previous_logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR); $new_log_entry = [ 'command' => $kill_command, 'output' => 'Deployment cancelled by user.', 'type' => 'stderr', 'order' => count($previous_logs) + 1, 'timestamp' => Carbon::now('UTC'), 'hidden' => false, ]; $previous_logs[] = $new_log_entry; $this->application_deployment_queue->update([ 'logs' => json_encode($previous_logs, flags: JSON_THROW_ON_ERROR), ]); } // Try to stop the helper container if it exists // Check if container exists first $checkCommand = "docker ps -a --filter name={$deployment_uuid} --format '{{.Names}}'"; $containerExists = instant_remote_process([$checkCommand], $server); if ($containerExists && str($containerExists)->trim()->isNotEmpty()) { // Container exists, kill it instant_remote_process([$kill_command], $server); } else { // Container hasn't started yet $this->application_deployment_queue->addLogEntry('Helper container not yet started. Deployment will be cancelled when job checks status.'); } // Also try to kill any running process if we have a process ID if ($this->application_deployment_queue->current_process_id) { try { $processKillCommand = "kill -9 {$this->application_deployment_queue->current_process_id}"; instant_remote_process([$processKillCommand], $server); } catch (\Throwable $e) { // Process might already be gone, that's ok } } } catch (\Throwable $e) { // Still mark as cancelled even if cleanup fails return handleError($e, $this); } finally { $this->application_deployment_queue->update([ 'current_process_id' => null, ]); next_after_cancel($server); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/General.php
app/Livewire/Project/Application/General.php
<?php namespace App\Livewire\Project\Application; use App\Actions\Application\GenerateConfig; use App\Models\Application; use App\Support\ValidationPatterns; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Attributes\Validate; use Livewire\Component; use Spatie\Url\Url; use Visus\Cuid2\Cuid2; class General extends Component { use AuthorizesRequests; public string $applicationId; public Application $application; public Collection $services; #[Validate('required|regex:/^[a-zA-Z0-9\s\-_.\/:()]+$/')] public string $name; #[Validate(['string', 'nullable'])] public ?string $description = null; #[Validate(['nullable'])] public ?string $fqdn = null; #[Validate(['required'])] public string $gitRepository; #[Validate(['required'])] public string $gitBranch; #[Validate(['string', 'nullable'])] public ?string $gitCommitSha = null; #[Validate(['string', 'nullable'])] public ?string $installCommand = null; #[Validate(['string', 'nullable'])] public ?string $buildCommand = null; #[Validate(['string', 'nullable'])] public ?string $startCommand = null; #[Validate(['required'])] public string $buildPack; #[Validate(['required'])] public string $staticImage; #[Validate(['required'])] public string $baseDirectory; #[Validate(['string', 'nullable'])] public ?string $publishDirectory = null; #[Validate(['string', 'nullable'])] public ?string $portsExposes = null; #[Validate(['string', 'nullable'])] public ?string $portsMappings = null; #[Validate(['string', 'nullable'])] public ?string $customNetworkAliases = null; #[Validate(['string', 'nullable'])] public ?string $dockerfile = null; #[Validate(['string', 'nullable'])] public ?string $dockerfileLocation = null; #[Validate(['string', 'nullable'])] public ?string $dockerfileTargetBuild = null; #[Validate(['string', 'nullable'])] public ?string $dockerRegistryImageName = null; #[Validate(['string', 'nullable'])] public ?string $dockerRegistryImageTag = null; #[Validate(['string', 'nullable'])] public ?string $dockerComposeLocation = null; #[Validate(['string', 'nullable'])] public ?string $dockerCompose = null; #[Validate(['string', 'nullable'])] public ?string $dockerComposeRaw = null; #[Validate(['string', 'nullable'])] public ?string $dockerComposeCustomStartCommand = null; #[Validate(['string', 'nullable'])] public ?string $dockerComposeCustomBuildCommand = null; #[Validate(['string', 'nullable'])] public ?string $customDockerRunOptions = null; #[Validate(['string', 'nullable'])] public ?string $preDeploymentCommand = null; #[Validate(['string', 'nullable'])] public ?string $preDeploymentCommandContainer = null; #[Validate(['string', 'nullable'])] public ?string $postDeploymentCommand = null; #[Validate(['string', 'nullable'])] public ?string $postDeploymentCommandContainer = null; #[Validate(['string', 'nullable'])] public ?string $customNginxConfiguration = null; #[Validate(['boolean', 'required'])] public bool $isStatic = false; #[Validate(['boolean', 'required'])] public bool $isSpa = false; #[Validate(['boolean', 'required'])] public bool $isBuildServerEnabled = false; #[Validate(['boolean', 'required'])] public bool $isPreserveRepositoryEnabled = false; #[Validate(['boolean', 'required'])] public bool $isContainerLabelEscapeEnabled = true; #[Validate(['boolean', 'required'])] public bool $isContainerLabelReadonlyEnabled = false; #[Validate(['boolean', 'required'])] public bool $isHttpBasicAuthEnabled = false; #[Validate(['string', 'nullable'])] public ?string $httpBasicAuthUsername = null; #[Validate(['string', 'nullable'])] public ?string $httpBasicAuthPassword = null; #[Validate(['nullable'])] public ?string $watchPaths = null; #[Validate(['string', 'required'])] public string $redirect; #[Validate(['nullable'])] public $customLabels; public bool $labelsChanged = false; public bool $initLoadingCompose = false; public ?string $initialDockerComposeLocation = null; public ?Collection $parsedServices; public $parsedServiceDomains = []; public $domainConflicts = []; public $showDomainConflictModal = false; public $forceSaveDomains = false; protected $listeners = [ 'resetDefaultLabels', 'configurationChanged' => '$refresh', 'confirmDomainUsage', ]; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'fqdn' => 'nullable', 'gitRepository' => 'required', 'gitBranch' => 'required', 'gitCommitSha' => 'nullable', 'installCommand' => 'nullable', 'buildCommand' => 'nullable', 'startCommand' => 'nullable', 'buildPack' => 'required', 'staticImage' => 'required', 'baseDirectory' => 'required', 'publishDirectory' => 'nullable', 'portsExposes' => 'required', 'portsMappings' => 'nullable', 'customNetworkAliases' => 'nullable', 'dockerfile' => 'nullable', 'dockerRegistryImageName' => 'nullable', 'dockerRegistryImageTag' => 'nullable', 'dockerfileLocation' => 'nullable', 'dockerComposeLocation' => 'nullable', 'dockerCompose' => 'nullable', 'dockerComposeRaw' => 'nullable', 'dockerfileTargetBuild' => 'nullable', 'dockerComposeCustomStartCommand' => 'nullable', 'dockerComposeCustomBuildCommand' => 'nullable', 'customLabels' => 'nullable', 'customDockerRunOptions' => 'nullable', 'preDeploymentCommand' => 'nullable', 'preDeploymentCommandContainer' => 'nullable', 'postDeploymentCommand' => 'nullable', 'postDeploymentCommandContainer' => 'nullable', 'customNginxConfiguration' => 'nullable', 'isStatic' => 'boolean|required', 'isSpa' => 'boolean|required', 'isBuildServerEnabled' => 'boolean|required', 'isContainerLabelEscapeEnabled' => 'boolean|required', 'isContainerLabelReadonlyEnabled' => 'boolean|required', 'isPreserveRepositoryEnabled' => 'boolean|required', 'isHttpBasicAuthEnabled' => 'boolean|required', 'httpBasicAuthUsername' => 'string|nullable', 'httpBasicAuthPassword' => 'string|nullable', 'watchPaths' => 'nullable', 'redirect' => 'string|required', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'gitRepository.required' => 'The Git Repository field is required.', 'gitBranch.required' => 'The Git Branch field is required.', 'buildPack.required' => 'The Build Pack field is required.', 'staticImage.required' => 'The Static Image field is required.', 'baseDirectory.required' => 'The Base Directory field is required.', 'portsExposes.required' => 'The Exposed Ports field is required.', 'isStatic.required' => 'The Static setting is required.', 'isStatic.boolean' => 'The Static setting must be true or false.', 'isSpa.required' => 'The SPA setting is required.', 'isSpa.boolean' => 'The SPA setting must be true or false.', 'isBuildServerEnabled.required' => 'The Build Server setting is required.', 'isBuildServerEnabled.boolean' => 'The Build Server setting must be true or false.', 'isContainerLabelEscapeEnabled.required' => 'The Container Label Escape setting is required.', 'isContainerLabelEscapeEnabled.boolean' => 'The Container Label Escape setting must be true or false.', 'isContainerLabelReadonlyEnabled.required' => 'The Container Label Readonly setting is required.', 'isContainerLabelReadonlyEnabled.boolean' => 'The Container Label Readonly setting must be true or false.', 'isPreserveRepositoryEnabled.required' => 'The Preserve Repository setting is required.', 'isPreserveRepositoryEnabled.boolean' => 'The Preserve Repository setting must be true or false.', 'isHttpBasicAuthEnabled.required' => 'The HTTP Basic Auth setting is required.', 'isHttpBasicAuthEnabled.boolean' => 'The HTTP Basic Auth setting must be true or false.', 'redirect.required' => 'The Redirect setting is required.', 'redirect.string' => 'The Redirect setting must be a string.', ] ); } protected $validationAttributes = [ 'name' => 'name', 'description' => 'description', 'fqdn' => 'FQDN', 'gitRepository' => 'Git repository', 'gitBranch' => 'Git branch', 'gitCommitSha' => 'Git commit SHA', 'installCommand' => 'Install command', 'buildCommand' => 'Build command', 'startCommand' => 'Start command', 'buildPack' => 'Build pack', 'staticImage' => 'Static image', 'baseDirectory' => 'Base directory', 'publishDirectory' => 'Publish directory', 'portsExposes' => 'Ports exposes', 'portsMappings' => 'Ports mappings', 'dockerfile' => 'Dockerfile', 'dockerRegistryImageName' => 'Docker registry image name', 'dockerRegistryImageTag' => 'Docker registry image tag', 'dockerfileLocation' => 'Dockerfile location', 'dockerComposeLocation' => 'Docker compose location', 'dockerCompose' => 'Docker compose', 'dockerComposeRaw' => 'Docker compose raw', 'customLabels' => 'Custom labels', 'dockerfileTargetBuild' => 'Dockerfile target build', 'customDockerRunOptions' => 'Custom docker run commands', 'customNetworkAliases' => 'Custom docker network aliases', 'dockerComposeCustomStartCommand' => 'Docker compose custom start command', 'dockerComposeCustomBuildCommand' => 'Docker compose custom build command', 'customNginxConfiguration' => 'Custom Nginx configuration', 'isStatic' => 'Is static', 'isSpa' => 'Is SPA', 'isBuildServerEnabled' => 'Is build server enabled', 'isContainerLabelEscapeEnabled' => 'Is container label escape enabled', 'isContainerLabelReadonlyEnabled' => 'Is container label readonly', 'isPreserveRepositoryEnabled' => 'Is preserve repository enabled', 'watchPaths' => 'Watch paths', 'redirect' => 'Redirect', ]; public function mount() { try { $this->parsedServices = $this->application->parse(); if (is_null($this->parsedServices) || empty($this->parsedServices)) { $this->dispatch('error', 'Failed to parse your docker-compose file. Please check the syntax and try again.'); // Still sync data even if parse fails, so form fields are populated $this->syncData(); return; } } catch (\Throwable $e) { $this->dispatch('error', $e->getMessage()); // Still sync data even on error, so form fields are populated $this->syncData(); } if ($this->application->build_pack === 'dockercompose') { // Only update if user has permission try { $this->authorize('update', $this->application); $this->application->fqdn = null; $this->application->settings->save(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User doesn't have update permission, just continue without saving } } $this->parsedServiceDomains = $this->application->docker_compose_domains ? json_decode($this->application->docker_compose_domains, true) : []; // Convert service names with dots and dashes to use underscores for HTML form binding $sanitizedDomains = []; foreach ($this->parsedServiceDomains as $serviceName => $domain) { $sanitizedKey = str($serviceName)->replace('-', '_')->replace('.', '_')->toString(); $sanitizedDomains[$sanitizedKey] = $domain; } $this->parsedServiceDomains = $sanitizedDomains; $this->customLabels = $this->application->parseContainerLabels(); if (! $this->customLabels && $this->application->destination->server->proxyType() !== 'NONE' && $this->application->settings->is_container_label_readonly_enabled === true) { // Only update custom labels if user has permission try { $this->authorize('update', $this->application); $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); $this->application->custom_labels = base64_encode($this->customLabels); $this->application->save(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User doesn't have update permission, just use existing labels // $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); } } $this->initialDockerComposeLocation = $this->application->docker_compose_location; if ($this->application->build_pack === 'dockercompose' && ! $this->application->docker_compose_raw) { // Only load compose file if user has update permission try { $this->authorize('update', $this->application); $this->initLoadingCompose = true; $this->dispatch('info', 'Loading docker compose file.'); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User doesn't have update permission, skip loading compose file } } if (str($this->application->status)->startsWith('running') && is_null($this->application->config_hash)) { $this->dispatch('configurationChanged'); } // Sync data from model to properties at the END, after all business logic // This ensures any modifications to $this->application during mount() are reflected in properties $this->syncData(); } public function syncData(bool $toModel = false): void { if ($toModel) { $this->validate(); // Application properties $this->application->name = $this->name; $this->application->description = $this->description; $this->application->fqdn = $this->fqdn; $this->application->git_repository = $this->gitRepository; $this->application->git_branch = $this->gitBranch; $this->application->git_commit_sha = $this->gitCommitSha; $this->application->install_command = $this->installCommand; $this->application->build_command = $this->buildCommand; $this->application->start_command = $this->startCommand; $this->application->build_pack = $this->buildPack; $this->application->static_image = $this->staticImage; $this->application->base_directory = $this->baseDirectory; $this->application->publish_directory = $this->publishDirectory; $this->application->ports_exposes = $this->portsExposes; $this->application->ports_mappings = $this->portsMappings; $this->application->custom_network_aliases = $this->customNetworkAliases; $this->application->dockerfile = $this->dockerfile; $this->application->dockerfile_location = $this->dockerfileLocation; $this->application->dockerfile_target_build = $this->dockerfileTargetBuild; $this->application->docker_registry_image_name = $this->dockerRegistryImageName; $this->application->docker_registry_image_tag = $this->dockerRegistryImageTag; $this->application->docker_compose_location = $this->dockerComposeLocation; $this->application->docker_compose = $this->dockerCompose; $this->application->docker_compose_raw = $this->dockerComposeRaw; $this->application->docker_compose_custom_start_command = $this->dockerComposeCustomStartCommand; $this->application->docker_compose_custom_build_command = $this->dockerComposeCustomBuildCommand; $this->application->custom_labels = is_null($this->customLabels) ? null : base64_encode($this->customLabels); $this->application->custom_docker_run_options = $this->customDockerRunOptions; $this->application->pre_deployment_command = $this->preDeploymentCommand; $this->application->pre_deployment_command_container = $this->preDeploymentCommandContainer; $this->application->post_deployment_command = $this->postDeploymentCommand; $this->application->post_deployment_command_container = $this->postDeploymentCommandContainer; $this->application->custom_nginx_configuration = $this->customNginxConfiguration; $this->application->is_http_basic_auth_enabled = $this->isHttpBasicAuthEnabled; $this->application->http_basic_auth_username = $this->httpBasicAuthUsername; $this->application->http_basic_auth_password = $this->httpBasicAuthPassword; $this->application->watch_paths = $this->watchPaths; $this->application->redirect = $this->redirect; // Application settings properties $this->application->settings->is_static = $this->isStatic; $this->application->settings->is_spa = $this->isSpa; $this->application->settings->is_build_server_enabled = $this->isBuildServerEnabled; $this->application->settings->is_preserve_repository_enabled = $this->isPreserveRepositoryEnabled; $this->application->settings->is_container_label_escape_enabled = $this->isContainerLabelEscapeEnabled; $this->application->settings->is_container_label_readonly_enabled = $this->isContainerLabelReadonlyEnabled; $this->application->settings->save(); } else { // From model to properties $this->name = $this->application->name; $this->description = $this->application->description; $this->fqdn = $this->application->fqdn; $this->gitRepository = $this->application->git_repository; $this->gitBranch = $this->application->git_branch; $this->gitCommitSha = $this->application->git_commit_sha; $this->installCommand = $this->application->install_command; $this->buildCommand = $this->application->build_command; $this->startCommand = $this->application->start_command; $this->buildPack = $this->application->build_pack; $this->staticImage = $this->application->static_image; $this->baseDirectory = $this->application->base_directory; $this->publishDirectory = $this->application->publish_directory; $this->portsExposes = $this->application->ports_exposes; $this->portsMappings = $this->application->ports_mappings; $this->customNetworkAliases = $this->application->custom_network_aliases; $this->dockerfile = $this->application->dockerfile; $this->dockerfileLocation = $this->application->dockerfile_location; $this->dockerfileTargetBuild = $this->application->dockerfile_target_build; $this->dockerRegistryImageName = $this->application->docker_registry_image_name; $this->dockerRegistryImageTag = $this->application->docker_registry_image_tag; $this->dockerComposeLocation = $this->application->docker_compose_location; $this->dockerCompose = $this->application->docker_compose; $this->dockerComposeRaw = $this->application->docker_compose_raw; $this->dockerComposeCustomStartCommand = $this->application->docker_compose_custom_start_command; $this->dockerComposeCustomBuildCommand = $this->application->docker_compose_custom_build_command; $this->customLabels = $this->application->parseContainerLabels(); $this->customDockerRunOptions = $this->application->custom_docker_run_options; $this->preDeploymentCommand = $this->application->pre_deployment_command; $this->preDeploymentCommandContainer = $this->application->pre_deployment_command_container; $this->postDeploymentCommand = $this->application->post_deployment_command; $this->postDeploymentCommandContainer = $this->application->post_deployment_command_container; $this->customNginxConfiguration = $this->application->custom_nginx_configuration; $this->isHttpBasicAuthEnabled = $this->application->is_http_basic_auth_enabled; $this->httpBasicAuthUsername = $this->application->http_basic_auth_username; $this->httpBasicAuthPassword = $this->application->http_basic_auth_password; $this->watchPaths = $this->application->watch_paths; $this->redirect = $this->application->redirect; // Application settings properties $this->isStatic = $this->application->settings->is_static; $this->isSpa = $this->application->settings->is_spa; $this->isBuildServerEnabled = $this->application->settings->is_build_server_enabled; $this->isPreserveRepositoryEnabled = $this->application->settings->is_preserve_repository_enabled; $this->isContainerLabelEscapeEnabled = $this->application->settings->is_container_label_escape_enabled; $this->isContainerLabelReadonlyEnabled = $this->application->settings->is_container_label_readonly_enabled; } } public function instantSave() { try { $this->authorize('update', $this->application); $oldPortsExposes = $this->application->ports_exposes; $oldIsContainerLabelEscapeEnabled = $this->application->settings->is_container_label_escape_enabled; $oldIsPreserveRepositoryEnabled = $this->application->settings->is_preserve_repository_enabled; $oldIsSpa = $this->application->settings->is_spa; $oldIsHttpBasicAuthEnabled = $this->application->is_http_basic_auth_enabled; $this->syncData(toModel: true); if ($oldIsSpa !== $this->isSpa) { $this->generateNginxConfiguration($this->isSpa ? 'spa' : 'static'); } if ($oldIsHttpBasicAuthEnabled !== $this->isHttpBasicAuthEnabled) { $this->application->save(); } $this->dispatch('success', 'Settings saved.'); $this->application->refresh(); $this->syncData(); // If port_exposes changed, reset default labels if ($oldPortsExposes !== $this->portsExposes || $oldIsContainerLabelEscapeEnabled !== $this->isContainerLabelEscapeEnabled) { $this->resetDefaultLabels(false); } if ($oldIsPreserveRepositoryEnabled !== $this->isPreserveRepositoryEnabled) { if ($this->isPreserveRepositoryEnabled === false) { $this->application->fileStorages->each(function ($storage) { $storage->is_based_on_git = $this->isPreserveRepositoryEnabled; $storage->save(); }); } } if ($this->isContainerLabelReadonlyEnabled) { $this->resetDefaultLabels(false); } } catch (\Throwable $e) { return handleError($e, $this); } } public function loadComposeFile($isInit = false, $showToast = true, ?string $restoreBaseDirectory = null, ?string $restoreDockerComposeLocation = null) { try { $this->authorize('update', $this->application); if ($isInit && $this->application->docker_compose_raw) { return; } ['parsedServices' => $this->parsedServices, 'initialDockerComposeLocation' => $this->initialDockerComposeLocation] = $this->application->loadComposeFile($isInit, $restoreBaseDirectory, $restoreDockerComposeLocation); if (is_null($this->parsedServices)) { $showToast && $this->dispatch('error', 'Failed to parse your docker-compose file. Please check the syntax and try again.'); return; } // Refresh parsedServiceDomains to reflect any changes in docker_compose_domains $this->application->refresh(); // Sync the docker_compose_raw from the model to the component property // This ensures the Monaco editor displays the loaded compose file $this->syncData(); $this->parsedServiceDomains = $this->application->docker_compose_domains ? json_decode($this->application->docker_compose_domains, true) : []; // Convert service names with dots and dashes to use underscores for HTML form binding $sanitizedDomains = []; foreach ($this->parsedServiceDomains as $serviceName => $domain) { $sanitizedKey = str($serviceName)->replace('-', '_')->replace('.', '_')->toString(); $sanitizedDomains[$sanitizedKey] = $domain; } $this->parsedServiceDomains = $sanitizedDomains; $showToast && $this->dispatch('success', 'Docker compose file loaded.'); $this->dispatch('compose_loaded'); $this->dispatch('refreshStorages'); $this->dispatch('refreshEnvs'); } catch (\Throwable $e) { // Refresh model to get restored values from Application::loadComposeFile $this->application->refresh(); // Sync restored values back to component properties for UI update $this->syncData(); return handleError($e, $this); } finally { $this->initLoadingCompose = false; } } public function generateDomain(string $serviceName) { try { $this->authorize('update', $this->application); $uuid = new Cuid2; $domain = generateUrl(server: $this->application->destination->server, random: $uuid); $sanitizedKey = str($serviceName)->replace('-', '_')->replace('.', '_')->toString(); $this->parsedServiceDomains[$sanitizedKey]['domain'] = $domain; // Convert back to original service names for storage $originalDomains = []; foreach ($this->parsedServiceDomains as $key => $value) { // Find the original service name by checking parsed services $originalServiceName = $key; if (isset($this->parsedServices['services'])) { foreach ($this->parsedServices['services'] as $originalName => $service) { if (str($originalName)->replace('-', '_')->replace('.', '_')->toString() === $key) { $originalServiceName = $originalName; break; } } } $originalDomains[$originalServiceName] = $value; } $this->application->docker_compose_domains = json_encode($originalDomains); $this->application->save(); $this->dispatch('success', 'Domain generated.'); if ($this->application->build_pack === 'dockercompose') { $this->loadComposeFile(showToast: false); } return $domain; } catch (\Throwable $e) { return handleError($e, $this); } } public function updatedIsStatic($value) { if ($value) { $this->generateNginxConfiguration(); } } public function updatedBuildPack() { // Check if user has permission to update try { $this->authorize('update', $this->application); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User doesn't have permission, revert the change and return $this->application->refresh(); $this->syncData(); return; } // Sync property to model before checking/modifying $this->syncData(toModel: true); if ($this->buildPack !== 'nixpacks') { $this->isStatic = false; $this->application->settings->is_static = false; $this->application->settings->save(); } else { $this->resetDefaultLabels(false); } if ($this->buildPack === 'dockercompose') { // Only update if user has permission try { $this->authorize('update', $this->application); $this->fqdn = null; $this->application->fqdn = null; $this->application->settings->save(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User doesn't have update permission, just continue without saving } } if ($this->buildPack === 'static') { $this->portsExposes = '80'; $this->application->ports_exposes = '80'; $this->resetDefaultLabels(false); $this->generateNginxConfiguration(); } $this->submit(); $this->dispatch('buildPackUpdated'); } public function getWildcardDomain() { try { $this->authorize('update', $this->application); $server = data_get($this->application, 'destination.server'); if ($server) { $fqdn = generateUrl(server: $server, random: $this->application->uuid); $this->fqdn = $fqdn; $this->syncData(toModel: true); $this->application->save(); $this->application->refresh(); $this->syncData(); $this->resetDefaultLabels(); $this->dispatch('success', 'Wildcard domain generated.'); } } catch (\Throwable $e) { return handleError($e, $this); } } public function generateNginxConfiguration($type = 'static') { try { $this->authorize('update', $this->application); $this->customNginxConfiguration = defaultNginxConfiguration($type); $this->syncData(toModel: true); $this->application->save(); $this->application->refresh(); $this->syncData(); $this->dispatch('success', 'Nginx configuration generated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function resetDefaultLabels($manualReset = false) { try { if (! $this->isContainerLabelReadonlyEnabled && ! $manualReset) { return; } $this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n"); $this->application->custom_labels = base64_encode($this->customLabels); $this->application->save(); $this->application->refresh(); $this->syncData(); if ($this->buildPack === 'dockercompose') { $this->loadComposeFile(showToast: false); } $this->dispatch('configurationChanged');
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
true
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Rollback.php
app/Livewire/Project/Application/Rollback.php
<?php namespace App\Livewire\Project\Application; use App\Models\Application; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; use Visus\Cuid2\Cuid2; class Rollback extends Component { use AuthorizesRequests; public Application $application; public $images = []; public ?string $current; public array $parameters; #[Validate(['integer', 'min:0', 'max:100'])] public int $dockerImagesToKeep = 2; public bool $serverRetentionDisabled = false; public function mount() { $this->parameters = get_route_parameters(); $this->dockerImagesToKeep = $this->application->settings->docker_images_to_keep ?? 2; $server = $this->application->destination->server; $this->serverRetentionDisabled = $server->settings->disable_application_image_retention ?? false; } public function saveSettings() { try { $this->authorize('update', $this->application); $this->validate(); $this->application->settings->docker_images_to_keep = $this->dockerImagesToKeep; $this->application->settings->save(); $this->dispatch('success', 'Settings saved.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function rollbackImage($commit) { $this->authorize('deploy', $this->application); $deployment_uuid = new Cuid2; $result = queue_application_deployment( application: $this->application, deployment_uuid: $deployment_uuid, commit: $commit, rollback: true, force_rebuild: false, ); if ($result['status'] === 'queue_full') { $this->dispatch('error', 'Deployment queue full', $result['message']); return; } return redirectRoute($this, 'project.application.deployment.show', [ 'project_uuid' => $this->parameters['project_uuid'], 'application_uuid' => $this->parameters['application_uuid'], 'deployment_uuid' => $deployment_uuid, 'environment_uuid' => $this->parameters['environment_uuid'], ]); } public function loadImages($showToast = false) { $this->authorize('view', $this->application); try { $image = $this->application->docker_registry_image_name ?? $this->application->uuid; if ($this->application->destination->server->isFunctional()) { $output = instant_remote_process([ "docker inspect --format='{{.Config.Image}}' {$this->application->uuid}", ], $this->application->destination->server, throwError: false); $current_tag = str($output)->trim()->explode(':'); $this->current = data_get($current_tag, 1); $output = instant_remote_process([ "docker images --format '{{.Repository}}#{{.Tag}}#{{.CreatedAt}}'", ], $this->application->destination->server); $this->images = str($output)->trim()->explode("\n")->filter(function ($item) use ($image) { return str($item)->contains($image); })->map(function ($item) { $item = str($item)->explode('#'); $is_current = $item[1] === $this->current; return [ 'tag' => $item[1], 'created_at' => $item[2], 'is_current' => $is_current, ]; })->toArray(); } $showToast && $this->dispatch('success', 'Images loaded.'); return []; } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Configuration.php
app/Livewire/Project/Application/Configuration.php
<?php namespace App\Livewire\Project\Application; use App\Models\Application; use Livewire\Component; class Configuration extends Component { public $currentRoute; public Application $application; public $project; public $environment; public $servers; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => '$refresh', "echo-private:team.{$teamId},ServiceStatusChanged" => '$refresh', 'buildPackUpdated' => '$refresh', 'refresh' => '$refresh', ]; } public function mount() { $this->currentRoute = request()->route()->getName(); $project = currentTeam() ->projects() ->select('id', 'uuid', 'team_id') ->where('uuid', request()->route('project_uuid')) ->firstOrFail(); $environment = $project->environments() ->select('id', 'uuid', 'name', 'project_id') ->where('uuid', request()->route('environment_uuid')) ->firstOrFail(); $application = $environment->applications() ->with(['destination']) ->where('uuid', request()->route('application_uuid')) ->firstOrFail(); $this->project = $project; $this->environment = $environment; $this->application = $application; if ($this->application->deploymentType() === 'deploy_key' && $this->currentRoute === 'project.application.preview-deployments') { return redirect()->route('project.application.configuration', ['project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, 'application_uuid' => $application->uuid]); } if ($this->application->build_pack === 'dockercompose' && $this->currentRoute === 'project.application.healthcheck') { return redirect()->route('project.application.configuration', ['project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, 'application_uuid' => $application->uuid]); } } public function render() { return view('livewire.project.application.configuration'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Source.php
app/Livewire/Project/Application/Source.php
<?php namespace App\Livewire\Project\Application; use App\Models\Application; use App\Models\PrivateKey; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class Source extends Component { use AuthorizesRequests; public Application $application; #[Locked] public $privateKeys; #[Validate(['nullable', 'string'])] public ?string $privateKeyName = null; #[Validate(['nullable', 'integer'])] public ?int $privateKeyId = null; #[Validate(['required', 'string'])] public string $gitRepository; #[Validate(['required', 'string'])] public string $gitBranch; #[Validate(['nullable', 'string'])] public ?string $gitCommitSha = null; #[Locked] public $sources; public function mount() { try { $this->syncData(); $this->getPrivateKeys(); $this->getSources(); } catch (\Throwable $e) { handleError($e, $this); } } public function updatedGitRepository() { $this->gitRepository = trim($this->gitRepository); } public function updatedGitBranch() { $this->gitBranch = trim($this->gitBranch); } public function updatedGitCommitSha() { $this->gitCommitSha = trim($this->gitCommitSha); } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->application->update([ 'git_repository' => $this->gitRepository, 'git_branch' => $this->gitBranch, 'git_commit_sha' => $this->gitCommitSha, 'private_key_id' => $this->privateKeyId, ]); // Refresh to get the trimmed values from the model $this->application->refresh(); $this->syncData(false); } else { $this->gitRepository = $this->application->git_repository; $this->gitBranch = $this->application->git_branch; $this->gitCommitSha = $this->application->git_commit_sha; $this->privateKeyId = $this->application->private_key_id; $this->privateKeyName = data_get($this->application, 'private_key.name'); } } private function getPrivateKeys() { $this->privateKeys = PrivateKey::whereTeamId(currentTeam()->id)->get()->reject(function ($key) { return $key->id == $this->privateKeyId; }); } private function getSources() { // filter the current source out $this->sources = currentTeam()->sources()->whereNotNull('app_id')->reject(function ($source) { return $source->id === $this->application->source_id; })->sortBy('name'); } public function setPrivateKey(int $privateKeyId) { try { $this->authorize('update', $this->application); $this->privateKeyId = $privateKeyId; $this->syncData(true); $this->getPrivateKeys(); $this->application->refresh(); $this->privateKeyName = $this->application->private_key->name; $this->dispatch('success', 'Private key updated!'); } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->application); if (str($this->gitCommitSha)->isEmpty()) { $this->gitCommitSha = 'HEAD'; } $this->syncData(true); $this->dispatch('success', 'Application source updated!'); } catch (\Throwable $e) { return handleError($e, $this); } } public function changeSource($sourceId, $sourceType) { try { $this->authorize('update', $this->application); $this->application->update([ 'source_id' => $sourceId, 'source_type' => $sourceType, ]); ['repository' => $customRepository] = $this->application->customRepository(); $repository = githubApi($this->application->source, "repos/{$customRepository}"); $data = data_get($repository, 'data'); $repository_project_id = data_get($data, 'id'); if (isset($repository_project_id)) { if ($this->application->repository_project_id !== $repository_project_id) { $this->application->repository_project_id = $repository_project_id; $this->application->save(); } } $this->application->refresh(); $this->getSources(); $this->dispatch('success', 'Source updated!'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Previews.php
app/Livewire/Project/Application/Previews.php
<?php namespace App\Livewire\Project\Application; use App\Actions\Docker\GetContainersStatus; use App\Jobs\DeleteResourceJob; use App\Models\Application; use App\Models\ApplicationPreview; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Component; use Visus\Cuid2\Cuid2; class Previews extends Component { use AuthorizesRequests; public Application $application; public string $deployment_uuid; public array $parameters; public Collection $pull_requests; public int $rate_limit_remaining; public $domainConflicts = []; public $showDomainConflictModal = false; public $forceSaveDomains = false; public $pendingPreviewId = null; public array $previewFqdns = []; protected $rules = [ 'previewFqdns.*' => 'string|nullable', ]; public function mount() { $this->pull_requests = collect(); $this->parameters = get_route_parameters(); $this->syncData(false); } private function syncData(bool $toModel = false): void { if ($toModel) { foreach ($this->previewFqdns as $key => $fqdn) { $preview = $this->application->previews->get($key); if ($preview) { $preview->fqdn = $fqdn; } } } else { $this->previewFqdns = []; foreach ($this->application->previews as $key => $preview) { $this->previewFqdns[$key] = $preview->fqdn; } } } public function load_prs() { try { $this->authorize('update', $this->application); ['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) { $this->rate_limit_remaining = 0; return handleError($e, $this); } } public function confirmDomainUsage() { $this->forceSaveDomains = true; $this->showDomainConflictModal = false; if ($this->pendingPreviewId) { $this->save_preview($this->pendingPreviewId); $this->pendingPreviewId = null; } } public function save_preview($preview_id) { try { $this->authorize('update', $this->application); $success = true; $preview = $this->application->previews->find($preview_id); if (! $preview) { throw new \Exception('Preview not found'); } // Find the key for this preview in the collection $previewKey = $this->application->previews->search(function ($item) use ($preview_id) { return $item->id == $preview_id; }); if ($previewKey !== false && isset($this->previewFqdns[$previewKey])) { $fqdn = $this->previewFqdns[$previewKey]; if (! empty($fqdn)) { $fqdn = str($fqdn)->replaceEnd(',', '')->trim(); $fqdn = str($fqdn)->replaceStart(',', '')->trim(); $fqdn = str($fqdn)->trim()->lower(); $this->previewFqdns[$previewKey] = $fqdn; if (! validateDNSEntry($fqdn, $this->application->destination->server)) { $this->dispatch('error', 'Validating DNS failed.', "Make sure you have added the DNS records correctly.<br><br>$fqdn->{$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."); $success = false; } // Check for domain conflicts if not forcing save if (! $this->forceSaveDomains) { $result = checkDomainUsage(resource: $this->application, domain: $fqdn); if ($result['hasConflicts']) { $this->domainConflicts = $result['conflicts']; $this->showDomainConflictModal = true; $this->pendingPreviewId = $preview_id; return; } } else { // Reset the force flag after using it $this->forceSaveDomains = false; } } } if ($success) { $this->syncData(true); $preview->save(); $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); } } public function generate_preview($preview_id) { try { $this->authorize('update', $this->application); $preview = $this->application->previews->find($preview_id); if (! $preview) { $this->dispatch('error', 'Preview not found.'); return; } if ($this->application->build_pack === 'dockercompose') { $preview->generate_preview_fqdn_compose(); $this->application->refresh(); $this->syncData(false); $this->dispatch('success', 'Domain generated.'); return; } $preview->generate_preview_fqdn(); $this->application->refresh(); $this->syncData(false); $this->dispatch('update_links'); $this->dispatch('success', 'Domain generated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function add(int $pull_request_id, ?string $pull_request_html_url = null) { try { $this->authorize('update', $this->application); if ($this->application->build_pack === 'dockercompose') { $this->setDeploymentUuid(); $found = ApplicationPreview::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([ 'application_id' => $this->application->id, 'pull_request_id' => $pull_request_id, 'pull_request_html_url' => $pull_request_html_url, 'docker_compose_domains' => $this->application->docker_compose_domains, ]); } $found->generate_preview_fqdn_compose(); $this->application->refresh(); $this->syncData(false); } else { $this->setDeploymentUuid(); $found = ApplicationPreview::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([ 'application_id' => $this->application->id, 'pull_request_id' => $pull_request_id, 'pull_request_html_url' => $pull_request_html_url, ]); } $found->generate_preview_fqdn(); $this->application->refresh(); $this->syncData(false); $this->dispatch('update_links'); $this->dispatch('success', 'Preview added.'); } } catch (\Throwable $e) { return handleError($e, $this); } } public function force_deploy_without_cache(int $pull_request_id, ?string $pull_request_html_url = null) { $this->authorize('deploy', $this->application); $this->deploy($pull_request_id, $pull_request_html_url, force_rebuild: true); } public function add_and_deploy(int $pull_request_id, ?string $pull_request_html_url = null) { $this->authorize('deploy', $this->application); $this->add($pull_request_id, $pull_request_html_url); $this->deploy($pull_request_id, $pull_request_html_url); } public function deploy(int $pull_request_id, ?string $pull_request_html_url = null, bool $force_rebuild = false) { $this->authorize('deploy', $this->application); try { $this->setDeploymentUuid(); $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first(); if (! $found && ! is_null($pull_request_html_url)) { ApplicationPreview::create([ 'application_id' => $this->application->id, 'pull_request_id' => $pull_request_id, 'pull_request_html_url' => $pull_request_html_url, ]); } $result = queue_application_deployment( application: $this->application, deployment_uuid: $this->deployment_uuid, force_rebuild: $force_rebuild, pull_request_id: $pull_request_id, git_type: $found->git_type ?? null, ); if ($result['status'] === 'queue_full') { $this->dispatch('error', 'Deployment queue full', $result['message']); return; } if ($result['status'] === 'skipped') { $this->dispatch('success', 'Deployment skipped', $result['message']); return; } return redirect()->route('project.application.deployment.show', [ 'project_uuid' => $this->parameters['project_uuid'], 'application_uuid' => $this->parameters['application_uuid'], 'deployment_uuid' => $this->deployment_uuid, 'environment_uuid' => $this->parameters['environment_uuid'], ]); } catch (\Throwable $e) { return handleError($e, $this); } } protected function setDeploymentUuid() { $this->deployment_uuid = new Cuid2; $this->parameters['deployment_uuid'] = $this->deployment_uuid; } private function stopContainers(array $containers, $server) { $containersToStop = collect($containers)->pluck('Names')->toArray(); foreach ($containersToStop as $containerName) { instant_remote_process(command: [ "docker stop -t 30 $containerName", "docker rm -f $containerName", ], server: $server, throwError: false); } } public function stop(int $pull_request_id) { $this->authorize('deploy', $this->application); try { $server = $this->application->destination->server; if ($this->application->destination->server->isSwarm()) { instant_remote_process(["docker stack rm {$this->application->uuid}-{$pull_request_id}"], $server); } else { $containers = getCurrentApplicationContainerStatus($server, $this->application->id, $pull_request_id)->toArray(); $this->stopContainers($containers, $server); } GetContainersStatus::run($server); $this->application->refresh(); $this->dispatch('containerStatusUpdated'); $this->dispatch('success', 'Preview Deployment stopped.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function delete(int $pull_request_id) { try { $this->authorize('delete', $this->application); $preview = ApplicationPreview::where('application_id', $this->application->id) ->where('pull_request_id', $pull_request_id) ->first(); if (! $preview) { $this->dispatch('error', 'Preview not found.'); return; } // Soft delete immediately for instant UI feedback $preview->delete(); // Dispatch the job for async cleanup (container stopping + force delete) DeleteResourceJob::dispatch($preview); // Refresh the application and its previews relationship to reflect the soft delete $this->application->load('previews'); $this->dispatch('update_links'); $this->dispatch('success', 'Preview deletion started. It may take a few moments to complete.'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/PreviewsCompose.php
app/Livewire/Project/Application/PreviewsCompose.php
<?php namespace App\Livewire\Project\Application; use App\Models\ApplicationPreview; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; use Spatie\Url\Url; use Visus\Cuid2\Cuid2; class PreviewsCompose extends Component { use AuthorizesRequests; public $service; public $serviceName; public ApplicationPreview $preview; public ?string $domain = null; public function mount() { $this->domain = data_get($this->service, 'domain'); } public function render() { return view('livewire.project.application.previews-compose'); } public function save() { try { $this->authorize('update', $this->preview->application); $docker_compose_domains = data_get($this->preview, 'docker_compose_domains'); $docker_compose_domains = json_decode($docker_compose_domains, true) ?: []; $docker_compose_domains[$this->serviceName] = $docker_compose_domains[$this->serviceName] ?? []; $docker_compose_domains[$this->serviceName]['domain'] = $this->domain; $this->preview->docker_compose_domains = json_encode($docker_compose_domains); $this->preview->save(); $this->dispatch('update_links'); $this->dispatch('success', 'Domain saved.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function generate() { try { $this->authorize('update', $this->preview->application); $domains = collect(json_decode($this->preview->application->docker_compose_domains, true) ?: []); $domain = $domains->first(function ($_, $key) { return $key === $this->serviceName; }); $domain_string = data_get($domain, 'domain'); // If no domain is set in the main application, generate a default domain if (empty($domain_string)) { $server = $this->preview->application->destination->server; $template = $this->preview->application->preview_url_template; $random = new Cuid2; // Generate a unique domain like main app services do $generated_fqdn = generateUrl(server: $server, random: $random); $preview_fqdn = str_replace('{{random}}', $random, $template); $preview_fqdn = str_replace('{{domain}}', str($generated_fqdn)->after('://'), $preview_fqdn); $preview_fqdn = str_replace('{{pr_id}}', $this->preview->pull_request_id, $preview_fqdn); $preview_fqdn = str($generated_fqdn)->before('://').'://'.$preview_fqdn; } else { // Use the existing domain from the main application // Handle multiple domains separated by commas $domain_list = explode(',', $domain_string); $preview_fqdns = []; $template = $this->preview->application->preview_url_template; $random = new Cuid2; foreach ($domain_list as $single_domain) { $single_domain = trim($single_domain); if (empty($single_domain)) { continue; } $url = Url::fromString($single_domain); $host = $url->getHost(); $schema = $url->getScheme(); $portInt = $url->getPort(); $port = $portInt !== null ? ':'.$portInt : ''; $preview_fqdn = str_replace('{{random}}', $random, $template); $preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn); $preview_fqdn = str_replace('{{pr_id}}', $this->preview->pull_request_id, $preview_fqdn); $preview_fqdns[] = "$schema://$preview_fqdn{$port}"; } $preview_fqdn = implode(',', $preview_fqdns); } // Save the generated domain $this->domain = $preview_fqdn; $docker_compose_domains = data_get($this->preview, 'docker_compose_domains'); $docker_compose_domains = json_decode($docker_compose_domains, true) ?: []; $docker_compose_domains[$this->serviceName] = $docker_compose_domains[$this->serviceName] ?? []; $docker_compose_domains[$this->serviceName]['domain'] = $this->domain; $this->preview->docker_compose_domains = json_encode($docker_compose_domains); $this->preview->save(); $this->dispatch('update_links'); $this->dispatch('success', 'Domain generated.'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Deployment/Show.php
app/Livewire/Project/Application/Deployment/Show.php
<?php namespace App\Livewire\Project\Application\Deployment; use App\Models\Application; use App\Models\ApplicationDeploymentQueue; use Livewire\Component; class Show extends Component { public Application $application; public ApplicationDeploymentQueue $application_deployment_queue; public string $deployment_uuid; public string $horizon_job_status; public $isKeepAliveOn = true; public bool $is_debug_enabled = false; public bool $fullscreen = false; private bool $deploymentFinishedDispatched = false; public function getListeners() { return [ 'refreshQueue', ]; } public function mount() { $deploymentUuid = request()->route('deployment_uuid'); $project = currentTeam()->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first(); if (! $project) { return redirect()->route('dashboard'); } $environment = $project->load(['environments'])->environments->where('uuid', request()->route('environment_uuid'))->first()->load(['applications']); if (! $environment) { return redirect()->route('dashboard'); } $application = $environment->applications->where('uuid', request()->route('application_uuid'))->first(); if (! $application) { return redirect()->route('dashboard'); } $application_deployment_queue = ApplicationDeploymentQueue::where('deployment_uuid', $deploymentUuid)->first(); if (! $application_deployment_queue) { return redirect()->route('project.application.deployment.index', [ 'project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, 'application_uuid' => $application->uuid, ]); } $this->application = $application; $this->application_deployment_queue = $application_deployment_queue; $this->horizon_job_status = $this->application_deployment_queue->getHorizonJobStatus(); $this->deployment_uuid = $deploymentUuid; $this->is_debug_enabled = $this->application->settings->is_debug_enabled; $this->isKeepAliveOn(); } public function toggleDebug() { try { $this->authorize('update', $this->application); $this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled; $this->application->settings->save(); $this->is_debug_enabled = $this->application->settings->is_debug_enabled; $this->application_deployment_queue->refresh(); } catch (\Throwable $e) { return handleError($e, $this); } } public function refreshQueue() { $this->application_deployment_queue->refresh(); } private function isKeepAliveOn() { if (data_get($this->application_deployment_queue, 'status') === 'finished' || data_get($this->application_deployment_queue, 'status') === 'failed') { $this->isKeepAliveOn = false; } else { $this->isKeepAliveOn = true; } } public function polling() { $this->application_deployment_queue->refresh(); $this->horizon_job_status = $this->application_deployment_queue->getHorizonJobStatus(); $this->isKeepAliveOn(); // Dispatch event when deployment finishes to stop auto-scroll (only once) if (! $this->isKeepAliveOn && ! $this->deploymentFinishedDispatched) { $this->deploymentFinishedDispatched = true; $this->dispatch('deploymentFinished'); } } public function getLogLinesProperty() { return decode_remote_command_output($this->application_deployment_queue); } public function copyLogs(): string { $logs = decode_remote_command_output($this->application_deployment_queue) ->map(function ($line) { return $line['timestamp'].' '. (isset($line['command']) && $line['command'] ? '[CMD]: ' : ''). trim($line['line']); }) ->join("\n"); return sanitizeLogsForExport($logs); } public function render() { return view('livewire.project.application.deployment.show'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Deployment/Index.php
app/Livewire/Project/Application/Deployment/Index.php
<?php namespace App\Livewire\Project\Application\Deployment; use App\Models\Application; use Illuminate\Support\Collection; use Livewire\Component; class Index extends Component { public Application $application; public ?Collection $deployments; public int $deployments_count = 0; public string $current_url; public int $skip = 0; public int $defaultTake = 10; public bool $showNext = false; public bool $showPrev = false; public int $currentPage = 1; public ?string $pull_request_id = null; protected $queryString = ['pull_request_id']; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => '$refresh', ]; } public function mount() { $project = currentTeam()->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first(); if (! $project) { return redirect()->route('dashboard'); } $environment = $project->load(['environments'])->environments->where('uuid', request()->route('environment_uuid'))->first()->load(['applications']); if (! $environment) { return redirect()->route('dashboard'); } $application = $environment->applications->where('uuid', request()->route('application_uuid'))->first(); if (! $application) { return redirect()->route('dashboard'); } // Validate pull request ID from URL parameters if ($this->pull_request_id !== null && $this->pull_request_id !== '') { if (! is_numeric($this->pull_request_id) || (float) $this->pull_request_id <= 0 || (float) $this->pull_request_id != (int) $this->pull_request_id) { $this->pull_request_id = null; $this->dispatch('error', 'Invalid Pull Request ID in URL. Filter cleared.'); } else { // Ensure it's stored as a string representation of a positive integer $this->pull_request_id = (string) (int) $this->pull_request_id; } } ['deployments' => $deployments, 'count' => $count] = $application->deployments(0, $this->defaultTake, $this->pull_request_id); $this->application = $application; $this->deployments = $deployments; $this->deployments_count = $count; $this->current_url = url()->current(); $this->updateCurrentPage(); $this->showMore(); } private function showMore() { if ($this->deployments->count() !== 0) { $this->showNext = true; if ($this->deployments->count() < $this->defaultTake) { $this->showNext = false; } return; } } public function reloadDeployments() { $this->loadDeployments(); } public function previousPage(?int $take = null) { if ($take) { $this->skip = $this->skip - $take; } $this->skip = $this->skip - $this->defaultTake; if ($this->skip < 0) { $this->showPrev = false; $this->skip = 0; } $this->updateCurrentPage(); $this->loadDeployments(); } public function nextPage(?int $take = null) { if ($take) { $this->skip = $this->skip + $take; } $this->showPrev = true; $this->updateCurrentPage(); $this->loadDeployments(); } public function loadDeployments() { ['deployments' => $deployments, 'count' => $count] = $this->application->deployments($this->skip, $this->defaultTake, $this->pull_request_id); $this->deployments = $deployments; $this->deployments_count = $count; $this->showMore(); } public function updatedPullRequestId($value) { // Sanitize and validate the pull request ID if ($value !== null && $value !== '') { // Check if it's numeric and positive if (! is_numeric($value) || (float) $value <= 0 || (float) $value != (int) $value) { $this->pull_request_id = null; $this->dispatch('error', 'Invalid Pull Request ID. Please enter a valid positive number.'); return; } // Ensure it's stored as a string representation of a positive integer $this->pull_request_id = (string) (int) $value; } else { $this->pull_request_id = null; } // Reset pagination when filter changes $this->skip = 0; $this->showPrev = false; $this->updateCurrentPage(); $this->loadDeployments(); } public function clearFilter() { $this->pull_request_id = null; $this->skip = 0; $this->showPrev = false; $this->updateCurrentPage(); $this->loadDeployments(); } private function updateCurrentPage() { $this->currentPage = intval($this->skip / $this->defaultTake) + 1; } public function render() { return view('livewire.project.application.deployment.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Application/Preview/Form.php
app/Livewire/Project/Application/Preview/Form.php
<?php namespace App\Livewire\Project\Application\Preview; use App\Models\Application; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; use Spatie\Url\Url; class Form extends Component { use AuthorizesRequests; public Application $application; #[Validate('required')] public string $previewUrlTemplate; public function mount() { try { $this->previewUrlTemplate = $this->application->preview_url_template; $this->generateRealUrl(); } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->application); $this->resetErrorBag(); $this->validate(); $this->application->preview_url_template = str_replace(' ', '', $this->previewUrlTemplate); $this->application->save(); $this->dispatch('success', 'Preview url template updated.'); $this->generateRealUrl(); } catch (\Throwable $e) { return handleError($e, $this); } } public function resetToDefault() { try { $this->authorize('update', $this->application); $this->application->preview_url_template = '{{pr_id}}.{{domain}}'; $this->previewUrlTemplate = $this->application->preview_url_template; $this->application->save(); $this->generateRealUrl(); $this->dispatch('success', 'Preview url template updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function generateRealUrl() { if (data_get($this->application, 'fqdn')) { $firstFqdn = str($this->application->fqdn)->before(','); $url = Url::fromString($firstFqdn); $host = $url->getHost(); $this->previewUrlTemplate = str($this->application->preview_url_template)->replace('{{domain}}', $host); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Resource/Create.php
app/Livewire/Project/Resource/Create.php
<?php namespace App\Livewire\Project\Resource; use App\Models\EnvironmentVariable; use App\Models\Service; use App\Models\StandaloneDocker; use Livewire\Component; class Create extends Component { public $type; public $project; public function mount() { $type = str(request()->query('type')); $destination_uuid = request()->query('destination'); $server_id = request()->query('server_id'); $database_image = request()->query('database_image'); $project = currentTeam()->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first(); if (! $project) { return redirect()->route('dashboard'); } $this->project = $project; $environment = $project->load(['environments'])->environments->where('uuid', request()->route('environment_uuid'))->first(); if (! $environment) { return redirect()->route('dashboard'); } if (isset($type) && isset($destination_uuid) && isset($server_id)) { $services = get_service_templates(); if (in_array($type, DATABASE_TYPES)) { if ($type->value() === 'postgresql') { // PostgreSQL requires database_image to be explicitly set // If not provided, fall through to Select component for version selection if (! $database_image) { $this->type = $type->value(); return; } $database = create_standalone_postgresql( environmentId: $environment->id, destinationUuid: $destination_uuid, databaseImage: $database_image ); } elseif ($type->value() === 'redis') { $database = create_standalone_redis($environment->id, $destination_uuid); } elseif ($type->value() === 'mongodb') { $database = create_standalone_mongodb($environment->id, $destination_uuid); } elseif ($type->value() === 'mysql') { $database = create_standalone_mysql($environment->id, $destination_uuid); } elseif ($type->value() === 'mariadb') { $database = create_standalone_mariadb($environment->id, $destination_uuid); } elseif ($type->value() === 'keydb') { $database = create_standalone_keydb($environment->id, $destination_uuid); } elseif ($type->value() === 'dragonfly') { $database = create_standalone_dragonfly($environment->id, $destination_uuid); } elseif ($type->value() === 'clickhouse') { $database = create_standalone_clickhouse($environment->id, $destination_uuid); } return redirect()->route('project.database.configuration', [ 'project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, 'database_uuid' => $database->uuid, ]); } if ($type->startsWith('one-click-service-') && ! is_null((int) $server_id)) { $oneClickServiceName = $type->after('one-click-service-')->value(); $oneClickService = data_get($services, "$oneClickServiceName.compose"); $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); }); } if ($oneClickService) { $destination = StandaloneDocker::whereUuid($destination_uuid)->first(); $service_payload = [ 'docker_compose_raw' => base64_decode($oneClickService), 'environment_id' => $environment->id, 'service_type' => $oneClickServiceName, 'server_id' => (int) $server_id, 'destination_id' => $destination->id, 'destination_type' => $destination->getMorphClass(), ]; if (in_array($oneClickServiceName, NEEDS_TO_CONNECT_TO_PREDEFINED_NETWORK)) { data_set($service_payload, 'connect_to_docker_network', true); } $service = Service::create($service_payload); $service->name = "$oneClickServiceName-".$service->uuid; $service->save(); if ($oneClickDotEnvs?->count() > 0) { $oneClickDotEnvs->each(function ($value) use ($service) { $key = str()->before($value, '='); $value = str(str()->after($value, '=')); if ($value) { EnvironmentVariable::create([ 'key' => $key, 'value' => $value, 'resourceable_id' => $service->id, 'resourceable_type' => $service->getMorphClass(), 'is_preview' => false, ]); } }); } $service->parse(isNew: true); // Apply service-specific application prerequisites applyServiceApplicationPrerequisites($service); return redirect()->route('project.service.configuration', [ 'service_uuid' => $service->uuid, 'environment_uuid' => $environment->uuid, 'project_uuid' => $project->uuid, ]); } } $this->type = $type->value(); } } public function render() { return view('livewire.project.resource.create'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Resource/Index.php
app/Livewire/Project/Resource/Index.php
<?php namespace App\Livewire\Project\Resource; use App\Models\Environment; use App\Models\Project; use Illuminate\Support\Collection; use Livewire\Component; class Index extends Component { public Project $project; public Environment $environment; public Collection $applications; public Collection $postgresqls; public Collection $redis; public Collection $mongodbs; public Collection $mysqls; public Collection $mariadbs; public Collection $keydbs; public Collection $dragonflies; public Collection $clickhouses; public Collection $services; public array $parameters; public function mount() { $this->applications = $this->postgresqls = $this->redis = $this->mongodbs = $this->mysqls = $this->mariadbs = $this->keydbs = $this->dragonflies = $this->clickhouses = $this->services = collect(); $this->parameters = get_route_parameters(); $project = currentTeam() ->projects() ->select('id', 'uuid', 'team_id', 'name') ->where('uuid', request()->route('project_uuid')) ->firstOrFail(); $environment = $project->environments() ->select('id', 'uuid', 'name', 'project_id') ->where('uuid', request()->route('environment_uuid')) ->firstOrFail(); $this->project = $project; $this->environment = $environment->loadCount([ 'applications', 'redis', 'postgresqls', 'mysqls', 'keydbs', 'dragonflies', 'clickhouses', 'mariadbs', 'mongodbs', 'services', ]); // Eager load all relationships for applications including nested ones $this->applications = $this->environment->applications()->with([ 'tags', 'additional_servers.settings', 'additional_networks', 'destination.server.settings', 'settings', ])->get()->sortBy('name'); $this->applications = $this->applications->map(function ($application) { $application->hrefLink = route('project.application.configuration', [ 'project_uuid' => data_get($application, 'environment.project.uuid'), 'environment_uuid' => data_get($application, 'environment.uuid'), 'application_uuid' => data_get($application, 'uuid'), ]); return $application; }); // Load all database resources in a single query per type $databaseTypes = [ 'postgresqls' => 'postgresqls', 'redis' => 'redis', 'mongodbs' => 'mongodbs', 'mysqls' => 'mysqls', 'mariadbs' => 'mariadbs', 'keydbs' => 'keydbs', 'dragonflies' => 'dragonflies', 'clickhouses' => 'clickhouses', ]; foreach ($databaseTypes as $property => $relation) { $this->{$property} = $this->environment->{$relation}()->with([ 'tags', 'destination.server.settings', ])->get()->sortBy('name'); $this->{$property} = $this->{$property}->map(function ($db) { $db->hrefLink = route('project.database.configuration', [ 'project_uuid' => $this->project->uuid, 'database_uuid' => $db->uuid, 'environment_uuid' => data_get($this->environment, 'uuid'), ]); return $db; }); } // Load services with their tags and server $this->services = $this->environment->services()->with([ 'tags', 'destination.server.settings', ])->get()->sortBy('name'); $this->services = $this->services->map(function ($service) { $service->hrefLink = route('project.service.configuration', [ 'project_uuid' => data_get($service, 'environment.project.uuid'), 'environment_uuid' => data_get($service, 'environment.uuid'), 'service_uuid' => data_get($service, 'uuid'), ]); return $service; }); } public function render() { return view('livewire.project.resource.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/BackupExecutions.php
app/Livewire/Project/Database/BackupExecutions.php
<?php namespace App\Livewire\Project\Database; use App\Models\ScheduledDatabaseBackup; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Livewire\Component; class BackupExecutions extends Component { public ?ScheduledDatabaseBackup $backup = null; public $database; public ?Collection $executions; public int $executions_count = 0; public int $skip = 0; public int $defaultTake = 10; public bool $showNext = false; public bool $showPrev = false; public int $currentPage = 1; public $setDeletableBackup; public $delete_backup_s3 = false; public $delete_backup_sftp = false; public function getListeners() { $userId = Auth::id(); return [ "echo-private:team.{$userId},BackupCreated" => 'refreshBackupExecutions', ]; } public function cleanupFailed() { if ($this->backup) { $this->backup->executions()->where('status', 'failed')->delete(); $this->refreshBackupExecutions(); $this->dispatch('success', 'Failed backups cleaned up.'); } } public function cleanupDeleted() { if ($this->backup) { $deletedCount = $this->backup->executions()->where('local_storage_deleted', true)->count(); if ($deletedCount > 0) { $this->backup->executions()->where('local_storage_deleted', true)->delete(); $this->refreshBackupExecutions(); $this->dispatch('success', "Cleaned up {$deletedCount} backup entries deleted from local storage."); } else { $this->dispatch('info', 'No backup entries found that are deleted from local storage.'); } } } public function deleteBackup($executionId, $password) { if (! verifyPasswordConfirmation($password, $this)) { return; } $execution = $this->backup->executions()->where('id', $executionId)->first(); if (is_null($execution)) { $this->dispatch('error', 'Backup execution not found.'); return; } $server = $execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class ? $execution->scheduledDatabaseBackup->database->service->destination->server : $execution->scheduledDatabaseBackup->database->destination->server; try { if ($execution->filename) { deleteBackupsLocally($execution->filename, $server); if ($this->delete_backup_s3 && $execution->scheduledDatabaseBackup->s3) { deleteBackupsS3($execution->filename, $execution->scheduledDatabaseBackup->s3); } } $execution->delete(); $this->dispatch('success', 'Backup deleted.'); $this->refreshBackupExecutions(); } catch (\Exception $e) { $this->dispatch('error', 'Failed to delete backup: '.$e->getMessage()); } } public function download_file($exeuctionId) { return redirect()->route('download.backup', $exeuctionId); } public function refreshBackupExecutions(): void { $this->loadExecutions(); } public function reloadExecutions() { $this->loadExecutions(); } public function previousPage(?int $take = null) { if ($take) { $this->skip = $this->skip - $take; } $this->skip = $this->skip - $this->defaultTake; if ($this->skip < 0) { $this->showPrev = false; $this->skip = 0; } $this->updateCurrentPage(); $this->loadExecutions(); } public function nextPage(?int $take = null) { if ($take) { $this->skip = $this->skip + $take; } $this->showPrev = true; $this->updateCurrentPage(); $this->loadExecutions(); } private function loadExecutions() { if ($this->backup && $this->backup->exists) { ['executions' => $executions, 'count' => $count] = $this->backup->executionsPaginated($this->skip, $this->defaultTake); $this->executions = $executions; $this->executions_count = $count; } else { $this->executions = collect([]); $this->executions_count = 0; } $this->showMore(); } private function showMore() { if ($this->executions->count() !== 0) { $this->showNext = true; if ($this->executions->count() < $this->defaultTake) { $this->showNext = false; } return; } } private function updateCurrentPage() { $this->currentPage = intval($this->skip / $this->defaultTake) + 1; } public function mount(ScheduledDatabaseBackup $backup) { $this->backup = $backup; $this->database = $backup->database; $this->updateCurrentPage(); $this->loadExecutions(); } public function server() { if ($this->database) { $server = null; if ($this->database instanceof \App\Models\ServiceDatabase) { $server = $this->database->service->destination->server; } elseif ($this->database->destination && $this->database->destination->server) { $server = $this->database->destination->server; } if ($server) { return $server; } } return null; } public function render() { return view('livewire.project.database.backup-executions'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/BackupEdit.php
app/Livewire/Project/Database/BackupEdit.php
<?php namespace App\Livewire\Project\Database; use App\Models\ScheduledDatabaseBackup; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; use Spatie\Url\Url; class BackupEdit extends Component { use AuthorizesRequests; public ScheduledDatabaseBackup $backup; #[Locked] public $s3s; #[Locked] public $parameters; #[Validate(['required', 'boolean'])] public bool $delete_associated_backups_locally = false; #[Validate(['required', 'boolean'])] public bool $delete_associated_backups_s3 = false; #[Validate(['required', 'boolean'])] public bool $delete_associated_backups_sftp = false; #[Validate(['nullable', 'string'])] public ?string $status = null; #[Validate(['required', 'boolean'])] public bool $backupEnabled = false; #[Validate(['required', 'string'])] public string $frequency = ''; #[Validate(['string'])] public string $timezone = ''; #[Validate(['required', 'integer'])] public int $databaseBackupRetentionAmountLocally = 0; #[Validate(['required', 'integer'])] public ?int $databaseBackupRetentionDaysLocally = 0; #[Validate(['required', 'numeric', 'min:0'])] public ?float $databaseBackupRetentionMaxStorageLocally = 0; #[Validate(['required', 'integer'])] public ?int $databaseBackupRetentionAmountS3 = 0; #[Validate(['required', 'integer'])] public ?int $databaseBackupRetentionDaysS3 = 0; #[Validate(['required', 'numeric', 'min:0'])] public ?float $databaseBackupRetentionMaxStorageS3 = 0; #[Validate(['required', 'boolean'])] public bool $saveS3 = false; #[Validate(['required', 'boolean'])] public bool $disableLocalBackup = false; #[Validate(['nullable', 'integer'])] public ?int $s3StorageId = 1; #[Validate(['nullable', 'string'])] public ?string $databasesToBackup = null; #[Validate(['required', 'boolean'])] public bool $dumpAll = false; #[Validate(['required', 'int', 'min:60', 'max:36000'])] public int $timeout = 3600; public function mount() { try { $this->authorize('view', $this->backup->database); $this->parameters = get_route_parameters(); $this->syncData(); } catch (Exception $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->backup->enabled = $this->backupEnabled; $this->backup->frequency = $this->frequency; $this->backup->database_backup_retention_amount_locally = $this->databaseBackupRetentionAmountLocally; $this->backup->database_backup_retention_days_locally = $this->databaseBackupRetentionDaysLocally; $this->backup->database_backup_retention_max_storage_locally = $this->databaseBackupRetentionMaxStorageLocally; $this->backup->database_backup_retention_amount_s3 = $this->databaseBackupRetentionAmountS3; $this->backup->database_backup_retention_days_s3 = $this->databaseBackupRetentionDaysS3; $this->backup->database_backup_retention_max_storage_s3 = $this->databaseBackupRetentionMaxStorageS3; $this->backup->save_s3 = $this->saveS3; $this->backup->disable_local_backup = $this->disableLocalBackup; $this->backup->s3_storage_id = $this->s3StorageId; // Validate databases_to_backup to prevent command injection if (filled($this->databasesToBackup)) { $databases = str($this->databasesToBackup)->explode(','); foreach ($databases as $index => $db) { $dbName = trim($db); try { validateShellSafePath($dbName, 'database name'); } catch (\Exception $e) { // Provide specific error message indicating which database failed validation $position = $index + 1; throw new \Exception( "Database #{$position} ('{$dbName}') validation failed: ". $e->getMessage() ); } } } $this->backup->databases_to_backup = $this->databasesToBackup; $this->backup->dump_all = $this->dumpAll; $this->backup->timeout = $this->timeout; $this->customValidate(); $this->backup->save(); } else { $this->backupEnabled = $this->backup->enabled; $this->frequency = $this->backup->frequency; $this->timezone = data_get($this->backup->server(), 'settings.server_timezone', 'Instance timezone'); $this->databaseBackupRetentionAmountLocally = $this->backup->database_backup_retention_amount_locally; $this->databaseBackupRetentionDaysLocally = $this->backup->database_backup_retention_days_locally; $this->databaseBackupRetentionMaxStorageLocally = $this->backup->database_backup_retention_max_storage_locally; $this->databaseBackupRetentionAmountS3 = $this->backup->database_backup_retention_amount_s3; $this->databaseBackupRetentionDaysS3 = $this->backup->database_backup_retention_days_s3; $this->databaseBackupRetentionMaxStorageS3 = $this->backup->database_backup_retention_max_storage_s3; $this->saveS3 = $this->backup->save_s3; $this->disableLocalBackup = $this->backup->disable_local_backup ?? false; $this->s3StorageId = $this->backup->s3_storage_id; $this->databasesToBackup = $this->backup->databases_to_backup; $this->dumpAll = $this->backup->dump_all; $this->timeout = $this->backup->timeout; } } public function delete($password) { $this->authorize('manageBackups', $this->backup->database); if (! verifyPasswordConfirmation($password, $this)) { return; } try { $server = null; if ($this->backup->database instanceof \App\Models\ServiceDatabase) { $server = $this->backup->database->service->destination->server; } elseif ($this->backup->database->destination && $this->backup->database->destination->server) { $server = $this->backup->database->destination->server; } $filenames = $this->backup->executions() ->whereNotNull('filename') ->where('filename', '!=', '') ->where('scheduled_database_backup_id', $this->backup->id) ->pluck('filename') ->filter() ->all(); if (! empty($filenames)) { if ($this->delete_associated_backups_locally && $server) { deleteBackupsLocally($filenames, $server); } if ($this->delete_associated_backups_s3 && $this->backup->s3) { deleteBackupsS3($filenames, $this->backup->s3); } } $this->backup->delete(); if ($this->backup->database->getMorphClass() === \App\Models\ServiceDatabase::class) { $previousUrl = url()->previous(); $url = Url::fromString($previousUrl); $url = $url->withoutQueryParameter('selectedBackupId'); $url = $url->withFragment('backups'); $url = $url->getPath()."#{$url->getFragment()}"; return redirect($url); } else { return redirect()->route('project.database.backup.index', $this->parameters); } } catch (\Exception $e) { $this->dispatch('error', 'Failed to delete backup: '.$e->getMessage()); return handleError($e, $this); } } public function instantSave() { try { $this->authorize('manageBackups', $this->backup->database); $this->syncData(true); $this->dispatch('success', 'Backup updated successfully.'); } catch (\Throwable $e) { $this->dispatch('error', $e->getMessage()); } } private function customValidate() { if (! is_numeric($this->backup->s3_storage_id)) { $this->backup->s3_storage_id = null; } // Validate that disable_local_backup can only be true when S3 backup is enabled if ($this->backup->disable_local_backup && ! $this->backup->save_s3) { $this->backup->disable_local_backup = $this->disableLocalBackup = false; } $isValid = validate_cron_expression($this->backup->frequency); if (! $isValid) { throw new \Exception('Invalid Cron / Human expression'); } $this->validate(); } public function submit() { try { $this->authorize('manageBackups', $this->backup->database); $this->syncData(true); $this->dispatch('success', 'Backup updated successfully.'); } catch (\Throwable $e) { $this->dispatch('error', $e->getMessage()); } } public function render() { return view('livewire.project.database.backup-edit', [ 'checkboxes' => [ ['id' => 'delete_associated_backups_locally', 'label' => __('database.delete_backups_locally')], ['id' => 'delete_associated_backups_s3', 'label' => 'All backups will be permanently deleted (associated with this backup job) from the selected S3 Storage.'], // ['id' => 'delete_associated_backups_sftp', 'label' => 'All backups associated with this backup job from this database will be permanently deleted from the selected SFTP Storage.'] ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Heading.php
app/Livewire/Project/Database/Heading.php
<?php namespace App\Livewire\Project\Database; use App\Actions\Database\RestartDatabase; use App\Actions\Database\StartDatabase; use App\Actions\Database\StopDatabase; use App\Actions\Docker\GetContainersStatus; use App\Events\ServiceStatusChanged; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Heading extends Component { use AuthorizesRequests; public $database; public array $parameters; public $docker_cleanup = true; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceStatusChanged" => 'checkStatus', "echo-private:team.{$teamId},ServiceChecked" => 'activityFinished', 'refresh' => '$refresh', 'compose_loaded' => '$refresh', 'update_links' => '$refresh', ]; } public function activityFinished() { try { // Only set started_at if database is actually running if ($this->database->isRunning()) { $this->database->started_at ??= now(); } $this->database->save(); if (is_null($this->database->config_hash) || $this->database->isConfigurationChanged()) { $this->database->isConfigurationChanged(true); } $this->dispatch('configurationChanged'); } catch (\Exception $e) { return handleError($e, $this); } finally { $this->dispatch('refresh'); } } public function checkStatus() { if ($this->database->destination->server->isFunctional()) { GetContainersStatus::dispatch($this->database->destination->server); } else { $this->dispatch('error', 'Server is not functional.'); } } public function manualCheckStatus() { $this->checkStatus(); } public function mount() { $this->parameters = get_route_parameters(); } public function stop() { try { $this->authorize('manage', $this->database); $this->dispatch('info', 'Gracefully stopping database.'); StopDatabase::dispatch($this->database, false, $this->docker_cleanup); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function restart() { $this->authorize('manage', $this->database); $activity = RestartDatabase::run($this->database); $this->dispatch('activityMonitor', $activity->id, ServiceStatusChanged::class); } public function start() { $this->authorize('manage', $this->database); $activity = StartDatabase::run($this->database); $this->dispatch('activityMonitor', $activity->id, ServiceStatusChanged::class); } public function render() { return view('livewire.project.database.heading', [ 'checkboxes' => [ ['id' => 'docker_cleanup', 'label' => __('resource.docker_cleanup')], ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/ScheduledBackups.php
app/Livewire/Project/Database/ScheduledBackups.php
<?php namespace App\Livewire\Project\Database; use App\Models\ScheduledDatabaseBackup; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class ScheduledBackups extends Component { use AuthorizesRequests; public $database; public $parameters; public $type; public ?ScheduledDatabaseBackup $selectedBackup; public $selectedBackupId; public $s3s; public string $custom_type = 'mysql'; protected $listeners = ['refreshScheduledBackups']; protected $queryString = ['selectedBackupId']; public function mount(): void { if ($this->selectedBackupId) { $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->s3s = currentTeam()->s3s; } public function setSelectedBackup($backupId, $force = false) { if ($this->selectedBackupId === $backupId && ! $force) { return; } $this->selectedBackupId = $backupId; $this->selectedBackup = $this->database->scheduledBackups->find($backupId); if (is_null($this->selectedBackup)) { $this->selectedBackupId = null; } } public function setCustomType() { $this->authorize('update', $this->database); $this->database->custom_type = $this->custom_type; $this->database->save(); $this->dispatch('success', 'Database type set.'); $this->refreshScheduledBackups(); } public function delete($scheduled_backup_id): void { $backup = $this->database->scheduledBackups->find($scheduled_backup_id); $this->authorize('manageBackups', $this->database); $backup->delete(); $this->dispatch('success', 'Scheduled backup deleted.'); $this->refreshScheduledBackups(); } public function refreshScheduledBackups(?int $id = null): void { $this->database->refresh(); if ($id) { $this->setSelectedBackup($id); } $this->dispatch('refreshScheduledBackups'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/InitScript.php
app/Livewire/Project/Database/InitScript.php
<?php namespace App\Livewire\Project\Database; use Exception; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class InitScript extends Component { #[Locked] public array $script; #[Locked] public int $index; #[Validate(['nullable', 'string'])] public ?string $filename = null; #[Validate(['nullable', 'string'])] public ?string $content = null; public function mount() { try { $this->index = data_get($this->script, 'index'); $this->filename = data_get($this->script, 'filename'); $this->content = data_get($this->script, 'content'); } catch (Exception $e) { return handleError($e, $this); } } public function submit() { try { $this->validate(); $this->script['index'] = $this->index; $this->script['content'] = $this->content; $this->script['filename'] = $this->filename; $this->dispatch('save_init_script', $this->script); } catch (Exception $e) { return handleError($e, $this); } } public function delete() { try { $this->dispatch('delete_init_script', $this->script); } catch (Exception $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/CreateScheduledBackup.php
app/Livewire/Project/Database/CreateScheduledBackup.php
<?php namespace App\Livewire\Project\Database; use App\Models\ScheduledDatabaseBackup; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class CreateScheduledBackup extends Component { use AuthorizesRequests; #[Validate(['required', 'string'])] public $frequency; #[Validate(['required', 'boolean'])] public bool $saveToS3 = false; #[Locked] public $database; public bool $enabled = true; #[Validate(['nullable', 'integer'])] public ?int $s3StorageId = null; public Collection $definedS3s; public function mount() { try { $this->definedS3s = currentTeam()->s3s; if ($this->definedS3s->count() > 0) { $this->s3StorageId = $this->definedS3s->first()->id; } } catch (\Throwable $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('manageBackups', $this->database); $this->validate(); $isValid = validate_cron_expression($this->frequency); if (! $isValid) { $this->dispatch('error', 'Invalid Cron / Human expression.'); return; } $payload = [ 'enabled' => true, 'frequency' => $this->frequency, 'save_s3' => $this->saveToS3, 's3_storage_id' => $this->s3StorageId, 'database_id' => $this->database->id, 'database_type' => $this->database->getMorphClass(), 'team_id' => currentTeam()->id, ]; if ($this->database->type() === 'standalone-postgresql') { $payload['databases_to_backup'] = $this->database->postgres_db; } elseif ($this->database->type() === 'standalone-mysql') { $payload['databases_to_backup'] = $this->database->mysql_database; } elseif ($this->database->type() === 'standalone-mariadb') { $payload['databases_to_backup'] = $this->database->mariadb_database; } $databaseBackup = ScheduledDatabaseBackup::create($payload); if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) { $this->dispatch('refreshScheduledBackups', $databaseBackup->id); } else { $this->dispatch('refreshScheduledBackups'); } } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->frequency = ''; } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Configuration.php
app/Livewire/Project/Database/Configuration.php
<?php namespace App\Livewire\Project\Database; use Auth; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Configuration extends Component { use AuthorizesRequests; public $currentRoute; public $database; public $project; public $environment; public function getListeners() { $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => '$refresh', ]; } public function mount() { try { $this->currentRoute = request()->route()->getName(); $project = currentTeam() ->projects() ->select('id', 'uuid', 'team_id') ->where('uuid', request()->route('project_uuid')) ->firstOrFail(); $environment = $project->environments() ->select('id', 'name', 'project_id', 'uuid') ->where('uuid', request()->route('environment_uuid')) ->firstOrFail(); $database = $environment->databases() ->where('uuid', request()->route('database_uuid')) ->firstOrFail(); $this->authorize('view', $database); $this->database = $database; $this->project = $project; $this->environment = $environment; if (str($this->database->status)->startsWith('running') && is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); $this->dispatch('configurationChanged'); } } catch (\Throwable $e) { if ($e instanceof \Illuminate\Auth\Access\AuthorizationException) { return redirect()->route('dashboard'); } if ($e instanceof \Illuminate\Support\ItemNotFoundException) { return redirect()->route('dashboard'); } return handleError($e, $this); } } public function render() { return view('livewire.project.database.configuration'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/BackupNow.php
app/Livewire/Project/Database/BackupNow.php
<?php namespace App\Livewire\Project\Database; use App\Jobs\DatabaseBackupJob; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class BackupNow extends Component { use AuthorizesRequests; public $backup; public function backupNow() { $this->authorize('manageBackups', $this->backup->database); DatabaseBackupJob::dispatch($this->backup); $this->dispatch('success', 'Backup queued. It will be available in a few minutes.'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Import.php
app/Livewire/Project/Database/Import.php
<?php namespace App\Livewire\Project\Database; use App\Models\S3Storage; use App\Models\Server; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Livewire\Component; class Import extends Component { use AuthorizesRequests; /** * Validate that a string is safe for use as an S3 bucket name. * Allows alphanumerics, dots, dashes, and underscores. */ private function validateBucketName(string $bucket): bool { return preg_match('/^[a-zA-Z0-9.\-_]+$/', $bucket) === 1; } /** * Validate that a string is safe for use as an S3 path. * Allows alphanumerics, dots, dashes, underscores, slashes, and common file characters. */ private function validateS3Path(string $path): bool { // Must not be empty if (empty($path)) { return false; } // Must not contain dangerous shell metacharacters or command injection patterns $dangerousPatterns = [ '..', // Directory traversal '$(', // Command substitution '`', // Backtick command substitution '|', // Pipe ';', // Command separator '&', // Background/AND '>', // Redirect '<', // Redirect "\n", // Newline "\r", // Carriage return "\0", // Null byte "'", // Single quote '"', // Double quote '\\', // Backslash ]; foreach ($dangerousPatterns as $pattern) { if (str_contains($path, $pattern)) { return false; } } // Allow alphanumerics, dots, dashes, underscores, slashes, spaces, plus, equals, at return preg_match('/^[a-zA-Z0-9.\-_\/\s+@=]+$/', $path) === 1; } /** * Validate that a string is safe for use as a file path on the server. */ private function validateServerPath(string $path): bool { // Must be an absolute path if (! str_starts_with($path, '/')) { return false; } // Must not contain dangerous shell metacharacters or command injection patterns $dangerousPatterns = [ '..', // Directory traversal '$(', // Command substitution '`', // Backtick command substitution '|', // Pipe ';', // Command separator '&', // Background/AND '>', // Redirect '<', // Redirect "\n", // Newline "\r", // Carriage return "\0", // Null byte "'", // Single quote '"', // Double quote '\\', // Backslash ]; foreach ($dangerousPatterns as $pattern) { if (str_contains($path, $pattern)) { return false; } } // Allow alphanumerics, dots, dashes, underscores, slashes, and spaces return preg_match('/^[a-zA-Z0-9.\-_\/\s]+$/', $path) === 1; } public bool $unsupported = false; public $resource; public $parameters; public $containers; public bool $scpInProgress = false; public bool $importRunning = false; public ?string $filename = null; public ?string $filesize = null; public bool $isUploading = false; public int $progress = 0; public bool $error = false; public Server $server; public string $container; public array $importCommands = []; public bool $dumpAll = false; public string $restoreCommandText = ''; public string $customLocation = ''; public ?int $activityId = null; public string $postgresqlRestoreCommand = 'pg_restore -U $POSTGRES_USER -d $POSTGRES_DB'; public string $mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE'; public string $mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE'; public string $mongodbRestoreCommand = 'mongorestore --authenticationDatabase=admin --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --uri mongodb://localhost:27017 --gzip --archive='; // S3 Restore properties public $availableS3Storages = []; public ?int $s3StorageId = null; public string $s3Path = ''; public ?int $s3FileSize = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', 'slideOverClosed' => 'resetActivityId', ]; } public function resetActivityId() { $this->activityId = null; } public function mount() { $this->parameters = get_route_parameters(); $this->getContainers(); $this->loadAvailableS3Storages(); } public function updatedDumpAll($value) { switch ($this->resource->getMorphClass()) { case \App\Models\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 mariadb -u root -p$MARIADB_ROOT_PASSWORD -e "KILL $pid" 2>/dev/null || true done && \ mariadb -u root -p$MARIADB_ROOT_PASSWORD -N -e "SELECT CONCAT('DROP DATABASE IF EXISTS \`',schema_name,'\`;') FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys');" | mariadb -u root -p$MARIADB_ROOT_PASSWORD && \ mariadb -u root -p$MARIADB_ROOT_PASSWORD -e "CREATE DATABASE IF NOT EXISTS \`default\`;" && \ (gunzip -cf $tmpPath 2>/dev/null || cat $tmpPath) | sed -e '/^CREATE DATABASE/d' -e '/^USE \`mysql\`/d' | mariadb -u root -p$MARIADB_ROOT_PASSWORD default EOD; $this->restoreCommandText = $this->mariadbRestoreCommand.' && (gunzip -cf <temp_backup_file> 2>/dev/null || cat <temp_backup_file>) | mariadb -u root -p$MARIADB_ROOT_PASSWORD default'; } else { $this->mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE'; } break; case \App\Models\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 mysql -u root -p$MYSQL_ROOT_PASSWORD -e "KILL $pid" 2>/dev/null || true done && \ mysql -u root -p$MYSQL_ROOT_PASSWORD -N -e "SELECT CONCAT('DROP DATABASE IF EXISTS \`',schema_name,'\`;') FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys');" | mysql -u root -p$MYSQL_ROOT_PASSWORD && \ mysql -u root -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE IF NOT EXISTS \`default\`;" && \ (gunzip -cf $tmpPath 2>/dev/null || cat $tmpPath) | sed -e '/^CREATE DATABASE/d' -e '/^USE \`mysql\`/d' | mysql -u root -p$MYSQL_ROOT_PASSWORD default EOD; $this->restoreCommandText = $this->mysqlRestoreCommand.' && (gunzip -cf <temp_backup_file> 2>/dev/null || cat <temp_backup_file>) | mysql -u root -p$MYSQL_ROOT_PASSWORD default'; } else { $this->mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE'; } break; case \App\Models\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()" && \ psql -U $POSTGRES_USER -t -c "SELECT datname FROM pg_database WHERE NOT datistemplate" | xargs -I {} dropdb -U $POSTGRES_USER --if-exists {} && \ createdb -U $POSTGRES_USER postgres EOD; $this->restoreCommandText = $this->postgresqlRestoreCommand.' && (gunzip -cf <temp_backup_file> 2>/dev/null || cat <temp_backup_file>) | psql -U $POSTGRES_USER postgres'; } else { $this->postgresqlRestoreCommand = 'pg_restore -U $POSTGRES_USER -d $POSTGRES_DB'; } break; } } public function getContainers() { $this->containers = collect(); if (! data_get($this->parameters, 'database_uuid')) { abort(404); } $resource = getResourceByUuid($this->parameters['database_uuid'], data_get(auth()->user()->currentTeam(), 'id')); if (is_null($resource)) { abort(404); } $this->authorize('view', $resource); $this->resource = $resource; $this->server = $this->resource->destination->server; $this->container = $this->resource->uuid; if (str(data_get($this, 'resource.status'))->startsWith('running')) { $this->containers->push($this->container); } 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->unsupported = true; } } public function checkFile() { if (filled($this->customLocation)) { // Validate the custom location to prevent command injection if (! $this->validateServerPath($this->customLocation)) { $this->dispatch('error', 'Invalid file path. Path must be absolute and contain only safe characters (alphanumerics, dots, dashes, underscores, slashes).'); return; } try { $escapedPath = escapeshellarg($this->customLocation); $result = instant_remote_process(["ls -l {$escapedPath}"], $this->server, throwError: false); if (blank($result)) { $this->dispatch('error', 'The file does not exist or has been deleted.'); return; } $this->filename = $this->customLocation; $this->dispatch('success', 'The file exists.'); } catch (\Throwable $e) { return handleError($e, $this); } } } public function runImport() { $this->authorize('update', $this->resource); if ($this->filename === '') { $this->dispatch('error', 'Please select a file to import.'); return; } try { $this->importRunning = true; $this->importCommands = []; $backupFileName = "upload/{$this->resource->uuid}/restore"; // Check if an uploaded file exists first (takes priority over custom location) if (Storage::exists($backupFileName)) { $path = Storage::path($backupFileName); $tmpPath = '/tmp/'.basename($backupFileName).'_'.$this->resource->uuid; instant_scp($path, $tmpPath, $this->server); Storage::delete($backupFileName); $this->importCommands[] = "docker cp {$tmpPath} {$this->container}:{$tmpPath}"; } elseif (filled($this->customLocation)) { // Validate the custom location to prevent command injection if (! $this->validateServerPath($this->customLocation)) { $this->dispatch('error', 'Invalid file path. Path must be absolute and contain only safe characters.'); return; } $tmpPath = '/tmp/restore_'.$this->resource->uuid; $escapedCustomLocation = escapeshellarg($this->customLocation); $this->importCommands[] = "docker cp {$escapedCustomLocation} {$this->container}:{$tmpPath}"; } else { $this->dispatch('error', 'The file does not exist or has been deleted.'); return; } // Copy the restore command to a script file $scriptPath = "/tmp/restore_{$this->resource->uuid}.sh"; $restoreCommand = $this->buildRestoreCommand($tmpPath); $restoreCommandBase64 = base64_encode($restoreCommand); $this->importCommands[] = "echo \"{$restoreCommandBase64}\" | base64 -d > {$scriptPath}"; $this->importCommands[] = "chmod +x {$scriptPath}"; $this->importCommands[] = "docker cp {$scriptPath} {$this->container}:{$scriptPath}"; $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)) { $activity = remote_process($this->importCommands, $this->server, ignore_errors: true, callEventOnFinish: 'RestoreJobFinished', callEventData: [ 'scriptPath' => $scriptPath, 'tmpPath' => $tmpPath, 'container' => $this->container, 'serverId' => $this->server->id, ]); // Track the activity ID $this->activityId = $activity->id; // Dispatch activity to the monitor and open slide-over $this->dispatch('activityMonitor', $activity->id); $this->dispatch('databaserestore'); } } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->filename = null; $this->importCommands = []; } } public function loadAvailableS3Storages() { try { $this->availableS3Storages = S3Storage::ownedByCurrentTeam(['id', 'name', 'description']) ->where('is_usable', true) ->get(); } catch (\Throwable $e) { $this->availableS3Storages = collect(); } } public function updatedS3Path($value) { // Reset validation state when path changes $this->s3FileSize = null; // Ensure path starts with a slash if ($value !== null && $value !== '') { $this->s3Path = str($value)->trim()->start('/')->value(); } } public function updatedS3StorageId() { // Reset validation state when storage changes $this->s3FileSize = null; } public function checkS3File() { if (! $this->s3StorageId) { $this->dispatch('error', 'Please select an S3 storage.'); return; } if (blank($this->s3Path)) { $this->dispatch('error', 'Please provide an S3 path.'); return; } // Clean the path (remove leading slash if present) $cleanPath = ltrim($this->s3Path, '/'); // Validate the S3 path early to prevent command injection in subsequent operations if (! $this->validateS3Path($cleanPath)) { $this->dispatch('error', 'Invalid S3 path. Path must contain only safe characters (alphanumerics, dots, dashes, underscores, slashes).'); return; } try { $s3Storage = S3Storage::ownedByCurrentTeam()->findOrFail($this->s3StorageId); // Validate bucket name early if (! $this->validateBucketName($s3Storage->bucket)) { $this->dispatch('error', 'Invalid S3 bucket name. Bucket name must contain only alphanumerics, dots, dashes, and underscores.'); return; } // Test connection $s3Storage->testConnection(); // Build S3 disk configuration $disk = Storage::build([ 'driver' => 's3', 'region' => $s3Storage->region, 'key' => $s3Storage->key, 'secret' => $s3Storage->secret, 'bucket' => $s3Storage->bucket, 'endpoint' => $s3Storage->endpoint, 'use_path_style_endpoint' => true, ]); // Check if file exists if (! $disk->exists($cleanPath)) { $this->dispatch('error', 'File not found in S3. Please check the path.'); return; } // Get file size $this->s3FileSize = $disk->size($cleanPath); $this->dispatch('success', 'File found in S3. Size: '.formatBytes($this->s3FileSize)); } catch (\Throwable $e) { $this->s3FileSize = null; return handleError($e, $this); } } public function restoreFromS3() { $this->authorize('update', $this->resource); if (! $this->s3StorageId || blank($this->s3Path)) { $this->dispatch('error', 'Please select S3 storage and provide a path first.'); return; } if (is_null($this->s3FileSize)) { $this->dispatch('error', 'Please check the file first by clicking "Check File".'); return; } try { $this->importRunning = true; $s3Storage = S3Storage::ownedByCurrentTeam()->findOrFail($this->s3StorageId); $key = $s3Storage->key; $secret = $s3Storage->secret; $bucket = $s3Storage->bucket; $endpoint = $s3Storage->endpoint; // Validate bucket name to prevent command injection if (! $this->validateBucketName($bucket)) { $this->dispatch('error', 'Invalid S3 bucket name. Bucket name must contain only alphanumerics, dots, dashes, and underscores.'); return; } // Clean the S3 path $cleanPath = ltrim($this->s3Path, '/'); // Validate the S3 path to prevent command injection if (! $this->validateS3Path($cleanPath)) { $this->dispatch('error', 'Invalid S3 path. Path must contain only safe characters (alphanumerics, dots, dashes, underscores, slashes).'); return; } // Get helper image $helperImage = config('constants.coolify.helper_image'); $latestVersion = getHelperVersion(); $fullImageName = "{$helperImage}:{$latestVersion}"; // Get the database destination network $destinationNetwork = $this->resource->destination->network ?? 'coolify'; // Generate unique names for this operation $containerName = "s3-restore-{$this->resource->uuid}"; $helperTmpPath = '/tmp/'.basename($cleanPath); $serverTmpPath = "/tmp/s3-restore-{$this->resource->uuid}-".basename($cleanPath); $containerTmpPath = "/tmp/restore_{$this->resource->uuid}-".basename($cleanPath); $scriptPath = "/tmp/restore_{$this->resource->uuid}.sh"; // Prepare all commands in sequence $commands = []; // 1. Clean up any existing helper container and temp files from previous runs $commands[] = "docker rm -f {$containerName} 2>/dev/null || true"; $commands[] = "rm -f {$serverTmpPath} 2>/dev/null || true"; $commands[] = "docker exec {$this->container} rm -f {$containerTmpPath} {$scriptPath} 2>/dev/null || true"; // 2. Start helper container on the database network $commands[] = "docker run -d --network {$destinationNetwork} --name {$containerName} {$fullImageName} sleep 3600"; // 3. Configure S3 access in helper container $escapedEndpoint = escapeshellarg($endpoint); $escapedKey = escapeshellarg($key); $escapedSecret = escapeshellarg($secret); $commands[] = "docker exec {$containerName} mc alias set s3temp {$escapedEndpoint} {$escapedKey} {$escapedSecret}"; // 4. Check file exists in S3 (bucket and path already validated above) $escapedBucket = escapeshellarg($bucket); $escapedCleanPath = escapeshellarg($cleanPath); $escapedS3Source = escapeshellarg("s3temp/{$bucket}/{$cleanPath}"); $commands[] = "docker exec {$containerName} mc stat {$escapedS3Source}"; // 5. Download from S3 to helper container (progress shown by default) $escapedHelperTmpPath = escapeshellarg($helperTmpPath); $commands[] = "docker exec {$containerName} mc cp {$escapedS3Source} {$escapedHelperTmpPath}"; // 6. Copy from helper to server, then immediately to database container $commands[] = "docker cp {$containerName}:{$helperTmpPath} {$serverTmpPath}"; $commands[] = "docker cp {$serverTmpPath} {$this->container}:{$containerTmpPath}"; // 7. Cleanup helper container and server temp file immediately (no longer needed) $commands[] = "docker rm -f {$containerName} 2>/dev/null || true"; $commands[] = "rm -f {$serverTmpPath} 2>/dev/null || true"; // 8. Build and execute restore command inside database container $restoreCommand = $this->buildRestoreCommand($containerTmpPath); $restoreCommandBase64 = base64_encode($restoreCommand); $commands[] = "echo \"{$restoreCommandBase64}\" | base64 -d > {$scriptPath}"; $commands[] = "chmod +x {$scriptPath}"; $commands[] = "docker cp {$scriptPath} {$this->container}:{$scriptPath}"; // 9. Execute restore and cleanup temp files immediately after completion $commands[] = "docker exec {$this->container} sh -c '{$scriptPath} && rm -f {$containerTmpPath} {$scriptPath}'"; $commands[] = "docker exec {$this->container} sh -c 'echo \"Import finished with exit code $?\"'"; // Execute all commands with cleanup event (as safety net for edge cases) $activity = remote_process($commands, $this->server, ignore_errors: true, callEventOnFinish: 'S3RestoreJobFinished', callEventData: [ 'containerName' => $containerName, 'serverTmpPath' => $serverTmpPath, 'scriptPath' => $scriptPath, 'containerTmpPath' => $containerTmpPath, 'container' => $this->container, 'serverId' => $this->server->id, ]); // Track the activity ID $this->activityId = $activity->id; // Dispatch activity to the monitor and open slide-over $this->dispatch('activityMonitor', $activity->id); $this->dispatch('databaserestore'); $this->dispatch('info', 'Restoring database from S3. Progress will be shown in the activity monitor...'); } catch (\Throwable $e) { $this->importRunning = false; return handleError($e, $this); } } public function buildRestoreCommand(string $tmpPath): string { switch ($this->resource->getMorphClass()) { case \App\Models\StandaloneMariadb::class: $restoreCommand = $this->mariadbRestoreCommand; if ($this->dumpAll) { $restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mariadb -u root -p\$MARIADB_ROOT_PASSWORD"; } else { $restoreCommand .= " < {$tmpPath}"; } break; case \App\Models\StandaloneMysql::class: $restoreCommand = $this->mysqlRestoreCommand; if ($this->dumpAll) { $restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mysql -u root -p\$MYSQL_ROOT_PASSWORD"; } else { $restoreCommand .= " < {$tmpPath}"; } break; case \App\Models\StandalonePostgresql::class: $restoreCommand = $this->postgresqlRestoreCommand; if ($this->dumpAll) { $restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | psql -U \$POSTGRES_USER postgres"; } else { $restoreCommand .= " {$tmpPath}"; } break; case \App\Models\StandaloneMongodb::class: $restoreCommand = $this->mongodbRestoreCommand; if ($this->dumpAll === false) { $restoreCommand .= "{$tmpPath}"; } break; default: $restoreCommand = ''; } return $restoreCommand; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Redis/General.php
app/Livewire/Project/Database/Redis/General.php
<?php namespace App\Livewire\Project\Database\Redis; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneRedis; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneRedis $database; public string $name; public ?string $description = null; public ?string $redisConf = null; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public bool $isLogDrainEnabled = false; public ?string $customDockerRunOptions = null; public string $redisUsername; public string $redisPassword; public string $redisVersion; public ?string $dbUrl = null; public ?string $dbUrlPublic = null; public bool $enableSsl = false; public ?Carbon $certificateValidUntil = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', 'envsUpdated' => 'refresh', ]; } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'redisConf' => 'nullable', 'image' => 'required', 'portsMappings' => 'nullable', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'isLogDrainEnabled' => 'nullable|boolean', 'customDockerRunOptions' => 'nullable', 'redisUsername' => 'required', 'redisPassword' => 'required', 'enableSsl' => 'boolean', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'image.required' => 'The Docker Image field is required.', 'publicPort.integer' => 'The Public Port must be an integer.', 'redisUsername.required' => 'The Redis Username field is required.', 'redisPassword.required' => 'The Redis Password field is required.', ] ); } protected $validationAttributes = [ 'name' => 'Name', 'description' => 'Description', 'redisConf' => 'Redis Configuration', 'image' => 'Image', 'portsMappings' => 'Port Mapping', 'isPublic' => 'Is Public', 'publicPort' => 'Public Port', 'customDockerRunOptions' => 'Custom Docker Options', 'redisUsername' => 'Redis Username', 'redisPassword' => 'Redis Password', 'enableSsl' => 'Enable SSL', ]; public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (\Throwable $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->redis_conf = $this->redisConf; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->enable_ssl = $this->enableSsl; $this->database->save(); $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->redisConf = $this->database->redis_conf; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->enableSsl = $this->database->enable_ssl; $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; $this->redisVersion = $this->database->getRedisVersion(); $this->redisUsername = $this->database->redis_username; $this->redisPassword = $this->database->redis_password; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('manageEnvironment', $this->database); $this->syncData(true); if (version_compare($this->redisVersion, '6.0', '>=')) { $this->database->runtime_environment_variables()->updateOrCreate( ['key' => 'REDIS_USERNAME'], ['value' => $this->redisUsername, 'resourceable_id' => $this->database->id] ); } $this->database->runtime_environment_variables()->updateOrCreate( ['key' => 'REDIS_PASSWORD'], ['value' => $this->redisPassword, 'resourceable_id' => $this->database->id] ); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { $this->dispatch('refreshEnvs'); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->dbUrlPublic = $this->database->external_db_url; $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; $this->syncData(true); return handleError($e, $this); } } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first(); SslHelper::generateSslCertificate( commonName: $existingCert->commonName, subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates regenerated. Restart database to apply changes.'); } catch (Exception $e) { handleError($e, $this); } } public function refresh(): void { $this->database->refresh(); $this->syncData(); } public function render() { return view('livewire.project.database.redis.general'); } public function isSharedVariable($name) { return $this->database->runtime_environment_variables()->where('key', $name)->where('is_shared', true)->exists(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Mysql/General.php
app/Livewire/Project/Database/Mysql/General.php
<?php namespace App\Livewire\Project\Database\Mysql; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneMysql; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public StandaloneMysql $database; public ?Server $server = null; public string $name; public ?string $description = null; public string $mysqlRootPassword; public string $mysqlUser; public string $mysqlPassword; public string $mysqlDatabase; public ?string $mysqlConf = null; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public bool $isLogDrainEnabled = false; public ?string $customDockerRunOptions = null; public bool $enableSsl = false; public ?string $sslMode = null; public ?string $db_url = null; public ?string $db_url_public = null; public ?Carbon $certificateValidUntil = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', ]; } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'mysqlRootPassword' => 'required', 'mysqlUser' => 'required', 'mysqlPassword' => 'required', 'mysqlDatabase' => 'required', 'mysqlConf' => 'nullable', 'image' => 'required', 'portsMappings' => 'nullable', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'isLogDrainEnabled' => 'nullable|boolean', 'customDockerRunOptions' => 'nullable', 'enableSsl' => 'boolean', 'sslMode' => 'nullable|string|in:PREFERRED,REQUIRED,VERIFY_CA,VERIFY_IDENTITY', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'mysqlRootPassword.required' => 'The Root Password field is required.', 'mysqlUser.required' => 'The MySQL User field is required.', 'mysqlPassword.required' => 'The MySQL Password field is required.', 'mysqlDatabase.required' => 'The MySQL Database field is required.', 'image.required' => 'The Docker Image field is required.', 'publicPort.integer' => 'The Public Port must be an integer.', 'sslMode.in' => 'The SSL Mode must be one of: PREFERRED, REQUIRED, VERIFY_CA, VERIFY_IDENTITY.', ] ); } protected $validationAttributes = [ 'name' => 'Name', 'description' => 'Description', 'mysqlRootPassword' => 'Root Password', 'mysqlUser' => 'User', 'mysqlPassword' => 'Password', 'mysqlDatabase' => 'Database', 'mysqlConf' => 'MySQL Configuration', 'image' => 'Image', 'portsMappings' => 'Port Mapping', 'isPublic' => 'Is Public', 'publicPort' => 'Public Port', 'customDockerRunOptions' => 'Custom Docker Run Options', 'enableSsl' => 'Enable SSL', 'sslMode' => 'SSL Mode', ]; public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (Exception $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->mysql_root_password = $this->mysqlRootPassword; $this->database->mysql_user = $this->mysqlUser; $this->database->mysql_password = $this->mysqlPassword; $this->database->mysql_database = $this->mysqlDatabase; $this->database->mysql_conf = $this->mysqlConf; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->enable_ssl = $this->enableSsl; $this->database->ssl_mode = $this->sslMode; $this->database->save(); $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->mysqlRootPassword = $this->database->mysql_root_password; $this->mysqlUser = $this->database->mysql_user; $this->mysqlPassword = $this->database->mysql_password; $this->mysqlDatabase = $this->database->mysql_database; $this->mysqlConf = $this->database->mysql_conf; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->enableSsl = $this->database->enable_ssl; $this->sslMode = $this->database->ssl_mode; $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; return handleError($e, $this); } } public function updatedSslMode() { $this->instantSaveSSL(); } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first(); SslHelper::generateSslCertificate( commonName: $existingCert->common_name, subjectAlternativeNames: $existingCert->subject_alternative_names ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates have been regenerated. Please restart the database for changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function refresh(): void { $this->database->refresh(); $this->syncData(); } public function render() { return view('livewire.project.database.mysql.general'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Clickhouse/General.php
app/Livewire/Project/Database/Clickhouse/General.php
<?php namespace App\Livewire\Project\Database\Clickhouse; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Models\Server; use App\Models\StandaloneClickhouse; use App\Support\ValidationPatterns; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneClickhouse $database; public string $name; public ?string $description = null; public string $clickhouseAdminUser; public string $clickhouseAdminPassword; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public ?string $customDockerRunOptions = null; public ?string $dbUrl = null; public ?string $dbUrlPublic = null; public bool $isLogDrainEnabled = false; public function getListeners() { $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},DatabaseProxyStopped" => 'databaseProxyStopped', ]; } public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } } catch (\Throwable $e) { return handleError($e, $this); } } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'clickhouseAdminUser' => 'required|string', 'clickhouseAdminPassword' => 'required|string', 'image' => 'required|string', 'portsMappings' => 'nullable|string', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'customDockerRunOptions' => 'nullable|string', 'dbUrl' => 'nullable|string', 'dbUrlPublic' => 'nullable|string', 'isLogDrainEnabled' => 'nullable|boolean', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'clickhouseAdminUser.required' => 'The Admin User field is required.', 'clickhouseAdminUser.string' => 'The Admin User must be a string.', 'clickhouseAdminPassword.required' => 'The Admin Password field is required.', 'clickhouseAdminPassword.string' => 'The Admin Password must be a string.', 'image.required' => 'The Docker Image field is required.', 'image.string' => 'The Docker Image must be a string.', 'publicPort.integer' => 'The Public Port must be an integer.', ] ); } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->clickhouse_admin_user = $this->clickhouseAdminUser; $this->database->clickhouse_admin_password = $this->clickhouseAdminPassword; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->save(); $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->clickhouseAdminUser = $this->database->clickhouse_admin_user; $this->clickhouseAdminPassword = $this->database->clickhouse_admin_password; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->dbUrlPublic = $this->database->external_db_url; $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; $this->syncData(true); return handleError($e, $this); } } public function databaseProxyStopped() { $this->syncData(); } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Dragonfly/General.php
app/Livewire/Project/Database/Dragonfly/General.php
<?php namespace App\Livewire\Project\Database\Dragonfly; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneDragonfly; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneDragonfly $database; public string $name; public ?string $description = null; public string $dragonflyPassword; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public ?string $customDockerRunOptions = null; public ?string $dbUrl = null; public ?string $dbUrlPublic = null; public bool $isLogDrainEnabled = false; public ?Carbon $certificateValidUntil = null; public bool $enable_ssl = false; public function getListeners() { $userId = Auth::id(); $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},DatabaseProxyStopped" => 'databaseProxyStopped', "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', ]; } public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (\Throwable $e) { return handleError($e, $this); } } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'dragonflyPassword' => 'required|string', 'image' => 'required|string', 'portsMappings' => 'nullable|string', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'customDockerRunOptions' => 'nullable|string', 'dbUrl' => 'nullable|string', 'dbUrlPublic' => 'nullable|string', 'isLogDrainEnabled' => 'nullable|boolean', 'enable_ssl' => 'nullable|boolean', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'dragonflyPassword.required' => 'The Dragonfly Password field is required.', 'dragonflyPassword.string' => 'The Dragonfly Password must be a string.', 'image.required' => 'The Docker Image field is required.', 'image.string' => 'The Docker Image must be a string.', 'publicPort.integer' => 'The Public Port must be an integer.', ] ); } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->dragonfly_password = $this->dragonflyPassword; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->enable_ssl = $this->enable_ssl; $this->database->save(); $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->dragonflyPassword = $this->database->dragonfly_password; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->enable_ssl = $this->database->enable_ssl; $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->dbUrlPublic = $this->database->external_db_url; $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; $this->syncData(true); return handleError($e, $this); } } public function databaseProxyStopped() { $this->syncData(); } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $server = $this->database->destination->server; $caCert = $server->sslCertificates() ->where('is_ca_certificate', true) ->first(); if (! $caCert) { $server->generateCaCertificate(); $caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first(); } if (! $caCert) { $this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.'); return; } SslHelper::generateSslCertificate( commonName: $existingCert->commonName, subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates regenerated. Restart database to apply changes.'); } catch (Exception $e) { handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Mongodb/General.php
app/Livewire/Project/Database/Mongodb/General.php
<?php namespace App\Livewire\Project\Database\Mongodb; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneMongodb; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneMongodb $database; public string $name; public ?string $description = null; public ?string $mongoConf = null; public string $mongoInitdbRootUsername; public string $mongoInitdbRootPassword; public string $mongoInitdbDatabase; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public bool $isLogDrainEnabled = false; public ?string $customDockerRunOptions = null; public bool $enableSsl = false; public ?string $sslMode = null; public ?string $db_url = null; public ?string $db_url_public = null; public ?Carbon $certificateValidUntil = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', ]; } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'mongoConf' => 'nullable', 'mongoInitdbRootUsername' => 'required', 'mongoInitdbRootPassword' => 'required', 'mongoInitdbDatabase' => 'required', 'image' => 'required', 'portsMappings' => 'nullable', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'isLogDrainEnabled' => 'nullable|boolean', 'customDockerRunOptions' => 'nullable', 'enableSsl' => 'boolean', 'sslMode' => 'nullable|string|in:allow,prefer,require,verify-full', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'mongoInitdbRootUsername.required' => 'The Root Username field is required.', 'mongoInitdbRootPassword.required' => 'The Root Password field is required.', 'mongoInitdbDatabase.required' => 'The MongoDB Database field is required.', 'image.required' => 'The Docker Image field is required.', 'publicPort.integer' => 'The Public Port must be an integer.', 'sslMode.in' => 'The SSL Mode must be one of: allow, prefer, require, verify-full.', ] ); } protected $validationAttributes = [ 'name' => 'Name', 'description' => 'Description', 'mongoConf' => 'Mongo Configuration', 'mongoInitdbRootUsername' => 'Root Username', 'mongoInitdbRootPassword' => 'Root Password', 'mongoInitdbDatabase' => 'Database', 'image' => 'Image', 'portsMappings' => 'Port Mapping', 'isPublic' => 'Is Public', 'publicPort' => 'Public Port', 'customDockerRunOptions' => 'Custom Docker Run Options', 'enableSsl' => 'Enable SSL', 'sslMode' => 'SSL Mode', ]; public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (Exception $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->mongo_conf = $this->mongoConf; $this->database->mongo_initdb_root_username = $this->mongoInitdbRootUsername; $this->database->mongo_initdb_root_password = $this->mongoInitdbRootPassword; $this->database->mongo_initdb_database = $this->mongoInitdbDatabase; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->enable_ssl = $this->enableSsl; $this->database->ssl_mode = $this->sslMode; $this->database->save(); $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->mongoConf = $this->database->mongo_conf; $this->mongoInitdbRootUsername = $this->database->mongo_initdb_root_username; $this->mongoInitdbRootPassword = $this->database->mongo_initdb_root_password; $this->mongoInitdbDatabase = $this->database->mongo_initdb_database; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->enableSsl = $this->database->enable_ssl; $this->sslMode = $this->database->ssl_mode; $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } if (str($this->mongoConf)->isEmpty()) { $this->mongoConf = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; return handleError($e, $this); } } public function updatedSslMode() { $this->instantSaveSSL(); } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first(); SslHelper::generateSslCertificate( commonName: $existingCert->common_name, subjectAlternativeNames: $existingCert->subject_alternative_names ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates have been regenerated. Please restart the database for changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function refresh(): void { $this->database->refresh(); $this->syncData(); } public function render() { return view('livewire.project.database.mongodb.general'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Postgresql/General.php
app/Livewire/Project/Database/Postgresql/General.php
<?php namespace App\Livewire\Project\Database\Postgresql; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandalonePostgresql; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public StandalonePostgresql $database; public ?Server $server = null; public string $name; public ?string $description = null; public string $postgresUser; public string $postgresPassword; public string $postgresDb; public ?string $postgresInitdbArgs = null; public ?string $postgresHostAuthMethod = null; public ?string $postgresConf = null; public ?array $initScripts = null; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public bool $isLogDrainEnabled = false; public ?string $customDockerRunOptions = null; public bool $enableSsl = false; public ?string $sslMode = null; public string $new_filename; public string $new_content; public ?string $db_url = null; public ?string $db_url_public = null; public ?Carbon $certificateValidUntil = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', 'save_init_script', 'delete_init_script', ]; } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'postgresUser' => 'required', 'postgresPassword' => 'required', 'postgresDb' => 'required', 'postgresInitdbArgs' => 'nullable', 'postgresHostAuthMethod' => 'nullable', 'postgresConf' => 'nullable', 'initScripts' => 'nullable', 'image' => 'required', 'portsMappings' => 'nullable', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'isLogDrainEnabled' => 'nullable|boolean', 'customDockerRunOptions' => 'nullable', 'enableSsl' => 'boolean', 'sslMode' => 'nullable|string|in:allow,prefer,require,verify-ca,verify-full', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'postgresUser.required' => 'The Postgres User field is required.', 'postgresPassword.required' => 'The Postgres Password field is required.', 'postgresDb.required' => 'The Postgres Database field is required.', 'image.required' => 'The Docker Image field is required.', 'publicPort.integer' => 'The Public Port must be an integer.', 'sslMode.in' => 'The SSL Mode must be one of: allow, prefer, require, verify-ca, verify-full.', ] ); } protected $validationAttributes = [ 'name' => 'Name', 'description' => 'Description', 'postgresUser' => 'Postgres User', 'postgresPassword' => 'Postgres Password', 'postgresDb' => 'Postgres DB', 'postgresInitdbArgs' => 'Postgres Initdb Args', 'postgresHostAuthMethod' => 'Postgres Host Auth Method', 'postgresConf' => 'Postgres Configuration', 'initScripts' => 'Init Scripts', 'image' => 'Image', 'portsMappings' => 'Port Mapping', 'isPublic' => 'Is Public', 'publicPort' => 'Public Port', 'customDockerRunOptions' => 'Custom Docker Run Options', 'enableSsl' => 'Enable SSL', 'sslMode' => 'SSL Mode', ]; public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (Exception $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->postgres_user = $this->postgresUser; $this->database->postgres_password = $this->postgresPassword; $this->database->postgres_db = $this->postgresDb; $this->database->postgres_initdb_args = $this->postgresInitdbArgs; $this->database->postgres_host_auth_method = $this->postgresHostAuthMethod; $this->database->postgres_conf = $this->postgresConf; $this->database->init_scripts = $this->initScripts; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->enable_ssl = $this->enableSsl; $this->database->ssl_mode = $this->sslMode; $this->database->save(); $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->postgresUser = $this->database->postgres_user; $this->postgresPassword = $this->database->postgres_password; $this->postgresDb = $this->database->postgres_db; $this->postgresInitdbArgs = $this->database->postgres_initdb_args; $this->postgresHostAuthMethod = $this->database->postgres_host_auth_method; $this->postgresConf = $this->database->postgres_conf; $this->initScripts = $this->database->init_scripts; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->enableSsl = $this->database->enable_ssl; $this->sslMode = $this->database->ssl_mode; $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function updatedSslMode() { $this->instantSaveSSL(); } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first(); SslHelper::generateSslCertificate( commonName: $existingCert->common_name, subjectAlternativeNames: $existingCert->subject_alternative_names ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates have been regenerated. Please restart the database for changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; return handleError($e, $this); } } public function save_init_script($script) { $this->authorize('update', $this->database); $initScripts = collect($this->initScripts ?? []); $existingScript = $initScripts->firstWhere('filename', $script['filename']); $oldScript = $initScripts->firstWhere('index', $script['index']); if ($existingScript && $existingScript['index'] !== $script['index']) { $this->dispatch('error', 'A script with this filename already exists.'); return; } $container_name = $this->database->uuid; $configuration_dir = database_configuration_dir().'/'.$container_name; if ($oldScript && $oldScript['filename'] !== $script['filename']) { try { // Validate and escape filename to prevent command injection validateShellSafePath($oldScript['filename'], 'init script filename'); $old_file_path = "$configuration_dir/docker-entrypoint-initdb.d/{$oldScript['filename']}"; $escapedOldPath = escapeshellarg($old_file_path); $delete_command = "rm -f {$escapedOldPath}"; instant_remote_process([$delete_command], $this->server); } catch (Exception $e) { $this->dispatch('error', $e->getMessage()); return; } } $index = $initScripts->search(function ($item) use ($script) { return $item['index'] === $script['index']; }); if ($index !== false) { $initScripts[$index] = $script; } else { $initScripts->push($script); } $this->initScripts = $initScripts->values() ->map(function ($item, $index) { $item['index'] = $index; return $item; }) ->all(); $this->syncData(true); $this->dispatch('success', 'Init script saved and updated.'); } public function delete_init_script($script) { $this->authorize('update', $this->database); $collection = collect($this->initScripts); $found = $collection->firstWhere('filename', $script['filename']); if ($found) { $container_name = $this->database->uuid; $configuration_dir = database_configuration_dir().'/'.$container_name; try { // Validate and escape filename to prevent command injection validateShellSafePath($script['filename'], 'init script filename'); $file_path = "$configuration_dir/docker-entrypoint-initdb.d/{$script['filename']}"; $escapedPath = escapeshellarg($file_path); $command = "rm -f {$escapedPath}"; instant_remote_process([$command], $this->server); } catch (Exception $e) { $this->dispatch('error', $e->getMessage()); return; } $updatedScripts = $collection->filter(fn ($s) => $s['filename'] !== $script['filename']) ->values() ->map(function ($item, $index) { $item['index'] = $index; return $item; }) ->all(); $this->initScripts = $updatedScripts; $this->syncData(true); $this->dispatch('refresh')->self(); $this->dispatch('success', 'Init script deleted from the database and the server.'); } } public function save_new_init_script() { $this->authorize('update', $this->database); $this->validate([ 'new_filename' => 'required|string', 'new_content' => 'required|string', ]); try { // Validate filename to prevent command injection validateShellSafePath($this->new_filename, 'init script filename'); } catch (Exception $e) { $this->dispatch('error', $e->getMessage()); return; } $found = collect($this->initScripts)->firstWhere('filename', $this->new_filename); if ($found) { $this->dispatch('error', 'Filename already exists.'); return; } if (! isset($this->initScripts)) { $this->initScripts = []; } $this->initScripts = array_merge($this->initScripts, [ [ 'index' => count($this->initScripts), 'filename' => $this->new_filename, 'content' => $this->new_content, ], ]); $this->syncData(true); $this->dispatch('success', 'Init script added.'); $this->new_content = ''; $this->new_filename = ''; } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Mariadb/General.php
app/Livewire/Project/Database/Mariadb/General.php
<?php namespace App\Livewire\Project\Database\Mariadb; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneMariadb; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneMariadb $database; public string $name; public ?string $description = null; public string $mariadbRootPassword; public string $mariadbUser; public string $mariadbPassword; public string $mariadbDatabase; public ?string $mariadbConf = null; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public bool $isLogDrainEnabled = false; public ?string $customDockerRunOptions = null; public bool $enableSsl = false; public ?string $db_url = null; public ?string $db_url_public = null; public ?Carbon $certificateValidUntil = null; public function getListeners() { $userId = Auth::id(); return [ "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', ]; } protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'mariadbRootPassword' => 'required', 'mariadbUser' => 'required', 'mariadbPassword' => 'required', 'mariadbDatabase' => 'required', 'mariadbConf' => 'nullable', 'image' => 'required', 'portsMappings' => 'nullable', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'isLogDrainEnabled' => 'nullable|boolean', 'customDockerRunOptions' => 'nullable', 'enableSsl' => 'boolean', ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'mariadbRootPassword.required' => 'The Root Password field is required.', 'mariadbUser.required' => 'The MariaDB User field is required.', 'mariadbPassword.required' => 'The MariaDB Password field is required.', 'mariadbDatabase.required' => 'The MariaDB Database field is required.', 'image.required' => 'The Docker Image field is required.', 'publicPort.integer' => 'The Public Port must be an integer.', ] ); } protected $validationAttributes = [ 'name' => 'Name', 'description' => 'Description', 'mariadbRootPassword' => 'Root Password', 'mariadbUser' => 'User', 'mariadbPassword' => 'Password', 'mariadbDatabase' => 'Database', 'mariadbConf' => 'MariaDB Configuration', 'image' => 'Image', 'portsMappings' => 'Port Mapping', 'isPublic' => 'Is Public', 'publicPort' => 'Public Port', 'customDockerRunOptions' => 'Custom Docker Options', 'enableSsl' => 'Enable SSL', ]; public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (Exception $e) { return handleError($e, $this); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->mariadb_root_password = $this->mariadbRootPassword; $this->database->mariadb_user = $this->mariadbUser; $this->database->mariadb_password = $this->mariadbPassword; $this->database->mariadb_database = $this->mariadbDatabase; $this->database->mariadb_conf = $this->mariadbConf; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->enable_ssl = $this->enableSsl; $this->database->save(); $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->mariadbRootPassword = $this->database->mariadb_root_password; $this->mariadbUser = $this->database->mariadb_user; $this->mariadbPassword = $this->database->mariadb_password; $this->mariadbDatabase = $this->database->mariadb_database; $this->mariadbConf = $this->database->mariadb_conf; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->enableSsl = $this->database->enable_ssl; $this->db_url = $this->database->internal_db_url; $this->db_url_public = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function submit() { try { $this->authorize('update', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; return handleError($e, $this); } } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates()->where('is_ca_certificate', true)->first(); SslHelper::generateSslCertificate( commonName: $existingCert->common_name, subjectAlternativeNames: $existingCert->subject_alternative_names ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates have been regenerated. Please restart the database for changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function refresh(): void { $this->database->refresh(); $this->syncData(); } public function render() { return view('livewire.project.database.mariadb.general'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Backup/Execution.php
app/Livewire/Project/Database/Backup/Execution.php
<?php namespace App\Livewire\Project\Database\Backup; use App\Models\ScheduledDatabaseBackup; use Livewire\Component; class Execution extends Component { public $database; public ?ScheduledDatabaseBackup $backup; public $executions; public $s3s; public function mount() { $backup_uuid = request()->route('backup_uuid'); $project = currentTeam()->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first(); if (! $project) { return redirect()->route('dashboard'); } $environment = $project->load(['environments'])->environments->where('uuid', request()->route('environment_uuid'))->first()->load(['applications']); if (! $environment) { return redirect()->route('dashboard'); } $database = $environment->databases()->where('uuid', request()->route('database_uuid'))->first(); if (! $database) { return redirect()->route('dashboard'); } $backup = $database->scheduledBackups->where('uuid', $backup_uuid)->first(); if (! $backup) { return redirect()->route('dashboard'); } $executions = collect($backup->executions)->sortByDesc('created_at'); $this->database = $database; $this->backup = $backup; $this->executions = $executions; $this->s3s = currentTeam()->s3s; } public function render() { return view('livewire.project.database.backup.execution'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Backup/Index.php
app/Livewire/Project/Database/Backup/Index.php
<?php namespace App\Livewire\Project\Database\Backup; use Livewire\Component; class Index extends Component { public $database; public function mount() { $project = currentTeam()->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first(); if (! $project) { return redirect()->route('dashboard'); } $environment = $project->load(['environments'])->environments->where('uuid', request()->route('environment_uuid'))->first()->load(['applications']); if (! $environment) { return redirect()->route('dashboard'); } $database = $environment->databases()->where('uuid', request()->route('database_uuid'))->first(); if (! $database) { return redirect()->route('dashboard'); } // No backups if ( $database->getMorphClass() === \App\Models\StandaloneRedis::class || $database->getMorphClass() === \App\Models\StandaloneKeydb::class || $database->getMorphClass() === \App\Models\StandaloneDragonfly::class || $database->getMorphClass() === \App\Models\StandaloneClickhouse::class ) { return redirect()->route('project.database.configuration', [ 'project_uuid' => $project->uuid, 'environment_uuid' => $environment->uuid, 'database_uuid' => $database->uuid, ]); } $this->database = $database; } public function render() { return view('livewire.project.database.backup.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Database/Keydb/General.php
app/Livewire/Project/Database/Keydb/General.php
<?php namespace App\Livewire\Project\Database\Keydb; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Helpers\SslHelper; use App\Models\Server; use App\Models\StandaloneKeydb; use App\Support\ValidationPatterns; use Carbon\Carbon; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class General extends Component { use AuthorizesRequests; public ?Server $server = null; public StandaloneKeydb $database; public string $name; public ?string $description = null; public ?string $keydbConf = null; public string $keydbPassword; public string $image; public ?string $portsMappings = null; public ?bool $isPublic = null; public ?int $publicPort = null; public ?string $customDockerRunOptions = null; public ?string $dbUrl = null; public ?string $dbUrlPublic = null; public bool $isLogDrainEnabled = false; public ?Carbon $certificateValidUntil = null; public bool $enable_ssl = false; public function getListeners() { $userId = Auth::id(); $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},DatabaseProxyStopped" => 'databaseProxyStopped', "echo-private:user.{$userId},DatabaseStatusChanged" => '$refresh', ]; } public function mount() { try { $this->authorize('view', $this->database); $this->syncData(); $this->server = data_get($this->database, 'destination.server'); if (! $this->server) { $this->dispatch('error', 'Database destination server is not configured.'); return; } $existingCert = $this->database->sslCertificates()->first(); if ($existingCert) { $this->certificateValidUntil = $existingCert->valid_until; } } catch (\Throwable $e) { return handleError($e, $this); } } protected function rules(): array { $baseRules = [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'keydbConf' => 'nullable|string', 'keydbPassword' => 'required|string', 'image' => 'required|string', 'portsMappings' => 'nullable|string', 'isPublic' => 'nullable|boolean', 'publicPort' => 'nullable|integer', 'customDockerRunOptions' => 'nullable|string', 'dbUrl' => 'nullable|string', 'dbUrlPublic' => 'nullable|string', 'isLogDrainEnabled' => 'nullable|boolean', 'enable_ssl' => 'boolean', ]; return $baseRules; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'keydbPassword.required' => 'The KeyDB Password field is required.', 'keydbPassword.string' => 'The KeyDB Password must be a string.', 'image.required' => 'The Docker Image field is required.', 'image.string' => 'The Docker Image must be a string.', 'publicPort.integer' => 'The Public Port must be an integer.', ] ); } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->database->name = $this->name; $this->database->description = $this->description; $this->database->keydb_conf = $this->keydbConf; $this->database->keydb_password = $this->keydbPassword; $this->database->image = $this->image; $this->database->ports_mappings = $this->portsMappings; $this->database->is_public = $this->isPublic; $this->database->public_port = $this->publicPort; $this->database->custom_docker_run_options = $this->customDockerRunOptions; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; $this->database->enable_ssl = $this->enable_ssl; $this->database->save(); $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } else { $this->name = $this->database->name; $this->description = $this->database->description; $this->keydbConf = $this->database->keydb_conf; $this->keydbPassword = $this->database->keydb_password; $this->image = $this->database->image; $this->portsMappings = $this->database->ports_mappings; $this->isPublic = $this->database->is_public; $this->publicPort = $this->database->public_port; $this->customDockerRunOptions = $this->database->custom_docker_run_options; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled; $this->enable_ssl = $this->database->enable_ssl; $this->dbUrl = $this->database->internal_db_url; $this->dbUrlPublic = $this->database->external_db_url; } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->database); if (! $this->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (Exception $e) { return handleError($e, $this); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } 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; } StartDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->dbUrlPublic = $this->database->external_db_url; $this->syncData(true); } catch (\Throwable $e) { $this->isPublic = ! $this->isPublic; $this->syncData(true); return handleError($e, $this); } } public function databaseProxyStopped() { $this->syncData(); } public function submit() { try { $this->authorize('manageEnvironment', $this->database); if (str($this->publicPort)->isEmpty()) { $this->publicPort = null; } $this->syncData(true); $this->dispatch('success', 'Database updated.'); } catch (Exception $e) { return handleError($e, $this); } finally { if (is_null($this->database->config_hash)) { $this->database->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function instantSaveSSL() { try { $this->authorize('update', $this->database); $this->syncData(true); $this->dispatch('success', 'SSL configuration updated.'); } catch (Exception $e) { return handleError($e, $this); } } public function regenerateSslCertificate() { try { $this->authorize('update', $this->database); $existingCert = $this->database->sslCertificates()->first(); if (! $existingCert) { $this->dispatch('error', 'No existing SSL certificate found for this database.'); return; } $caCert = $this->server->sslCertificates() ->where('is_ca_certificate', true) ->first(); SslHelper::generateSslCertificate( commonName: $existingCert->commonName, subjectAlternativeNames: $existingCert->subjectAlternativeNames ?? [], resourceType: $existingCert->resource_type, resourceId: $existingCert->resource_id, serverId: $existingCert->server_id, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, configurationDir: $existingCert->configuration_dir, mountPath: $existingCert->mount_path, isPemKeyFileRequired: true, ); $this->dispatch('success', 'SSL certificates regenerated. Restart database to apply changes.'); } catch (Exception $e) { handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Webhooks.php
app/Livewire/Project/Shared/Webhooks.php
<?php namespace App\Livewire\Project\Shared; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; // Refactored ✅ class Webhooks extends Component { use AuthorizesRequests; public $resource; public ?string $deploywebhook; public ?string $githubManualWebhook; public ?string $gitlabManualWebhook; public ?string $bitbucketManualWebhook; public ?string $giteaManualWebhook; public ?string $githubManualWebhookSecret = null; public ?string $gitlabManualWebhookSecret = null; public ?string $bitbucketManualWebhookSecret = null; public ?string $giteaManualWebhookSecret = null; public function mount() { $this->deploywebhook = generateDeployWebhook($this->resource); $this->githubManualWebhookSecret = data_get($this->resource, 'manual_webhook_secret_github'); $this->githubManualWebhook = generateGitManualWebhook($this->resource, 'github'); $this->gitlabManualWebhookSecret = data_get($this->resource, 'manual_webhook_secret_gitlab'); $this->gitlabManualWebhook = generateGitManualWebhook($this->resource, 'gitlab'); $this->bitbucketManualWebhookSecret = data_get($this->resource, 'manual_webhook_secret_bitbucket'); $this->bitbucketManualWebhook = generateGitManualWebhook($this->resource, 'bitbucket'); $this->giteaManualWebhookSecret = data_get($this->resource, 'manual_webhook_secret_gitea'); $this->giteaManualWebhook = generateGitManualWebhook($this->resource, 'gitea'); } public function submit() { try { $this->authorize('update', $this->resource); $this->resource->update([ 'manual_webhook_secret_github' => $this->githubManualWebhookSecret, 'manual_webhook_secret_gitlab' => $this->gitlabManualWebhookSecret, 'manual_webhook_secret_bitbucket' => $this->bitbucketManualWebhookSecret, 'manual_webhook_secret_gitea' => $this->giteaManualWebhookSecret, ]); $this->dispatch('success', 'Secret Saved.'); } catch (\Exception $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ConfigurationChecker.php
app/Livewire/Project/Shared/ConfigurationChecker.php
<?php namespace App\Livewire\Project\Shared; use App\Models\Application; use App\Models\Service; 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 Livewire\Component; class ConfigurationChecker extends Component { public bool $isConfigurationChanged = false; public Application|Service|StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ApplicationConfigurationChanged" => 'configurationChanged', 'configurationChanged' => 'configurationChanged', ]; } public function mount() { $this->configurationChanged(); } public function render() { return view('livewire.project.shared.configuration-checker'); } public function configurationChanged() { $this->isConfigurationChanged = $this->resource->isConfigurationChanged(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Logs.php
app/Livewire/Project/Shared/Logs.php
<?php namespace App\Livewire\Project\Shared; use App\Models\Application; use App\Models\Service; 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\Collection; use Livewire\Component; class Logs extends Component { public ?string $type = null; public Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource; public Collection $servers; public Collection $containers; public array $serverContainers = []; public $container = []; public $parameters; public $query; public $status; public $serviceSubType; public $cpu; public bool $containersLoaded = false; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => '$refresh', ]; } public function loadAllContainers() { try { foreach ($this->servers as $server) { $this->serverContainers[$server->id] = $this->getContainersForServer($server); } $this->containersLoaded = true; } catch (\Exception $e) { $this->containersLoaded = true; // Set to true to stop loading spinner return handleError($e, $this); } } private function getContainersForServer($server) { if (! $server->isFunctional()) { return []; } try { if ($server->isSwarm()) { $containers = collect([ [ 'ID' => $this->resource->uuid, 'Names' => $this->resource->uuid.'_'.$this->resource->uuid, ], ]); return $containers->toArray(); } else { $containers = getCurrentApplicationContainerStatus($server, $this->resource->id, includePullrequests: true); if ($containers && $containers->count() > 0) { return $containers->sort()->toArray(); } return []; } } catch (\Exception $e) { // Log error but don't fail the entire operation ray("Error loading containers for server {$server->name}: ".$e->getMessage()); return []; } } public function mount() { try { $this->containers = collect(); $this->servers = collect(); $this->serverContainers = []; $this->parameters = get_route_parameters(); $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->status = $this->resource->status; if ($this->resource->destination->server->isFunctional()) { $server = $this->resource->destination->server; $this->servers = $this->servers->push($server); } foreach ($this->resource->additional_servers as $server) { if ($server->isFunctional()) { $this->servers = $this->servers->push($server); } } } elseif (data_get($this->parameters, 'database_uuid')) { $this->type = 'database'; $resource = getResourceByUuid($this->parameters['database_uuid'], data_get(auth()->user()->currentTeam(), 'id')); if (is_null($resource)) { abort(404); } $this->resource = $resource; $this->status = $this->resource->status; if ($this->resource->destination->server->isFunctional()) { $server = $this->resource->destination->server; $this->servers = $this->servers->push($server); } $this->container = $this->resource->uuid; $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->applications()->get()->each(function ($application) { $this->containers->push(data_get($application, 'name').'-'.data_get($this->resource, 'uuid')); }); $this->resource->databases()->get()->each(function ($database) { $this->containers->push(data_get($database, 'name').'-'.data_get($this->resource, 'uuid')); }); if ($this->resource->server->isFunctional()) { $server = $this->resource->server; $this->servers = $this->servers->push($server); } } $this->containers = $this->containers->sort(); if (data_get($this->query, 'pull_request_id')) { $this->containers = $this->containers->filter(function ($container) { return str_contains($container, $this->query['pull_request_id']); }); } } catch (\Exception $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.shared.logs'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Tags.php
app/Livewire/Project/Shared/Tags.php
<?php namespace App\Livewire\Project\Shared; use App\Models\Tag; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; // Refactored ✅ class Tags extends Component { use AuthorizesRequests; public $resource = null; #[Validate('required|string|min:2')] public string $newTags; public $tags = []; public $filteredTags = []; public function mount() { $this->loadTags(); } public function loadTags() { $this->tags = Tag::ownedByCurrentTeam()->get(); $this->filteredTags = $this->tags->filter(function ($tag) { return ! $this->resource->tags->contains($tag); }); } public function submit() { try { $this->authorize('update', $this->resource); $this->validate(); $tags = str($this->newTags)->trim()->explode(' '); foreach ($tags as $tag) { $tag = strip_tags($tag); if (strlen($tag) < 2) { $this->dispatch('error', 'Invalid tag.', "Tag <span class='dark:text-warning'>$tag</span> is invalid. Min length is 2."); continue; } if ($this->resource->tags()->where('name', $tag)->exists()) { $this->dispatch('error', 'Duplicate tags.', "Tag <span class='dark:text-warning'>$tag</span> already added."); continue; } $found = Tag::ownedByCurrentTeam()->where(['name' => $tag])->exists(); if (! $found) { $found = Tag::create([ 'name' => $tag, 'team_id' => currentTeam()->id, ]); } $this->resource->tags()->attach($found->id); } $this->refresh(); } catch (\Exception $e) { return handleError($e, $this); } } public function addTag(string $id, string $name) { try { $this->authorize('update', $this->resource); $name = strip_tags($name); if ($this->resource->tags()->where('id', $id)->exists()) { $this->dispatch('error', 'Duplicate tags.', "Tag <span class='dark:text-warning'>$name</span> already added."); return; } $this->resource->tags()->attach($id); $this->refresh(); $this->dispatch('success', 'Tag added.'); } catch (\Exception $e) { return handleError($e, $this); } } public function deleteTag(string $id) { try { $this->authorize('update', $this->resource); $this->resource->tags()->detach($id); $found_more_tags = Tag::ownedByCurrentTeam()->find($id); if ($found_more_tags && $found_more_tags->applications()->count() == 0 && $found_more_tags->services()->count() == 0) { $found_more_tags->delete(); } $this->refresh(); $this->dispatch('success', 'Tag deleted.'); } catch (\Exception $e) { return handleError($e, $this); } } public function refresh() { $this->resource->refresh(); // Remove this when legacy_model_binding is false $this->loadTags(); $this->reset('newTags'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/UploadConfig.php
app/Livewire/Project/Shared/UploadConfig.php
<?php namespace App\Livewire\Project\Shared; use App\Models\Application; use Livewire\Component; class UploadConfig extends Component { public $config; public $applicationId; public function mount() { if (isDev()) { $this->config = '{ "build_pack": "nixpacks", "base_directory": "/nodejs", "publish_directory": "/", "ports_exposes": "3000", "settings": { "is_static": false } }'; } } public function uploadConfig() { try { $application = Application::findOrFail($this->applicationId); $application->setConfig($this->config); $this->dispatch('success', 'Application settings updated'); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); return; } } public function render() { return view('livewire.project.shared.upload-config'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ExecuteContainerCommand.php
app/Livewire/Project/Shared/ExecuteContainerCommand.php
<?php namespace App\Livewire\Project\Shared; use App\Models\Application; use App\Models\Server; use App\Models\Service; use Illuminate\Support\Collection; use Livewire\Attributes\On; use Livewire\Component; class ExecuteContainerCommand extends Component { public $selected_container = 'default'; public Collection $containers; public $parameters; public $resource; public string $type; public Collection $servers; public bool $isConnecting = false; protected $rules = [ 'server' => 'required', 'container' => 'required', 'command' => 'required', ]; public function mount() { $this->parameters = get_route_parameters(); $this->containers = collect(); $this->servers = collect(); if (data_get($this->parameters, 'application_uuid')) { $this->type = 'application'; $this->resource = Application::where('uuid', $this->parameters['application_uuid'])->firstOrFail(); if ($this->resource->destination->server->isFunctional()) { $this->servers = $this->servers->push($this->resource->destination->server); } foreach ($this->resource->additional_servers as $server) { if ($server->isFunctional()) { $this->servers = $this->servers->push($server); } } $this->loadContainers(); } elseif (data_get($this->parameters, 'database_uuid')) { $this->type = 'database'; $resource = getResourceByUuid($this->parameters['database_uuid'], data_get(auth()->user()->currentTeam(), 'id')); if (is_null($resource)) { abort(404); } $this->resource = $resource; if ($this->resource->destination->server->isFunctional()) { $this->servers = $this->servers->push($this->resource->destination->server); } $this->loadContainers(); } elseif (data_get($this->parameters, 'service_uuid')) { $this->type = 'service'; $this->resource = Service::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->servers = $this->servers->push($this->resource); } $this->servers = $this->servers->sortByDesc(fn ($server) => $server->isTerminalEnabled()); } public function loadContainers() { foreach ($this->servers as $server) { if (data_get($this->parameters, 'application_uuid')) { if ($server->isSwarm()) { $containers = collect([ [ 'Names' => $this->resource->uuid.'_'.$this->resource->uuid, ], ]); } else { $containers = getCurrentApplicationContainerStatus($server, $this->resource->id, includePullrequests: true); } foreach ($containers as $container) { // if container state is running if (data_get($container, 'State') === 'running' && $server->isTerminalEnabled()) { $payload = [ 'server' => $server, 'container' => $container, ]; $this->containers = $this->containers->push($payload); } } } elseif (data_get($this->parameters, 'database_uuid')) { if ($this->resource->isRunning() && $server->isTerminalEnabled()) { $this->containers = $this->containers->push([ 'server' => $server, 'container' => [ 'Names' => $this->resource->uuid, ], ]); } } elseif (data_get($this->parameters, 'service_uuid')) { $this->resource->applications()->get()->each(function ($application) { if ($application->isRunning() && $this->resource->server->isTerminalEnabled()) { $this->containers->push([ 'server' => $this->resource->server, 'container' => [ 'Names' => data_get($application, 'name').'-'.data_get($this->resource, 'uuid'), ], ]); } }); $this->resource->databases()->get()->each(function ($database) { if ($database->isRunning()) { $this->containers->push([ 'server' => $this->resource->server, 'container' => [ 'Names' => data_get($database, 'name').'-'.data_get($this->resource, 'uuid'), ], ]); } }); } } // Sort containers alphabetically by name $this->containers = $this->containers->sortBy(function ($container) { return data_get($container, 'container.Names'); }); if ($this->containers->count() === 1) { $this->selected_container = data_get($this->containers->first(), 'container.Names'); } } public function updatedSelectedContainer() { if ($this->selected_container !== 'default') { $this->connectToContainer(); } } #[On('connectToServer')] public function connectToServer() { try { $server = $this->servers->first(); if ($server->isForceDisabled()) { throw new \RuntimeException('Server is disabled.'); } $this->dispatch( 'send-terminal-command', false, data_get($server, 'name'), data_get($server, 'uuid') ); // Dispatch a frontend event to ensure terminal gets focus after connection $this->dispatch('terminal-should-focus'); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->isConnecting = false; } } #[On('connectToContainer')] public function connectToContainer() { if ($this->selected_container === 'default') { $this->dispatch('error', 'Please select a container.'); return; } try { // Validate container name format if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $this->selected_container)) { 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.'); } // Verify server ownership and status $server = data_get($container, 'server'); if (! $server || ! $server instanceof Server) { throw new \RuntimeException('Invalid server configuration.'); } if ($server->isForceDisabled()) { throw new \RuntimeException('Server is disabled.'); } // Additional ownership verification based on resource type $resourceServer = match ($this->type) { 'application' => $this->resource->destination->server, 'database' => $this->resource->destination->server, 'service' => $this->resource->server, 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.'); } $this->dispatch( 'send-terminal-command', true, data_get($container, 'container.Names'), data_get($container, 'server.uuid') ); // Dispatch a frontend event to ensure terminal gets focus after connection $this->dispatch('terminal-should-focus'); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->isConnecting = false; } } public function render() { return view('livewire.project.shared.execute-container-command'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/HealthChecks.php
app/Livewire/Project/Shared/HealthChecks.php
<?php namespace App\Livewire\Project\Shared; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; class HealthChecks extends Component { use AuthorizesRequests; public $resource; // Explicit properties #[Validate(['boolean'])] public bool $healthCheckEnabled = false; #[Validate(['string'])] public string $healthCheckMethod; #[Validate(['string'])] public string $healthCheckScheme; #[Validate(['string'])] public string $healthCheckHost; #[Validate(['nullable', 'string'])] public ?string $healthCheckPort = null; #[Validate(['string'])] public string $healthCheckPath; #[Validate(['integer'])] public int $healthCheckReturnCode; #[Validate(['nullable', 'string'])] public ?string $healthCheckResponseText = null; #[Validate(['integer', 'min:1'])] public int $healthCheckInterval; #[Validate(['integer', 'min:1'])] public int $healthCheckTimeout; #[Validate(['integer', 'min:1'])] public int $healthCheckRetries; #[Validate(['integer'])] public int $healthCheckStartPeriod; #[Validate(['boolean'])] public bool $customHealthcheckFound = false; protected $rules = [ 'healthCheckEnabled' => 'boolean', 'healthCheckPath' => 'string', 'healthCheckPort' => 'nullable|string', 'healthCheckHost' => 'string', 'healthCheckMethod' => 'string', 'healthCheckReturnCode' => 'integer', 'healthCheckScheme' => 'string', 'healthCheckResponseText' => 'nullable|string', 'healthCheckInterval' => 'integer|min:1', 'healthCheckTimeout' => 'integer|min:1', 'healthCheckRetries' => 'integer|min:1', 'healthCheckStartPeriod' => 'integer', 'customHealthcheckFound' => 'boolean', ]; public function mount() { $this->authorize('view', $this->resource); $this->syncData(); } public function syncData(bool $toModel = false): void { if ($toModel) { $this->validate(); // Sync to model $this->resource->health_check_enabled = $this->healthCheckEnabled; $this->resource->health_check_method = $this->healthCheckMethod; $this->resource->health_check_scheme = $this->healthCheckScheme; $this->resource->health_check_host = $this->healthCheckHost; $this->resource->health_check_port = $this->healthCheckPort; $this->resource->health_check_path = $this->healthCheckPath; $this->resource->health_check_return_code = $this->healthCheckReturnCode; $this->resource->health_check_response_text = $this->healthCheckResponseText; $this->resource->health_check_interval = $this->healthCheckInterval; $this->resource->health_check_timeout = $this->healthCheckTimeout; $this->resource->health_check_retries = $this->healthCheckRetries; $this->resource->health_check_start_period = $this->healthCheckStartPeriod; $this->resource->custom_healthcheck_found = $this->customHealthcheckFound; $this->resource->save(); } else { // Sync from model $this->healthCheckEnabled = $this->resource->health_check_enabled; $this->healthCheckMethod = $this->resource->health_check_method; $this->healthCheckScheme = $this->resource->health_check_scheme; $this->healthCheckHost = $this->resource->health_check_host; $this->healthCheckPort = $this->resource->health_check_port; $this->healthCheckPath = $this->resource->health_check_path; $this->healthCheckReturnCode = $this->resource->health_check_return_code; $this->healthCheckResponseText = $this->resource->health_check_response_text; $this->healthCheckInterval = $this->resource->health_check_interval; $this->healthCheckTimeout = $this->resource->health_check_timeout; $this->healthCheckRetries = $this->resource->health_check_retries; $this->healthCheckStartPeriod = $this->resource->health_check_start_period; $this->customHealthcheckFound = $this->resource->custom_healthcheck_found; } } public function instantSave() { $this->authorize('update', $this->resource); // Sync component properties to model $this->resource->health_check_enabled = $this->healthCheckEnabled; $this->resource->health_check_method = $this->healthCheckMethod; $this->resource->health_check_scheme = $this->healthCheckScheme; $this->resource->health_check_host = $this->healthCheckHost; $this->resource->health_check_port = $this->healthCheckPort; $this->resource->health_check_path = $this->healthCheckPath; $this->resource->health_check_return_code = $this->healthCheckReturnCode; $this->resource->health_check_response_text = $this->healthCheckResponseText; $this->resource->health_check_interval = $this->healthCheckInterval; $this->resource->health_check_timeout = $this->healthCheckTimeout; $this->resource->health_check_retries = $this->healthCheckRetries; $this->resource->health_check_start_period = $this->healthCheckStartPeriod; $this->resource->custom_healthcheck_found = $this->customHealthcheckFound; $this->resource->save(); $this->dispatch('success', 'Health check updated.'); } public function submit() { try { $this->authorize('update', $this->resource); $this->validate(); // Sync component properties to model $this->resource->health_check_enabled = $this->healthCheckEnabled; $this->resource->health_check_method = $this->healthCheckMethod; $this->resource->health_check_scheme = $this->healthCheckScheme; $this->resource->health_check_host = $this->healthCheckHost; $this->resource->health_check_port = $this->healthCheckPort; $this->resource->health_check_path = $this->healthCheckPath; $this->resource->health_check_return_code = $this->healthCheckReturnCode; $this->resource->health_check_response_text = $this->healthCheckResponseText; $this->resource->health_check_interval = $this->healthCheckInterval; $this->resource->health_check_timeout = $this->healthCheckTimeout; $this->resource->health_check_retries = $this->healthCheckRetries; $this->resource->health_check_start_period = $this->healthCheckStartPeriod; $this->resource->custom_healthcheck_found = $this->customHealthcheckFound; $this->resource->save(); $this->dispatch('success', 'Health check updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function toggleHealthcheck() { try { $this->authorize('update', $this->resource); $wasEnabled = $this->healthCheckEnabled; $this->healthCheckEnabled = ! $this->healthCheckEnabled; // Sync component properties to model $this->resource->health_check_enabled = $this->healthCheckEnabled; $this->resource->health_check_method = $this->healthCheckMethod; $this->resource->health_check_scheme = $this->healthCheckScheme; $this->resource->health_check_host = $this->healthCheckHost; $this->resource->health_check_port = $this->healthCheckPort; $this->resource->health_check_path = $this->healthCheckPath; $this->resource->health_check_return_code = $this->healthCheckReturnCode; $this->resource->health_check_response_text = $this->healthCheckResponseText; $this->resource->health_check_interval = $this->healthCheckInterval; $this->resource->health_check_timeout = $this->healthCheckTimeout; $this->resource->health_check_retries = $this->healthCheckRetries; $this->resource->health_check_start_period = $this->healthCheckStartPeriod; $this->resource->custom_healthcheck_found = $this->customHealthcheckFound; $this->resource->save(); if ($this->healthCheckEnabled && ! $wasEnabled && $this->resource->isRunning()) { $this->dispatch('info', 'Health check has been enabled. A restart is required to apply the new settings.'); } else { $this->dispatch('success', 'Health check '.($this->healthCheckEnabled ? 'enabled' : 'disabled').'.'); } } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.shared.health-checks'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Terminal.php
app/Livewire/Project/Shared/Terminal.php
<?php namespace App\Livewire\Project\Shared; use App\Helpers\SshMultiplexingHelper; use App\Models\Server; use Livewire\Attributes\On; use Livewire\Component; class Terminal extends Component { public bool $hasShell = true; private function checkShellAvailability(Server $server, string $container): bool { $escapedContainer = escapeshellarg($container); try { instant_remote_process([ "docker exec {$escapedContainer} bash -c 'exit 0' 2>/dev/null || ". "docker exec {$escapedContainer} sh -c 'exit 0' 2>/dev/null", ], $server); return true; } catch (\Throwable) { return false; } } #[On('send-terminal-command')] public function sendTerminalCommand($isContainer, $identifier, $serverUuid) { $server = Server::ownedByCurrentTeam()->whereUuid($serverUuid)->firstOrFail(); if (! $server->isTerminalEnabled() || $server->isForceDisabled()) { abort(403, 'Terminal access is disabled on this server.'); } if ($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'); } // Verify container exists and belongs to the user's team $status = getContainerStatus($server, $identifier); if ($status !== 'running') { return; } // Check shell availability $this->hasShell = $this->checkShellAvailability($server, $identifier); if (! $this->hasShell) { return; } // Escape the identifier for shell usage $escapedIdentifier = escapeshellarg($identifier); $shellCommand = 'PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin && '. 'if [ -f ~/.profile ]; then . ~/.profile; fi && '. 'if [ -n "$SHELL" ] && [ -x "$SHELL" ]; then exec $SHELL; else sh; fi'; // Add sudo for non-root users to access Docker socket $dockerCommand = "docker exec -it {$escapedIdentifier} sh -c '{$shellCommand}'"; if ($server->isNonRoot()) { $dockerCommand = "sudo {$dockerCommand}"; } $command = SshMultiplexingHelper::generateSshCommand($server, $dockerCommand); } else { $shellCommand = 'PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin && '. 'if [ -f ~/.profile ]; then . ~/.profile; fi && '. 'if [ -n "$SHELL" ] && [ -x "$SHELL" ]; then exec $SHELL; else sh; fi'; $command = SshMultiplexingHelper::generateSshCommand($server, $shellCommand); } // ssh command is sent back to frontend then to websocket // this is done because the websocket connection is not available here // a better solution would be to remove websocket on NodeJS and work with something like // 1. Laravel Pusher/Echo connection (not possible without a sdk) // 2. Ratchet / Revolt / ReactPHP / Event Loop (possible but hard to implement and huge dependencies) // 3. Just found out about this https://github.com/sirn-se/websocket-php, perhaps it can be used // 4. Follow-up discussions here: // - https://github.com/coollabsio/coolify/issues/2298 // - https://github.com/coollabsio/coolify/discussions/3362 $this->dispatch('send-back-command', $command); } public function render() { return view('livewire.project.shared.terminal'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/GetLogs.php
app/Livewire/Project/Shared/GetLogs.php
<?php namespace App\Livewire\Project\Shared; use App\Helpers\SshMultiplexingHelper; use App\Models\Application; use App\Models\Server; use App\Models\Service; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; 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\Process; use Livewire\Component; class GetLogs extends Component { public string $outputs = ''; public string $errors = ''; public Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse|null $resource = null; public ServiceApplication|ServiceDatabase|null $servicesubtype = null; public Server $server; public ?string $container = null; public ?string $displayName = null; public ?string $pull_request = null; public ?bool $streamLogs = false; public ?bool $showTimeStamps = true; public ?int $numberOfLines = 100; public bool $expandByDefault = false; public bool $collapsible = true; public function mount() { if (! is_null($this->resource)) { if ($this->resource->getMorphClass() === \App\Models\Application::class) { $this->showTimeStamps = $this->resource->settings->is_include_timestamps; } else { if ($this->servicesubtype) { $this->showTimeStamps = $this->servicesubtype->is_include_timestamps; } else { $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(); } } } } public function instantSave() { if (! is_null($this->resource)) { if ($this->resource->getMorphClass() === \App\Models\Application::class) { $this->resource->settings->is_include_timestamps = $this->showTimeStamps; $this->resource->settings->save(); } if ($this->resource->getMorphClass() === \App\Models\Service::class) { $serviceName = str($this->container)->beforeLast('-')->value(); $subType = $this->resource->applications()->where('name', $serviceName)->first(); if ($subType) { $subType->is_include_timestamps = $this->showTimeStamps; $subType->save(); } else { $subType = $this->resource->databases()->where('name', $serviceName)->first(); if ($subType) { $subType->is_include_timestamps = $this->showTimeStamps; $subType->save(); } } } } } public function toggleTimestamps() { $previousValue = $this->showTimeStamps; $this->showTimeStamps = ! $this->showTimeStamps; try { $this->instantSave(); $this->getLogs(true); } catch (\Throwable $e) { // Revert the flag to its previous value on failure $this->showTimeStamps = $previousValue; return handleError($e, $this); } } public function toggleStreamLogs() { $this->streamLogs = ! $this->streamLogs; } public function getLogs($refresh = false) { if (! $this->server->isFunctional()) { return; } if (! $refresh && ! $this->expandByDefault && ($this->resource?->getMorphClass() === \App\Models\Service::class || str($this->container)->contains('-pr-'))) { return; } if ($this->numberOfLines <= 0 || is_null($this->numberOfLines)) { $this->numberOfLines = 1000; } if ($this->container) { if ($this->showTimeStamps) { if ($this->server->isSwarm()) { $command = "docker service logs -n {$this->numberOfLines} -t {$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} -t {$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); } } // Collect new logs into temporary variable first to prevent flickering // (avoids clearing output before new data is ready) $newOutputs = ''; Process::run($sshCommand, function (string $type, string $output) use (&$newOutputs) { $newOutputs .= removeAnsiColors($output); }); if ($this->showTimeStamps) { $newOutputs = str($newOutputs)->split('/\n/')->sort(function ($a, $b) { $a = explode(' ', $a); $b = explode(' ', $b); return $a[0] <=> $b[0]; })->join("\n"); } // Only update outputs after new data is ready (atomic update prevents flicker) $this->outputs = $newOutputs; } } public function copyLogs(): string { return sanitizeLogsForExport($this->outputs); } public function render() { return view('livewire.project.shared.get-logs'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ResourceOperations.php
app/Livewire/Project/Shared/ResourceOperations.php
<?php namespace App\Livewire\Project\Shared; use App\Actions\Database\StartDatabase; use App\Actions\Database\StopDatabase; use App\Actions\Service\StartService; use App\Actions\Service\StopService; use App\Jobs\VolumeCloneJob; use App\Models\Environment; use App\Models\Project; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; use Visus\Cuid2\Cuid2; class ResourceOperations extends Component { use AuthorizesRequests; public $resource; public $projectUuid; public $environmentUuid; public $projects; public $servers; public bool $cloneVolumeData = false; public function mount() { $parameters = get_route_parameters(); $this->projectUuid = data_get($parameters, 'project_uuid'); $this->environmentUuid = data_get($parameters, 'environment_uuid'); $this->projects = Project::ownedByCurrentTeamCached(); $this->servers = currentTeam()->servers->filter(fn ($server) => ! $server->isBuildServer()); } public function toggleVolumeCloning(bool $value) { $this->cloneVolumeData = $value; } public function cloneTo($destination_id) { $this->authorize('update', $this->resource); $new_destination = StandaloneDocker::find($destination_id); if (! $new_destination) { $new_destination = SwarmDocker::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) { $new_resource = clone_application($this->resource, $new_destination, ['uuid' => $uuid], $this->cloneVolumeData); $route = route('project.application.configuration', [ 'project_uuid' => $this->projectUuid, 'environment_uuid' => $this->environmentUuid, 'application_uuid' => $new_resource->uuid, ]).'#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 ) { $uuid = (string) new Cuid2; $new_resource = $this->resource->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'name' => $this->resource->name.'-clone-'.$uuid, 'status' => 'exited', 'started_at' => null, 'destination_id' => $new_destination->id, ]); $new_resource->save(); $tags = $this->resource->tags; foreach ($tags as $tag) { $new_resource->tags()->attach($tag->id); } $new_resource->persistentStorages()->delete(); $persistentVolumes = $this->resource->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $originalName = $volume->name; $newName = ''; if (str_starts_with($originalName, 'postgres-data-')) { $newName = 'postgres-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'mysql-data-')) { $newName = 'mysql-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'redis-data-')) { $newName = 'redis-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'clickhouse-data-')) { $newName = 'clickhouse-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'mariadb-data-')) { $newName = 'mariadb-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'mongodb-data-')) { $newName = 'mongodb-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'keydb-data-')) { $newName = 'keydb-data-'.$new_resource->uuid; } elseif (str_starts_with($originalName, 'dragonfly-data-')) { $newName = 'dragonfly-data-'.$new_resource->uuid; } else { if (str_starts_with($volume->name, $this->resource->uuid)) { $newName = str($volume->name)->replace($this->resource->uuid, $new_resource->uuid); } else { $newName = $new_resource->uuid.'-'.$volume->name; } } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $new_resource->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopDatabase::dispatch($this->resource); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $this->resource->destination->server; $targetServer = $new_resource->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartDatabase::dispatch($this->resource); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } $fileStorages = $this->resource->fileStorages()->get(); foreach ($fileStorages as $storage) { $newStorage = $storage->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resource_id' => $new_resource->id, ]); $newStorage->save(); } $scheduledBackups = $this->resource->scheduledBackups()->get(); foreach ($scheduledBackups as $backup) { $uuid = (string) new Cuid2; $newBackup = $backup->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'database_id' => $new_resource->id, 'database_type' => $new_resource->getMorphClass(), 'team_id' => currentTeam()->id, ]); $newBackup->save(); } $environmentVaribles = $this->resource->environment_variables()->get(); foreach ($environmentVaribles as $environmentVarible) { $payload = [ 'resourceable_id' => $new_resource->id, 'resourceable_type' => $new_resource->getMorphClass(), ]; $newEnvironmentVariable = $environmentVarible->replicate([ 'id', 'created_at', 'updated_at', ])->fill($payload); $newEnvironmentVariable->save(); } $route = route('project.database.configuration', [ 'project_uuid' => $this->projectUuid, 'environment_uuid' => $this->environmentUuid, 'database_uuid' => $new_resource->uuid, ]).'#resource-operations'; return redirect()->to($route); } elseif ($this->resource->type() === 'service') { $uuid = (string) new Cuid2; $new_resource = $this->resource->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => $uuid, 'name' => $this->resource->name.'-clone-'.$uuid, 'destination_id' => $new_destination->id, 'destination_type' => $new_destination->getMorphClass(), 'server_id' => $new_destination->server_id, // server_id is probably not needed anymore because of the new polymorphic relationships (here it is needed for clone to a different server to work - but maybe we can drop the column) ]); $new_resource->save(); $tags = $this->resource->tags; foreach ($tags as $tag) { $new_resource->tags()->attach($tag->id); } $scheduledTasks = $this->resource->scheduled_tasks()->get(); foreach ($scheduledTasks as $task) { $newTask = $task->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'uuid' => (string) new Cuid2, 'service_id' => $new_resource->id, 'team_id' => currentTeam()->id, ]); $newTask->save(); } $environmentVariables = $this->resource->environment_variables()->get(); foreach ($environmentVariables as $environmentVariable) { $newEnvironmentVariable = $environmentVariable->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'resourceable_id' => $new_resource->id, 'resourceable_type' => $new_resource->getMorphClass(), ]); $newEnvironmentVariable->save(); } foreach ($new_resource->applications() as $application) { $application->update([ 'status' => 'exited', ]); $persistentVolumes = $application->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $newName = ''; if (str_starts_with($volume->name, $volume->resource->uuid)) { $newName = str($volume->name)->replace($volume->resource->uuid, $application->uuid); } else { $newName = $application->uuid.'-'.str($volume->name)->afterLast('-'); } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $application->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopService::dispatch($application); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $application->service->destination->server; $targetServer = $new_resource->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartService::dispatch($application); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } } foreach ($new_resource->databases() as $database) { $database->update([ 'status' => 'exited', ]); $persistentVolumes = $database->persistentStorages()->get(); foreach ($persistentVolumes as $volume) { $newName = ''; if (str_starts_with($volume->name, $volume->resource->uuid)) { $newName = str($volume->name)->replace($volume->resource->uuid, $database->uuid); } else { $newName = $database->uuid.'-'.str($volume->name)->afterLast('-'); } $newPersistentVolume = $volume->replicate([ 'id', 'created_at', 'updated_at', ])->fill([ 'name' => $newName, 'resource_id' => $database->id, ]); $newPersistentVolume->save(); if ($this->cloneVolumeData) { try { StopService::dispatch($database->service); $sourceVolume = $volume->name; $targetVolume = $newPersistentVolume->name; $sourceServer = $database->service->destination->server; $targetServer = $new_resource->destination->server; VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume); StartService::dispatch($database->service); } catch (\Exception $e) { \Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage()); } } } } $new_resource->parse(); $route = route('project.service.configuration', [ 'project_uuid' => $this->projectUuid, 'environment_uuid' => $this->environmentUuid, 'service_uuid' => $new_resource->uuid, ]).'#resource-operations'; return redirect()->to($route); } } public function moveTo($environment_id) { try { $this->authorize('update', $this->resource); $new_environment = Environment::findOrFail($environment_id); $this->resource->update([ 'environment_id' => $environment_id, ]); if ($this->resource->type() === 'application') { $route = route('project.application.configuration', [ 'project_uuid' => $new_environment->project->uuid, 'environment_uuid' => $new_environment->uuid, 'application_uuid' => $this->resource->uuid, ]).'#resource-operations'; return redirect()->to($route); } elseif (str($this->resource->type())->startsWith('standalone-')) { $route = route('project.database.configuration', [ 'project_uuid' => $new_environment->project->uuid, 'environment_uuid' => $new_environment->uuid, 'database_uuid' => $this->resource->uuid, ]).'#resource-operations'; return redirect()->to($route); } elseif ($this->resource->type() === 'service') { $route = route('project.service.configuration', [ 'project_uuid' => $new_environment->project->uuid, 'environment_uuid' => $new_environment->uuid, 'service_uuid' => $this->resource->uuid, ]).'#resource-operations'; return redirect()->to($route); } } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.shared.resource-operations'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ResourceLimits.php
app/Livewire/Project/Shared/ResourceLimits.php
<?php namespace App\Livewire\Project\Shared; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class ResourceLimits extends Component { use AuthorizesRequests; public $resource; // Explicit properties public ?string $limitsCpus = null; public ?string $limitsCpuset = null; public ?int $limitsCpuShares = null; public string $limitsMemory; public string $limitsMemorySwap; public int $limitsMemorySwappiness; public string $limitsMemoryReservation; protected $rules = [ 'limitsMemory' => 'required|string', 'limitsMemorySwap' => 'required|string', 'limitsMemorySwappiness' => 'required|integer|min:0|max:100', 'limitsMemoryReservation' => 'required|string', 'limitsCpus' => 'nullable', 'limitsCpuset' => 'nullable', 'limitsCpuShares' => 'nullable', ]; protected $validationAttributes = [ 'limitsMemory' => 'memory', 'limitsMemorySwap' => 'swap', 'limitsMemorySwappiness' => 'swappiness', 'limitsMemoryReservation' => 'reservation', 'limitsCpus' => 'cpus', 'limitsCpuset' => 'cpuset', 'limitsCpuShares' => 'cpu shares', ]; /** * Sync data between component properties and model * * @param bool $toModel If true, sync FROM properties TO model. If false, sync FROM model TO properties. */ private function syncData(bool $toModel = false): void { if ($toModel) { // Sync TO model (before save) $this->resource->limits_cpus = $this->limitsCpus; $this->resource->limits_cpuset = $this->limitsCpuset; $this->resource->limits_cpu_shares = $this->limitsCpuShares; $this->resource->limits_memory = $this->limitsMemory; $this->resource->limits_memory_swap = $this->limitsMemorySwap; $this->resource->limits_memory_swappiness = $this->limitsMemorySwappiness; $this->resource->limits_memory_reservation = $this->limitsMemoryReservation; } else { // Sync FROM model (on load/refresh) $this->limitsCpus = $this->resource->limits_cpus; $this->limitsCpuset = $this->resource->limits_cpuset; $this->limitsCpuShares = $this->resource->limits_cpu_shares; $this->limitsMemory = $this->resource->limits_memory; $this->limitsMemorySwap = $this->resource->limits_memory_swap; $this->limitsMemorySwappiness = $this->resource->limits_memory_swappiness; $this->limitsMemoryReservation = $this->resource->limits_memory_reservation; } } public function mount() { $this->syncData(false); } public function submit() { try { $this->authorize('update', $this->resource); // Apply default values to properties if (! $this->limitsMemory) { $this->limitsMemory = '0'; } if (! $this->limitsMemorySwap) { $this->limitsMemorySwap = '0'; } if (is_null($this->limitsMemorySwappiness)) { $this->limitsMemorySwappiness = 60; } if (! $this->limitsMemoryReservation) { $this->limitsMemoryReservation = '0'; } if (! $this->limitsCpus) { $this->limitsCpus = '0'; } if ($this->limitsCpuset === '') { $this->limitsCpuset = null; } if (is_null($this->limitsCpuShares)) { $this->limitsCpuShares = 1024; } $this->validate(); $this->syncData(true); $this->resource->save(); $this->dispatch('success', 'Resource limits updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Danger.php
app/Livewire/Project/Shared/Danger.php
<?php namespace App\Livewire\Project\Shared; use App\Jobs\DeleteResourceJob; use App\Models\Service; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; use Visus\Cuid2\Cuid2; class Danger extends Component { use AuthorizesRequests; public $resource; public $resourceName; public $projectUuid; public $environmentUuid; public bool $delete_configurations = true; public bool $delete_volumes = true; public bool $docker_cleanup = true; public bool $delete_connected_networks = true; public ?string $modalId = null; public string $resourceDomain = ''; public bool $canDelete = false; public function mount() { $parameters = get_route_parameters(); $this->modalId = new Cuid2; $this->projectUuid = data_get($parameters, 'project_uuid'); $this->environmentUuid = data_get($parameters, 'environment_uuid'); if ($this->resource === null) { if (isset($parameters['service_uuid'])) { $this->resource = Service::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(); } } if ($this->resource === null) { $this->resourceName = 'Unknown Resource'; return; } if (! method_exists($this->resource, 'type')) { $this->resourceName = 'Unknown Resource'; return; } $this->resourceName = match ($this->resource->type()) { 'application' => $this->resource->name ?? 'Application', 'standalone-postgresql', 'standalone-redis', 'standalone-mongodb', 'standalone-mysql', 'standalone-mariadb', 'standalone-keydb', 'standalone-dragonfly', 'standalone-clickhouse' => $this->resource->name ?? 'Database', 'service' => $this->resource->name ?? 'Service', 'service-application' => $this->resource->name ?? 'Service Application', 'service-database' => $this->resource->name ?? 'Service Database', default => 'Unknown Resource', }; // Check if user can delete this resource try { $this->canDelete = auth()->user()->can('delete', $this->resource); } catch (\Exception $e) { $this->canDelete = false; } } public function delete($password) { if (! verifyPasswordConfirmation($password, $this)) { return; } if (! $this->resource) { $this->addError('resource', 'Resource not found.'); return; } try { $this->authorize('delete', $this->resource); $this->resource->delete(); DeleteResourceJob::dispatch( $this->resource, $this->delete_volumes, $this->delete_connected_networks, $this->delete_configurations, $this->docker_cleanup ); return redirectRoute($this, 'project.resource.index', [ 'project_uuid' => $this->projectUuid, 'environment_uuid' => $this->environmentUuid, ]); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.shared.danger', [ 'checkboxes' => [ ['id' => 'delete_volumes', 'label' => __('resource.delete_volumes')], ['id' => 'delete_connected_networks', 'label' => __('resource.delete_connected_networks')], ['id' => 'delete_configurations', 'label' => __('resource.delete_configurations')], ['id' => 'docker_cleanup', 'label' => __('resource.docker_cleanup')], // ['id' => 'delete_associated_backups_locally', 'label' => 'All backups associated with this Ressource will be permanently deleted from local storage.'], // ['id' => 'delete_associated_backups_s3', 'label' => 'All backups associated with this Ressource will be permanently deleted from the selected S3 Storage.'], // ['id' => 'delete_associated_backups_sftp', 'label' => 'All backups associated with this Ressource will be permanently deleted from the selected SFTP Storage.'] ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Destination.php
app/Livewire/Project/Shared/Destination.php
<?php namespace App\Livewire\Project\Shared; use App\Actions\Application\StopApplicationOneServer; use App\Actions\Docker\GetContainersStatus; use App\Events\ApplicationStatusChanged; use App\Models\Server; use App\Models\StandaloneDocker; use Illuminate\Support\Collection; use Livewire\Component; use Visus\Cuid2\Cuid2; class Destination extends Component { public $resource; public Collection $networks; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ApplicationStatusChanged" => 'loadData', "echo-private:team.{$teamId},ServiceStatusChanged" => 'mount', 'refresh' => 'mount', ]; } public function mount() { $this->networks = collect([]); $this->loadData(); } public function loadData() { $all_networks = collect([]); $all_networks = $all_networks->push($this->resource->destination); $all_networks = $all_networks->merge($this->resource->additional_networks); $this->networks = Server::isUsable()->get()->map(function ($server) { return $server->standaloneDockers; })->flatten(); $this->networks = $this->networks->reject(function ($network) use ($all_networks) { return $all_networks->pluck('id')->contains($network->id); }); $this->networks = $this->networks->reject(function ($network) { return $this->resource->destination->server->id == $network->server->id; }); if ($this->resource?->additional_servers?->count() > 0) { $this->networks = $this->networks->reject(function ($network) { return $this->resource->additional_servers->pluck('id')->contains($network->server->id); }); } } public function stop($serverId) { try { $server = Server::ownedByCurrentTeam()->findOrFail($serverId); StopApplicationOneServer::run($this->resource, $server); $this->refreshServers(); } catch (\Exception $e) { return handleError($e, $this); } } public function redeploy(int $network_id, int $server_id) { try { if ($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; } $deployment_uuid = new Cuid2; $server = Server::ownedByCurrentTeam()->findOrFail($server_id); $destination = $server->standaloneDockers->where('id', $network_id)->firstOrFail(); $result = queue_application_deployment( deployment_uuid: $deployment_uuid, application: $this->resource, server: $server, destination: $destination, only_this_server: true, no_questions_asked: true, ); if ($result['status'] === 'queue_full') { $this->dispatch('error', 'Deployment queue full', $result['message']); return; } if ($result['status'] === 'skipped') { $this->dispatch('success', 'Deployment skipped', $result['message']); return; } return redirectRoute($this, 'project.application.deployment.show', [ 'project_uuid' => data_get($this->resource, 'environment.project.uuid'), 'application_uuid' => data_get($this->resource, 'uuid'), 'deployment_uuid' => $deployment_uuid, 'environment_uuid' => data_get($this->resource, 'environment.uuid'), ]); } catch (\Exception $e) { return handleError($e, $this); } } public function promote(int $network_id, int $server_id) { $main_destination = $this->resource->destination; $this->resource->update([ 'destination_id' => $network_id, 'destination_type' => StandaloneDocker::class, ]); $this->resource->additional_networks()->detach($network_id, ['server_id' => $server_id]); $this->resource->additional_networks()->attach($main_destination->id, ['server_id' => $main_destination->server->id]); $this->refreshServers(); $this->resource->refresh(); } public function refreshServers() { GetContainersStatus::run($this->resource->destination->server); $this->loadData(); $this->dispatch('refresh'); } public function addServer(int $network_id, int $server_id) { $this->resource->additional_networks()->attach($network_id, ['server_id' => $server_id]); $this->dispatch('refresh'); } public function removeServer(int $network_id, int $server_id, $password) { try { if (! verifyPasswordConfirmation($password, $this)) { return; } if ($this->resource->destination->server->id == $server_id && $this->resource->destination->id == $network_id) { $this->dispatch('error', 'You are trying to remove the main server.'); return; } $server = Server::ownedByCurrentTeam()->findOrFail($server_id); StopApplicationOneServer::run($this->resource, $server); $this->resource->additional_networks()->detach($network_id, ['server_id' => $server_id]); $this->loadData(); $this->dispatch('refresh'); ApplicationStatusChanged::dispatch(data_get($this->resource, 'environment.project.team.id')); } catch (\Exception $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Metrics.php
app/Livewire/Project/Shared/Metrics.php
<?php namespace App\Livewire\Project\Shared; use Livewire\Component; class Metrics extends Component { public $resource; public $chartId = 'metrics'; public $data; public $categories; public int $interval = 5; public bool $poll = true; public function pollData() { if ($this->poll || $this->interval <= 10) { $this->loadData(); if ($this->interval > 10) { $this->poll = false; } } } public function loadData() { try { $cpuMetrics = $this->resource->getCpuMetrics($this->interval); $memoryMetrics = $this->resource->getMemoryMetrics($this->interval); $this->dispatch("refreshChartData-{$this->chartId}-cpu", [ 'seriesData' => $cpuMetrics, ]); $this->dispatch("refreshChartData-{$this->chartId}-memory", [ 'seriesData' => $memoryMetrics, ]); } catch (\Throwable $e) { return handleError($e, $this); } } public function setInterval() { if ($this->interval <= 10) { $this->poll = true; } $this->loadData(); } public function render() { return view('livewire.project.shared.metrics'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ScheduledTask/Add.php
app/Livewire/Project/Shared/ScheduledTask/Add.php
<?php namespace App\Livewire\Project\Shared\ScheduledTask; use App\Models\ScheduledTask; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Attributes\Locked; use Livewire\Component; class Add extends Component { use AuthorizesRequests; public $parameters; #[Locked] public string $id; #[Locked] public string $type; #[Locked] public Collection $containerNames; #[Locked] public $resource; public string $name; public string $command; public string $frequency; public ?string $container = ''; public int $timeout = 300; protected $rules = [ 'name' => 'required|string', 'command' => 'required|string', 'frequency' => 'required|string', 'container' => 'nullable|string', 'timeout' => 'required|integer|min:60|max:36000', ]; protected $validationAttributes = [ 'name' => 'name', 'command' => 'command', 'frequency' => 'frequency', 'container' => 'container', 'timeout' => 'timeout', ]; public function mount() { $this->parameters = get_route_parameters(); // Get the resource based on type and id switch ($this->type) { case 'application': $this->resource = \App\Models\Application::findOrFail($this->id); break; case 'service': $this->resource = \App\Models\Service::findOrFail($this->id); break; case 'standalone-postgresql': $this->resource = \App\Models\StandalonePostgresql::findOrFail($this->id); break; default: throw new \Exception('Invalid resource type'); } if ($this->containerNames->count() > 0) { $this->container = $this->containerNames->first(); } } public function submit() { try { $this->authorize('update', $this->resource); $this->validate(); $isValid = validate_cron_expression($this->frequency); if (! $isValid) { $this->dispatch('error', 'Invalid Cron / Human expression.'); return; } if (empty($this->container) || $this->container === 'null') { if ($this->type === 'service') { $this->container = $this->subServiceName; } } $this->saveScheduledTask(); $this->clear(); } catch (\Exception $e) { return handleError($e, $this); } } public function saveScheduledTask() { try { $task = new ScheduledTask; $task->name = $this->name; $task->command = $this->command; $task->frequency = $this->frequency; $task->container = $this->container; $task->timeout = $this->timeout; $task->team_id = currentTeam()->id; switch ($this->type) { case 'application': $task->application_id = $this->id; break; case 'standalone-postgresql': $task->standalone_postgresql_id = $this->id; break; case 'service': $task->service_id = $this->id; break; } $task->save(); $this->dispatch('refreshTasks'); $this->dispatch('success', 'Scheduled task added.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function clear() { $this->name = ''; $this->command = ''; $this->frequency = ''; $this->container = ''; $this->timeout = 300; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ScheduledTask/Executions.php
app/Livewire/Project/Shared/ScheduledTask/Executions.php
<?php namespace App\Livewire\Project\Shared\ScheduledTask; use App\Models\ScheduledTask; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Livewire\Attributes\Locked; use Livewire\Component; class Executions extends Component { public ScheduledTask $task; #[Locked] public int $taskId; #[Locked] public Collection $executions; #[Locked] public ?int $selectedKey = null; #[Locked] public ?string $serverTimezone = null; public $currentPage = 1; public $logsPerPage = 100; public $selectedExecution = null; public $isPollingActive = false; public function getListeners() { $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ScheduledTaskDone" => 'refreshExecutions', ]; } public function mount($taskId) { try { $this->taskId = $taskId; $this->task = ScheduledTask::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) { $this->serverTimezone = data_get($this->task, 'service.destination.server.settings.server_timezone'); } if (! $this->serverTimezone) { $this->serverTimezone = 'UTC'; } } catch (\Exception $e) { return handleError($e); } } public function refreshExecutions(): void { $this->executions = $this->task->executions()->take(20)->get(); if ($this->selectedKey) { $this->selectedExecution = $this->task->executions()->find($this->selectedKey); if ($this->selectedExecution && $this->selectedExecution->status !== 'running') { $this->isPollingActive = false; } } } public function selectTask($key): void { if ($key == $this->selectedKey) { $this->selectedKey = null; $this->selectedExecution = null; $this->currentPage = 1; $this->isPollingActive = false; return; } $this->selectedKey = $key; $this->selectedExecution = $this->task->executions()->find($key); $this->currentPage = 1; // Start polling if task is running if ($this->selectedExecution && $this->selectedExecution->status === 'running') { $this->isPollingActive = true; } } public function polling() { if ($this->selectedExecution && $this->isPollingActive) { $this->selectedExecution->refresh(); if ($this->selectedExecution->status !== 'running') { $this->isPollingActive = false; } } } public function loadMoreLogs() { $this->currentPage++; } public function loadAllLogs() { if (! $this->selectedExecution || ! $this->selectedExecution->message) { return; } $lines = collect(explode("\n", $this->selectedExecution->message)); $totalLines = $lines->count(); $totalPages = ceil($totalLines / $this->logsPerPage); $this->currentPage = $totalPages; } public function getLogLinesProperty() { if (! $this->selectedExecution) { return collect(); } if (! $this->selectedExecution->message) { return collect(['Waiting for task output...']); } $lines = collect(explode("\n", $this->selectedExecution->message)); return $lines->take($this->currentPage * $this->logsPerPage); } public function downloadLogs(int $executionId) { $execution = $this->executions->firstWhere('id', $executionId); if (! $execution) { return; } return response()->streamDownload(function () use ($execution) { echo $execution->message; }, 'task-execution-'.$execution->id.'.log'); } public function hasMoreLogs() { if (! $this->selectedExecution || ! $this->selectedExecution->message) { return false; } $lines = collect(explode("\n", $this->selectedExecution->message)); return $lines->count() > ($this->currentPage * $this->logsPerPage); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ScheduledTask/Show.php
app/Livewire/Project/Shared/ScheduledTask/Show.php
<?php namespace App\Livewire\Project\Shared\ScheduledTask; use App\Jobs\ScheduledTaskJob; use App\Models\Application; use App\Models\ScheduledTask; use App\Models\Service; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class Show extends Component { use AuthorizesRequests; public Application|Service $resource; public ScheduledTask $task; #[Locked] public array $parameters; #[Locked] public string $type; #[Validate(['boolean'])] public bool $isEnabled = false; #[Validate(['string', 'required'])] public string $name; #[Validate(['string', 'required'])] public string $command; #[Validate(['string', 'required'])] public string $frequency; #[Validate(['string', 'nullable'])] public ?string $container = null; #[Validate(['integer', 'required', 'min:60', 'max:36000'])] public $timeout = 300; #[Locked] public ?string $application_uuid; #[Locked] public ?string $service_uuid; #[Locked] public string $task_uuid; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => '$refresh', ]; } public function mount(string $task_uuid, string $project_uuid, string $environment_uuid, ?string $application_uuid = null, ?string $service_uuid = null) { try { $this->task_uuid = $task_uuid; if ($application_uuid) { $this->type = 'application'; $this->application_uuid = $application_uuid; $this->resource = Application::ownedByCurrentTeam()->where('uuid', $application_uuid)->firstOrFail(); } elseif ($service_uuid) { $this->type = 'service'; $this->service_uuid = $service_uuid; $this->resource = Service::ownedByCurrentTeamCached()->where('uuid', $service_uuid)->firstOrFail(); } $this->parameters = [ 'environment_uuid' => $environment_uuid, 'project_uuid' => $project_uuid, 'application_uuid' => $application_uuid, 'service_uuid' => $service_uuid, ]; $this->task = $this->resource->scheduled_tasks()->where('uuid', $task_uuid)->firstOrFail(); $this->syncData(); } catch (\Exception $e) { return handleError($e); } } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $isValid = validate_cron_expression($this->frequency); if (! $isValid) { $this->frequency = $this->task->frequency; throw new \Exception('Invalid Cron / Human expression.'); } $this->task->enabled = $this->isEnabled; $this->task->name = str($this->name)->trim()->value(); $this->task->command = str($this->command)->trim()->value(); $this->task->frequency = str($this->frequency)->trim()->value(); $this->task->container = str($this->container)->trim()->value(); $this->task->timeout = (int) $this->timeout; $this->task->save(); } else { $this->isEnabled = $this->task->enabled; $this->name = $this->task->name; $this->command = $this->task->command; $this->frequency = $this->task->frequency; $this->container = $this->task->container; $this->timeout = $this->task->timeout ?? 300; } } public function instantSave() { try { $this->authorize('update', $this->resource); $this->syncData(true); $this->dispatch('success', 'Scheduled task updated.'); $this->refreshTasks(); } catch (\Exception $e) { return handleError($e); } } public function submit() { try { $this->authorize('update', $this->resource); $this->syncData(true); $this->dispatch('success', 'Scheduled task updated.'); } catch (\Exception $e) { return handleError($e, $this); } } public function refreshTasks() { try { $this->task->refresh(); } catch (\Exception $e) { return handleError($e); } } public function delete() { try { $this->authorize('update', $this->resource); $this->task->delete(); if ($this->type === 'application') { return redirect()->route('project.application.scheduled-tasks.show', $this->parameters); } else { return redirect()->route('project.service.scheduled-tasks.show', $this->parameters); } } catch (\Exception $e) { return handleError($e); } } public function executeNow() { try { $this->authorize('update', $this->resource); ScheduledTaskJob::dispatch($this->task); $this->dispatch('success', 'Scheduled task executed.'); } catch (\Exception $e) { return handleError($e); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/ScheduledTask/All.php
app/Livewire/Project/Shared/ScheduledTask/All.php
<?php namespace App\Livewire\Project\Shared\ScheduledTask; use Illuminate\Support\Collection; use Livewire\Attributes\Locked; use Livewire\Attributes\On; use Livewire\Component; class All extends Component { #[Locked] public $resource; #[Locked] public array $parameters; public Collection $containerNames; public ?string $variables = null; public function mount() { $this->parameters = get_route_parameters(); if ($this->resource->type() === 'service') { $this->containerNames = $this->resource->applications()->pluck('name'); $this->containerNames = $this->containerNames->merge($this->resource->databases()->pluck('name')); } elseif ($this->resource->type() === 'application') { if ($this->resource->build_pack === 'dockercompose') { $parsed = $this->resource->parse(); $containers = collect(data_get($parsed, 'services'))->keys(); $this->containerNames = $containers; } else { $this->containerNames = collect([]); } } } #[On('refreshTasks')] public function refreshTasks() { $this->resource->refresh(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/EnvironmentVariable/Add.php
app/Livewire/Project/Shared/EnvironmentVariable/Add.php
<?php namespace App\Livewire\Project\Shared\EnvironmentVariable; use App\Models\Environment; use App\Models\Project; use App\Traits\EnvironmentVariableAnalyzer; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Computed; use Livewire\Component; class Add extends Component { use AuthorizesRequests, EnvironmentVariableAnalyzer; public $parameters; public bool $shared = false; public bool $is_preview = false; public string $key; public ?string $value = null; public bool $is_multiline = false; public bool $is_literal = false; public bool $is_runtime = true; public bool $is_buildtime = true; public array $problematicVariables = []; protected $listeners = ['clearAddEnv' => 'clear']; protected $rules = [ 'key' => 'required|string', 'value' => 'nullable', 'is_multiline' => 'required|boolean', 'is_literal' => 'required|boolean', 'is_runtime' => 'required|boolean', 'is_buildtime' => 'required|boolean', ]; protected $validationAttributes = [ 'key' => 'key', 'value' => 'value', 'is_multiline' => 'multiline', 'is_literal' => 'literal', 'is_runtime' => 'runtime', 'is_buildtime' => 'buildtime', ]; public function mount() { $this->parameters = get_route_parameters(); $this->problematicVariables = self::getProblematicVariablesForFrontend(); } #[Computed] public function availableSharedVariables(): array { $team = currentTeam(); $result = [ 'team' => [], 'project' => [], 'environment' => [], ]; // Early return if no team if (! $team) { return $result; } // Check if user can view team variables try { $this->authorize('view', $team); $result['team'] = $team->environment_variables() ->pluck('key') ->toArray(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view team variables } // Get project variables if we have a project_uuid in route $projectUuid = data_get($this->parameters, 'project_uuid'); if ($projectUuid) { $project = Project::where('team_id', $team->id) ->where('uuid', $projectUuid) ->first(); if ($project) { try { $this->authorize('view', $project); $result['project'] = $project->environment_variables() ->pluck('key') ->toArray(); // Get environment variables if we have an environment_uuid in route $environmentUuid = data_get($this->parameters, 'environment_uuid'); if ($environmentUuid) { $environment = $project->environments() ->where('uuid', $environmentUuid) ->first(); if ($environment) { try { $this->authorize('view', $environment); $result['environment'] = $environment->environment_variables() ->pluck('key') ->toArray(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view environment variables } } } } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view project variables } } } return $result; } public function submit() { $this->validate(); $this->dispatch('saveKey', [ 'key' => $this->key, 'value' => $this->value, 'is_multiline' => $this->is_multiline, 'is_literal' => $this->is_literal, 'is_runtime' => $this->is_runtime, 'is_buildtime' => $this->is_buildtime, 'is_preview' => $this->is_preview, ]); $this->clear(); } public function clear() { $this->key = ''; $this->value = ''; $this->is_multiline = false; $this->is_literal = false; $this->is_runtime = true; $this->is_buildtime = true; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
app/Livewire/Project/Shared/EnvironmentVariable/Show.php
<?php namespace App\Livewire\Project\Shared\EnvironmentVariable; use App\Models\Environment; use App\Models\EnvironmentVariable as ModelsEnvironmentVariable; use App\Models\Project; use App\Models\SharedEnvironmentVariable; use App\Traits\EnvironmentVariableAnalyzer; use App\Traits\EnvironmentVariableProtection; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Computed; use Livewire\Component; class Show extends Component { use AuthorizesRequests, EnvironmentVariableAnalyzer, EnvironmentVariableProtection; public $parameters; public ModelsEnvironmentVariable|SharedEnvironmentVariable $env; public bool $isDisabled = false; public bool $isLocked = false; public bool $isSharedVariable = false; public string $type; public string $key; public ?string $value = null; public ?string $real_value = null; public bool $is_shared = false; public bool $is_multiline = false; public bool $is_literal = false; public bool $is_shown_once = false; public bool $is_runtime = true; public bool $is_buildtime = true; public bool $is_required = false; public bool $is_really_required = false; public bool $is_redis_credential = false; public array $problematicVariables = []; protected $listeners = [ 'refreshEnvs' => 'refresh', 'refresh', 'compose_loaded' => '$refresh', ]; protected $rules = [ 'key' => 'required|string', 'value' => 'nullable', 'is_multiline' => 'required|boolean', 'is_literal' => 'required|boolean', 'is_shown_once' => 'required|boolean', 'is_runtime' => 'required|boolean', 'is_buildtime' => 'required|boolean', 'real_value' => 'nullable', 'is_required' => 'required|boolean', ]; public function mount() { $this->syncData(); if ($this->env->getMorphClass() === \App\Models\SharedEnvironmentVariable::class) { $this->isSharedVariable = true; } $this->parameters = get_route_parameters(); $this->checkEnvs(); if ($this->type === 'standalone-redis' && ($this->env->key === 'REDIS_PASSWORD' || $this->env->key === 'REDIS_USERNAME')) { $this->is_redis_credential = true; } $this->problematicVariables = self::getProblematicVariablesForFrontend(); } public function getResourceProperty() { return $this->env->resourceable ?? $this->env; } public function refresh() { $this->syncData(); $this->checkEnvs(); } public function syncData(bool $toModel = false) { if ($toModel) { if ($this->isSharedVariable) { $this->validate([ 'key' => 'required|string', 'value' => 'nullable', 'is_multiline' => 'required|boolean', 'is_literal' => 'required|boolean', 'is_shown_once' => 'required|boolean', 'real_value' => 'nullable', ]); } else { $this->validate(); $this->env->is_required = $this->is_required; $this->env->is_runtime = $this->is_runtime; $this->env->is_buildtime = $this->is_buildtime; $this->env->is_shared = $this->is_shared; } $this->env->key = $this->key; $this->env->value = $this->value; $this->env->is_multiline = $this->is_multiline; $this->env->is_literal = $this->is_literal; $this->env->is_shown_once = $this->is_shown_once; $this->env->save(); } else { $this->key = $this->env->key; $this->value = $this->env->value; $this->is_multiline = $this->env->is_multiline; $this->is_literal = $this->env->is_literal; $this->is_shown_once = $this->env->is_shown_once; $this->is_runtime = $this->env->is_runtime ?? true; $this->is_buildtime = $this->env->is_buildtime ?? true; $this->is_required = $this->env->is_required ?? false; $this->is_really_required = $this->env->is_really_required ?? false; $this->is_shared = $this->env->is_shared ?? false; $this->real_value = $this->env->real_value; } } public function checkEnvs() { $this->isDisabled = false; if (str($this->env->key)->startsWith('SERVICE_FQDN') || str($this->env->key)->startsWith('SERVICE_URL') || str($this->env->key)->startsWith('SERVICE_NAME')) { $this->isDisabled = true; } if ($this->env->is_shown_once) { $this->isLocked = true; } } public function serialize() { data_forget($this->env, 'real_value'); } public function lock() { $this->authorize('update', $this->env); $this->env->is_shown_once = true; if ($this->isSharedVariable) { unset($this->env->is_required); } $this->serialize(); $this->env->save(); $this->checkEnvs(); $this->dispatch('refreshEnvs'); } public function instantSave() { $this->submit(); } public function submit() { try { $this->authorize('update', $this->env); if (! $this->isSharedVariable && $this->is_required && str($this->value)->isEmpty()) { $oldValue = $this->env->getOriginal('value'); $this->value = $oldValue; $this->dispatch('error', 'Required environment variables cannot be empty.'); return; } $this->serialize(); $this->syncData(true); $this->syncData(false); $this->dispatch('success', 'Environment variable updated.'); $this->dispatch('envsUpdated'); $this->dispatch('configurationChanged'); } catch (\Exception $e) { return handleError($e); } } #[Computed] public function availableSharedVariables(): array { $team = currentTeam(); $result = [ 'team' => [], 'project' => [], 'environment' => [], ]; // Early return if no team if (! $team) { return $result; } // Check if user can view team variables try { $this->authorize('view', $team); $result['team'] = $team->environment_variables() ->pluck('key') ->toArray(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view team variables } // Get project variables if we have a project_uuid in route $projectUuid = data_get($this->parameters, 'project_uuid'); if ($projectUuid) { $project = Project::where('team_id', $team->id) ->where('uuid', $projectUuid) ->first(); if ($project) { try { $this->authorize('view', $project); $result['project'] = $project->environment_variables() ->pluck('key') ->toArray(); // Get environment variables if we have an environment_uuid in route $environmentUuid = data_get($this->parameters, 'environment_uuid'); if ($environmentUuid) { $environment = $project->environments() ->where('uuid', $environmentUuid) ->first(); if ($environment) { try { $this->authorize('view', $environment); $result['environment'] = $environment->environment_variables() ->pluck('key') ->toArray(); } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view environment variables } } } } catch (\Illuminate\Auth\Access\AuthorizationException $e) { // User not authorized to view project variables } } } return $result; } public function delete() { try { $this->authorize('delete', $this->env); // Check if the variable is used in Docker Compose if ($this->type === 'service' || $this->type === 'application' && $this->env->resourceable?->docker_compose) { [$isUsed, $reason] = $this->isEnvironmentVariableUsedInDockerCompose($this->env->key, $this->env->resourceable?->docker_compose); if ($isUsed) { $this->dispatch('error', "Cannot delete environment variable '{$this->env->key}' <br><br>Please remove it from the Docker Compose file first."); return; } } $this->env->delete(); $this->dispatch('environmentVariableDeleted'); $this->dispatch('success', 'Environment variable deleted successfully.'); } catch (\Exception $e) { return handleError($e); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/EnvironmentVariable/All.php
app/Livewire/Project/Shared/EnvironmentVariable/All.php
<?php namespace App\Livewire\Project\Shared\EnvironmentVariable; use App\Models\EnvironmentVariable; use App\Traits\EnvironmentVariableProtection; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class All extends Component { use AuthorizesRequests, EnvironmentVariableProtection; public $resource; public string $resourceClass; public bool $showPreview = false; public ?string $variables = null; public ?string $variablesPreview = null; public string $view = 'normal'; public bool $is_env_sorting_enabled = false; public bool $use_build_secrets = false; protected $listeners = [ 'saveKey' => 'submit', 'refreshEnvs', 'environmentVariableDeleted' => 'refreshEnvs', ]; public function mount() { $this->is_env_sorting_enabled = data_get($this->resource, 'settings.is_env_sorting_enabled', false); $this->use_build_secrets = data_get($this->resource, 'settings.use_build_secrets', false); $this->resourceClass = get_class($this->resource); $resourceWithPreviews = [\App\Models\Application::class]; $simpleDockerfile = filled(data_get($this->resource, 'dockerfile')); if (str($this->resourceClass)->contains($resourceWithPreviews) && ! $simpleDockerfile) { $this->showPreview = true; } $this->getDevView(); } public function instantSave() { try { $this->authorize('manageEnvironment', $this->resource); $this->resource->settings->is_env_sorting_enabled = $this->is_env_sorting_enabled; $this->resource->settings->use_build_secrets = $this->use_build_secrets; $this->resource->settings->save(); $this->getDevView(); $this->dispatch('success', 'Environment variable settings updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function getEnvironmentVariablesProperty() { if ($this->is_env_sorting_enabled === false) { return $this->resource->environment_variables()->orderBy('order')->get(); } return $this->resource->environment_variables; } public function getEnvironmentVariablesPreviewProperty() { if ($this->is_env_sorting_enabled === false) { return $this->resource->environment_variables_preview()->orderBy('order')->get(); } return $this->resource->environment_variables_preview; } public function getDevView() { $this->variables = $this->formatEnvironmentVariables($this->environmentVariables); if ($this->showPreview) { $this->variablesPreview = $this->formatEnvironmentVariables($this->environmentVariablesPreview); } } private function formatEnvironmentVariables($variables) { return $variables->map(function ($item) { if ($item->is_shown_once) { return "$item->key=(Locked Secret, delete and add again to change)"; } if ($item->is_multiline) { return "$item->key=(Multiline environment variable, edit in normal view)"; } return "$item->key=$item->value"; })->join("\n"); } public function switch() { $this->view = $this->view === 'normal' ? 'dev' : 'normal'; $this->getDevView(); } public function submit($data = null) { try { $this->authorize('manageEnvironment', $this->resource); if ($data === null) { $this->handleBulkSubmit(); } else { $this->handleSingleSubmit($data); } $this->updateOrder(); $this->getDevView(); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->refreshEnvs(); } } private function updateOrder() { $variables = parseEnvFormatToArray($this->variables); $order = 1; foreach ($variables as $key => $value) { $env = $this->resource->environment_variables()->where('key', $key)->first(); if ($env) { $env->order = $order; $env->save(); } $order++; } if ($this->showPreview) { $previewVariables = parseEnvFormatToArray($this->variablesPreview); $order = 1; foreach ($previewVariables as $key => $value) { $env = $this->resource->environment_variables_preview()->where('key', $key)->first(); if ($env) { $env->order = $order; $env->save(); } $order++; } } } private function handleBulkSubmit() { $variables = parseEnvFormatToArray($this->variables); $changesMade = false; $errorOccurred = false; // Try to delete removed variables $deletedCount = $this->deleteRemovedVariables(false, $variables); if ($deletedCount > 0) { $changesMade = true; } elseif ($deletedCount === 0 && $this->resource->environment_variables()->whereNotIn('key', array_keys($variables))->exists()) { // If we tried to delete but couldn't (due to Docker Compose), mark as error $errorOccurred = true; } // Update or create variables $updatedCount = $this->updateOrCreateVariables(false, $variables); if ($updatedCount > 0) { $changesMade = true; } if ($this->showPreview) { $previewVariables = parseEnvFormatToArray($this->variablesPreview); // Try to delete removed preview variables $deletedPreviewCount = $this->deleteRemovedVariables(true, $previewVariables); if ($deletedPreviewCount > 0) { $changesMade = true; } elseif ($deletedPreviewCount === 0 && $this->resource->environment_variables_preview()->whereNotIn('key', array_keys($previewVariables))->exists()) { // If we tried to delete but couldn't (due to Docker Compose), mark as error $errorOccurred = true; } // Update or create preview variables $updatedPreviewCount = $this->updateOrCreateVariables(true, $previewVariables); if ($updatedPreviewCount > 0) { $changesMade = true; } } // Only show success message if changes were actually made and no errors occurred if ($changesMade && ! $errorOccurred) { $this->dispatch('success', 'Environment variables updated.'); } } private function handleSingleSubmit($data) { $found = $this->resource->environment_variables()->where('key', $data['key'])->first(); if ($found) { $this->dispatch('error', 'Environment variable already exists.'); return; } $maxOrder = $this->resource->environment_variables()->max('order') ?? 0; $environment = $this->createEnvironmentVariable($data); $environment->order = $maxOrder + 1; $environment->save(); // Clear computed property cache to force refresh unset($this->environmentVariables); unset($this->environmentVariablesPreview); $this->dispatch('success', 'Environment variable added.'); } private function createEnvironmentVariable($data) { $environment = new EnvironmentVariable; $environment->key = $data['key']; $environment->value = $data['value']; $environment->is_multiline = $data['is_multiline'] ?? false; $environment->is_literal = $data['is_literal'] ?? false; $environment->is_runtime = $data['is_runtime'] ?? true; $environment->is_buildtime = $data['is_buildtime'] ?? true; $environment->is_preview = $data['is_preview'] ?? false; $environment->resourceable_id = $this->resource->id; $environment->resourceable_type = $this->resource->getMorphClass(); return $environment; } private function deleteRemovedVariables($isPreview, $variables) { $method = $isPreview ? 'environment_variables_preview' : 'environment_variables'; // Get all environment variables that will be deleted $variablesToDelete = $this->resource->$method()->whereNotIn('key', array_keys($variables))->get(); // If there are no variables to delete, return 0 if ($variablesToDelete->isEmpty()) { return 0; } // Check if any of these variables are used in Docker Compose if ($this->resource->type() === 'service' || $this->resource->build_pack === 'dockercompose') { foreach ($variablesToDelete as $envVar) { [$isUsed, $reason] = $this->isEnvironmentVariableUsedInDockerCompose($envVar->key, $this->resource->docker_compose); if ($isUsed) { $this->dispatch('error', "Cannot delete environment variable '{$envVar->key}' <br><br>Please remove it from the Docker Compose file first."); return 0; } } } // If we get here, no variables are used in Docker Compose, so we can delete them $this->resource->$method()->whereNotIn('key', array_keys($variables))->delete(); return $variablesToDelete->count(); } private function updateOrCreateVariables($isPreview, $variables) { $count = 0; foreach ($variables as $key => $value) { if (str($key)->startsWith('SERVICE_FQDN') || str($key)->startsWith('SERVICE_URL') || str($key)->startsWith('SERVICE_NAME')) { continue; } $method = $isPreview ? 'environment_variables_preview' : 'environment_variables'; $found = $this->resource->$method()->where('key', $key)->first(); if ($found) { if (! $found->is_shown_once && ! $found->is_multiline) { // Only count as a change if the value actually changed if ($found->value !== $value) { $found->value = $value; $found->save(); $count++; } } } else { $environment = new EnvironmentVariable; $environment->key = $key; $environment->value = $value; $environment->is_multiline = false; $environment->is_preview = $isPreview; $environment->resourceable_id = $this->resource->id; $environment->resourceable_type = $this->resource->getMorphClass(); $environment->save(); $count++; } } return $count; } public function refreshEnvs() { $this->resource->refresh(); // Clear computed property cache to force refresh unset($this->environmentVariables); unset($this->environmentVariablesPreview); $this->getDevView(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Storages/Show.php
app/Livewire/Project/Shared/Storages/Show.php
<?php namespace App\Livewire\Project\Shared\Storages; use App\Models\LocalPersistentVolume; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Show extends Component { use AuthorizesRequests; public LocalPersistentVolume $storage; public $resource; public bool $isReadOnly = false; public bool $isFirst = true; public bool $isService = false; public ?string $startedAt = null; // Explicit properties public string $name; public string $mountPath; public ?string $hostPath = null; protected $rules = [ 'name' => 'required|string', 'mountPath' => 'required|string', 'hostPath' => 'string|nullable', ]; protected $validationAttributes = [ 'name' => 'name', 'mountPath' => 'mount', 'hostPath' => 'host', ]; /** * Sync data between component properties and model * * @param bool $toModel If true, sync FROM properties TO model. If false, sync FROM model TO properties. */ private function syncData(bool $toModel = false): void { if ($toModel) { // Sync TO model (before save) $this->storage->name = $this->name; $this->storage->mount_path = $this->mountPath; $this->storage->host_path = $this->hostPath; } else { // Sync FROM model (on load/refresh) $this->name = $this->storage->name; $this->mountPath = $this->storage->mount_path; $this->hostPath = $this->storage->host_path; } } public function mount() { $this->syncData(false); $this->isReadOnly = $this->storage->shouldBeReadOnlyInUI(); } public function submit() { $this->authorize('update', $this->resource); $this->validate(); $this->syncData(true); $this->storage->save(); $this->dispatch('success', 'Storage updated successfully'); } public function delete($password) { $this->authorize('update', $this->resource); if (! verifyPasswordConfirmation($password, $this)) { return; } $this->storage->delete(); $this->dispatch('refreshStorages'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Shared/Storages/All.php
app/Livewire/Project/Shared/Storages/All.php
<?php namespace App\Livewire\Project\Shared\Storages; use Livewire\Component; class All extends Component { public $resource; protected $listeners = ['refreshStorages' => '$refresh']; public function getFirstStorageIdProperty() { if ($this->resource->persistentStorages->isEmpty()) { return null; } // Use the storage with the smallest ID as the "first" one // This ensures stability even when storages are deleted return $this->resource->persistentStorages->sortBy('id')->first()->id; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/Storage.php
app/Livewire/Project/Service/Storage.php
<?php namespace App\Livewire\Project\Service; use App\Models\LocalPersistentVolume; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Storage extends Component { use AuthorizesRequests; public $resource; public $fileStorage; public $isSwarm = false; public string $name = ''; public string $mount_path = ''; public ?string $host_path = null; public string $file_storage_path = ''; public ?string $file_storage_content = null; public string $file_storage_directory_source = ''; public string $file_storage_directory_destination = ''; public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},FileStorageChanged" => 'refreshStoragesFromEvent', 'refreshStorages', 'addNewVolume', ]; } public function mount() { if (str($this->resource->getMorphClass())->contains('Standalone')) { $this->file_storage_directory_source = database_configuration_dir()."/{$this->resource->uuid}"; } else { $this->file_storage_directory_source = application_configuration_dir()."/{$this->resource->uuid}"; } if ($this->resource->getMorphClass() === \App\Models\Application::class) { if ($this->resource->destination->server->isSwarm()) { $this->isSwarm = true; } } $this->refreshStorages(); } public function refreshStoragesFromEvent() { $this->refreshStorages(); $this->dispatch('warning', 'File storage changed. Usually it means that the file / directory is already defined on the server, so Coolify set it up for you properly on the UI.'); } public function refreshStorages() { $this->fileStorage = $this->resource->fileStorages()->get(); $this->resource->load('persistentStorages.resource'); } public function getFilesProperty() { return $this->fileStorage->where('is_directory', false); } public function getDirectoriesProperty() { return $this->fileStorage->where('is_directory', true); } public function getVolumeCountProperty() { return $this->resource->persistentStorages()->count(); } public function getFileCountProperty() { return $this->files->count(); } public function getDirectoryCountProperty() { return $this->directories->count(); } public function submitPersistentVolume() { try { $this->authorize('update', $this->resource); $this->validate([ 'name' => 'required|string', 'mount_path' => 'required|string', 'host_path' => $this->isSwarm ? 'required|string' : 'string|nullable', ]); $name = $this->resource->uuid.'-'.$this->name; LocalPersistentVolume::create([ 'name' => $name, 'mount_path' => $this->mount_path, 'host_path' => $this->host_path, 'resource_id' => $this->resource->id, 'resource_type' => $this->resource->getMorphClass(), ]); $this->resource->refresh(); $this->dispatch('success', 'Volume added successfully'); $this->dispatch('closeStorageModal', 'volume'); $this->clearForm(); $this->refreshStorages(); } catch (\Throwable $e) { return handleError($e, $this); } } public function submitFileStorage() { try { $this->authorize('update', $this->resource); $this->validate([ 'file_storage_path' => 'required|string', 'file_storage_content' => 'nullable|string', ]); $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) { $fs_path = application_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path; } elseif (str($this->resource->getMorphClass())->contains('Standalone')) { $fs_path = database_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path; } else { throw new \Exception('No valid resource type for file mount storage type!'); } \App\Models\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), ]); $this->dispatch('success', 'File mount added successfully'); $this->dispatch('closeStorageModal', 'file'); $this->clearForm(); $this->refreshStorages(); } catch (\Throwable $e) { return handleError($e, $this); } } public function submitFileStorageDirectory() { try { $this->authorize('update', $this->resource); $this->validate([ 'file_storage_directory_source' => 'required|string', 'file_storage_directory_destination' => 'required|string', ]); $this->file_storage_directory_source = trim($this->file_storage_directory_source); $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(); // Validate paths to prevent command injection validateShellSafePath($this->file_storage_directory_source, 'storage source path'); validateShellSafePath($this->file_storage_directory_destination, 'storage destination path'); \App\Models\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), ]); $this->dispatch('success', 'Directory mount added successfully'); $this->dispatch('closeStorageModal', 'directory'); $this->clearForm(); $this->refreshStorages(); } catch (\Throwable $e) { return handleError($e, $this); } } public function clearForm() { $this->name = ''; $this->mount_path = ''; $this->host_path = null; $this->file_storage_path = ''; $this->file_storage_content = null; $this->file_storage_directory_destination = ''; if (str($this->resource->getMorphClass())->contains('Standalone')) { $this->file_storage_directory_source = database_configuration_dir()."/{$this->resource->uuid}"; } else { $this->file_storage_directory_source = application_configuration_dir()."/{$this->resource->uuid}"; } } public function render() { return view('livewire.project.service.storage'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/Database.php
app/Livewire/Project/Service/Database.php
<?php namespace App\Livewire\Project\Service; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Models\ServiceDatabase; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\DB; use Livewire\Component; class Database extends Component { use AuthorizesRequests; public ServiceDatabase $database; public ?string $db_url_public = null; public $fileStorages; public $parameters; public ?string $humanName = null; public ?string $description = null; public ?string $image = null; public bool $excludeFromStatus = false; public ?int $publicPort = null; public bool $isPublic = false; public bool $isLogDrainEnabled = false; protected $listeners = ['refreshFileStorages']; protected $rules = [ 'humanName' => 'nullable', 'description' => 'nullable', 'image' => 'required', 'excludeFromStatus' => 'required|boolean', 'publicPort' => 'nullable|integer', 'isPublic' => 'required|boolean', 'isLogDrainEnabled' => 'required|boolean', ]; public function render() { return view('livewire.project.service.database'); } public function mount() { try { $this->parameters = get_route_parameters(); $this->authorize('view', $this->database); if ($this->database->is_public) { $this->db_url_public = $this->database->getServiceDatabaseUrl(); } $this->refreshFileStorages(); $this->syncData(false); } catch (\Throwable $e) { return handleError($e, $this); } } private function syncData(bool $toModel = false): void { if ($toModel) { $this->database->human_name = $this->humanName; $this->database->description = $this->description; $this->database->image = $this->image; $this->database->exclude_from_status = $this->excludeFromStatus; $this->database->public_port = $this->publicPort; $this->database->is_public = $this->isPublic; $this->database->is_log_drain_enabled = $this->isLogDrainEnabled; } else { $this->humanName = $this->database->human_name; $this->description = $this->database->description; $this->image = $this->database->image; $this->excludeFromStatus = $this->database->exclude_from_status ?? false; $this->publicPort = $this->database->public_port; $this->isPublic = $this->database->is_public ?? false; $this->isLogDrainEnabled = $this->database->is_log_drain_enabled ?? false; } } public function delete($password) { try { $this->authorize('delete', $this->database); if (! verifyPasswordConfirmation($password, $this)) { return; } $this->database->delete(); $this->dispatch('success', 'Database deleted.'); return redirectRoute($this, 'project.service.configuration', $this->parameters); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSaveExclude() { try { $this->authorize('update', $this->database); $this->submit(); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSaveLogDrain() { try { $this->authorize('update', $this->database); if (! $this->database->service->destination->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } $this->submit(); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function convertToApplication() { try { $this->authorize('update', $this->database); $service = $this->database->service; $serviceDatabase = $this->database; // Check if application with same name already exists if ($service->applications()->where('name', $serviceDatabase->name)->exists()) { throw new \Exception('An application with this name already exists.'); } // Create new parameters removing database_uuid $redirectParams = collect($this->parameters) ->except('database_uuid') ->all(); DB::transaction(function () use ($service, $serviceDatabase) { $service->applications()->create([ 'name' => $serviceDatabase->name, 'human_name' => $serviceDatabase->human_name, 'description' => $serviceDatabase->description, 'exclude_from_status' => $serviceDatabase->exclude_from_status, 'is_log_drain_enabled' => $serviceDatabase->is_log_drain_enabled, 'image' => $serviceDatabase->image, 'service_id' => $service->id, 'is_migrated' => true, ]); $serviceDatabase->delete(); }); return redirectRoute($this, 'project.service.configuration', $redirectParams); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSave() { try { $this->authorize('update', $this->database); if ($this->isPublic && ! $this->publicPort) { $this->dispatch('error', 'Public port is required.'); $this->isPublic = false; return; } $this->syncData(true); if ($this->database->is_public) { if (! str($this->database->status)->startsWith('running')) { $this->dispatch('error', 'Database must be started to be publicly accessible.'); $this->isPublic = false; $this->database->is_public = false; return; } StartDatabaseProxy::run($this->database); $this->db_url_public = $this->database->getServiceDatabaseUrl(); $this->dispatch('success', 'Database is now publicly accessible.'); } else { StopDatabaseProxy::run($this->database); $this->db_url_public = null; $this->dispatch('success', 'Database is no longer publicly accessible.'); } $this->submit(); } catch (\Throwable $e) { return handleError($e, $this); } } public function refreshFileStorages() { $this->fileStorages = $this->database->fileStorages()->get(); } public function submit() { try { $this->authorize('update', $this->database); $this->validate(); $this->syncData(true); $this->database->save(); $this->database->refresh(); $this->syncData(false); updateCompose($this->database); $this->dispatch('success', 'Database saved.'); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->dispatch('generateDockerCompose'); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/ServiceApplicationView.php
app/Livewire/Project/Service/ServiceApplicationView.php
<?php namespace App\Livewire\Project\Service; use App\Models\ServiceApplication; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\DB; use Livewire\Attributes\Validate; use Livewire\Component; use Spatie\Url\Url; class ServiceApplicationView extends Component { use AuthorizesRequests; public ServiceApplication $application; public $parameters; public $docker_cleanup = true; public $delete_volumes = true; public $domainConflicts = []; public $showDomainConflictModal = false; public $forceSaveDomains = false; public $showPortWarningModal = false; public $forceRemovePort = false; public $requiredPort = null; #[Validate(['nullable'])] public ?string $humanName = null; #[Validate(['nullable'])] public ?string $description = null; #[Validate(['nullable'])] public ?string $fqdn = null; #[Validate(['string', 'nullable'])] public ?string $image = null; #[Validate(['required', 'boolean'])] public bool $excludeFromStatus = false; #[Validate(['nullable', 'boolean'])] public bool $isLogDrainEnabled = false; #[Validate(['nullable', 'boolean'])] public bool $isGzipEnabled = false; #[Validate(['nullable', 'boolean'])] public bool $isStripprefixEnabled = false; protected $rules = [ 'humanName' => 'nullable', 'description' => 'nullable', 'fqdn' => 'nullable', 'image' => 'string|nullable', 'excludeFromStatus' => 'required|boolean', 'application.required_fqdn' => 'required|boolean', 'isLogDrainEnabled' => 'nullable|boolean', 'isGzipEnabled' => 'nullable|boolean', 'isStripprefixEnabled' => 'nullable|boolean', ]; public function instantSave() { try { $this->authorize('update', $this->application); $this->submit(); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSaveSettings() { try { $this->authorize('update', $this->application); // Save checkbox states without port validation $this->application->is_gzip_enabled = $this->isGzipEnabled; $this->application->is_stripprefix_enabled = $this->isStripprefixEnabled; $this->application->exclude_from_status = $this->excludeFromStatus; $this->application->save(); $this->dispatch('success', 'Settings saved.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSaveAdvanced() { try { $this->authorize('update', $this->application); if (! $this->application->service->destination->server->isLogDrainEnabled()) { $this->isLogDrainEnabled = false; $this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.'); return; } // Sync component properties to model $this->application->human_name = $this->humanName; $this->application->description = $this->description; $this->application->fqdn = $this->fqdn; $this->application->image = $this->image; $this->application->exclude_from_status = $this->excludeFromStatus; $this->application->is_log_drain_enabled = $this->isLogDrainEnabled; $this->application->is_gzip_enabled = $this->isGzipEnabled; $this->application->is_stripprefix_enabled = $this->isStripprefixEnabled; $this->application->save(); $this->dispatch('success', 'You need to restart the service for the changes to take effect.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function delete($password) { try { $this->authorize('delete', $this->application); if (! verifyPasswordConfirmation($password, $this)) { return; } $this->application->delete(); $this->dispatch('success', 'Application deleted.'); return redirect()->route('project.service.configuration', $this->parameters); } catch (\Throwable $e) { return handleError($e, $this); } } public function mount() { try { $this->parameters = get_route_parameters(); $this->authorize('view', $this->application); $this->requiredPort = $this->application->getRequiredPort(); $this->syncData(); } catch (\Throwable $e) { return handleError($e, $this); } } public function confirmRemovePort() { $this->forceRemovePort = true; $this->showPortWarningModal = false; $this->submit(); } public function cancelRemovePort() { $this->showPortWarningModal = false; $this->syncData(); // Reset to original FQDN } public function syncData(bool $toModel = false): void { if ($toModel) { $this->validate(); // Sync to model $this->application->human_name = $this->humanName; $this->application->description = $this->description; $this->application->fqdn = $this->fqdn; $this->application->image = $this->image; $this->application->exclude_from_status = $this->excludeFromStatus; $this->application->is_log_drain_enabled = $this->isLogDrainEnabled; $this->application->is_gzip_enabled = $this->isGzipEnabled; $this->application->is_stripprefix_enabled = $this->isStripprefixEnabled; $this->application->save(); } else { // Sync from model $this->humanName = $this->application->human_name; $this->description = $this->application->description; $this->fqdn = $this->application->fqdn; $this->image = $this->application->image; $this->excludeFromStatus = data_get($this->application, 'exclude_from_status', false); $this->isLogDrainEnabled = data_get($this->application, 'is_log_drain_enabled', false); $this->isGzipEnabled = data_get($this->application, 'is_gzip_enabled', true); $this->isStripprefixEnabled = data_get($this->application, 'is_stripprefix_enabled', true); } } public function convertToDatabase() { try { $this->authorize('update', $this->application); $service = $this->application->service; $serviceApplication = $this->application; // Check if database with same name already exists if ($service->databases()->where('name', $serviceApplication->name)->exists()) { throw new \Exception('A database with this name already exists.'); } $redirectParams = collect($this->parameters) ->except('database_uuid') ->all(); DB::transaction(function () use ($service, $serviceApplication) { $service->databases()->create([ 'name' => $serviceApplication->name, 'human_name' => $serviceApplication->human_name, 'description' => $serviceApplication->description, 'exclude_from_status' => $serviceApplication->exclude_from_status, 'is_log_drain_enabled' => $serviceApplication->is_log_drain_enabled, 'image' => $serviceApplication->image, 'service_id' => $service->id, 'is_migrated' => true, ]); $serviceApplication->delete(); }); return redirect()->route('project.service.configuration', $redirectParams); } catch (\Throwable $e) { return handleError($e, $this); } } public function confirmDomainUsage() { $this->forceSaveDomains = true; $this->showDomainConflictModal = false; $this->submit(); } public function submit() { try { $this->authorize('update', $this->application); $this->fqdn = str($this->fqdn)->replaceEnd(',', '')->trim()->toString(); $this->fqdn = str($this->fqdn)->replaceStart(',', '')->trim()->toString(); $domains = str($this->fqdn)->trim()->explode(',')->map(function ($domain) { $domain = trim($domain); Url::fromString($domain, ['http', 'https']); return str($domain)->lower(); }); $this->fqdn = $domains->unique()->implode(','); $warning = sslipDomainWarning($this->fqdn); if ($warning) { $this->dispatch('warning', __('warning.sslipdomain')); } // Sync to model for domain conflict check (without validation) $this->application->human_name = $this->humanName; $this->application->description = $this->description; $this->application->fqdn = $this->fqdn; $this->application->image = $this->image; $this->application->exclude_from_status = $this->excludeFromStatus; $this->application->is_log_drain_enabled = $this->isLogDrainEnabled; $this->application->is_gzip_enabled = $this->isGzipEnabled; $this->application->is_stripprefix_enabled = $this->isStripprefixEnabled; // Check for domain conflicts if not forcing save if (! $this->forceSaveDomains) { $result = checkDomainUsage(resource: $this->application); if ($result['hasConflicts']) { $this->domainConflicts = $result['conflicts']; $this->showDomainConflictModal = true; return; } } else { // Reset the force flag after using it $this->forceSaveDomains = false; } // Check for required port if (! $this->forceRemovePort) { $requiredPort = $this->application->getRequiredPort(); if ($requiredPort !== null) { // Check if all FQDNs have a port $fqdns = str($this->fqdn)->trim()->explode(','); $missingPort = false; foreach ($fqdns as $fqdn) { $fqdn = trim($fqdn); if (empty($fqdn)) { continue; } $port = ServiceApplication::extractPortFromUrl($fqdn); if ($port === null) { $missingPort = true; break; } } if ($missingPort) { $this->requiredPort = $requiredPort; $this->showPortWarningModal = true; return; } } } else { // Reset the force flag after using it $this->forceRemovePort = false; } $this->validate(); $this->application->save(); $this->application->refresh(); $this->syncData(); updateCompose($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.'); } $this->dispatch('generateDockerCompose'); } catch (\Throwable $e) { $originalFqdn = $this->application->getOriginal('fqdn'); if ($originalFqdn !== $this->application->fqdn) { $this->application->fqdn = $originalFqdn; $this->syncData(); } return handleError($e, $this); } } public function render() { return view('livewire.project.service.service-application-view', [ 'checkboxes' => [ ['id' => 'delete_volumes', 'label' => __('resource.delete_volumes')], ['id' => 'docker_cleanup', 'label' => __('resource.docker_cleanup')], // ['id' => 'delete_associated_backups_locally', 'label' => 'All backups associated with this Ressource will be permanently deleted from local storage.'], // ['id' => 'delete_associated_backups_s3', 'label' => 'All backups associated with this Ressource will be permanently deleted from the selected S3 Storage.'], // ['id' => 'delete_associated_backups_sftp', 'label' => 'All backups associated with this Ressource will be permanently deleted from the selected SFTP Storage.'] ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/Heading.php
app/Livewire/Project/Service/Heading.php
<?php namespace App\Livewire\Project\Service; use App\Actions\Docker\GetContainersStatus; use App\Actions\Service\StartService; use App\Actions\Service\StopService; use App\Enums\ProcessStatus; use App\Models\Service; use Illuminate\Support\Facades\Auth; use Livewire\Component; use Spatie\Activitylog\Models\Activity; class Heading extends Component { public Service $service; public array $parameters; public array $query; public $isDeploymentProgress = false; public $docker_cleanup = true; public $title = 'Configuration'; public function mount() { if (str($this->service->status)->contains('running') && is_null($this->service->config_hash)) { $this->service->isConfigurationChanged(true); $this->dispatch('configurationChanged'); } } public function getListeners() { $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceStatusChanged" => 'checkStatus', "echo-private:team.{$teamId},ServiceChecked" => 'serviceChecked', 'refresh' => '$refresh', 'envsUpdated' => '$refresh', ]; } public function checkStatus() { if ($this->service->server->isFunctional()) { GetContainersStatus::dispatch($this->service->server); } else { $this->dispatch('error', 'Server is not functional.'); } } public function manualCheckStatus() { $this->checkStatus(); } public function serviceChecked() { try { $this->service->applications->each(function ($application) { $application->refresh(); }); $this->service->databases->each(function ($database) { $database->refresh(); }); if (is_null($this->service->config_hash)) { $this->service->isConfigurationChanged(true); } $this->dispatch('configurationChanged'); } catch (\Exception $e) { return handleError($e, $this); } finally { $this->dispatch('refresh')->self(); } } public function checkDeployments() { try { $activity = Activity::where('properties->type_uuid', $this->service->uuid)->latest()->first(); $status = data_get($activity, 'properties.status'); if ($status === ProcessStatus::QUEUED->value || $status === ProcessStatus::IN_PROGRESS->value) { $this->isDeploymentProgress = true; } else { $this->isDeploymentProgress = false; } } catch (\Throwable) { $this->isDeploymentProgress = false; } return $this->isDeploymentProgress; } public function start() { $activity = StartService::run($this->service, pullLatestImages: true); $this->dispatch('activityMonitor', $activity->id); } public function forceDeploy() { try { $activities = Activity::where('properties->type_uuid', $this->service->uuid) ->where(function ($q) { $q->where('properties->status', ProcessStatus::IN_PROGRESS->value) ->orWhere('properties->status', ProcessStatus::QUEUED->value); })->get(); foreach ($activities as $activity) { $activity->properties->status = ProcessStatus::ERROR->value; $activity->save(); } $activity = StartService::run($this->service, pullLatestImages: true, stopBeforeStart: true); $this->dispatch('activityMonitor', $activity->id); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function stop() { try { StopService::dispatch($this->service, false, $this->docker_cleanup); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function restart() { $this->checkDeployments(); if ($this->isDeploymentProgress) { $this->dispatch('error', 'There is a deployment in progress.'); return; } $activity = StartService::run($this->service, stopBeforeStart: true); $this->dispatch('activityMonitor', $activity->id); } public function pullAndRestartEvent() { $this->checkDeployments(); if ($this->isDeploymentProgress) { $this->dispatch('error', 'There is a deployment in progress.'); return; } $activity = StartService::run($this->service, pullLatestImages: true, stopBeforeStart: true); $this->dispatch('activityMonitor', $activity->id); } public function render() { return view('livewire.project.service.heading', [ 'checkboxes' => [ ['id' => 'docker_cleanup', 'label' => __('resource.docker_cleanup')], ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/EditCompose.php
app/Livewire/Project/Service/EditCompose.php
<?php namespace App\Livewire\Project\Service; use App\Models\Service; use Livewire\Component; class EditCompose extends Component { public Service $service; public $serviceId; public ?string $dockerComposeRaw = null; public ?string $dockerCompose = null; public bool $isContainerLabelEscapeEnabled = false; protected $listeners = [ 'refreshEnvs', 'envsUpdated', 'refresh' => 'envsUpdated', ]; protected $rules = [ 'dockerComposeRaw' => 'required', 'dockerCompose' => 'required', 'isContainerLabelEscapeEnabled' => 'required', ]; public function envsUpdated() { $this->dispatch('saveCompose', $this->dockerComposeRaw); $this->refreshEnvs(); } public function refreshEnvs() { $this->service = Service::ownedByCurrentTeam()->find($this->serviceId); $this->syncData(false); } public function mount() { $this->service = Service::ownedByCurrentTeam()->find($this->serviceId); $this->syncData(false); } private function syncData(bool $toModel = false): void { if ($toModel) { $this->service->docker_compose_raw = $this->dockerComposeRaw; $this->service->docker_compose = $this->dockerCompose; $this->service->is_container_label_escape_enabled = $this->isContainerLabelEscapeEnabled; } else { $this->dockerComposeRaw = $this->service->docker_compose_raw; $this->dockerCompose = $this->service->docker_compose; $this->isContainerLabelEscapeEnabled = $this->service->is_container_label_escape_enabled ?? false; } } public function validateCompose() { $isValid = validateComposeFile($this->dockerComposeRaw, $this->service->server_id); if ($isValid !== 'OK') { $this->dispatch('error', "Invalid docker-compose file.\n$isValid"); } else { $this->dispatch('success', 'Docker compose is valid.'); } } public function saveEditedCompose() { $this->dispatch('info', 'Saving new docker compose...'); $this->dispatch('saveCompose', $this->dockerComposeRaw); $this->dispatch('refreshStorages'); } public function instantSave() { $this->validate([ 'isContainerLabelEscapeEnabled' => 'required', ]); $this->syncData(true); $this->service->save(['is_container_label_escape_enabled' => $this->isContainerLabelEscapeEnabled]); $this->dispatch('success', 'Service updated successfully'); } public function render() { return view('livewire.project.service.edit-compose'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/EditDomain.php
app/Livewire/Project/Service/EditDomain.php
<?php namespace App\Livewire\Project\Service; use App\Models\ServiceApplication; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; use Spatie\Url\Url; class EditDomain extends Component { use AuthorizesRequests; public $applicationId; public ServiceApplication $application; public $domainConflicts = []; public $showDomainConflictModal = false; public $forceSaveDomains = false; public $showPortWarningModal = false; public $forceRemovePort = false; public $requiredPort = null; #[Validate(['nullable'])] public ?string $fqdn = null; protected $rules = [ 'fqdn' => 'nullable', ]; public function mount() { $this->application = ServiceApplication::ownedByCurrentTeam()->findOrFail($this->applicationId); $this->authorize('view', $this->application); $this->requiredPort = $this->application->getRequiredPort(); $this->syncData(); } public function syncData(bool $toModel = false): void { if ($toModel) { $this->validate(); // Sync to model $this->application->fqdn = $this->fqdn; $this->application->save(); } else { // Sync from model $this->fqdn = $this->application->fqdn; } } public function confirmDomainUsage() { $this->forceSaveDomains = true; $this->showDomainConflictModal = false; $this->submit(); } public function confirmRemovePort() { $this->forceRemovePort = true; $this->showPortWarningModal = false; $this->submit(); } public function cancelRemovePort() { $this->showPortWarningModal = false; $this->syncData(); // Reset to original FQDN } public function submit() { try { $this->authorize('update', $this->application); $this->fqdn = str($this->fqdn)->replaceEnd(',', '')->trim()->toString(); $this->fqdn = str($this->fqdn)->replaceStart(',', '')->trim()->toString(); $domains = str($this->fqdn)->trim()->explode(',')->map(function ($domain) { $domain = trim($domain); Url::fromString($domain, ['http', 'https']); return str($domain)->lower(); }); $this->fqdn = $domains->unique()->implode(','); $warning = sslipDomainWarning($this->fqdn); if ($warning) { $this->dispatch('warning', __('warning.sslipdomain')); } // Sync to model for domain conflict check (without validation) $this->application->fqdn = $this->fqdn; // Check for domain conflicts if not forcing save if (! $this->forceSaveDomains) { $result = checkDomainUsage(resource: $this->application); if ($result['hasConflicts']) { $this->domainConflicts = $result['conflicts']; $this->showDomainConflictModal = true; return; } } else { // Reset the force flag after using it $this->forceSaveDomains = false; } // Check for required port if (! $this->forceRemovePort) { $requiredPort = $this->application->getRequiredPort(); if ($requiredPort !== null) { // Check if all FQDNs have a port $fqdns = str($this->fqdn)->trim()->explode(','); $missingPort = false; foreach ($fqdns as $fqdn) { $fqdn = trim($fqdn); if (empty($fqdn)) { continue; } $port = ServiceApplication::extractPortFromUrl($fqdn); if ($port === null) { $missingPort = true; break; } } if ($missingPort) { $this->requiredPort = $requiredPort; $this->showPortWarningModal = true; return; } } } else { // Reset the force flag after using it $this->forceRemovePort = false; } $this->validate(); $this->application->save(); $this->application->refresh(); $this->syncData(); updateCompose($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.'); } $this->application->service->parse(); $this->dispatch('refresh'); $this->dispatch('refreshServices'); $this->dispatch('configurationChanged'); } catch (\Throwable $e) { $originalFqdn = $this->application->getOriginal('fqdn'); if ($originalFqdn !== $this->application->fqdn) { $this->application->fqdn = $originalFqdn; $this->syncData(); } return handleError($e, $this); } } public function render() { return view('livewire.project.service.edit-domain'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/Configuration.php
app/Livewire/Project/Service/Configuration.php
<?php namespace App\Livewire\Project\Service; use App\Models\Service; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Livewire\Component; class Configuration extends Component { use AuthorizesRequests; public $currentRoute; public $project; public $environment; public ?Service $service = null; public $applications; public $databases; public array $query; public array $parameters; public function getListeners() { $teamId = Auth::user()->currentTeam()->id; return [ "echo-private:team.{$teamId},ServiceChecked" => 'serviceChecked', 'refreshServices' => 'refreshServices', 'refresh' => 'refreshServices', ]; } public function render() { return view('livewire.project.service.configuration'); } public function mount() { try { $this->parameters = get_route_parameters(); $this->currentRoute = request()->route()->getName(); $this->query = request()->query(); $project = currentTeam() ->projects() ->select('id', 'uuid', 'team_id') ->where('uuid', request()->route('project_uuid')) ->firstOrFail(); $environment = $project->environments() ->select('id', 'uuid', 'name', 'project_id') ->where('uuid', request()->route('environment_uuid')) ->firstOrFail(); $this->service = $environment->services()->whereUuid(request()->route('service_uuid'))->firstOrFail(); $this->authorize('view', $this->service); $this->project = $project; $this->environment = $environment; $this->applications = $this->service->applications->sort(); $this->databases = $this->service->databases->sort(); } catch (\Throwable $e) { return handleError($e, $this); } } public function refreshServices() { $this->service->refresh(); $this->applications = $this->service->applications->sort(); $this->databases = $this->service->databases->sort(); } public function restartApplication($id) { try { $this->authorize('update', $this->service); $application = $this->service->applications->find($id); if ($application) { $application->restart(); $this->dispatch('success', 'Service application restarted successfully.'); } } catch (\Exception $e) { return handleError($e, $this); } } public function restartDatabase($id) { try { $this->authorize('update', $this->service); $database = $this->service->databases->find($id); if ($database) { $database->restart(); $this->dispatch('success', 'Service database restarted successfully.'); } } catch (\Exception $e) { return handleError($e, $this); } } public function serviceChecked() { try { $this->service->applications->each(function ($application) { $application->refresh(); }); $this->service->databases->each(function ($database) { $database->refresh(); }); } catch (\Exception $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/FileStorage.php
app/Livewire/Project/Service/FileStorage.php
<?php namespace App\Livewire\Project\Service; use App\Models\Application; use App\Models\LocalFileVolume; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; 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\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Attributes\Validate; use Livewire\Component; class FileStorage extends Component { use AuthorizesRequests; public LocalFileVolume $fileStorage; public ServiceApplication|StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse|ServiceDatabase|Application $resource; public string $fs_path; public ?string $workdir = null; public bool $permanently_delete = true; public bool $isReadOnly = false; #[Validate(['nullable'])] public ?string $content = null; #[Validate(['required', 'boolean'])] public bool $isBasedOnGit = false; protected $rules = [ 'fileStorage.is_directory' => 'required', 'fileStorage.fs_path' => 'required', 'fileStorage.mount_path' => 'required', 'content' => 'nullable', 'isBasedOnGit' => 'required|boolean', ]; public function mount() { $this->resource = $this->fileStorage->service; if (str($this->fileStorage->fs_path)->startsWith('.')) { $this->workdir = $this->resource->service?->workdir(); $this->fs_path = str($this->fileStorage->fs_path)->after('.'); } else { $this->workdir = null; $this->fs_path = $this->fileStorage->fs_path; } $this->isReadOnly = $this->fileStorage->shouldBeReadOnlyInUI(); $this->syncData(); } public function syncData(bool $toModel = false): void { if ($toModel) { $this->validate(); // Sync to model $this->fileStorage->content = $this->content; $this->fileStorage->is_based_on_git = $this->isBasedOnGit; $this->fileStorage->save(); } else { // Sync from model $this->content = $this->fileStorage->content; $this->isBasedOnGit = $this->fileStorage->is_based_on_git; } } public function convertToDirectory() { try { $this->authorize('update', $this->resource); $this->fileStorage->deleteStorageOnServer(); $this->fileStorage->is_directory = true; $this->fileStorage->content = null; $this->fileStorage->is_based_on_git = false; $this->fileStorage->save(); $this->fileStorage->saveStorageOnServer(); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->dispatch('refreshStorages'); } } public function loadStorageOnServer() { try { // Loading content is a read operation, so we use 'view' permission $this->authorize('view', $this->resource); $this->fileStorage->loadStorageOnServer(); $this->syncData(); $this->dispatch('success', 'File storage loaded from server.'); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->dispatch('refreshStorages'); } } public function convertToFile() { try { $this->authorize('update', $this->resource); $this->fileStorage->deleteStorageOnServer(); $this->fileStorage->is_directory = false; $this->fileStorage->content = null; if (data_get($this->resource, 'settings.is_preserve_repository_enabled')) { $this->fileStorage->is_based_on_git = true; } $this->fileStorage->save(); $this->fileStorage->saveStorageOnServer(); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->dispatch('refreshStorages'); } } public function delete($password) { $this->authorize('update', $this->resource); if (! verifyPasswordConfirmation($password, $this)) { return; } try { $message = 'File deleted.'; if ($this->fileStorage->is_directory) { $message = 'Directory deleted.'; } if ($this->permanently_delete) { $message = 'Directory deleted from the server.'; $this->fileStorage->deleteStorageOnServer(); } $this->fileStorage->delete(); $this->dispatch('success', $message); } catch (\Throwable $e) { return handleError($e, $this); } finally { $this->dispatch('refreshStorages'); } } public function submit() { $this->authorize('update', $this->resource); $original = $this->fileStorage->getOriginal(); try { $this->validate(); if ($this->fileStorage->is_directory) { $this->content = null; } // Sync component properties to model $this->fileStorage->content = $this->content; $this->fileStorage->is_based_on_git = $this->isBasedOnGit; $this->fileStorage->save(); $this->fileStorage->saveStorageOnServer(); $this->dispatch('success', 'File updated.'); } catch (\Throwable $e) { $this->fileStorage->setRawAttributes($original); $this->fileStorage->save(); $this->syncData(); return handleError($e, $this); } } public function instantSave() { $this->submit(); } public function render() { return view('livewire.project.service.file-storage', [ 'directoryDeletionCheckboxes' => [ ['id' => 'permanently_delete', 'label' => 'The selected directory and all its contents will be permantely deleted form the server.'], ], 'fileDeletionCheckboxes' => [ ['id' => 'permanently_delete', 'label' => 'The selected file will be permanently deleted form the server.'], ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/StackForm.php
app/Livewire/Project/Service/StackForm.php
<?php namespace App\Livewire\Project\Service; use App\Models\Service; use App\Support\ValidationPatterns; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Livewire\Component; class StackForm extends Component { public Service $service; public Collection $fields; protected $listeners = ['saveCompose']; // Explicit properties public string $name; public ?string $description = null; public string $dockerComposeRaw; public ?string $dockerCompose = null; public ?bool $connectToDockerNetwork = null; protected function rules(): array { $baseRules = [ 'dockerComposeRaw' => 'required', 'dockerCompose' => 'nullable', 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), 'connectToDockerNetwork' => 'nullable', ]; // Add dynamic field rules foreach ($this->fields ?? collect() as $key => $field) { $rules = data_get($field, 'rules', 'nullable'); $baseRules["fields.$key.value"] = $rules; } return $baseRules; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', 'dockerComposeRaw.required' => 'The Docker Compose Raw field is required.', 'dockerCompose.required' => 'The Docker Compose field is required.', ] ); } public $validationAttributes = []; /** * Sync data between component properties and model * * @param bool $toModel If true, sync FROM properties TO model. If false, sync FROM model TO properties. */ private function syncData(bool $toModel = false): void { if ($toModel) { // Sync TO model (before save) $this->service->name = $this->name; $this->service->description = $this->description; $this->service->docker_compose_raw = $this->dockerComposeRaw; $this->service->docker_compose = $this->dockerCompose; $this->service->connect_to_docker_network = $this->connectToDockerNetwork; } else { // Sync FROM model (on load/refresh) $this->name = $this->service->name; $this->description = $this->service->description; $this->dockerComposeRaw = $this->service->docker_compose_raw; $this->dockerCompose = $this->service->docker_compose; $this->connectToDockerNetwork = $this->service->connect_to_docker_network; } } public function mount() { $this->syncData(false); $this->fields = collect([]); $extraFields = $this->service->extraFields(); foreach ($extraFields as $serviceName => $fields) { foreach ($fields as $fieldKey => $field) { $key = data_get($field, 'key'); $value = data_get($field, 'value'); $rules = data_get($field, 'rules', 'nullable'); $isPassword = data_get($field, 'isPassword', false); $customHelper = data_get($field, 'customHelper', false); $this->fields->put($key, [ 'serviceName' => $serviceName, 'key' => $key, 'name' => $fieldKey, 'value' => $value, 'isPassword' => $isPassword, 'rules' => $rules, 'customHelper' => $customHelper, ]); $this->validationAttributes["fields.$key.value"] = $fieldKey; } } $this->fields = $this->fields->groupBy('serviceName')->map(function ($group) { return $group->sortBy(function ($field) { return data_get($field, 'isPassword') ? 1 : 0; })->mapWithKeys(function ($field) { return [$field['key'] => $field]; }); })->flatMap(function ($group) { return $group; }); } public function saveCompose($raw) { $this->dockerComposeRaw = $raw; $this->submit(notify: true); } public function instantSave() { $this->syncData(true); $this->service->save(); $this->dispatch('success', 'Service settings saved.'); } public function submit($notify = true) { try { $this->validate(); $this->syncData(true); // Validate for command injection BEFORE any database operations validateDockerComposeForInjection($this->service->docker_compose_raw); // Use transaction to ensure atomicity - if parse fails, save is rolled back DB::transaction(function () { $this->service->save(); $this->service->saveExtraFields($this->fields); $this->service->parse(); }); // Refresh and write files after a successful commit $this->service->refresh(); $this->service->saveComposeConfigs(); $this->dispatch('refreshEnvs'); $this->dispatch('refreshServices'); $notify && $this->dispatch('success', 'Service saved.'); } catch (\Throwable $e) { // On error, refresh from database to restore clean state $this->service->refresh(); $this->syncData(false); return handleError($e, $this); } finally { if (is_null($this->service->config_hash)) { $this->service->isConfigurationChanged(true); } else { $this->dispatch('configurationChanged'); } } } public function render() { return view('livewire.project.service.stack-form'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Project/Service/Index.php
app/Livewire/Project/Service/Index.php
<?php namespace App\Livewire\Project\Service; use App\Models\Service; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Collection; use Livewire\Component; class Index extends Component { use AuthorizesRequests; public ?Service $service = null; public ?ServiceApplication $serviceApplication = null; public ?ServiceDatabase $serviceDatabase = null; public array $parameters; public array $query; public Collection $services; public $s3s; protected $listeners = ['generateDockerCompose', 'refreshScheduledBackups' => '$refresh']; public function mount() { try { $this->services = collect([]); $this->parameters = get_route_parameters(); $this->query = request()->query(); $this->service = Service::whereUuid($this->parameters['service_uuid'])->first(); if (! $this->service) { return redirect()->route('dashboard'); } $this->authorize('view', $this->service); $service = $this->service->applications()->whereUuid($this->parameters['stack_service_uuid'])->first(); if ($service) { $this->serviceApplication = $service; $this->serviceApplication->getFilesFromServer(); } else { $this->serviceDatabase = $this->service->databases()->whereUuid($this->parameters['stack_service_uuid'])->first(); $this->serviceDatabase->getFilesFromServer(); } $this->s3s = currentTeam()->s3s; } catch (\Throwable $e) { return handleError($e, $this); } } public function generateDockerCompose() { try { $this->authorize('update', $this->service); $this->service->parse(); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.project.service.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Tags/Deployments.php
app/Livewire/Tags/Deployments.php
<?php namespace App\Livewire\Tags; use App\Models\ApplicationDeploymentQueue; use Livewire\Component; class Deployments extends Component { public $deploymentsPerTagPerServer = []; public $resourceIds = []; public function render() { return view('livewire.tags.deployments'); } public function getDeployments() { try { $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $this->resourceIds)->get([ 'id', 'application_id', 'application_name', 'deployment_url', 'pull_request_id', 'server_name', 'server_id', 'status', ])->sortBy('id')->groupBy('server_name')->toArray(); $this->dispatch('deployments', $this->deploymentsPerTagPerServer); } catch (\Exception $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Tags/Show.php
app/Livewire/Tags/Show.php
<?php namespace App\Livewire\Tags; use App\Http\Controllers\Api\DeployController; use App\Models\ApplicationDeploymentQueue; use App\Models\Tag; use Illuminate\Support\Collection; use Livewire\Attributes\Locked; use Livewire\Attributes\Title; use Livewire\Component; #[Title('Tags | Coolify')] class Show extends Component { #[Locked] public ?string $tagName = null; #[Locked] public ?Collection $tags = null; #[Locked] public ?Tag $tag = null; #[Locked] public ?Collection $applications = null; #[Locked] public ?Collection $services = null; #[Locked] public ?string $webhook = null; #[Locked] public ?array $deploymentsPerTagPerServer = null; public function mount() { try { $this->tags = Tag::ownedByCurrentTeam()->get()->unique('name')->sortBy('name'); if (str($this->tagName)->isNotEmpty()) { $tag = $this->tags->where('name', $this->tagName)->first(); $this->webhook = generateTagDeployWebhook($tag->name); $this->applications = $tag->applications()->get(); $this->services = $tag->services()->get(); $this->tag = $tag; $this->getDeployments(); } } catch (\Exception $e) { return handleError($e, $this); } } public function getDeployments() { try { $resource_ids = $this->applications->pluck('id'); $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $resource_ids)->get([ 'id', 'application_id', 'application_name', 'deployment_url', 'pull_request_id', 'server_name', 'server_id', 'status', ])->sortBy('id')->groupBy('server_name')->toArray(); } catch (\Exception $e) { return handleError($e, $this); } } public function redeployAll() { try { $message = collect([]); $this->applications->each(function ($resource) use ($message) { $deploy = new DeployController; $message->push($deploy->deploy_resource($resource)); }); $this->services->each(function ($resource) use ($message) { $deploy = new DeployController; $message->push($deploy->deploy_resource($resource)); }); $this->dispatch('success', 'Mass deployment started.'); } catch (\Exception $e) { return handleError($e, $this); } } public function render() { return view('livewire.tags.show'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Subscription/PricingPlans.php
app/Livewire/Subscription/PricingPlans.php
<?php namespace App\Livewire\Subscription; use Illuminate\Support\Facades\Auth; use Livewire\Component; use Stripe\Checkout\Session; use Stripe\Stripe; class PricingPlans extends Component { public function subscribeStripe($type) { Stripe::setApiKey(config('subscription.stripe_api_key')); $priceId = match ($type) { 'dynamic-monthly' => config('subscription.stripe_price_id_dynamic_monthly'), 'dynamic-yearly' => config('subscription.stripe_price_id_dynamic_yearly'), default => config('subscription.stripe_price_id_dynamic_monthly'), }; if (! $priceId) { $this->dispatch('error', 'Price ID not found! Please contact the administrator.'); return; } $payload = [ 'allow_promotion_codes' => true, 'billing_address_collection' => 'required', 'client_reference_id' => Auth::id().':'.currentTeam()->id, 'line_items' => [[ 'price' => $priceId, 'adjustable_quantity' => [ 'enabled' => true, 'minimum' => 2, ], 'quantity' => 2, ]], 'tax_id_collection' => [ 'enabled' => true, ], 'automatic_tax' => [ 'enabled' => true, ], 'subscription_data' => [ 'metadata' => [ 'user_id' => Auth::id(), 'team_id' => currentTeam()->id, ], ], 'payment_method_collection' => 'if_required', 'mode' => 'subscription', 'success_url' => route('dashboard', ['success' => true]), 'cancel_url' => route('subscription.index', ['cancelled' => true]), ]; $customer = currentTeam()->subscription?->stripe_customer_id ?? null; if ($customer) { $payload['customer'] = $customer; $payload['customer_update'] = [ 'name' => 'auto', ]; } else { $payload['customer_email'] = Auth::user()->email; } $session = Session::create($payload); return redirect($session->url, 303); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Subscription/Actions.php
app/Livewire/Subscription/Actions.php
<?php namespace App\Livewire\Subscription; use App\Models\Team; use Livewire\Component; class Actions extends Component { public $server_limits = 0; public function mount() { $this->server_limits = Team::serverLimit(); } public function stripeCustomerPortal() { $session = getStripeCustomerPortalSession(currentTeam()); redirect($session->url); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Subscription/Show.php
app/Livewire/Subscription/Show.php
<?php namespace App\Livewire\Subscription; use Livewire\Component; class Show extends Component { public function mount() { if (! isCloud()) { return redirect()->route('dashboard'); } if (auth()->user()?->isMember()) { return redirect()->route('dashboard'); } if (! data_get(currentTeam(), 'subscription')) { return redirect()->route('subscription.index'); } } public function render() { return view('livewire.subscription.show'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Subscription/Index.php
app/Livewire/Subscription/Index.php
<?php namespace App\Livewire\Subscription; use App\Models\InstanceSettings; use App\Providers\RouteServiceProvider; use Livewire\Component; class Index extends Component { public InstanceSettings $settings; public bool $alreadySubscribed = false; public bool $isUnpaid = false; public bool $isCancelled = false; public bool $isMember = false; public bool $loading = true; public function mount() { if (! isCloud()) { return redirect(RouteServiceProvider::HOME); } if (auth()->user()?->isMember()) { $this->isMember = true; } if (data_get(currentTeam(), 'subscription') && isSubscriptionActive()) { return redirect()->route('subscription.show'); } $this->settings = instanceSettings(); $this->alreadySubscribed = currentTeam()->subscription()->exists(); if (! $this->alreadySubscribed) { $this->loading = false; } } public function stripeCustomerPortal() { $session = getStripeCustomerPortalSession(currentTeam()); if (is_null($session)) { return; } return redirect($session->url); } public function getStripeStatus() { try { $subscription = currentTeam()->subscription; $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $customer = $stripe->customers->retrieve(currentTeam()->subscription->stripe_customer_id); if ($customer) { $subscriptions = $stripe->subscriptions->all(['customer' => $customer->id]); $currentTeam = currentTeam()->id ?? null; if (count($subscriptions->data) > 0 && $currentTeam) { $foundSubscription = collect($subscriptions->data)->firstWhere('metadata.team_id', $currentTeam); if ($foundSubscription) { $status = data_get($foundSubscription, 'status'); $subscription->update([ 'stripe_subscription_id' => $foundSubscription->id, ]); if ($status === 'unpaid') { $this->isUnpaid = true; } } } if (count($subscriptions->data) === 0) { $this->isCancelled = true; } } } catch (\Exception $e) { // Log the error logger()->error('Stripe API error: '.$e->getMessage()); // Set a flag to show an error message to the user $this->addError('stripe', 'Could not retrieve subscription information. Please try again later.'); } finally { $this->loading = false; } } public function render() { return view('livewire.subscription.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Admin/Index.php
app/Livewire/Admin/Index.php
<?php namespace App\Livewire\Admin; 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 { public int $activeSubscribers; public int $inactiveSubscribers; public Collection $foundUsers; public string $search = ''; public function mount() { if (! isCloud() && ! isDev()) { return redirect()->route('dashboard'); } if (Auth::id() !== 0 && ! session('impersonating')) { return redirect()->route('dashboard'); } $this->getSubscribers(); } public function back() { if (session('impersonating')) { session()->forget('impersonating'); $user = User::find(0); $team_to_switch_to = $user->teams->first(); Auth::login($user); refreshSession($team_to_switch_to); return redirect(request()->header('Referer')); } } public function submitSearch() { if ($this->search !== '') { $this->foundUsers = User::where(function ($query) { $query->where('name', 'like', "%{$this->search}%") ->orWhere('email', 'like', "%{$this->search}%"); })->get(); } } public function getSubscribers() { $this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count(); $this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count(); } public function switchUser(int $user_id) { if (Auth::id() !== 0) { return redirect()->route('dashboard'); } session(['impersonating' => true]); $user = User::find($user_id); $team_to_switch_to = $user->teams->first(); // Cache::forget("team:{$user->id}"); Auth::login($user); refreshSession($team_to_switch_to); return redirect(request()->header('Referer')); } public function render() { return view('livewire.admin.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/InviteLink.php
app/Livewire/Team/InviteLink.php
<?php namespace App\Livewire\Team; use App\Models\TeamInvitation; use App\Models\User; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Livewire\Component; use Visus\Cuid2\Cuid2; class InviteLink extends Component { use AuthorizesRequests; public string $email; public string $role = 'member'; protected $rules = [ 'email' => 'required|email', 'role' => 'required|string', ]; public function mount() { $this->email = isDev() ? 'test3@example.com' : ''; } public function viaEmail() { $this->generateInviteLink(sendEmail: true); } public function viaLink() { $this->generateInviteLink(sendEmail: false); } private function generateInviteLink(bool $sendEmail = false) { try { $this->authorize('manageInvitations', currentTeam()); $this->validate(); // Prevent privilege escalation: users cannot invite someone with higher privileges $userRole = auth()->user()->role(); if ($userRole === 'member' && in_array($this->role, ['admin', 'owner'])) { throw new \Exception('Members cannot invite admins or owners.'); } if ($userRole === 'admin' && $this->role === 'owner') { throw new \Exception('Admins cannot invite owners.'); } $this->email = strtolower($this->email); $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; $user = User::whereEmail($this->email)->first(); if (is_null($user)) { $password = Str::password(); $user = User::create([ 'name' => str($this->email)->before('@'), 'email' => $this->email, 'password' => Hash::make($password), 'force_password_reset' => true, ]); $token = Crypt::encryptString("{$user->email}@@@$password"); $link = route('auth.link', ['token' => $token]); } $invitation = TeamInvitation::whereEmail($this->email)->first(); if (! is_null($invitation)) { $invitationValid = $invitation->isValid(); if ($invitationValid) { return handleError(livewire: $this, customErrorMessage: "Pending invitation already exists for $this->email."); } else { $invitation->delete(); } } $invitation = TeamInvitation::firstOrCreate([ 'team_id' => currentTeam()->id, 'uuid' => $uuid, 'email' => $this->email, 'role' => $this->role, 'link' => $link, 'via' => $sendEmail ? 'email' : 'link', ]); if ($sendEmail) { $mail = new MailMessage; $mail->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); $this->dispatch('success', 'Invitation sent via email.'); $this->dispatch('refreshInvitations'); return; } else { $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.'; } return handleError(error: $e, livewire: $this, customErrorMessage: $error_message); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Invitations.php
app/Livewire/Team/Invitations.php
<?php namespace App\Livewire\Team; use App\Models\TeamInvitation; use App\Models\User; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Invitations extends Component { use AuthorizesRequests; public $invitations; protected $listeners = ['refreshInvitations']; public function deleteInvitation(int $invitation_id) { try { $this->authorize('manageInvitations', currentTeam()); $invitation = TeamInvitation::ownedByCurrentTeam()->findOrFail($invitation_id); $user = User::whereEmail($invitation->email)->first(); if (filled($user)) { $user->deleteIfNotVerifiedAndForcePasswordReset(); } $invitation->delete(); $this->refreshInvitations(); $this->dispatch('success', 'Invitation revoked.'); } catch (\Exception) { return $this->dispatch('error', 'Invitation not found.'); } } public function refreshInvitations() { $this->invitations = TeamInvitation::ownedByCurrentTeam()->get(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/AdminView.php
app/Livewire/Team/AdminView.php
<?php namespace App\Livewire\Team; use App\Models\User; use Livewire\Component; class AdminView extends Component { public $users; public ?string $search = ''; public bool $lots_of_users = false; private $number_of_users_to_show = 20; public function mount() { if (! isInstanceAdmin()) { return redirect()->route('dashboard'); } $this->getUsers(); } public function submitSearch() { if ($this->search !== '') { $this->users = User::where(function ($query) { $query->where('name', 'like', "%{$this->search}%") ->orWhere('email', 'like', "%{$this->search}%"); })->get()->filter(function ($user) { return $user->id !== auth()->id(); }); } else { $this->getUsers(); } } public function getUsers() { $users = User::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); } else { $this->lots_of_users = false; $this->users = $users; } } public function delete($id, $password) { if (! isInstanceAdmin()) { return redirect()->route('dashboard'); } if (! verifyPasswordConfirmation($password, $this)) { return; } if (! auth()->user()->isInstanceAdmin()) { return $this->dispatch('error', 'You are not authorized to delete users'); } $user = User::find($id); if (! $user) { return $this->dispatch('error', 'User not found'); } try { $user->delete(); $this->getUsers(); } catch (\Exception $e) { return $this->dispatch('error', $e->getMessage()); } } public function render() { return view('livewire.team.admin-view'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Member.php
app/Livewire/Team/Member.php
<?php namespace App\Livewire\Team; use App\Enums\Role; use App\Models\User; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Cache; use Livewire\Component; class Member extends Component { use AuthorizesRequests; public User $member; public function makeAdmin() { try { $this->authorize('manageMembers', currentTeam()); 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.'); } $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::ADMIN->value]); $this->dispatch('reloadWindow'); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function makeOwner() { try { $this->authorize('manageMembers', currentTeam()); 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.'); } $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::OWNER->value]); $this->dispatch('reloadWindow'); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function makeReadonly() { try { $this->authorize('manageMembers', currentTeam()); 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.'); } $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::MEMBER->value]); $this->dispatch('reloadWindow'); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } public function remove() { try { $this->authorize('manageMembers', currentTeam()); 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.'); } $this->member->teams()->detach(currentTeam()); Cache::forget("team:{$this->member->id}"); Cache::remember('team:'.$this->member->id, 3600, function () { return $this->member->teams()->first(); }); $this->dispatch('reloadWindow'); } catch (\Exception $e) { $this->dispatch('error', $e->getMessage()); } } private function getMemberRole() { return $this->member->teams()->where('teams.id', currentTeam()->id)->first()?->pivot?->role; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Create.php
app/Livewire/Team/Create.php
<?php namespace App\Livewire\Team; use App\Models\Team; use App\Support\ValidationPatterns; use Livewire\Component; class Create extends Component { public string $name = ''; public ?string $description = null; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return ValidationPatterns::combinedMessages(); } public function submit() { try { $this->validate(); $team = Team::create([ 'name' => $this->name, 'description' => $this->description, 'personal_team' => false, ]); auth()->user()->teams()->attach($team, ['role' => 'admin']); refreshSession($team); return redirectRoute($this, 'team.index'); } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Index.php
app/Livewire/Team/Index.php
<?php namespace App\Livewire\Team; use App\Models\Team; use App\Models\TeamInvitation; use App\Support\ValidationPatterns; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Livewire\Component; class Index extends Component { use AuthorizesRequests; public $invitations = []; public Team $team; // Explicit properties public string $name; public ?string $description = null; protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), ]; } protected function messages(): array { return array_merge( ValidationPatterns::combinedMessages(), [ 'name.required' => 'The Name field is required.', 'name.regex' => 'The Name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().', 'description.regex' => 'The Description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.', ] ); } protected $validationAttributes = [ 'name' => 'name', 'description' => 'description', ]; /** * Sync data between component properties and model * * @param bool $toModel If true, sync FROM properties TO model. If false, sync FROM model TO properties. */ private function syncData(bool $toModel = false): void { if ($toModel) { // Sync TO model (before save) $this->team->name = $this->name; $this->team->description = $this->description; } else { // Sync FROM model (on load/refresh) $this->name = $this->team->name; $this->description = $this->team->description; } } public function mount() { $this->team = currentTeam(); $this->syncData(false); if (auth()->user()->isAdminFromSession()) { $this->invitations = TeamInvitation::whereTeamId(currentTeam()->id)->get(); } } public function render() { return view('livewire.team.index'); } public function submit() { $this->validate(); try { $this->authorize('update', $this->team); $this->syncData(true); $this->team->save(); refreshSession(); $this->dispatch('success', 'Team updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function delete() { $currentTeam = currentTeam(); $this->authorize('delete', $currentTeam); $currentTeam->delete(); $currentTeam->members->each(function ($user) use ($currentTeam) { if ($user->id === Auth::id()) { return; } $user->teams()->detach($currentTeam); $session = DB::table('sessions')->where('user_id', $user->id)->first(); if ($session) { DB::table('sessions')->where('id', $session->id)->delete(); } }); refreshSession(); return redirect()->route('team.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Member/Index.php
app/Livewire/Team/Member/Index.php
<?php namespace App\Livewire\Team\Member; use App\Models\TeamInvitation; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Livewire\Component; class Index extends Component { use AuthorizesRequests; public $invitations = []; public function mount() { // Only load invitations for users who can manage them if (auth()->user()->can('manageInvitations', currentTeam())) { $this->invitations = TeamInvitation::whereTeamId(currentTeam()->id)->get(); } } public function render() { return view('livewire.team.member.index'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Team/Storage/Show.php
app/Livewire/Team/Storage/Show.php
<?php namespace App\Livewire\Team\Storage; use App\Models\S3Storage; use Livewire\Component; class Show extends Component { public $storage = null; public function mount() { $this->storage = S3Storage::ownedByCurrentTeam()->whereUuid(request()->storage_uuid)->first(); if (! $this->storage) { abort(404); } } public function render() { return view('livewire.storage.show'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false