]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
Added issue template
[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         // Hold the old details to compare later
312         $oldHtml = $page->html;
313         $oldName = $page->name;
314
315         // Prevent slug being updated if no name change
316         if ($page->name !== $input['name']) {
317             $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
318         }
319
320         // Save page tags if present
321         if (isset($input['tags'])) {
322             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
323         }
324
325         // Update with new details
326         $userId = auth()->user()->id;
327         $page->fill($input);
328         $page->html = $this->formatHtml($input['html']);
329         $page->text = strip_tags($page->html);
330         if (setting('app-editor') !== 'markdown') $page->markdown = '';
331         $page->updated_by = $userId;
332         $page->save();
333
334         // Remove all update drafts for this user & page.
335         $this->userUpdateDraftsQuery($page, $userId)->delete();
336
337         // Save a revision after updating
338         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
339             $this->saveRevision($page, $input['summary']);
340         }
341
342         return $page;
343     }
344
345     /**
346      * Restores a revision's content back into a page.
347      * @param Page $page
348      * @param Book $book
349      * @param  int $revisionId
350      * @return Page
351      */
352     public function restoreRevision(Page $page, Book $book, $revisionId)
353     {
354         $this->saveRevision($page);
355         $revision = $this->getRevisionById($revisionId);
356         $page->fill($revision->toArray());
357         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
358         $page->text = strip_tags($page->html);
359         $page->updated_by = auth()->user()->id;
360         $page->save();
361         return $page;
362     }
363
364     /**
365      * Saves a page revision into the system.
366      * @param Page $page
367      * @param null|string $summary
368      * @return $this
369      */
370     public function saveRevision(Page $page, $summary = null)
371     {
372         $revision = $this->pageRevision->fill($page->toArray());
373         if (setting('app-editor') !== 'markdown') $revision->markdown = '';
374         $revision->page_id = $page->id;
375         $revision->slug = $page->slug;
376         $revision->book_slug = $page->book->slug;
377         $revision->created_by = auth()->user()->id;
378         $revision->created_at = $page->updated_at;
379         $revision->type = 'version';
380         $revision->summary = $summary;
381         $revision->save();
382         // Clear old revisions
383         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
384             $this->pageRevision->where('page_id', '=', $page->id)
385                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
386         }
387         return $revision;
388     }
389
390     /**
391      * Save a page update draft.
392      * @param Page $page
393      * @param array $data
394      * @return PageRevision
395      */
396     public function saveUpdateDraft(Page $page, $data = [])
397     {
398         $userId = auth()->user()->id;
399         $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
400
401         if ($drafts->count() > 0) {
402             $draft = $drafts->first();
403         } else {
404             $draft = $this->pageRevision->newInstance();
405             $draft->page_id = $page->id;
406             $draft->slug = $page->slug;
407             $draft->book_slug = $page->book->slug;
408             $draft->created_by = $userId;
409             $draft->type = 'update_draft';
410         }
411
412         $draft->fill($data);
413         if (setting('app-editor') !== 'markdown') $draft->markdown = '';
414
415         $draft->save();
416         return $draft;
417     }
418
419     /**
420      * Update a draft page.
421      * @param Page $page
422      * @param array $data
423      * @return Page
424      */
425     public function updateDraftPage(Page $page, $data = [])
426     {
427         $page->fill($data);
428
429         if (isset($data['html'])) {
430             $page->text = strip_tags($data['html']);
431         }
432
433         $page->save();
434         return $page;
435     }
436
437     /**
438      * The base query for getting user update drafts.
439      * @param Page $page
440      * @param $userId
441      * @return mixed
442      */
443     private function userUpdateDraftsQuery(Page $page, $userId)
444     {
445         return $this->pageRevision->where('created_by', '=', $userId)
446             ->where('type', 'update_draft')
447             ->where('page_id', '=', $page->id)
448             ->orderBy('created_at', 'desc');
449     }
450
451     /**
452      * Checks whether a user has a draft version of a particular page or not.
453      * @param Page $page
454      * @param $userId
455      * @return bool
456      */
457     public function hasUserGotPageDraft(Page $page, $userId)
458     {
459         return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
460     }
461
462     /**
463      * Get the latest updated draft revision for a particular page and user.
464      * @param Page $page
465      * @param $userId
466      * @return mixed
467      */
468     public function getUserPageDraft(Page $page, $userId)
469     {
470         return $this->userUpdateDraftsQuery($page, $userId)->first();
471     }
472
473     /**
474      * Get the notification message that informs the user that they are editing a draft page.
475      * @param PageRevision $draft
476      * @return string
477      */
478     public function getUserPageDraftMessage(PageRevision $draft)
479     {
480         $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
481         if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
482             $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
483         }
484         return $message;
485     }
486
487     /**
488      * Check if a page is being actively editing.
489      * Checks for edits since last page updated.
490      * Passing in a minuted range will check for edits
491      * within the last x minutes.
492      * @param Page $page
493      * @param null $minRange
494      * @return bool
495      */
496     public function isPageEditingActive(Page $page, $minRange = null)
497     {
498         $draftSearch = $this->activePageEditingQuery($page, $minRange);
499         return $draftSearch->count() > 0;
500     }
501
502     /**
503      * Get a notification message concerning the editing activity on
504      * a particular page.
505      * @param Page $page
506      * @param null $minRange
507      * @return string
508      */
509     public function getPageEditingActiveMessage(Page $page, $minRange = null)
510     {
511         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
512         $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
513         $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
514         $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
515         return sprintf($message, $userMessage, $timeMessage);
516     }
517
518     /**
519      * A query to check for active update drafts on a particular page.
520      * @param Page $page
521      * @param null $minRange
522      * @return mixed
523      */
524     private function activePageEditingQuery(Page $page, $minRange = null)
525     {
526         $query = $this->pageRevision->where('type', '=', 'update_draft')
527             ->where('page_id', '=', $page->id)
528             ->where('updated_at', '>', $page->updated_at)
529             ->where('created_by', '!=', auth()->user()->id)
530             ->with('createdBy');
531
532         if ($minRange !== null) {
533             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
534         }
535
536         return $query;
537     }
538
539     /**
540      * Gets a single revision via it's id.
541      * @param $id
542      * @return mixed
543      */
544     public function getRevisionById($id)
545     {
546         return $this->pageRevision->findOrFail($id);
547     }
548
549     /**
550      * Checks if a slug exists within a book already.
551      * @param            $slug
552      * @param            $bookId
553      * @param bool|false $currentId
554      * @return bool
555      */
556     public function doesSlugExist($slug, $bookId, $currentId = false)
557     {
558         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
559         if ($currentId) $query = $query->where('id', '!=', $currentId);
560         return $query->count() > 0;
561     }
562
563     /**
564      * Changes the related book for the specified page.
565      * Changes the book id of any relations to the page that store the book id.
566      * @param int $bookId
567      * @param Page $page
568      * @return Page
569      */
570     public function changeBook($bookId, Page $page)
571     {
572         $page->book_id = $bookId;
573         foreach ($page->activity as $activity) {
574             $activity->book_id = $bookId;
575             $activity->save();
576         }
577         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
578         $page->save();
579         return $page;
580     }
581
582
583     /**
584      * Change the page's parent to the given entity.
585      * @param Page $page
586      * @param Entity $parent
587      */
588     public function changePageParent(Page $page, Entity $parent)
589     {
590         $book = $parent->isA('book') ? $parent : $parent->book;
591         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
592         $page->save();
593         $page = $this->changeBook($book->id, $page);
594         $page->load('book');
595         $this->permissionService->buildJointPermissionsForEntity($book);
596     }
597
598     /**
599      * Gets a suitable slug for the resource
600      * @param            $name
601      * @param            $bookId
602      * @param bool|false $currentId
603      * @return string
604      */
605     public function findSuitableSlug($name, $bookId, $currentId = false)
606     {
607         $slug = Str::slug($name);
608         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
609             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
610         }
611         return $slug;
612     }
613
614     /**
615      * Destroy a given page along with its dependencies.
616      * @param $page
617      */
618     public function destroy(Page $page)
619     {
620         Activity::removeEntity($page);
621         $page->views()->delete();
622         $page->tags()->delete();
623         $page->revisions()->delete();
624         $page->permissions()->delete();
625         $this->permissionService->deleteJointPermissionsForEntity($page);
626         $page->delete();
627     }
628
629     /**
630      * Get the latest pages added to the system.
631      * @param $count
632      */
633     public function getRecentlyCreatedPaginated($count = 20)
634     {
635         return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
636     }
637
638     /**
639      * Get the latest pages added to the system.
640      * @param $count
641      */
642     public function getRecentlyUpdatedPaginated($count = 20)
643     {
644         return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
645     }
646
647 }