]> BookStack Code Mirror - bookstack/blob - app/Uploads/Attachment.php
a470ec5346ccfc091642eee052d5e8022a28d40b
[bookstack] / app / Uploads / Attachment.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Model;
10 use BookStack\Traits\HasCreatorAndUpdater;
11 use Illuminate\Database\Eloquent\Builder;
12 use Illuminate\Database\Eloquent\Relations\BelongsTo;
13
14 /**
15  * @property int    $id
16  * @property string $name
17  * @property string $path
18  * @property string $extension
19  * @property ?Page  $page
20  * @property bool   $external
21  * @property int    $uploaded_to
22  * @property User   $updatedBy
23  * @property User   $createdBy
24  *
25  * @method static Entity|Builder visible()
26  */
27 class Attachment extends Model
28 {
29     use HasCreatorAndUpdater;
30
31     protected $fillable = ['name', 'order'];
32     protected $hidden = ['path', 'page'];
33     protected $casts = [
34         'external' => 'bool',
35     ];
36
37     /**
38      * Get the downloadable file name for this upload.
39      *
40      * @return mixed|string
41      */
42     public function getFileName()
43     {
44         if (strpos($this->name, '.') !== false) {
45             return $this->name;
46         }
47
48         return $this->name . '.' . $this->extension;
49     }
50
51     /**
52      * Get the page this file was uploaded to.
53      */
54     public function page(): BelongsTo
55     {
56         return $this->belongsTo(Page::class, 'uploaded_to');
57     }
58
59     /**
60      * Get the url of this file.
61      */
62     public function getUrl($openInline = false): string
63     {
64         if ($this->external && strpos($this->path, 'http') !== 0) {
65             return $this->path;
66         }
67
68         return url('/attachments/' . $this->id . ($openInline ? '?open=true' : ''));
69     }
70
71     /**
72      * Generate a HTML link to this attachment.
73      */
74     public function htmlLink(): string
75     {
76         return '<a target="_blank" href="' . e($this->getUrl()) . '">' . e($this->name) . '</a>';
77     }
78
79     /**
80      * Generate a markdown link to this attachment.
81      */
82     public function markdownLink(): string
83     {
84         return '[' . $this->name . '](' . $this->getUrl() . ')';
85     }
86
87     /**
88      * Scope the query to those attachments that are visible based upon related page permissions.
89      */
90     public function scopeVisible(): Builder
91     {
92         $permissionService = app()->make(PermissionService::class);
93
94         return $permissionService->filterRelatedEntity(
95             Page::class,
96             Attachment::query(),
97             'attachments',
98             'uploaded_to'
99         );
100     }
101 }