]> BookStack Code Mirror - bookstack/blob - app/Activity/TagRepo.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Activity / TagRepo.php
1 <?php
2
3 namespace BookStack\Activity;
4
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Permissions\PermissionApplicator;
8 use BookStack\Util\SimpleListOptions;
9 use Illuminate\Database\Eloquent\Builder;
10 use Illuminate\Support\Collection;
11 use Illuminate\Support\Facades\DB;
12
13 class TagRepo
14 {
15     public function __construct(
16         protected PermissionApplicator $permissions
17     ) {
18     }
19
20     /**
21      * Start a query against all tags in the system.
22      */
23     public function queryWithTotals(SimpleListOptions $listOptions, string $nameFilter): Builder
24     {
25         $searchTerm = $listOptions->getSearch();
26         $sort = $listOptions->getSort();
27         if ($sort === 'name' && $nameFilter) {
28             $sort = 'value';
29         }
30
31         $query = Tag::query()
32             ->select([
33                 'name',
34                 ($searchTerm || $nameFilter) ? 'value' : DB::raw('COUNT(distinct value) as `values`'),
35                 DB::raw('COUNT(id) as usages'),
36                 DB::raw('SUM(IF(entity_type = \'page\', 1, 0)) as page_count'),
37                 DB::raw('SUM(IF(entity_type = \'chapter\', 1, 0)) as chapter_count'),
38                 DB::raw('SUM(IF(entity_type = \'book\', 1, 0)) as book_count'),
39                 DB::raw('SUM(IF(entity_type = \'bookshelf\', 1, 0)) as shelf_count'),
40             ])
41             ->orderBy($sort, $listOptions->getOrder())
42             ->whereHas('entity');
43
44         if ($nameFilter) {
45             $query->where('name', '=', $nameFilter);
46             $query->groupBy('value');
47         } elseif ($searchTerm) {
48             $query->groupBy('name', 'value');
49         } else {
50             $query->groupBy('name');
51         }
52
53         if ($searchTerm) {
54             $query->where(function (Builder $query) use ($searchTerm) {
55                 $query->where('name', 'like', '%' . $searchTerm . '%')
56                     ->orWhere('value', 'like', '%' . $searchTerm . '%');
57             });
58         }
59
60         return $this->permissions->restrictEntityRelationQuery($query, 'tags', 'entity_id', 'entity_type');
61     }
62
63     /**
64      * Get tag name suggestions from scanning existing tag names.
65      * If no search term is given the 50 most popular tag names are provided.
66      */
67     public function getNameSuggestions(string $searchTerm): Collection
68     {
69         $query = Tag::query()
70             ->select('*', DB::raw('count(*) as count'))
71             ->groupBy('name');
72
73         if ($searchTerm) {
74             $query = $query->where('name', 'LIKE', $searchTerm . '%')->orderBy('name', 'asc');
75         } else {
76             $query = $query->orderBy('count', 'desc')->take(50);
77         }
78
79         $query = $this->permissions->restrictEntityRelationQuery($query, 'tags', 'entity_id', 'entity_type');
80
81         return $query->pluck('name');
82     }
83
84     /**
85      * Get tag value suggestions from scanning existing tag values.
86      * If no search is given the 50 most popular values are provided.
87      * Passing a tagName will only find values for a tags with a particular name.
88      */
89     public function getValueSuggestions(string $searchTerm, string $tagName): Collection
90     {
91         $query = Tag::query()
92             ->select('*', DB::raw('count(*) as count'))
93             ->where('value', '!=', '')
94             ->groupBy('value');
95
96         if ($searchTerm) {
97             $query = $query->where('value', 'LIKE', $searchTerm . '%')->orderBy('value', 'desc');
98         } else {
99             $query = $query->orderBy('count', 'desc')->take(50);
100         }
101
102         if ($tagName) {
103             $query = $query->where('name', '=', $tagName);
104         }
105
106         $query = $this->permissions->restrictEntityRelationQuery($query, 'tags', 'entity_id', 'entity_type');
107
108         return $query->pluck('value');
109     }
110
111     /**
112      * Save an array of tags to an entity.
113      */
114     public function saveTagsToEntity(Entity $entity, array $tags = []): iterable
115     {
116         $entity->tags()->delete();
117
118         $newTags = collect($tags)->filter(function ($tag) {
119             return boolval(trim($tag['name']));
120         })->map(function ($tag) {
121             return $this->newInstanceFromInput($tag);
122         })->all();
123
124         return $entity->tags()->saveMany($newTags);
125     }
126
127     /**
128      * Create a new Tag instance from user input.
129      * Input must be an array with a 'name' and an optional 'value' key.
130      */
131     protected function newInstanceFromInput(array $input): Tag
132     {
133         return new Tag([
134             'name'  => trim($input['name']),
135             'value' => trim($input['value'] ?? ''),
136         ]);
137     }
138 }