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