2021-06-26 23:23:15 +08:00
|
|
|
<?php
|
|
|
|
|
2023-05-18 00:56:55 +08:00
|
|
|
namespace BookStack\Activity\Models;
|
2018-09-25 19:30:50 +08:00
|
|
|
|
2023-05-18 00:56:55 +08:00
|
|
|
use BookStack\App\Model;
|
|
|
|
use BookStack\Permissions\Models\JointPermission;
|
2023-01-24 22:55:34 +08:00
|
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
2021-05-16 07:29:56 +08:00
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
2015-11-22 01:22:14 +08:00
|
|
|
|
2021-05-16 17:49:37 +08:00
|
|
|
/**
|
|
|
|
* Class View
|
|
|
|
* Views are stored per-item per-person within the database.
|
|
|
|
* They can be used to find popular items or recently viewed items
|
|
|
|
* at a per-person level. They do not record every view instance as an
|
|
|
|
* activity. Only the latest and original view times could be recognised.
|
|
|
|
*
|
|
|
|
* @property int $views
|
|
|
|
* @property int $user_id
|
|
|
|
*/
|
2015-11-22 01:22:14 +08:00
|
|
|
class View extends Model
|
|
|
|
{
|
|
|
|
protected $fillable = ['user_id', 'views'];
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get all owning viewable models.
|
|
|
|
*/
|
2021-05-16 07:29:56 +08:00
|
|
|
public function viewable(): MorphTo
|
2015-11-22 01:22:14 +08:00
|
|
|
{
|
|
|
|
return $this->morphTo();
|
|
|
|
}
|
2021-05-16 17:49:37 +08:00
|
|
|
|
2023-01-24 22:55:34 +08:00
|
|
|
public function jointPermissions(): HasMany
|
|
|
|
{
|
|
|
|
return $this->hasMany(JointPermission::class, 'entity_id', 'viewable_id')
|
|
|
|
->whereColumn('views.viewable_type', '=', 'joint_permissions.entity_type');
|
|
|
|
}
|
|
|
|
|
2021-05-16 17:49:37 +08:00
|
|
|
/**
|
|
|
|
* Increment the current user's view count for the given viewable model.
|
|
|
|
*/
|
|
|
|
public static function incrementFor(Viewable $viewable): int
|
|
|
|
{
|
|
|
|
$user = user();
|
2023-09-16 20:49:03 +08:00
|
|
|
if ($user->isGuest()) {
|
2021-05-16 17:49:37 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @var View $view */
|
|
|
|
$view = $viewable->views()->firstOrNew([
|
|
|
|
'user_id' => $user->id,
|
|
|
|
], ['views' => 0]);
|
|
|
|
|
2021-05-22 21:05:28 +08:00
|
|
|
$view->forceFill(['views' => $view->views + 1])->save();
|
2021-05-16 17:49:37 +08:00
|
|
|
|
|
|
|
return $view->views;
|
|
|
|
}
|
2015-11-22 01:22:14 +08:00
|
|
|
}
|