3 namespace BookStack\Uploads;
5 use BookStack\Auth\Permissions\JointPermission;
6 use BookStack\Auth\Permissions\PermissionApplicator;
7 use BookStack\Auth\User;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Eloquent\Factories\HasFactory;
14 use Illuminate\Database\Eloquent\Relations\BelongsTo;
15 use Illuminate\Database\Eloquent\Relations\HasMany;
19 * @property string $name
20 * @property string $path
21 * @property string $extension
22 * @property ?Page $page
23 * @property bool $external
24 * @property int $uploaded_to
25 * @property User $updatedBy
26 * @property User $createdBy
28 * @method static Entity|Builder visible()
30 class Attachment extends Model
32 use HasCreatorAndUpdater;
35 protected $fillable = ['name', 'order'];
36 protected $hidden = ['path', 'page'];
42 * Get the downloadable file name for this upload.
44 public function getFileName(): string
46 if (str_contains($this->name, '.')) {
50 return $this->name . '.' . $this->extension;
54 * Get the page this file was uploaded to.
56 public function page(): BelongsTo
58 return $this->belongsTo(Page::class, 'uploaded_to');
61 public function jointPermissions(): HasMany
63 return $this->hasMany(JointPermission::class, 'entity_id', 'uploaded_to')
64 ->where('joint_permissions.entity_type', '=', 'page');
68 * Get the url of this file.
70 public function getUrl($openInline = false): string
72 if ($this->external && !str_starts_with($this->path, 'http')) {
76 return url('/attachments/' . $this->id . ($openInline ? '?open=true' : ''));
80 * Generate a HTML link to this attachment.
82 public function htmlLink(): string
84 return '<a target="_blank" href="' . e($this->getUrl()) . '">' . e($this->name) . '</a>';
88 * Generate a markdown link to this attachment.
90 public function markdownLink(): string
92 return '[' . $this->name . '](' . $this->getUrl() . ')';
96 * Scope the query to those attachments that are visible based upon related page permissions.
98 public function scopeVisible(): Builder
100 $permissions = app()->make(PermissionApplicator::class);
102 return $permissions->restrictPageRelationQuery(