]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
Added in restriction queries for most lists
[bookstack] / app / Repos / PageRepo.php
1 <?php namespace BookStack\Repos;
2
3
4 use Activity;
5 use BookStack\Book;
6 use BookStack\Chapter;
7 use BookStack\Services\RestrictionService;
8 use Illuminate\Http\Request;
9 use Illuminate\Support\Facades\Auth;
10 use Illuminate\Support\Facades\Log;
11 use Illuminate\Support\Str;
12 use BookStack\Page;
13 use BookStack\PageRevision;
14 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
16 class PageRepo
17 {
18     protected $page;
19     protected $pageRevision;
20     protected $restrictionService;
21
22     /**
23      * PageRepo constructor.
24      * @param Page $page
25      * @param PageRevision $pageRevision
26      * @param RestrictionService $restrictionService
27      */
28     public function __construct(Page $page, PageRevision $pageRevision, RestrictionService $restrictionService)
29     {
30         $this->page = $page;
31         $this->pageRevision = $pageRevision;
32         $this->restrictionService = $restrictionService;
33     }
34
35     /**
36      * Base query for getting pages, Takes restrictions into account.
37      * @return mixed
38      */
39     private function pageQuery()
40     {
41         return $this->restrictionService->enforcePageRestrictions($this->page, 'view');
42     }
43
44     /**
45      * Get a page via a specific ID.
46      * @param $id
47      * @return mixed
48      */
49     public function getById($id)
50     {
51         return $this->pageQuery()->findOrFail($id);
52     }
53
54     /**
55      * Get a page identified by the given slug.
56      * @param $slug
57      * @param $bookId
58      * @return mixed
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 NotFoundHttpException('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('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
82             ->with('page')->first();
83         return $revision !== null ? $revision->page : null;
84     }
85
86     /**
87      * Get a new Page instance from the given input.
88      * @param $input
89      * @return Page
90      */
91     public function newFromInput($input)
92     {
93         $page = $this->page->fill($input);
94         return $page;
95     }
96
97
98     /**
99      * Save a new page into the system.
100      * Input validation must be done beforehand.
101      * @param array $input
102      * @param Book  $book
103      * @param int   $chapterId
104      * @return Page
105      */
106     public function saveNew(array $input, Book $book, $chapterId = null)
107     {
108         $page = $this->newFromInput($input);
109         $page->slug = $this->findSuitableSlug($page->name, $book->id);
110
111         if ($chapterId) $page->chapter_id = $chapterId;
112
113         $page->html = $this->formatHtml($input['html']);
114         $page->text = strip_tags($page->html);
115         $page->created_by = auth()->user()->id;
116         $page->updated_by = auth()->user()->id;
117
118         $book->pages()->save($page);
119         return $page;
120     }
121
122     /**
123      * Formats a page's html to be tagged correctly
124      * within the system.
125      * @param string $htmlText
126      * @return string
127      */
128     protected function formatHtml($htmlText)
129     {
130         if($htmlText == '') return $htmlText;
131         libxml_use_internal_errors(true);
132         $doc = new \DOMDocument();
133         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
134
135         $container = $doc->documentElement;
136         $body = $container->childNodes->item(0);
137         $childNodes = $body->childNodes;
138
139         // Ensure no duplicate ids are used
140         $idArray = [];
141
142         foreach ($childNodes as $index => $childNode) {
143             /** @var \DOMElement $childNode */
144             if (get_class($childNode) !== 'DOMElement') continue;
145
146             // Overwrite id if not a BookStack custom id
147             if ($childNode->hasAttribute('id')) {
148                 $id = $childNode->getAttribute('id');
149                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
150                     $idArray[] = $id;
151                     continue;
152                 };
153             }
154
155             // Create an unique id for the element
156             // Uses the content as a basis to ensure output is the same every time
157             // the same content is passed through.
158             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
159             $newId = urlencode($contentId);
160             $loopIndex = 0;
161             while (in_array($newId, $idArray)) {
162                 $newId = urlencode($contentId . '-' . $loopIndex);
163                 $loopIndex++;
164             }
165
166             $childNode->setAttribute('id', $newId);
167             $idArray[] = $newId;
168         }
169
170         // Generate inner html as a string
171         $html = '';
172         foreach ($childNodes as $childNode) {
173             $html .= $doc->saveHTML($childNode);
174         }
175
176         return $html;
177     }
178
179
180     /**
181      * Gets pages by a search term.
182      * Highlights page content for showing in results.
183      * @param string $term
184      * @param array $whereTerms
185      * @param int $count
186      * @param array $paginationAppends
187      * @return mixed
188      */
189     public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
190     {
191         $terms = explode(' ', $term);
192         $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
193             ->paginate($count)->appends($paginationAppends);
194
195         // Add highlights to page text.
196         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
197         //lookahead/behind assertions ensures cut between words
198         $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
199
200         foreach ($pages as $page) {
201             preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
202             //delimiter between occurrences
203             $results = [];
204             foreach ($matches as $line) {
205                 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
206             }
207             $matchLimit = 6;
208             if (count($results) > $matchLimit) {
209                 $results = array_slice($results, 0, $matchLimit);
210             }
211             $result = join('... ', $results);
212
213             //highlight
214             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
215             if (strlen($result) < 5) {
216                 $result = $page->getExcerpt(80);
217             }
218             $page->searchSnippet = $result;
219         }
220         return $pages;
221     }
222
223     /**
224      * Search for image usage.
225      * @param $imageString
226      * @return mixed
227      */
228     public function searchForImage($imageString)
229     {
230         $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
231         foreach ($pages as $page) {
232             $page->url = $page->getUrl();
233             $page->html = '';
234             $page->text = '';
235         }
236         return count($pages) > 0 ? $pages : false;
237     }
238
239     /**
240      * Updates a page with any fillable data and saves it into the database.
241      * @param Page   $page
242      * @param int    $book_id
243      * @param string $input
244      * @return Page
245      */
246     public function updatePage(Page $page, $book_id, $input)
247     {
248         // Save a revision before updating
249         if ($page->html !== $input['html'] || $page->name !== $input['name']) {
250             $this->saveRevision($page);
251         }
252
253         // Prevent slug being updated if no name change
254         if ($page->name !== $input['name']) {
255             $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
256         }
257
258         // Update with new details
259         $page->fill($input);
260         $page->html = $this->formatHtml($input['html']);
261         $page->text = strip_tags($page->html);
262         $page->updated_by = auth()->user()->id;
263         $page->save();
264         return $page;
265     }
266
267     /**
268      * Restores a revision's content back into a page.
269      * @param Page $page
270      * @param Book $book
271      * @param  int $revisionId
272      * @return Page
273      */
274     public function restoreRevision(Page $page, Book $book, $revisionId)
275     {
276         $this->saveRevision($page);
277         $revision = $this->getRevisionById($revisionId);
278         $page->fill($revision->toArray());
279         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
280         $page->text = strip_tags($page->html);
281         $page->updated_by = auth()->user()->id;
282         $page->save();
283         return $page;
284     }
285
286     /**
287      * Saves a page revision into the system.
288      * @param Page $page
289      * @return $this
290      */
291     public function saveRevision(Page $page)
292     {
293         $revision = $this->pageRevision->fill($page->toArray());
294         $revision->page_id = $page->id;
295         $revision->slug = $page->slug;
296         $revision->book_slug = $page->book->slug;
297         $revision->created_by = auth()->user()->id;
298         $revision->created_at = $page->updated_at;
299         $revision->save();
300         // Clear old revisions
301         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
302             $this->pageRevision->where('page_id', '=', $page->id)
303                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
304         }
305         return $revision;
306     }
307
308     /**
309      * Gets a single revision via it's id.
310      * @param $id
311      * @return mixed
312      */
313     public function getRevisionById($id)
314     {
315         return $this->pageRevision->findOrFail($id);
316     }
317
318     /**
319      * Checks if a slug exists within a book already.
320      * @param            $slug
321      * @param            $bookId
322      * @param bool|false $currentId
323      * @return bool
324      */
325     public function doesSlugExist($slug, $bookId, $currentId = false)
326     {
327         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
328         if ($currentId) $query = $query->where('id', '!=', $currentId);
329         return $query->count() > 0;
330     }
331
332     /**
333      * Changes the related book for the specified page.
334      * Changes the book id of any relations to the page that store the book id.
335      * @param int  $bookId
336      * @param Page $page
337      * @return Page
338      */
339     public function changeBook($bookId, Page $page)
340     {
341         $page->book_id = $bookId;
342         foreach ($page->activity as $activity) {
343             $activity->book_id = $bookId;
344             $activity->save();
345         }
346         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
347         $page->save();
348         return $page;
349     }
350
351     /**
352      * Gets a suitable slug for the resource
353      * @param            $name
354      * @param            $bookId
355      * @param bool|false $currentId
356      * @return string
357      */
358     public function findSuitableSlug($name, $bookId, $currentId = false)
359     {
360         $slug = Str::slug($name);
361         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
362             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
363         }
364         return $slug;
365     }
366
367     /**
368      * Destroy a given page along with its dependencies.
369      * @param $page
370      */
371     public function destroy($page)
372     {
373         Activity::removeEntity($page);
374         $page->views()->delete();
375         $page->revisions()->delete();
376         $page->delete();
377     }
378
379     /**
380      * Get the latest pages added to the system.
381      * @param $count
382      */
383     public function getRecentlyCreatedPaginated($count = 20)
384     {
385         return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
386     }
387
388     /**
389      * Get the latest pages added to the system.
390      * @param $count
391      */
392     public function getRecentlyUpdatedPaginated($count = 20)
393     {
394         return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
395     }
396
397     /**
398      * Updates pages restrictions from a request
399      * @param $request
400      * @param $page
401      */
402     public function updateRestrictionsFromRequest($request, $page)
403     {
404         // TODO - extract into shared repo
405         $page->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
406         $page->restrictions()->delete();
407         if ($request->has('restrictions')) {
408             foreach($request->get('restrictions') as $roleId => $restrictions) {
409                 foreach ($restrictions as $action => $value) {
410                     $page->restrictions()->create([
411                         'role_id' => $roleId,
412                         'action'  => strtolower($action)
413                     ]);
414                 }
415             }
416         }
417         $page->save();
418     }
419
420 }