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