]> BookStack Code Mirror - bookstack/blob - app/Activity/Models/Comment.php
7d1c54646c1f6c8f77cdd80bb32be185a6fd760d
[bookstack] / app / Activity / Models / Comment.php
1 <?php
2
3 namespace BookStack\Activity\Models;
4
5 use BookStack\App\Model;
6 use BookStack\Users\Models\HasCreatorAndUpdater;
7 use BookStack\Util\HtmlContentFilter;
8 use Illuminate\Database\Eloquent\Factories\HasFactory;
9 use Illuminate\Database\Eloquent\Relations\BelongsTo;
10 use Illuminate\Database\Eloquent\Relations\MorphTo;
11
12 /**
13  * @property int      $id
14  * @property string   $text - Deprecated & now unused (#4821)
15  * @property string   $html
16  * @property int|null $parent_id  - Relates to local_id, not id
17  * @property int      $local_id
18  * @property string   $entity_type
19  * @property int      $entity_id
20  * @property int      $created_by
21  * @property int      $updated_by
22  */
23 class Comment extends Model implements Loggable
24 {
25     use HasFactory;
26     use HasCreatorAndUpdater;
27
28     protected $fillable = ['parent_id'];
29     protected $appends = ['created', 'updated'];
30
31     /**
32      * Get the entity that this comment belongs to.
33      */
34     public function entity(): MorphTo
35     {
36         return $this->morphTo('entity');
37     }
38
39     /**
40      * Get the parent comment this is in reply to (if existing).
41      */
42     public function parent(): BelongsTo
43     {
44         return $this->belongsTo(Comment::class, 'parent_id', 'local_id', 'parent')
45             ->where('entity_type', '=', $this->entity_type)
46             ->where('entity_id', '=', $this->entity_id);
47     }
48
49     /**
50      * Check if a comment has been updated since creation.
51      */
52     public function isUpdated(): bool
53     {
54         return $this->updated_at->timestamp > $this->created_at->timestamp;
55     }
56
57     /**
58      * Get created date as a relative diff.
59      */
60     public function getCreatedAttribute(): string
61     {
62         return $this->created_at->diffForHumans();
63     }
64
65     /**
66      * Get updated date as a relative diff.
67      */
68     public function getUpdatedAttribute(): string
69     {
70         return $this->updated_at->diffForHumans();
71     }
72
73     public function logDescriptor(): string
74     {
75         return "Comment #{$this->local_id} (ID: {$this->id}) for {$this->entity_type} (ID: {$this->entity_id})";
76     }
77
78     public function safeHtml(): string
79     {
80         return HtmlContentFilter::removeScriptsFromHtmlString($this->html ?? '');
81     }
82 }