]> BookStack Code Mirror - bookstack/blob - app/Repos/PageRepo.php
e049ae57b67a6cde77d18d07683f349f5891e817
[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 Illuminate\Http\Request;
8 use Illuminate\Support\Facades\Auth;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
11 use BookStack\Page;
12 use BookStack\PageRevision;
13
14 class PageRepo
15 {
16     protected $page;
17     protected $pageRevision;
18
19     /**
20      * PageRepo constructor.
21      * @param Page         $page
22      * @param PageRevision $pageRevision
23      */
24     public function __construct(Page $page, PageRevision $pageRevision)
25     {
26         $this->page = $page;
27         $this->pageRevision = $pageRevision;
28     }
29
30     /**
31      * Check if a page id exists.
32      * @param $id
33      * @return bool
34      */
35     public function idExists($id)
36     {
37         return $this->page->where('page_id', '=', $id)->count() > 0;
38     }
39
40     /**
41      * Get a page via a specific ID.
42      * @param $id
43      * @return mixed
44      */
45     public function getById($id)
46     {
47         return $this->page->findOrFail($id);
48     }
49
50     /**
51      * Get all pages.
52      * @return \Illuminate\Database\Eloquent\Collection|static[]
53      */
54     public function getAll()
55     {
56         return $this->page->all();
57     }
58
59     /**
60      * Get a page identified by the given slug.
61      * @param $slug
62      * @param $bookId
63      * @return mixed
64      */
65     public function getBySlug($slug, $bookId)
66     {
67         $page = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
68         if ($page === null) abort(404);
69         return $page;
70     }
71
72     /**
73      * @param $input
74      * @return Page
75      */
76     public function newFromInput($input)
77     {
78         $page = $this->page->fill($input);
79         return $page;
80     }
81
82     /**
83      * Count the pages with a particular slug within a book.
84      * @param $slug
85      * @param $bookId
86      * @return mixed
87      */
88     public function countBySlug($slug, $bookId)
89     {
90         return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
91     }
92
93     /**
94      * Save a new page into the system.
95      * Input validation must be done beforehand.
96      * @param array $input
97      * @param Book  $book
98      * @param int   $chapterId
99      * @return Page
100      */
101     public function saveNew(array $input, Book $book, $chapterId = null)
102     {
103         $page = $this->newFromInput($input);
104         $page->slug = $this->findSuitableSlug($page->name, $book->id);
105
106         if ($chapterId) $page->chapter_id = $chapterId;
107
108         $page->html = $this->formatHtml($input['html']);
109         $page->text = strip_tags($page->html);
110         $page->created_by = auth()->user()->id;
111         $page->updated_by = auth()->user()->id;
112
113         $book->pages()->save($page);
114         return $page;
115     }
116
117     /**
118      * Formats a page's html to be tagged correctly
119      * within the system.
120      * @param string $htmlText
121      * @return string
122      */
123     protected function formatHtml($htmlText)
124     {
125         if($htmlText == '') return $htmlText;
126         libxml_use_internal_errors(true);
127         $doc = new \DOMDocument();
128         $doc->loadHTML($htmlText);
129
130         $container = $doc->documentElement;
131         $body = $container->childNodes->item(0);
132         $childNodes = $body->childNodes;
133
134         // Ensure no duplicate ids are used
135         $lastId = false;
136         $idArray = [];
137
138         foreach ($childNodes as $index => $childNode) {
139             /** @var \DOMElement $childNode */
140             if (get_class($childNode) !== 'DOMElement') continue;
141
142             // Overwrite id if not a bookstack custom id
143             if ($childNode->hasAttribute('id')) {
144                 $id = $childNode->getAttribute('id');
145                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
146                     $idArray[] = $id;
147                     continue;
148                 };
149             }
150
151             // Create an unique id for the element
152             do {
153                 $id = 'bkmrk-' . substr(uniqid(), -5);
154             } while ($id == $lastId);
155             $lastId = $id;
156
157             $childNode->setAttribute('id', $id);
158             $idArray[] = $id;
159         }
160
161         // Generate inner html as a string
162         $html = '';
163         foreach ($childNodes as $childNode) {
164             $html .= $doc->saveHTML($childNode);
165         }
166
167         return $html;
168     }
169
170
171     /**
172      * Gets pages by a search term.
173      * Highlights page content for showing in results.
174      * @param string      $term
175      * @param array $whereTerms
176      * @return mixed
177      */
178     public function getBySearch($term, $whereTerms = [])
179     {
180         $terms = explode(' ', preg_quote(trim($term)));
181         $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
182
183         // Add highlights to page text.
184         $words = join('|', $terms);
185         //lookahead/behind assertions ensures cut between words
186         $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
187
188         foreach ($pages as $page) {
189             preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
190             //delimiter between occurrences
191             $results = [];
192             foreach ($matches as $line) {
193                 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
194             }
195             $matchLimit = 6;
196             if (count($results) > $matchLimit) {
197                 $results = array_slice($results, 0, $matchLimit);
198             }
199             $result = join('... ', $results);
200
201             //highlight
202             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
203             if (strlen($result) < 5) {
204                 $result = $page->getExcerpt(80);
205             }
206             $page->searchSnippet = $result;
207         }
208         return $pages;
209     }
210
211     /**
212      * Search for image usage.
213      * @param $imageString
214      * @return mixed
215      */
216     public function searchForImage($imageString)
217     {
218         $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
219         foreach ($pages as $page) {
220             $page->url = $page->getUrl();
221             $page->html = '';
222             $page->text = '';
223         }
224         return count($pages) > 0 ? $pages : false;
225     }
226
227     /**
228      * Updates a page with any fillable data and saves it into the database.
229      * @param Page   $page
230      * @param int    $book_id
231      * @param string $input
232      * @return Page
233      */
234     public function updatePage(Page $page, $book_id, $input)
235     {
236         // Save a revision before updating
237         if ($page->html !== $input['html'] || $page->name !== $input['name']) {
238             $this->saveRevision($page);
239         }
240
241         // Update with new details
242         $page->fill($input);
243         $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
244         $page->html = $this->formatHtml($input['html']);
245         $page->text = strip_tags($page->html);
246         $page->updated_by = auth()->user()->id;
247         $page->save();
248         return $page;
249     }
250
251     /**
252      * Restores a revision's content back into a page.
253      * @param Page $page
254      * @param Book $book
255      * @param  int $revisionId
256      * @return Page
257      */
258     public function restoreRevision(Page $page, Book $book, $revisionId)
259     {
260         $this->saveRevision($page);
261         $revision = $this->getRevisionById($revisionId);
262         $page->fill($revision->toArray());
263         $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
264         $page->text = strip_tags($page->html);
265         $page->updated_by = auth()->user()->id;
266         $page->save();
267         return $page;
268     }
269
270     /**
271      * Saves a page revision into the system.
272      * @param Page $page
273      * @return $this
274      */
275     public function saveRevision(Page $page)
276     {
277         $revision = $this->pageRevision->fill($page->toArray());
278         $revision->page_id = $page->id;
279         $revision->created_by = auth()->user()->id;
280         $revision->created_at = $page->updated_at;
281         $revision->save();
282         // Clear old revisions
283         if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
284             $this->pageRevision->where('page_id', '=', $page->id)
285                 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
286         }
287         return $revision;
288     }
289
290     /**
291      * Gets a single revision via it's id.
292      * @param $id
293      * @return mixed
294      */
295     public function getRevisionById($id)
296     {
297         return $this->pageRevision->findOrFail($id);
298     }
299
300     /**
301      * Checks if a slug exists within a book already.
302      * @param            $slug
303      * @param            $bookId
304      * @param bool|false $currentId
305      * @return bool
306      */
307     public function doesSlugExist($slug, $bookId, $currentId = false)
308     {
309         $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
310         if ($currentId) $query = $query->where('id', '!=', $currentId);
311         return $query->count() > 0;
312     }
313
314     /**
315      * Changes the related book for the specified page.
316      * Changes the book id of any relations to the page that store the book id.
317      * @param int  $bookId
318      * @param Page $page
319      * @return Page
320      */
321     public function changeBook($bookId, Page $page)
322     {
323         $page->book_id = $bookId;
324         foreach ($page->activity as $activity) {
325             $activity->book_id = $bookId;
326             $activity->save();
327         }
328         $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
329         $page->save();
330         return $page;
331     }
332
333     /**
334      * Gets a suitable slug for the resource
335      * @param            $name
336      * @param            $bookId
337      * @param bool|false $currentId
338      * @return string
339      */
340     public function findSuitableSlug($name, $bookId, $currentId = false)
341     {
342         $slug = Str::slug($name);
343         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
344             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
345         }
346         return $slug;
347     }
348
349     /**
350      * Destroy a given page along with its dependencies.
351      * @param $page
352      */
353     public function destroy($page)
354     {
355         Activity::removeEntity($page);
356         $page->views()->delete();
357         $page->revisions()->delete();
358         $page->delete();
359     }
360
361
362 }