-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLibraryItem.php
More file actions
700 lines (598 loc) · 19.8 KB
/
LibraryItem.php
File metadata and controls
700 lines (598 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
<?php
namespace Tapp\FilamentLibrary\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Tapp\FilamentLibrary\FilamentLibraryPlugin;
use Tapp\FilamentLibrary\Models\Traits\BelongsToTenant;
/**
* @property int $id
* @property string $name
* @property string $slug
* @property string $type
* @property int|null $parent_id
* @property int $created_by
* @property int|null $updated_by
* @property string|null $external_url
* @property string|null $link_description
* @property string|null $general_access
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $deleted_at
* @property-read LibraryItem|null $parent
* @property-read Collection<int, LibraryItem> $children
* @property-read Model $creator
* @property-read Model|null $updater
* @property-read Collection<int, LibraryItemPermission> $permissions
* @property-read Collection<int, LibraryItemTag> $tags
*/
class LibraryItem extends Model implements HasMedia
{
use BelongsToTenant;
use HasFactory;
use InteractsWithMedia;
use SoftDeletes;
protected $fillable = [
'name',
'slug',
'type',
'parent_id',
'created_by',
'updated_by',
'external_url',
'link_description',
'general_access',
];
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
];
/**
* Boot the model.
*/
protected static function boot(): void
{
parent::boot();
static::creating(function (self $item) {
if (empty($item->slug)) {
$item->slug = static::generateUniqueSlug($item->name, $item->parent_id);
}
// Set created_by and updated_by on creation (like Laravel does with timestamps)
if (auth()->check()) {
$item->created_by = auth()->id();
$item->updated_by = auth()->id(); // Set both on creation
}
});
static::created(function (self $item) {
// Copy parent folder permissions to the new item
if ($item->parent_id && $item->parent) {
$parentPermissions = $item->parent->permissions()->get();
foreach ($parentPermissions as $permission) {
if (isset($permission->user_id) && isset($permission->role)) {
$item->permissions()->create([
'user_id' => $permission->user_id,
'role' => $permission->role,
]);
}
}
}
});
static::updating(function (self $item) {
if ($item->isDirty('name') && ! $item->isDirty('slug')) {
$item->slug = static::generateUniqueSlug($item->name, $item->parent_id, $item->id);
}
// Set updated_by on updates
if (auth()->check()) {
$item->updated_by = auth()->id();
}
});
}
/**
* Get the parent folder.
*/
public function parent(): BelongsTo
{
return $this->belongsTo(LibraryItem::class, 'parent_id');
}
/**
* Get the child items.
*/
public function children(): HasMany
{
return $this->hasMany(LibraryItem::class, 'parent_id');
}
/**
* Get the user who created this item.
*/
public function creator(): BelongsTo
{
$userModel = config('filament-library.user_model', config('auth.providers.users.model', 'App\\Models\\User'));
return $this->belongsTo($userModel, 'created_by')->withDefault(function ($instance) {
// Check if 'name' field exists
if (Schema::hasColumn('users', 'name')) {
$instance->name = 'Unknown User';
$instance->email = 'deleted@example.com';
} else {
// Fall back to first_name/last_name
$instance->first_name = 'Unknown';
$instance->last_name = 'User';
$instance->email = 'deleted@example.com';
}
});
}
/**
* Get the user who last updated this item.
*/
public function updater(): BelongsTo
{
$userModel = config('filament-library.user_model', config('auth.providers.users.model', 'App\\Models\\User'));
return $this->belongsTo($userModel, 'updated_by');
}
/**
* Get the permissions for this item.
*/
public function permissions(): HasMany
{
return $this->hasMany(LibraryItemPermission::class);
}
/**
* Scope to get only folders.
*/
public function scopeFolders($query)
{
return $query->where('type', 'folder');
}
/**
* Scope to get only files.
*/
public function scopeFiles($query)
{
return $query->where('type', 'file');
}
/**
* Scope to get only links.
*/
public function scopeLinks($query)
{
return $query->where('type', 'link');
}
/**
* Scope to get items accessible by a user.
*/
public function scopeForUser($query, $user)
{
return $query->where(function ($q) use ($user) {
$q->where('created_by', $user->id)
->orWhereHas('permissions', function ($permissionQuery) use ($user) {
$permissionQuery->where('user_id', $user->id);
});
});
}
/**
* Get the effective role for a user on this item.
*/
public function getEffectiveRole($user): ?string
{
if (! $user) {
return null;
}
// Check if user is the creator (always has access)
if ($this->created_by === $user->id) {
// Creator always has access, but check if they're also the owner
$currentOwner = $this->getCurrentOwner();
if ($currentOwner && $currentOwner->id === $user->id) {
return 'owner'; // Creator is also owner
}
return 'creator'; // Creator but not owner
}
// Check direct resource permissions
$directPermission = $this->permissions()
->where('user_id', $user->id)
->first();
if ($directPermission && isset($directPermission->role)) {
return $directPermission->role;
}
// Check inherited permissions from parent folders
if ($this->parent_id) {
return $this->parent->getEffectiveRole($user);
}
// Check general access
$effectiveGeneralAccess = $this->getEffectiveGeneralAccess();
if ($effectiveGeneralAccess === 'anyone_can_view') {
return 'viewer';
}
return null; // No access
}
/**
* Get the current owner of this item.
*/
public function getCurrentOwner(): ?Model
{
$ownerPermission = $this->permissions()
->where('role', 'owner')
->first();
if ($ownerPermission && $ownerPermission->user) {
return $ownerPermission->user;
}
// If no owner in permissions table, creator is the owner
return $this->creator;
}
/**
* Check if the creator is the current owner.
*/
public function isCreatorOwner(): bool
{
$currentOwner = $this->getCurrentOwner();
return $currentOwner && $currentOwner->id === $this->created_by;
}
/**
* Transfer ownership to another user.
*/
public function transferOwnership(Model $newOwner): void
{
// Remove existing owner permissions
$this->permissions()->where('role', 'owner')->delete();
// Check if the new owner already has a permission for this item
$existingPermission = $this->permissions()->where('user_id', $newOwner->id)->first();
if ($existingPermission) {
// Update existing permission to owner
$existingPermission->update(['role' => 'owner']);
} else {
// Create new owner permission
$this->permissions()->create([
'user_id' => $newOwner->id,
'role' => 'owner',
]);
}
}
/**
* Ensure a user has a personal folder (like Google Drive's "My Drive").
*/
public static function ensurePersonalFolder(Model $user): self
{
// Check if user already has a personal folder via the relationship
if ($user->personal_folder_id) {
$personalFolder = static::find($user->personal_folder_id);
if ($personalFolder) {
return $personalFolder;
}
}
// Create personal folder
$personalFolder = static::create([
'name' => static::getPersonalFolderName($user),
'type' => 'folder',
'parent_id' => null,
'created_by' => $user->id,
'updated_by' => $user->id,
'general_access' => 'private',
]);
// Set the user as owner of their personal folder
$personalFolder->permissions()->create([
'user_id' => $user->id,
'role' => 'owner',
]);
// Update the user's personal_folder_id
$user->update(['personal_folder_id' => $personalFolder->id]);
return $personalFolder;
}
/**
* Get a user's personal folder.
*/
public static function getPersonalFolder(Model $user): ?self
{
if (! $user->personal_folder_id) {
return null;
}
return static::find($user->personal_folder_id);
}
/**
* Generate the personal folder name for a user.
*/
public static function getPersonalFolderName(Model $user): string
{
// Try to get a display name from various user fields
$name = $user->first_name ?? $user->name ?? $user->email ?? 'User';
// Clean the name (remove special characters that might cause issues)
$name = preg_replace('/[^\w\s-]/', '', $name);
$name = trim($name);
// Fallback if name is empty
if (empty($name)) {
$name = 'User';
}
return $name . "'s Personal Folder";
}
/**
* Get the effective general access setting (resolves inheritance).
*/
public function getEffectiveGeneralAccess(): string
{
// Handle null values (existing records before migration)
if ($this->general_access === null || $this->general_access === 'inherit') {
// Inherit from parent
if ($this->parent_id) {
return $this->parent->getEffectiveGeneralAccess();
}
// Root level defaults to private
return 'private';
}
return $this->general_access;
}
/**
* Get the inherited general access value from parent (for display purposes).
*/
public function getInheritedGeneralAccess(): ?string
{
if (! $this->parent_id) {
return null;
}
return $this->parent->getEffectiveGeneralAccess();
}
/**
* Get the display text for inherited general access.
*/
public function getInheritedGeneralAccessDisplay(): ?string
{
$inherited = $this->getInheritedGeneralAccess();
if (! $inherited) {
return null;
}
$options = self::getGeneralAccessOptions();
return $options[$inherited] ?? $inherited;
}
/**
* Check if a user has a specific permission on this item.
*/
public function hasPermission($user, string $permission): bool
{
// Admin users always have all permissions
if ($user && FilamentLibraryPlugin::isLibraryAdmin($user)) {
return true;
}
$effectiveRole = $this->getEffectiveRole($user);
if (! $effectiveRole) {
return false;
}
return match ($permission) {
'view' => in_array($effectiveRole, ['viewer', 'editor', 'owner', 'creator']),
'edit' => in_array($effectiveRole, ['editor', 'owner', 'creator']),
'share' => in_array($effectiveRole, ['owner', 'creator']),
'delete' => in_array($effectiveRole, ['owner', 'creator']),
'upload' => in_array($effectiveRole, ['editor', 'owner', 'creator']),
'manage_permissions' => in_array($effectiveRole, ['owner', 'creator']),
default => false,
};
}
/**
* Check if a user can view this item (including anonymous access).
*/
public function canBeViewedBy($user = null): bool
{
// If user is logged in, check their effective role
if ($user) {
return $this->hasPermission($user, 'view');
}
// For anonymous users, check if general access allows viewing
$effectiveGeneralAccess = $this->getEffectiveGeneralAccess();
return $effectiveGeneralAccess === 'anyone_can_view';
}
/**
* Get the full path of this item.
*/
public function getPath(): string
{
$path = collect([$this->name]);
$parent = $this->parent;
while ($parent) {
$path->prepend($parent->name);
$parent = $parent->parent;
}
return $path->implode('/');
}
/**
* Get the file size for files.
*/
public function getSizeAttribute(): ?int
{
if ($this->type !== 'file') {
return null;
}
$media = $this->getFirstMedia('files');
return $media ? $media->size : null;
}
/**
* Check if the external URL is a video URL.
*/
public function isVideoUrl(): bool
{
if (! $this->external_url || $this->type !== 'link') {
return false;
}
$videoDomains = config('filament-library.video.supported_domains', [
'youtube.com',
'youtu.be',
'vimeo.com',
'wistia.com',
]);
foreach ($videoDomains as $domain) {
if (str_contains($this->external_url, $domain)) {
return true;
}
}
return false;
}
/**
* Get the appropriate display icon for this item.
*/
public function getDisplayIcon(): string
{
return match ($this->type) {
'folder' => 'heroicon-s-folder',
'file' => 'heroicon-o-document',
'link' => 'heroicon-o-link',
default => 'heroicon-o-document',
};
}
/**
* Register media collections.
*/
public function registerMediaCollections(): void
{
// Using default collection - no need to register custom collection
}
/**
* Register media conversions.
*/
public function registerMediaConversions(?Media $media = null): void
{
$this->addMediaConversion('thumb')
->width(300)
->height(300);
}
/**
* Get a secure URL for the file with temporary URL fallback.
*/
public function getSecureUrl(?int $expirationMinutes = null): string
{
$media = $this->getFirstMedia();
if (! $media) {
return '';
}
$expirationMinutes = $expirationMinutes ?? config('filament-library.url.temporary_expiration_minutes', 60);
try {
return $media->getTemporaryUrl(now()->addMinutes($expirationMinutes));
} catch (\Exception $e) {
$url = $media->getUrl();
// Ensure HTTPS for security
if (str_starts_with($url, 'http://')) {
$url = str_replace('http://', 'https://', $url);
}
return $url;
}
}
/**
* Generate a unique slug for the given name and parent.
*/
protected static function generateUniqueSlug(string $name, ?int $parentId = null, ?int $excludeId = null): string
{
$baseSlug = Str::slug($name);
$slug = $baseSlug;
$counter = 1;
// Check for existing slugs (including soft-deleted ones)
while (static::withTrashed()
->where('slug', $slug)
->where('parent_id', $parentId)
->when($excludeId, fn ($q) => $q->where('id', '!=', $excludeId))
->exists()) {
$slug = $baseSlug . '-' . $counter;
$counter++;
}
return $slug;
}
/**
* Get the access control options for the general access select.
*/
public static function getAccessControlOptions(): array
{
return [
'inherit' => 'Inherit from parent',
'private' => 'Private (owner only)',
'anyone_can_view' => 'Anyone can view',
];
}
/**
* Get the effective access control setting.
*/
public function getEffectiveAccessControl(): string
{
// If not inheriting, use the item's own setting
if ($this->general_access && $this->general_access !== 'inherit') {
return $this->general_access;
}
// If inheriting from parent, check parent's access control
if ($this->parent_id) {
return $this->parent->getEffectiveAccessControl();
}
// Root level items default to private
return 'private';
}
/**
* Get the general access options.
*/
public static function getGeneralAccessOptions(): array
{
return [
'inherit' => 'Inherit from parent',
'private' => 'Private (owner only)',
'anyone_can_view' => 'Anyone can view',
];
}
/**
* Get the tags for this library item.
*/
public function tags(): BelongsToMany
{
return $this->belongsToMany(LibraryItemTag::class, 'library_item_tag_pivot')
->withTimestamps();
}
/**
* Get the users who favorited this library item.
* Note: This uses a generic user model - projects should extend this
* or override this relationship in their own LibraryItem model.
*/
public function favoritedBy(): BelongsToMany
{
// Use a configurable user model or fallback to a generic approach
$userModel = config('filament-library.user_model', 'App\\Models\\User');
return $this->belongsToMany($userModel, 'library_item_favorites')
->withTimestamps();
}
/**
* Toggle favorite status for the current user.
*/
public function toggleFavorite(): void
{
if (auth()->check()) {
$user = auth()->user();
// Assuming the user model uses LibraryUser trait
// @phpstan-ignore-next-line
if ($user->favoriteLibraryItems()->where('library_item_id', $this->id)->exists()) {
// @phpstan-ignore-next-line
$user->favoriteLibraryItems()->detach($this->id);
} else {
// @phpstan-ignore-next-line
$user->favoriteLibraryItems()->attach($this->id);
}
}
}
/**
* Check if this item is favorited by the current user.
*/
public function isFavorite(): bool
{
if (! auth()->check()) {
return false;
}
$user = auth()->user();
// Assuming the user model uses LibraryUser trait
// @phpstan-ignore-next-line
return $user->favoriteLibraryItems()->where('library_item_id', $this->id)->exists();
}
/**
* Get the is_favorite attribute.
*/
public function getIsFavoriteAttribute(): bool
{
return $this->isFavorite();
}
}