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