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 * @return mixed|string
46 public function getFileName()
48 if (strpos($this->name, '.') !== false) {
52 return $this->name . '.' . $this->extension;
56 * Get the page this file was uploaded to.
58 public function page(): BelongsTo
60 return $this->belongsTo(Page::class, 'uploaded_to');
63 public function jointPermissions(): HasMany
65 return $this->hasMany(JointPermission::class, 'entity_id', 'uploaded_to')
66 ->where('joint_permissions.entity_type', '=', 'page');
70 * Get the url of this file.
72 public function getUrl($openInline = false): string
74 if ($this->external && strpos($this->path, 'http') !== 0) {
78 return url('/attachments/' . $this->id . ($openInline ? '?open=true' : ''));
82 * Generate a HTML link to this attachment.
84 public function htmlLink(): string
86 return '<a target="_blank" href="' . e($this->getUrl()) . '">' . e($this->name) . '</a>';
90 * Generate a markdown link to this attachment.
92 public function markdownLink(): string
94 return '[' . $this->name . '](' . $this->getUrl() . ')';
98 * Scope the query to those attachments that are visible based upon related page permissions.
100 public function scopeVisible(): Builder
102 $permissions = app()->make(PermissionApplicator::class);
104 return $permissions->restrictPageRelationQuery(