]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
699e6ecc564e50d3c59527f7557e0130891f2eb9
[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      * Count the pages with a particular slug within a book.
70      * @param $slug
71      * @param $bookId
72      * @return mixed
73      */
74     public function countBySlug($slug, $bookId)
75     {
76         return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
77     }
78
79     /**
80      * Publish a draft page to make it a normal page.
81      * Sets the slug and updates the content.
82      * @param Page $draftPage
83      * @param array $input
84      * @return Page
85      */
86     public function publishDraft(Page $draftPage, array $input)
87     {
88         $draftPage->fill($input);
89
90         // Save page tags if present
91         if (isset($input['tags'])) {
92             $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
93         }
94
95         $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
96         $draftPage->html = $this->formatHtml($input['html']);
97         $draftPage->text = strip_tags($draftPage->html);
98         $draftPage->draft = false;
99
100         $draftPage->save();
101         $this->saveRevision($draftPage, trans('entities.pages_initial_revision'));
102         
103         return $draftPage;
104     }
105
106     /**
107      * Get a new draft page instance.
108      * @param Book $book
109      * @param Chapter|bool $chapter
110      * @return Page
111      */
112     public function getDraftPage(Book $book, $chapter = false)
113     {
114         $page = $this->page->newInstance();
115         $page->name = trans('entities.pages_initial_name');
116         $page->created_by = user()->id;
117         $page->updated_by = user()->id;
118         $page->draft = true;
119
120         if ($chapter) $page->chapter_id = $chapter->id;
121
122         $book->pages()->save($page);
123         $this->permissionService->buildJointPermissionsForEntity($page);
124         return $page;
125     }
126
127     /**
128      * Parse te headers on the page to get a navigation menu
129      * @param Page $page
130      * @return array
131      */
132     public function getPageNav(Page $page)
133     {
134         if ($page->html == '') return null;
135         libxml_use_internal_errors(true);
136         $doc = new DOMDocument();
137         $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
138         $xPath = new DOMXPath($doc);
139         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
140
141         if (is_null($headers)) return null;
142
143         $tree = [];
144         foreach ($headers as $header) {
145             $text = $header->nodeValue;
146             $tree[] = [
147                 'nodeName' => strtolower($header->nodeName),
148                 'level' => intval(str_replace('h', '', $header->nodeName)),
149                 'link' => '#' . $header->getAttribute('id'),
150                 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
151             ];
152         }
153         return $tree;
154     }
155
156     /**
157      * Formats a page's html to be tagged correctly
158      * within the system.
159      * @param string $htmlText
160      * @return string
161      */
162     protected function formatHtml($htmlText)
163     {
164         if ($htmlText == '') return $htmlText;
165         libxml_use_internal_errors(true);
166         $doc = new DOMDocument();
167         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
168
169         $container = $doc->documentElement;
170         $body = $container->childNodes->item(0);
171         $childNodes = $body->childNodes;
172
173         // Ensure no duplicate ids are used
174         $idArray = [];
175
176         foreach ($childNodes as $index => $childNode) {
177             /** @var \DOMElement $childNode */
178             if (get_class($childNode) !== 'DOMElement') continue;
179
180             // Overwrite id if not a BookStack custom id
181             if ($childNode->hasAttribute('id')) {
182                 $id = $childNode->getAttribute('id');
183                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
184                     $idArray[] = $id;
185                     continue;
186                 };
187             }
188
189             // Create an unique id for the element
190             // Uses the content as a basis to ensure output is the same every time
191             // the same content is passed through.
192             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
193             $newId = urlencode($contentId);
194             $loopIndex = 0;
195             while (in_array($newId, $idArray)) {
196                 $newId = urlencode($contentId . '-' . $loopIndex);
197                 $loopIndex++;
198             }
199
200             $childNode->setAttribute('id', $newId);
201             $idArray[] = $newId;
202         }
203
204         // Generate inner html as a string
205         $html = '';
206         foreach ($childNodes as $childNode) {
207             $html .= $doc->saveHTML($childNode);
208         }
209
210         return $html;
211     }
212
213
214     /**
215      * Search for image usage.
216      * @param $imageString
217      * @return mixed
218      */
219     public function searchForImage($imageString)
220     {
221         $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
222         foreach ($pages as $page) {
223             $page->url = $page->getUrl();
224             $page->html = '';
225             $page->text = '';
226         }
227         return count($pages) > 0 ? $pages : false;
228     }
229
230     /**
231      * Updates a page with any fillable data and saves it into the database.
232      * @param Page $page
233      * @param int $book_id
234      * @param string $input
235      * @return Page
236      */
237     public function updatePage(Page $page, $book_id, $input)
238     {
239         // Hold the old details to compare later
240         $oldHtml = $page->html;
241         $oldName = $page->name;
242
243         // Prevent slug being updated if no name change
244         if ($page->name !== $input['name']) {
245             $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
246         }
247
248         // Save page tags if present
249         if (isset($input['tags'])) {
250             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
251         }
252
253         // Update with new details
254         $userId = user()->id;
255         $page->fill($input);
256         $page->html = $this->formatHtml($input['html']);
257         $page->text = strip_tags($page->html);
258         if (setting('app-editor') !== 'markdown') $page->markdown = '';
259         $page->updated_by = $userId;
260         $page->save();
261
262         // Remove all update drafts for this user & page.
263         $this->userUpdateDraftsQuery($page, $userId)->delete();
264
265         // Save a revision after updating
266         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
267             $this->saveRevision($page, $input['summary']);
268         }
269
270         return $page;
271     }
272
273     /**
274      * Restores a revision's content back into a page.
275      * @param Page $page
276      * @param Book $book
277      * @param  int $revisionId
278      * @return Page
279      */
280     public function restoreRevision(Page $page, Book $book, $revisionId)
281     {
282         $this->saveRevision($page);
283         $revision = $this->getRevisionById($revisionId);
284         $page->fill($revision->toArray());
285         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
286         $page->text = strip_tags($page->html);
287         $page->updated_by = user()->id;
288         $page->save();
289         return $page;
290     }
291
292     /**
293      * Saves a page revision into the system.
294      * @param Page $page
295      * @param null|string $summary
296      * @return $this
297      */
298     public function saveRevision(Page $page, $summary = null)
299     {
300         $revision = $this->pageRevision->newInstance($page->toArray());
301         if (setting('app-editor') !== 'markdown') $revision->markdown = '';
302         $revision->page_id = $page->id;
303         $revision->slug = $page->slug;
304         $revision->book_slug = $page->book->slug;
305         $revision->created_by = user()->id;
306         $revision->created_at = $page->updated_at;
307         $revision->type = 'version';
308         $revision->summary = $summary;
309         $revision->save();
310
311         // Clear old revisions
312         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
313             $this->pageRevision->where('page_id', '=', $page->id)
314                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
315         }
316
317         return $revision;
318     }
319
320     /**
321      * Save a page update draft.
322      * @param Page $page
323      * @param array $data
324      * @return PageRevision
325      */
326     public function saveUpdateDraft(Page $page, $data = [])
327     {
328         $userId = user()->id;
329         $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
330
331         if ($drafts->count() > 0) {
332             $draft = $drafts->first();
333         } else {
334             $draft = $this->pageRevision->newInstance();
335             $draft->page_id = $page->id;
336             $draft->slug = $page->slug;
337             $draft->book_slug = $page->book->slug;
338             $draft->created_by = $userId;
339             $draft->type = 'update_draft';
340         }
341
342         $draft->fill($data);
343         if (setting('app-editor') !== 'markdown') $draft->markdown = '';
344
345         $draft->save();
346         return $draft;
347     }
348
349     /**
350      * Update a draft page.
351      * @param Page $page
352      * @param array $data
353      * @return Page
354      */
355     public function updateDraftPage(Page $page, $data = [])
356     {
357         $page->fill($data);
358
359         if (isset($data['html'])) {
360             $page->text = strip_tags($data['html']);
361         }
362
363         $page->save();
364         return $page;
365     }
366
367     /**
368      * The base query for getting user update drafts.
369      * @param Page $page
370      * @param $userId
371      * @return mixed
372      */
373     private function userUpdateDraftsQuery(Page $page, $userId)
374     {
375         return $this->pageRevision->where('created_by', '=', $userId)
376             ->where('type', 'update_draft')
377             ->where('page_id', '=', $page->id)
378             ->orderBy('created_at', 'desc');
379     }
380
381     /**
382      * Checks whether a user has a draft version of a particular page or not.
383      * @param Page $page
384      * @param $userId
385      * @return bool
386      */
387     public function hasUserGotPageDraft(Page $page, $userId)
388     {
389         return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
390     }
391
392     /**
393      * Get the latest updated draft revision for a particular page and user.
394      * @param Page $page
395      * @param $userId
396      * @return mixed
397      */
398     public function getUserPageDraft(Page $page, $userId)
399     {
400         return $this->userUpdateDraftsQuery($page, $userId)->first();
401     }
402
403     /**
404      * Get the notification message that informs the user that they are editing a draft page.
405      * @param PageRevision $draft
406      * @return string
407      */
408     public function getUserPageDraftMessage(PageRevision $draft)
409     {
410         $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
411         if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
412         return $message . "\n" . trans('entities.pages_draft_edited_notification');
413     }
414
415     /**
416      * Check if a page is being actively editing.
417      * Checks for edits since last page updated.
418      * Passing in a minuted range will check for edits
419      * within the last x minutes.
420      * @param Page $page
421      * @param null $minRange
422      * @return bool
423      */
424     public function isPageEditingActive(Page $page, $minRange = null)
425     {
426         $draftSearch = $this->activePageEditingQuery($page, $minRange);
427         return $draftSearch->count() > 0;
428     }
429
430     /**
431      * Get a notification message concerning the editing activity on
432      * a particular page.
433      * @param Page $page
434      * @param null $minRange
435      * @return string
436      */
437     public function getPageEditingActiveMessage(Page $page, $minRange = null)
438     {
439         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
440
441         $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]);
442         $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
443         return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
444     }
445
446     /**
447      * A query to check for active update drafts on a particular page.
448      * @param Page $page
449      * @param null $minRange
450      * @return mixed
451      */
452     private function activePageEditingQuery(Page $page, $minRange = null)
453     {
454         $query = $this->pageRevision->where('type', '=', 'update_draft')
455             ->where('page_id', '=', $page->id)
456             ->where('updated_at', '>', $page->updated_at)
457             ->where('created_by', '!=', user()->id)
458             ->with('createdBy');
459
460         if ($minRange !== null) {
461             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
462         }
463
464         return $query;
465     }
466
467     /**
468      * Gets a single revision via it's id.
469      * @param $id
470      * @return PageRevision
471      */
472     public function getRevisionById($id)
473     {
474         return $this->pageRevision->findOrFail($id);
475     }
476
477     /**
478      * Changes the related book for the specified page.
479      * Changes the book id of any relations to the page that store the book id.
480      * @param int $bookId
481      * @param Page $page
482      * @return Page
483      */
484     public function changeBook($bookId, Page $page)
485     {
486         $page->book_id = $bookId;
487         foreach ($page->activity as $activity) {
488             $activity->book_id = $bookId;
489             $activity->save();
490         }
491         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $bookId);
492         $page->save();
493         return $page;
494     }
495
496
497     /**
498      * Change the page's parent to the given entity.
499      * @param Page $page
500      * @param Entity $parent
501      */
502     public function changePageParent(Page $page, Entity $parent)
503     {
504         $book = $parent->isA('book') ? $parent : $parent->book;
505         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
506         $page->save();
507         $page = $this->changeBook($book->id, $page);
508         $page->load('book');
509         $this->permissionService->buildJointPermissionsForEntity($book);
510     }
511
512     /**
513      * Destroy a given page along with its dependencies.
514      * @param $page
515      */
516     public function destroy(Page $page)
517     {
518         Activity::removeEntity($page);
519         $page->views()->delete();
520         $page->tags()->delete();
521         $page->revisions()->delete();
522         $page->permissions()->delete();
523         $this->permissionService->deleteJointPermissionsForEntity($page);
524
525         // Delete AttachedFiles
526         $attachmentService = app(AttachmentService::class);
527         foreach ($page->attachments as $attachment) {
528             $attachmentService->deleteFile($attachment);
529         }
530
531         $page->delete();
532     }
533
534     /**
535      * Get the latest pages added to the system.
536      * @param $count
537      * @return mixed
538      */
539     public function getRecentlyCreatedPaginated($count = 20)
540     {
541         return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
542     }
543
544     /**
545      * Get the latest pages added to the system.
546      * @param $count
547      * @return mixed
548      */
549     public function getRecentlyUpdatedPaginated($count = 20)
550     {
551         return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
552     }
553
554 }