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