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