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