Skip to content

Commit

Permalink
Delete attachments when model is deleted (fixes #445)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMicky-FR committed May 18, 2024
1 parent 9c0516d commit 0be2873
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 6 deletions.
2 changes: 1 addition & 1 deletion app/Azuriom.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Azuriom
*
* @var string
*/
private const VERSION = '1.1.9';
private const VERSION = '1.1.10';

/**
* Get the current version of Azuriom CMS.
Expand Down
11 changes: 11 additions & 0 deletions app/Http/Controllers/Admin/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,5 +216,16 @@ protected function validateRole(User $user, Role $role, User $target = null): vo
'role_id' => trans('admin.roles.unauthorized'),
]);
}

$adminUsers = User::whereHas('role', function (Builder $query) {
$query->where('is_admin', true);
});

// So many users lost access to the admin panel because they were the only admin
if (! $role->is_admin && $user->isAdmin() && $adminUsers->count() < 2) {
throw ValidationException::withMessages([
'role_id' => trans('admin.roles.no_admin'),
]);
}
}
}
3 changes: 1 addition & 2 deletions app/Http/Controllers/FallbackController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Azuriom\Models\Page;
use Azuriom\Models\Redirect;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class FallbackController extends Controller
{
Expand All @@ -14,7 +13,7 @@ class FallbackController extends Controller
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function get(Request $request, string $path)
public function get(string $path)
{
/** @var \Azuriom\Models\Redirect|null $redirect */
$redirect = Redirect::enabled()->firstWhere('source', $path);
Expand Down
10 changes: 10 additions & 0 deletions app/Models/Traits/Attachable.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use Illuminate\Support\Str;

/**
* Associate multiple attachments to a model.
*
* @property \Illuminate\Support\Collection|\Azuriom\Models\Attachment[] $attachments
*/
trait Attachable
Expand All @@ -34,6 +36,14 @@ public static function bootAttachable(): void
}
}
});

static::deleted(function (Model $model) {
$attachments = $model->attachments()->withTrashed()->get();

foreach ($attachments as $attachment) {
$attachment->setRelation('attachable', $model)->forceDelete();
}
});
}

public static function storePendingAttachment(string $pendingId, UploadedFile $file): string
Expand Down
44 changes: 44 additions & 0 deletions app/Models/Traits/AttachableParent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Azuriom\Models\Traits;

use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

/**
* Parent class for models that can have attachments.
* Used to automatically delete attachments from the associated children.
*/
trait AttachableParent
{
public static function bootAttachableParent(): void
{
$pendingDelete = [];

static::deleting(function (Model $model) use (&$pendingDelete) {
$children = $model->getAttribute(static::$attachableRelation ?? null);

if ($children !== null) {
// The relation can be either a collection or a single model
$pendingDelete[$model->getKey()] = collect($children->load([
'attachments' => fn (Builder $query) => $query->withTrashed(),
]));
}
});

static::deleted(function (Model $model) use (&$pendingDelete) {
$children = Arr::get($pendingDelete, $model->getKey(), []);

foreach ($children as $child) {
if ($child->fresh() !== null) {
continue; // Ensure the model is actually deleted
}

foreach ($child->attachments as $attachment) {
$attachment->setRelation('attachable', $child)->forceDelete();
}
}
});
}
}
1 change: 1 addition & 0 deletions resources/lang/en/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@
'unauthorized' => 'This role is higher than your own role.',
'add_admin' => 'You can\'t add the admin permission to a role.',
'remove_admin' => 'You can\'t remove the admin permission of your role.',
'no_admin' => 'There must be at least one other admin user to remove your admin role.',
'delete_default' => 'This role cannot be deleted.',
'delete_own' => 'You cannot delete your role.',

Expand Down
1 change: 1 addition & 0 deletions resources/lang/fr/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@
'unauthorized' => 'Ce grade est plus élevé que votre propre grade.',
'add_admin' => 'Vous ne pouvez pas mettre la permission administrateur à un grade.',
'remove_admin' => 'Vous ne pouvez pas retirer la permission admin de votre grade.',
'no_admin' => 'Il doit y avoir au moins un autre admin pour retirer votre grade admin.',
'delete_default' => 'Ce grade ne peut pas être supprimé.',
'delete_own' => 'Vous ne pouvez pas supprimer votre grade.',

Expand Down
5 changes: 3 additions & 2 deletions resources/views/admin/elements/editor.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
min_height: 200,
entity_encoding: 'raw',
plugins: 'searchreplace autolink code image link anchor lists table',
toolbar: 'formatselect | bold italic underline strikethrough forecolor | link image | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat code | undo redo',
toolbar: 'blocks | bold italic underline strikethrough forecolor | link image | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat code | undo redo',
relative_urls: false,
valid_children: "+body[style]",
extended_valid_elements: 'i[class]',
Expand All @@ -20,7 +20,6 @@
@endif
@isset($imagesUploadUrl)
paste_data_images: true,
images_upload_handler: function (blobInfo, progress) {
return new Promise(function (resolve, reject) {
const formData = new FormData();
Expand All @@ -42,6 +41,8 @@
});
});
},
@else
paste_data_images: false,
@endisset
});
</script>
Expand Down
2 changes: 1 addition & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,4 @@
Route::resource('posts.comments', PostCommentController::class)
->middleware(['auth', 'verified'])->only(['store', 'destroy']);

Route::get('/{path}', [FallbackController::class, 'get'])->where('path', '.*')->name('pages.show');
Route::get('/{path}', [FallbackController::class, 'get'])->where('path', '.*')->name('pages.show')->fallback();

0 comments on commit 0be2873

Please sign in to comment.