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