]> BookStack Code Mirror - bookstack/blob - app/Actions/View.php
Added prevention of nested chapters on sort
[bookstack] / app / Actions / View.php
1 <?php
2
3 namespace BookStack\Actions;
4
5 use BookStack\Auth\Permissions\JointPermission;
6 use BookStack\Interfaces\Viewable;
7 use BookStack\Model;
8 use Illuminate\Database\Eloquent\Relations\HasMany;
9 use Illuminate\Database\Eloquent\Relations\MorphTo;
10
11 /**
12  * Class View
13  * Views are stored per-item per-person within the database.
14  * They can be used to find popular items or recently viewed items
15  * at a per-person level. They do not record every view instance as an
16  * activity. Only the latest and original view times could be recognised.
17  *
18  * @property int $views
19  * @property int $user_id
20  */
21 class View extends Model
22 {
23     protected $fillable = ['user_id', 'views'];
24
25     /**
26      * Get all owning viewable models.
27      */
28     public function viewable(): MorphTo
29     {
30         return $this->morphTo();
31     }
32
33     public function jointPermissions(): HasMany
34     {
35         return $this->hasMany(JointPermission::class, 'entity_id', 'viewable_id')
36             ->whereColumn('views.viewable_type', '=', 'joint_permissions.entity_type');
37     }
38
39     /**
40      * Increment the current user's view count for the given viewable model.
41      */
42     public static function incrementFor(Viewable $viewable): int
43     {
44         $user = user();
45         if (is_null($user) || $user->isDefault()) {
46             return 0;
47         }
48
49         /** @var View $view */
50         $view = $viewable->views()->firstOrNew([
51             'user_id' => $user->id,
52         ], ['views' => 0]);
53
54         $view->forceFill(['views' => $view->views + 1])->save();
55
56         return $view->views;
57     }
58
59     /**
60      * Clear all views from the system.
61      */
62     public static function clearAll()
63     {
64         static::query()->truncate();
65     }
66 }