]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
Added basic system tests for markdown editor, Added extra test helpers
[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->restrictionService->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->restrictionService->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|null $chapter
158      * @return static
159      */
160     public function getDraftPage(Book $book, $chapter)
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         return $page;
172     }
173
174     /**
175      * Formats a page's html to be tagged correctly
176      * within the system.
177      * @param string $htmlText
178      * @return string
179      */
180     protected function formatHtml($htmlText)
181     {
182         if ($htmlText == '') return $htmlText;
183         libxml_use_internal_errors(true);
184         $doc = new DOMDocument();
185         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
186
187         $container = $doc->documentElement;
188         $body = $container->childNodes->item(0);
189         $childNodes = $body->childNodes;
190
191         // Ensure no duplicate ids are used
192         $idArray = [];
193
194         foreach ($childNodes as $index => $childNode) {
195             /** @var \DOMElement $childNode */
196             if (get_class($childNode) !== 'DOMElement') continue;
197
198             // Overwrite id if not a BookStack custom id
199             if ($childNode->hasAttribute('id')) {
200                 $id = $childNode->getAttribute('id');
201                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
202                     $idArray[] = $id;
203                     continue;
204                 };
205             }
206
207             // Create an unique id for the element
208             // Uses the content as a basis to ensure output is the same every time
209             // the same content is passed through.
210             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
211             $newId = urlencode($contentId);
212             $loopIndex = 0;
213             while (in_array($newId, $idArray)) {
214                 $newId = urlencode($contentId . '-' . $loopIndex);
215                 $loopIndex++;
216             }
217
218             $childNode->setAttribute('id', $newId);
219             $idArray[] = $newId;
220         }
221
222         // Generate inner html as a string
223         $html = '';
224         foreach ($childNodes as $childNode) {
225             $html .= $doc->saveHTML($childNode);
226         }
227
228         return $html;
229     }
230
231
232     /**
233      * Gets pages by a search term.
234      * Highlights page content for showing in results.
235      * @param string $term
236      * @param array $whereTerms
237      * @param int $count
238      * @param array $paginationAppends
239      * @return mixed
240      */
241     public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
242     {
243         $terms = $this->prepareSearchTerms($term);
244         $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
245             ->paginate($count)->appends($paginationAppends);
246
247         // Add highlights to page text.
248         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
249         //lookahead/behind assertions ensures cut between words
250         $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
251
252         foreach ($pages as $page) {
253             preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
254             //delimiter between occurrences
255             $results = [];
256             foreach ($matches as $line) {
257                 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
258             }
259             $matchLimit = 6;
260             if (count($results) > $matchLimit) {
261                 $results = array_slice($results, 0, $matchLimit);
262             }
263             $result = join('... ', $results);
264
265             //highlight
266             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
267             if (strlen($result) < 5) {
268                 $result = $page->getExcerpt(80);
269             }
270             $page->searchSnippet = $result;
271         }
272         return $pages;
273     }
274
275     /**
276      * Search for image usage.
277      * @param $imageString
278      * @return mixed
279      */
280     public function searchForImage($imageString)
281     {
282         $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
283         foreach ($pages as $page) {
284             $page->url = $page->getUrl();
285             $page->html = '';
286             $page->text = '';
287         }
288         return count($pages) > 0 ? $pages : false;
289     }
290
291     /**
292      * Updates a page with any fillable data and saves it into the database.
293      * @param Page $page
294      * @param int $book_id
295      * @param string $input
296      * @return Page
297      */
298     public function updatePage(Page $page, $book_id, $input)
299     {
300         // Save a revision before updating
301         if ($page->html !== $input['html'] || $page->name !== $input['name']) {
302             $this->saveRevision($page);
303         }
304
305         // Prevent slug being updated if no name change
306         if ($page->name !== $input['name']) {
307             $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
308         }
309
310         // Update with new details
311         $userId = auth()->user()->id;
312         $page->fill($input);
313         $page->html = $this->formatHtml($input['html']);
314         $page->text = strip_tags($page->html);
315         if (setting('app-editor') !== 'markdown') $page->markdown = '';
316         $page->updated_by = $userId;
317         $page->save();
318
319         // Remove all update drafts for this user & page.
320         $this->userUpdateDraftsQuery($page, $userId)->delete();
321
322         return $page;
323     }
324
325     /**
326      * Restores a revision's content back into a page.
327      * @param Page $page
328      * @param Book $book
329      * @param  int $revisionId
330      * @return Page
331      */
332     public function restoreRevision(Page $page, Book $book, $revisionId)
333     {
334         $this->saveRevision($page);
335         $revision = $this->getRevisionById($revisionId);
336         $page->fill($revision->toArray());
337         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
338         $page->text = strip_tags($page->html);
339         $page->updated_by = auth()->user()->id;
340         $page->save();
341         return $page;
342     }
343
344     /**
345      * Saves a page revision into the system.
346      * @param Page $page
347      * @return $this
348      */
349     public function saveRevision(Page $page)
350     {
351         $revision = $this->pageRevision->fill($page->toArray());
352         if (setting('app-editor') !== 'markdown') $revision->markdown = '';
353         $revision->page_id = $page->id;
354         $revision->slug = $page->slug;
355         $revision->book_slug = $page->book->slug;
356         $revision->created_by = auth()->user()->id;
357         $revision->created_at = $page->updated_at;
358         $revision->type = 'version';
359         $revision->save();
360         // Clear old revisions
361         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
362             $this->pageRevision->where('page_id', '=', $page->id)
363                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
364         }
365         return $revision;
366     }
367
368     /**
369      * Save a page update draft.
370      * @param Page $page
371      * @param array $data
372      * @return PageRevision
373      */
374     public function saveUpdateDraft(Page $page, $data = [])
375     {
376         $userId = auth()->user()->id;
377         $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
378
379         if ($drafts->count() > 0) {
380             $draft = $drafts->first();
381         } else {
382             $draft = $this->pageRevision->newInstance();
383             $draft->page_id = $page->id;
384             $draft->slug = $page->slug;
385             $draft->book_slug = $page->book->slug;
386             $draft->created_by = $userId;
387             $draft->type = 'update_draft';
388         }
389
390         $draft->fill($data);
391         if (setting('app-editor') !== 'markdown') $draft->markdown = '';
392         
393         $draft->save();
394         return $draft;
395     }
396
397     /**
398      * Update a draft page.
399      * @param Page $page
400      * @param array $data
401      * @return Page
402      */
403     public function updateDraftPage(Page $page, $data = [])
404     {
405         $page->fill($data);
406
407         if (isset($data['html'])) {
408             $page->text = strip_tags($data['html']);
409         }
410
411         $page->save();
412         return $page;
413     }
414
415     /**
416      * The base query for getting user update drafts.
417      * @param Page $page
418      * @param $userId
419      * @return mixed
420      */
421     private function userUpdateDraftsQuery(Page $page, $userId)
422     {
423         return $this->pageRevision->where('created_by', '=', $userId)
424             ->where('type', 'update_draft')
425             ->where('page_id', '=', $page->id)
426             ->orderBy('created_at', 'desc');
427     }
428
429     /**
430      * Checks whether a user has a draft version of a particular page or not.
431      * @param Page $page
432      * @param $userId
433      * @return bool
434      */
435     public function hasUserGotPageDraft(Page $page, $userId)
436     {
437         return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
438     }
439
440     /**
441      * Get the latest updated draft revision for a particular page and user.
442      * @param Page $page
443      * @param $userId
444      * @return mixed
445      */
446     public function getUserPageDraft(Page $page, $userId)
447     {
448         return $this->userUpdateDraftsQuery($page, $userId)->first();
449     }
450
451     /**
452      * Get the notification message that informs the user that they are editing a draft page.
453      * @param PageRevision $draft
454      * @return string
455      */
456     public function getUserPageDraftMessage(PageRevision $draft)
457     {
458         $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
459         if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
460             $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
461         }
462         return $message;
463     }
464
465     /**
466      * Check if a page is being actively editing.
467      * Checks for edits since last page updated.
468      * Passing in a minuted range will check for edits
469      * within the last x minutes.
470      * @param Page $page
471      * @param null $minRange
472      * @return bool
473      */
474     public function isPageEditingActive(Page $page, $minRange = null)
475     {
476         $draftSearch = $this->activePageEditingQuery($page, $minRange);
477         return $draftSearch->count() > 0;
478     }
479
480     /**
481      * Get a notification message concerning the editing activity on
482      * a particular page.
483      * @param Page $page
484      * @param null $minRange
485      * @return string
486      */
487     public function getPageEditingActiveMessage(Page $page, $minRange = null)
488     {
489         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
490         $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
491         $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
492         $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
493         return sprintf($message, $userMessage, $timeMessage);
494     }
495
496     /**
497      * A query to check for active update drafts on a particular page.
498      * @param Page $page
499      * @param null $minRange
500      * @return mixed
501      */
502     private function activePageEditingQuery(Page $page, $minRange = null)
503     {
504         $query = $this->pageRevision->where('type', '=', 'update_draft')
505             ->where('page_id', '=', $page->id)
506             ->where('updated_at', '>', $page->updated_at)
507             ->where('created_by', '!=', auth()->user()->id)
508             ->with('createdBy');
509
510         if ($minRange !== null) {
511             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
512         }
513
514         return $query;
515     }
516
517     /**
518      * Gets a single revision via it's id.
519      * @param $id
520      * @return mixed
521      */
522     public function getRevisionById($id)
523     {
524         return $this->pageRevision->findOrFail($id);
525     }
526
527     /**
528      * Checks if a slug exists within a book already.
529      * @param            $slug
530      * @param            $bookId
531      * @param bool|false $currentId
532      * @return bool
533      */
534     public function doesSlugExist($slug, $bookId, $currentId = false)
535     {
536         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
537         if ($currentId) $query = $query->where('id', '!=', $currentId);
538         return $query->count() > 0;
539     }
540
541     /**
542      * Changes the related book for the specified page.
543      * Changes the book id of any relations to the page that store the book id.
544      * @param int $bookId
545      * @param Page $page
546      * @return Page
547      */
548     public function changeBook($bookId, Page $page)
549     {
550         $page->book_id = $bookId;
551         foreach ($page->activity as $activity) {
552             $activity->book_id = $bookId;
553             $activity->save();
554         }
555         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
556         $page->save();
557         return $page;
558     }
559
560     /**
561      * Gets a suitable slug for the resource
562      * @param            $name
563      * @param            $bookId
564      * @param bool|false $currentId
565      * @return string
566      */
567     public function findSuitableSlug($name, $bookId, $currentId = false)
568     {
569         $slug = Str::slug($name);
570         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
571             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
572         }
573         return $slug;
574     }
575
576     /**
577      * Destroy a given page along with its dependencies.
578      * @param $page
579      */
580     public function destroy($page)
581     {
582         Activity::removeEntity($page);
583         $page->views()->delete();
584         $page->revisions()->delete();
585         $page->restrictions()->delete();
586         $page->delete();
587     }
588
589     /**
590      * Get the latest pages added to the system.
591      * @param $count
592      */
593     public function getRecentlyCreatedPaginated($count = 20)
594     {
595         return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
596     }
597
598     /**
599      * Get the latest pages added to the system.
600      * @param $count
601      */
602     public function getRecentlyUpdatedPaginated($count = 20)
603     {
604         return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
605     }
606
607 }