]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
Added entity-specific search results pages. Cleaned & Fixed search results bugs
[bookstack] / app / Repos / PageRepo.php
1 <?php namespace BookStack\Repos;
2
3
4 use Activity;
5 use BookStack\Book;
6 use BookStack\Chapter;
7 use Illuminate\Http\Request;
8 use Illuminate\Support\Facades\Auth;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
11 use BookStack\Page;
12 use BookStack\PageRevision;
13
14 class PageRepo
15 {
16     protected $page;
17     protected $pageRevision;
18
19     /**
20      * PageRepo constructor.
21      * @param Page         $page
22      * @param PageRevision $pageRevision
23      */
24     public function __construct(Page $page, PageRevision $pageRevision)
25     {
26         $this->page = $page;
27         $this->pageRevision = $pageRevision;
28     }
29
30     /**
31      * Check if a page id exists.
32      * @param $id
33      * @return bool
34      */
35     public function idExists($id)
36     {
37         return $this->page->where('page_id', '=', $id)->count() > 0;
38     }
39
40     /**
41      * Get a page via a specific ID.
42      * @param $id
43      * @return mixed
44      */
45     public function getById($id)
46     {
47         return $this->page->findOrFail($id);
48     }
49
50     /**
51      * Get all pages.
52      * @return \Illuminate\Database\Eloquent\Collection|static[]
53      */
54     public function getAll()
55     {
56         return $this->page->all();
57     }
58
59     /**
60      * Get a page identified by the given slug.
61      * @param $slug
62      * @param $bookId
63      * @return mixed
64      */
65     public function getBySlug($slug, $bookId)
66     {
67         $page = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
68         if ($page === null) abort(404);
69         return $page;
70     }
71
72     /**
73      * @param $input
74      * @return Page
75      */
76     public function newFromInput($input)
77     {
78         $page = $this->page->fill($input);
79         return $page;
80     }
81
82     /**
83      * Count the pages with a particular slug within a book.
84      * @param $slug
85      * @param $bookId
86      * @return mixed
87      */
88     public function countBySlug($slug, $bookId)
89     {
90         return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
91     }
92
93     /**
94      * Save a new page into the system.
95      * Input validation must be done beforehand.
96      * @param array $input
97      * @param Book  $book
98      * @param int   $chapterId
99      * @return Page
100      */
101     public function saveNew(array $input, Book $book, $chapterId = null)
102     {
103         $page = $this->newFromInput($input);
104         $page->slug = $this->findSuitableSlug($page->name, $book->id);
105
106         if ($chapterId) $page->chapter_id = $chapterId;
107
108         $page->html = $this->formatHtml($input['html']);
109         $page->text = strip_tags($page->html);
110         $page->created_by = auth()->user()->id;
111         $page->updated_by = auth()->user()->id;
112
113         $book->pages()->save($page);
114         return $page;
115     }
116
117     /**
118      * Formats a page's html to be tagged correctly
119      * within the system.
120      * @param string $htmlText
121      * @return string
122      */
123     protected function formatHtml($htmlText)
124     {
125         if($htmlText == '') return $htmlText;
126         libxml_use_internal_errors(true);
127         $doc = new \DOMDocument();
128         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
129
130         $container = $doc->documentElement;
131         $body = $container->childNodes->item(0);
132         $childNodes = $body->childNodes;
133
134         // Ensure no duplicate ids are used
135         $idArray = [];
136
137         foreach ($childNodes as $index => $childNode) {
138             /** @var \DOMElement $childNode */
139             if (get_class($childNode) !== 'DOMElement') continue;
140
141             // Overwrite id if not a BookStack custom id
142             if ($childNode->hasAttribute('id')) {
143                 $id = $childNode->getAttribute('id');
144                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
145                     $idArray[] = $id;
146                     continue;
147                 };
148             }
149
150             // Create an unique id for the element
151             // Uses the content as a basis to ensure output is the same every time
152             // the same content is passed through.
153             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
154             $newId = urlencode($contentId);
155             $loopIndex = 0;
156             while (in_array($newId, $idArray)) {
157                 $newId = urlencode($contentId . '-' . $loopIndex);
158                 $loopIndex++;
159             }
160
161             $childNode->setAttribute('id', $newId);
162             $idArray[] = $newId;
163         }
164
165         // Generate inner html as a string
166         $html = '';
167         foreach ($childNodes as $childNode) {
168             $html .= $doc->saveHTML($childNode);
169         }
170
171         return $html;
172     }
173
174
175     /**
176      * Gets pages by a search term.
177      * Highlights page content for showing in results.
178      * @param string $term
179      * @param array $whereTerms
180      * @param int $count
181      * @param array $paginationAppends
182      * @return mixed
183      */
184     public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
185     {
186         $terms = explode(' ', $term);
187         $pages = $this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)
188             ->paginate($count)->appends($paginationAppends);
189
190         // Add highlights to page text.
191         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
192         //lookahead/behind assertions ensures cut between words
193         $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
194
195         foreach ($pages as $page) {
196             preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
197             //delimiter between occurrences
198             $results = [];
199             foreach ($matches as $line) {
200                 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
201             }
202             $matchLimit = 6;
203             if (count($results) > $matchLimit) {
204                 $results = array_slice($results, 0, $matchLimit);
205             }
206             $result = join('... ', $results);
207
208             //highlight
209             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
210             if (strlen($result) < 5) {
211                 $result = $page->getExcerpt(80);
212             }
213             $page->searchSnippet = $result;
214         }
215         return $pages;
216     }
217
218     /**
219      * Search for image usage.
220      * @param $imageString
221      * @return mixed
222      */
223     public function searchForImage($imageString)
224     {
225         $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
226         foreach ($pages as $page) {
227             $page->url = $page->getUrl();
228             $page->html = '';
229             $page->text = '';
230         }
231         return count($pages) > 0 ? $pages : false;
232     }
233
234     /**
235      * Updates a page with any fillable data and saves it into the database.
236      * @param Page   $page
237      * @param int    $book_id
238      * @param string $input
239      * @return Page
240      */
241     public function updatePage(Page $page, $book_id, $input)
242     {
243         // Save a revision before updating
244         if ($page->html !== $input['html'] || $page->name !== $input['name']) {
245             $this->saveRevision($page);
246         }
247
248         // Update with new details
249         $page->fill($input);
250         $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
251         $page->html = $this->formatHtml($input['html']);
252         $page->text = strip_tags($page->html);
253         $page->updated_by = auth()->user()->id;
254         $page->save();
255         return $page;
256     }
257
258     /**
259      * Restores a revision's content back into a page.
260      * @param Page $page
261      * @param Book $book
262      * @param  int $revisionId
263      * @return Page
264      */
265     public function restoreRevision(Page $page, Book $book, $revisionId)
266     {
267         $this->saveRevision($page);
268         $revision = $this->getRevisionById($revisionId);
269         $page->fill($revision->toArray());
270         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
271         $page->text = strip_tags($page->html);
272         $page->updated_by = auth()->user()->id;
273         $page->save();
274         return $page;
275     }
276
277     /**
278      * Saves a page revision into the system.
279      * @param Page $page
280      * @return $this
281      */
282     public function saveRevision(Page $page)
283     {
284         $revision = $this->pageRevision->fill($page->toArray());
285         $revision->page_id = $page->id;
286         $revision->created_by = auth()->user()->id;
287         $revision->created_at = $page->updated_at;
288         $revision->save();
289         // Clear old revisions
290         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
291             $this->pageRevision->where('page_id', '=', $page->id)
292                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
293         }
294         return $revision;
295     }
296
297     /**
298      * Gets a single revision via it's id.
299      * @param $id
300      * @return mixed
301      */
302     public function getRevisionById($id)
303     {
304         return $this->pageRevision->findOrFail($id);
305     }
306
307     /**
308      * Checks if a slug exists within a book already.
309      * @param            $slug
310      * @param            $bookId
311      * @param bool|false $currentId
312      * @return bool
313      */
314     public function doesSlugExist($slug, $bookId, $currentId = false)
315     {
316         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
317         if ($currentId) $query = $query->where('id', '!=', $currentId);
318         return $query->count() > 0;
319     }
320
321     /**
322      * Changes the related book for the specified page.
323      * Changes the book id of any relations to the page that store the book id.
324      * @param int  $bookId
325      * @param Page $page
326      * @return Page
327      */
328     public function changeBook($bookId, Page $page)
329     {
330         $page->book_id = $bookId;
331         foreach ($page->activity as $activity) {
332             $activity->book_id = $bookId;
333             $activity->save();
334         }
335         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
336         $page->save();
337         return $page;
338     }
339
340     /**
341      * Gets a suitable slug for the resource
342      * @param            $name
343      * @param            $bookId
344      * @param bool|false $currentId
345      * @return string
346      */
347     public function findSuitableSlug($name, $bookId, $currentId = false)
348     {
349         $slug = Str::slug($name);
350         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
351             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
352         }
353         return $slug;
354     }
355
356     /**
357      * Destroy a given page along with its dependencies.
358      * @param $page
359      */
360     public function destroy($page)
361     {
362         Activity::removeEntity($page);
363         $page->views()->delete();
364         $page->revisions()->delete();
365         $page->delete();
366     }
367
368     /**
369      * Get the latest pages added to the system.
370      * @param $count
371      */
372     public function getRecentlyCreatedPaginated($count = 20)
373     {
374         return $this->page->orderBy('created_at', 'desc')->paginate($count);
375     }
376
377     /**
378      * Get the latest pages added to the system.
379      * @param $count
380      */
381     public function getRecentlyUpdatedPaginated($count = 20)
382     {
383         return $this->page->orderBy('updated_at', 'desc')->paginate($count);
384     }
385
386 }