]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
Major permission naming refactor and database migration cleanup
[bookstack] / app / Repos / PageRepo.php
1 <?php namespace BookStack\Repos;
2
3 use Activity;
4 use BookStack\Book;
5 use BookStack\Chapter;
6 use BookStack\Exceptions\NotFoundException;
7 use Carbon\Carbon;
8 use DOMDocument;
9 use Illuminate\Support\Str;
10 use BookStack\Page;
11 use BookStack\PageRevision;
12
13 class PageRepo extends EntityRepo
14 {
15
16     protected $pageRevision;
17
18     /**
19      * PageRepo constructor.
20      * @param PageRevision $pageRevision
21      */
22     public function __construct(PageRevision $pageRevision)
23     {
24         $this->pageRevision = $pageRevision;
25         parent::__construct();
26     }
27
28     /**
29      * Base query for getting pages, Takes restrictions into account.
30      * @param bool $allowDrafts
31      * @return mixed
32      */
33     private function pageQuery($allowDrafts = false)
34     {
35         $query = $this->permissionService->enforcePageRestrictions($this->page, 'view');
36         if (!$allowDrafts) {
37             $query = $query->where('draft', '=', false);
38         }
39         return $query;
40     }
41
42     /**
43      * Get a page via a specific ID.
44      * @param $id
45      * @param bool $allowDrafts
46      * @return mixed
47      */
48     public function getById($id, $allowDrafts = false)
49     {
50         return $this->pageQuery($allowDrafts)->findOrFail($id);
51     }
52
53     /**
54      * Get a page identified by the given slug.
55      * @param $slug
56      * @param $bookId
57      * @return mixed
58      * @throws NotFoundException
59      */
60     public function getBySlug($slug, $bookId)
61     {
62         $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
63         if ($page === null) throw new NotFoundException('Page not found');
64         return $page;
65     }
66
67     /**
68      * Search through page revisions and retrieve
69      * the last page in the current book that
70      * has a slug equal to the one given.
71      * @param $pageSlug
72      * @param $bookSlug
73      * @return null | Page
74      */
75     public function findPageUsingOldSlug($pageSlug, $bookSlug)
76     {
77         $revision = $this->pageRevision->where('slug', '=', $pageSlug)
78             ->whereHas('page', function ($query) {
79                 $this->permissionService->enforcePageRestrictions($query);
80             })
81             ->where('type', '=', 'version')
82             ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
83             ->with('page')->first();
84         return $revision !== null ? $revision->page : null;
85     }
86
87     /**
88      * Get a new Page instance from the given input.
89      * @param $input
90      * @return Page
91      */
92     public function newFromInput($input)
93     {
94         $page = $this->page->fill($input);
95         return $page;
96     }
97
98     /**
99      * Count the pages with a particular slug within a book.
100      * @param $slug
101      * @param $bookId
102      * @return mixed
103      */
104     public function countBySlug($slug, $bookId)
105     {
106         return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
107     }
108
109     /**
110      * Save a new page into the system.
111      * Input validation must be done beforehand.
112      * @param array $input
113      * @param Book $book
114      * @param int $chapterId
115      * @return Page
116      */
117     public function saveNew(array $input, Book $book, $chapterId = null)
118     {
119         $page = $this->newFromInput($input);
120         $page->slug = $this->findSuitableSlug($page->name, $book->id);
121
122         if ($chapterId) $page->chapter_id = $chapterId;
123
124         $page->html = $this->formatHtml($input['html']);
125         $page->text = strip_tags($page->html);
126         $page->created_by = auth()->user()->id;
127         $page->updated_by = auth()->user()->id;
128
129         $book->pages()->save($page);
130         return $page;
131     }
132
133
134     /**
135      * Publish a draft page to make it a normal page.
136      * Sets the slug and updates the content.
137      * @param Page $draftPage
138      * @param array $input
139      * @return Page
140      */
141     public function publishDraft(Page $draftPage, array $input)
142     {
143         $draftPage->fill($input);
144
145         $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
146         $draftPage->html = $this->formatHtml($input['html']);
147         $draftPage->text = strip_tags($draftPage->html);
148         $draftPage->draft = false;
149
150         $draftPage->save();
151         return $draftPage;
152     }
153
154     /**
155      * Get a new draft page instance.
156      * @param Book $book
157      * @param Chapter|bool $chapter
158      * @return static
159      */
160     public function getDraftPage(Book $book, $chapter = false)
161     {
162         $page = $this->page->newInstance();
163         $page->name = 'New Page';
164         $page->created_by = auth()->user()->id;
165         $page->updated_by = auth()->user()->id;
166         $page->draft = true;
167
168         if ($chapter) $page->chapter_id = $chapter->id;
169
170         $book->pages()->save($page);
171         $this->permissionService->buildJointPermissionsForEntity($page);
172         return $page;
173     }
174
175     /**
176      * Formats a page's html to be tagged correctly
177      * within the system.
178      * @param string $htmlText
179      * @return string
180      */
181     protected function formatHtml($htmlText)
182     {
183         if ($htmlText == '') return $htmlText;
184         libxml_use_internal_errors(true);
185         $doc = new DOMDocument();
186         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
187
188         $container = $doc->documentElement;
189         $body = $container->childNodes->item(0);
190         $childNodes = $body->childNodes;
191
192         // Ensure no duplicate ids are used
193         $idArray = [];
194
195         foreach ($childNodes as $index => $childNode) {
196             /** @var \DOMElement $childNode */
197             if (get_class($childNode) !== 'DOMElement') continue;
198
199             // Overwrite id if not a BookStack custom id
200             if ($childNode->hasAttribute('id')) {
201                 $id = $childNode->getAttribute('id');
202                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
203                     $idArray[] = $id;
204                     continue;
205                 };
206             }
207
208             // Create an unique id for the element
209             // Uses the content as a basis to ensure output is the same every time
210             // the same content is passed through.
211             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
212             $newId = urlencode($contentId);
213             $loopIndex = 0;
214             while (in_array($newId, $idArray)) {
215                 $newId = urlencode($contentId . '-' . $loopIndex);
216                 $loopIndex++;
217             }
218
219             $childNode->setAttribute('id', $newId);
220             $idArray[] = $newId;
221         }
222
223         // Generate inner html as a string
224         $html = '';
225         foreach ($childNodes as $childNode) {
226             $html .= $doc->saveHTML($childNode);
227         }
228
229         return $html;
230     }
231
232
233     /**
234      * Gets pages by a search term.
235      * Highlights page content for showing in results.
236      * @param string $term
237      * @param array $whereTerms
238      * @param int $count
239      * @param array $paginationAppends
240      * @return mixed
241      */
242     public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
243     {
244         $terms = $this->prepareSearchTerms($term);
245         $pages = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
246             ->paginate($count)->appends($paginationAppends);
247
248         // Add highlights to page text.
249         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
250         //lookahead/behind assertions ensures cut between words
251         $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
252
253         foreach ($pages as $page) {
254             preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
255             //delimiter between occurrences
256             $results = [];
257             foreach ($matches as $line) {
258                 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
259             }
260             $matchLimit = 6;
261             if (count($results) > $matchLimit) {
262                 $results = array_slice($results, 0, $matchLimit);
263             }
264             $result = join('... ', $results);
265
266             //highlight
267             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
268             if (strlen($result) < 5) {
269                 $result = $page->getExcerpt(80);
270             }
271             $page->searchSnippet = $result;
272         }
273         return $pages;
274     }
275
276     /**
277      * Search for image usage.
278      * @param $imageString
279      * @return mixed
280      */
281     public function searchForImage($imageString)
282     {
283         $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
284         foreach ($pages as $page) {
285             $page->url = $page->getUrl();
286             $page->html = '';
287             $page->text = '';
288         }
289         return count($pages) > 0 ? $pages : false;
290     }
291
292     /**
293      * Updates a page with any fillable data and saves it into the database.
294      * @param Page $page
295      * @param int $book_id
296      * @param string $input
297      * @return Page
298      */
299     public function updatePage(Page $page, $book_id, $input)
300     {
301         // Save a revision before updating
302         if ($page->html !== $input['html'] || $page->name !== $input['name']) {
303             $this->saveRevision($page);
304         }
305
306         // Prevent slug being updated if no name change
307         if ($page->name !== $input['name']) {
308             $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
309         }
310
311         // Update with new details
312         $userId = auth()->user()->id;
313         $page->fill($input);
314         $page->html = $this->formatHtml($input['html']);
315         $page->text = strip_tags($page->html);
316         if (setting('app-editor') !== 'markdown') $page->markdown = '';
317         $page->updated_by = $userId;
318         $page->save();
319
320         // Remove all update drafts for this user & page.
321         $this->userUpdateDraftsQuery($page, $userId)->delete();
322
323         return $page;
324     }
325
326     /**
327      * Restores a revision's content back into a page.
328      * @param Page $page
329      * @param Book $book
330      * @param  int $revisionId
331      * @return Page
332      */
333     public function restoreRevision(Page $page, Book $book, $revisionId)
334     {
335         $this->saveRevision($page);
336         $revision = $this->getRevisionById($revisionId);
337         $page->fill($revision->toArray());
338         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
339         $page->text = strip_tags($page->html);
340         $page->updated_by = auth()->user()->id;
341         $page->save();
342         return $page;
343     }
344
345     /**
346      * Saves a page revision into the system.
347      * @param Page $page
348      * @return $this
349      */
350     public function saveRevision(Page $page)
351     {
352         $revision = $this->pageRevision->fill($page->toArray());
353         if (setting('app-editor') !== 'markdown') $revision->markdown = '';
354         $revision->page_id = $page->id;
355         $revision->slug = $page->slug;
356         $revision->book_slug = $page->book->slug;
357         $revision->created_by = auth()->user()->id;
358         $revision->created_at = $page->updated_at;
359         $revision->type = 'version';
360         $revision->save();
361         // Clear old revisions
362         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
363             $this->pageRevision->where('page_id', '=', $page->id)
364                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
365         }
366         return $revision;
367     }
368
369     /**
370      * Save a page update draft.
371      * @param Page $page
372      * @param array $data
373      * @return PageRevision
374      */
375     public function saveUpdateDraft(Page $page, $data = [])
376     {
377         $userId = auth()->user()->id;
378         $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
379
380         if ($drafts->count() > 0) {
381             $draft = $drafts->first();
382         } else {
383             $draft = $this->pageRevision->newInstance();
384             $draft->page_id = $page->id;
385             $draft->slug = $page->slug;
386             $draft->book_slug = $page->book->slug;
387             $draft->created_by = $userId;
388             $draft->type = 'update_draft';
389         }
390
391         $draft->fill($data);
392         if (setting('app-editor') !== 'markdown') $draft->markdown = '';
393         
394         $draft->save();
395         return $draft;
396     }
397
398     /**
399      * Update a draft page.
400      * @param Page $page
401      * @param array $data
402      * @return Page
403      */
404     public function updateDraftPage(Page $page, $data = [])
405     {
406         $page->fill($data);
407
408         if (isset($data['html'])) {
409             $page->text = strip_tags($data['html']);
410         }
411
412         $page->save();
413         return $page;
414     }
415
416     /**
417      * The base query for getting user update drafts.
418      * @param Page $page
419      * @param $userId
420      * @return mixed
421      */
422     private function userUpdateDraftsQuery(Page $page, $userId)
423     {
424         return $this->pageRevision->where('created_by', '=', $userId)
425             ->where('type', 'update_draft')
426             ->where('page_id', '=', $page->id)
427             ->orderBy('created_at', 'desc');
428     }
429
430     /**
431      * Checks whether a user has a draft version of a particular page or not.
432      * @param Page $page
433      * @param $userId
434      * @return bool
435      */
436     public function hasUserGotPageDraft(Page $page, $userId)
437     {
438         return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
439     }
440
441     /**
442      * Get the latest updated draft revision for a particular page and user.
443      * @param Page $page
444      * @param $userId
445      * @return mixed
446      */
447     public function getUserPageDraft(Page $page, $userId)
448     {
449         return $this->userUpdateDraftsQuery($page, $userId)->first();
450     }
451
452     /**
453      * Get the notification message that informs the user that they are editing a draft page.
454      * @param PageRevision $draft
455      * @return string
456      */
457     public function getUserPageDraftMessage(PageRevision $draft)
458     {
459         $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
460         if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
461             $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
462         }
463         return $message;
464     }
465
466     /**
467      * Check if a page is being actively editing.
468      * Checks for edits since last page updated.
469      * Passing in a minuted range will check for edits
470      * within the last x minutes.
471      * @param Page $page
472      * @param null $minRange
473      * @return bool
474      */
475     public function isPageEditingActive(Page $page, $minRange = null)
476     {
477         $draftSearch = $this->activePageEditingQuery($page, $minRange);
478         return $draftSearch->count() > 0;
479     }
480
481     /**
482      * Get a notification message concerning the editing activity on
483      * a particular page.
484      * @param Page $page
485      * @param null $minRange
486      * @return string
487      */
488     public function getPageEditingActiveMessage(Page $page, $minRange = null)
489     {
490         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
491         $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
492         $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
493         $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
494         return sprintf($message, $userMessage, $timeMessage);
495     }
496
497     /**
498      * A query to check for active update drafts on a particular page.
499      * @param Page $page
500      * @param null $minRange
501      * @return mixed
502      */
503     private function activePageEditingQuery(Page $page, $minRange = null)
504     {
505         $query = $this->pageRevision->where('type', '=', 'update_draft')
506             ->where('page_id', '=', $page->id)
507             ->where('updated_at', '>', $page->updated_at)
508             ->where('created_by', '!=', auth()->user()->id)
509             ->with('createdBy');
510
511         if ($minRange !== null) {
512             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
513         }
514
515         return $query;
516     }
517
518     /**
519      * Gets a single revision via it's id.
520      * @param $id
521      * @return mixed
522      */
523     public function getRevisionById($id)
524     {
525         return $this->pageRevision->findOrFail($id);
526     }
527
528     /**
529      * Checks if a slug exists within a book already.
530      * @param            $slug
531      * @param            $bookId
532      * @param bool|false $currentId
533      * @return bool
534      */
535     public function doesSlugExist($slug, $bookId, $currentId = false)
536     {
537         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
538         if ($currentId) $query = $query->where('id', '!=', $currentId);
539         return $query->count() > 0;
540     }
541
542     /**
543      * Changes the related book for the specified page.
544      * Changes the book id of any relations to the page that store the book id.
545      * @param int $bookId
546      * @param Page $page
547      * @return Page
548      */
549     public function changeBook($bookId, Page $page)
550     {
551         $page->book_id = $bookId;
552         foreach ($page->activity as $activity) {
553             $activity->book_id = $bookId;
554             $activity->save();
555         }
556         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
557         $page->save();
558         return $page;
559     }
560
561     /**
562      * Gets a suitable slug for the resource
563      * @param            $name
564      * @param            $bookId
565      * @param bool|false $currentId
566      * @return string
567      */
568     public function findSuitableSlug($name, $bookId, $currentId = false)
569     {
570         $slug = Str::slug($name);
571         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
572             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
573         }
574         return $slug;
575     }
576
577     /**
578      * Destroy a given page along with its dependencies.
579      * @param $page
580      */
581     public function destroy(Page $page)
582     {
583         Activity::removeEntity($page);
584         $page->views()->delete();
585         $page->revisions()->delete();
586         $page->permissions()->delete();
587         $this->permissionService->deleteJointPermissionsForEntity($page);
588         $page->delete();
589     }
590
591     /**
592      * Get the latest pages added to the system.
593      * @param $count
594      */
595     public function getRecentlyCreatedPaginated($count = 20)
596     {
597         return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
598     }
599
600     /**
601      * Get the latest pages added to the system.
602      * @param $count
603      */
604     public function getRecentlyUpdatedPaginated($count = 20)
605     {
606         return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
607     }
608
609 }