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