]> BookStack Code Mirror - bookstack/blob - app/Uploads/Image.php
Tests: Updated comment test to account for new editor usage
[bookstack] / app / Uploads / Image.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\App\Model;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Permissions\Models\JointPermission;
8 use BookStack\Permissions\PermissionApplicator;
9 use BookStack\Users\Models\HasCreatorAndUpdater;
10 use Illuminate\Database\Eloquent\Builder;
11 use Illuminate\Database\Eloquent\Factories\HasFactory;
12 use Illuminate\Database\Eloquent\Relations\HasMany;
13
14 /**
15  * @property int    $id
16  * @property string $name
17  * @property string $url
18  * @property string $path
19  * @property string $type
20  * @property int    $uploaded_to
21  * @property int    $created_by
22  * @property int    $updated_by
23  */
24 class Image extends Model
25 {
26     use HasFactory;
27     use HasCreatorAndUpdater;
28
29     protected $fillable = ['name'];
30     protected $hidden = [];
31
32     public function jointPermissions(): HasMany
33     {
34         return $this->hasMany(JointPermission::class, 'entity_id', 'uploaded_to')
35             ->where('joint_permissions.entity_type', '=', 'page');
36     }
37
38     /**
39      * Scope the query to just the images visible to the user based upon the
40      * user visibility of the uploaded_to page.
41      */
42     public function scopeVisible(Builder $query): Builder
43     {
44         return app()->make(PermissionApplicator::class)->restrictPageRelationQuery($query, 'images', 'uploaded_to');
45     }
46
47     /**
48      * Get a thumbnail URL for this image.
49      * Attempts to generate the thumbnail if not already existing.
50      *
51      * @throws \Exception
52      */
53     public function getThumb(?int $width, ?int $height, bool $keepRatio = false): ?string
54     {
55         return app()->make(ImageResizer::class)->resizeToThumbnailUrl($this, $width, $height, $keepRatio, false);
56     }
57
58     /**
59      * Get the page this image has been uploaded to.
60      * Only applicable to gallery or drawio image types.
61      */
62     public function getPage(): ?Page
63     {
64         return $this->belongsTo(Page::class, 'uploaded_to')->first();
65     }
66 }