1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
7 use Illuminate\Support\Str;
9 use BookStack\PageRevision;
11 class PageRepo extends EntityRepo
13 protected $pageRevision;
16 * PageRepo constructor.
17 * @param PageRevision $pageRevision
19 public function __construct(PageRevision $pageRevision)
21 $this->pageRevision = $pageRevision;
22 parent::__construct();
26 * Base query for getting pages, Takes restrictions into account.
29 private function pageQuery()
31 return $this->restrictionService->enforcePageRestrictions($this->page, 'view');
35 * Get a page via a specific ID.
39 public function getById($id)
41 return $this->pageQuery()->findOrFail($id);
45 * Get a page identified by the given slug.
49 * @throws NotFoundException
51 public function getBySlug($slug, $bookId)
53 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
54 if ($page === null) throw new NotFoundException('Page not found');
59 * Search through page revisions and retrieve
60 * the last page in the current book that
61 * has a slug equal to the one given.
66 public function findPageUsingOldSlug($pageSlug, $bookSlug)
68 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
69 ->whereHas('page', function($query) {
70 $this->restrictionService->enforcePageRestrictions($query);
72 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
73 ->with('page')->first();
74 return $revision !== null ? $revision->page : null;
78 * Get a new Page instance from the given input.
82 public function newFromInput($input)
84 $page = $this->page->fill($input);
89 * Count the pages with a particular slug within a book.
94 public function countBySlug($slug, $bookId)
96 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
100 * Save a new page into the system.
101 * Input validation must be done beforehand.
102 * @param array $input
104 * @param int $chapterId
107 public function saveNew(array $input, Book $book, $chapterId = null)
109 $page = $this->newFromInput($input);
110 $page->slug = $this->findSuitableSlug($page->name, $book->id);
112 if ($chapterId) $page->chapter_id = $chapterId;
114 $page->html = $this->formatHtml($input['html']);
115 $page->text = strip_tags($page->html);
116 $page->created_by = auth()->user()->id;
117 $page->updated_by = auth()->user()->id;
119 $book->pages()->save($page);
124 * Formats a page's html to be tagged correctly
126 * @param string $htmlText
129 protected function formatHtml($htmlText)
131 if($htmlText == '') return $htmlText;
132 libxml_use_internal_errors(true);
133 $doc = new \DOMDocument();
134 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
136 $container = $doc->documentElement;
137 $body = $container->childNodes->item(0);
138 $childNodes = $body->childNodes;
140 // Ensure no duplicate ids are used
143 foreach ($childNodes as $index => $childNode) {
144 /** @var \DOMElement $childNode */
145 if (get_class($childNode) !== 'DOMElement') continue;
147 // Overwrite id if not a BookStack custom id
148 if ($childNode->hasAttribute('id')) {
149 $id = $childNode->getAttribute('id');
150 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
156 // Create an unique id for the element
157 // Uses the content as a basis to ensure output is the same every time
158 // the same content is passed through.
159 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
160 $newId = urlencode($contentId);
162 while (in_array($newId, $idArray)) {
163 $newId = urlencode($contentId . '-' . $loopIndex);
167 $childNode->setAttribute('id', $newId);
171 // Generate inner html as a string
173 foreach ($childNodes as $childNode) {
174 $html .= $doc->saveHTML($childNode);
182 * Gets pages by a search term.
183 * Highlights page content for showing in results.
184 * @param string $term
185 * @param array $whereTerms
187 * @param array $paginationAppends
190 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
192 $terms = $this->prepareSearchTerms($term);
193 $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
194 ->paginate($count)->appends($paginationAppends);
196 // Add highlights to page text.
197 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
198 //lookahead/behind assertions ensures cut between words
199 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
201 foreach ($pages as $page) {
202 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
203 //delimiter between occurrences
205 foreach ($matches as $line) {
206 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
209 if (count($results) > $matchLimit) {
210 $results = array_slice($results, 0, $matchLimit);
212 $result = join('... ', $results);
215 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
216 if (strlen($result) < 5) {
217 $result = $page->getExcerpt(80);
219 $page->searchSnippet = $result;
225 * Search for image usage.
226 * @param $imageString
229 public function searchForImage($imageString)
231 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
232 foreach ($pages as $page) {
233 $page->url = $page->getUrl();
237 return count($pages) > 0 ? $pages : false;
241 * Updates a page with any fillable data and saves it into the database.
243 * @param int $book_id
244 * @param string $input
247 public function updatePage(Page $page, $book_id, $input)
249 // Save a revision before updating
250 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
251 $this->saveRevision($page);
254 // Prevent slug being updated if no name change
255 if ($page->name !== $input['name']) {
256 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
259 // Update with new details
261 $page->html = $this->formatHtml($input['html']);
262 $page->text = strip_tags($page->html);
263 $page->updated_by = auth()->user()->id;
269 * Restores a revision's content back into a page.
272 * @param int $revisionId
275 public function restoreRevision(Page $page, Book $book, $revisionId)
277 $this->saveRevision($page);
278 $revision = $this->getRevisionById($revisionId);
279 $page->fill($revision->toArray());
280 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
281 $page->text = strip_tags($page->html);
282 $page->updated_by = auth()->user()->id;
288 * Saves a page revision into the system.
292 public function saveRevision(Page $page)
294 $revision = $this->pageRevision->fill($page->toArray());
295 $revision->page_id = $page->id;
296 $revision->slug = $page->slug;
297 $revision->book_slug = $page->book->slug;
298 $revision->created_by = auth()->user()->id;
299 $revision->created_at = $page->updated_at;
301 // Clear old revisions
302 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
303 $this->pageRevision->where('page_id', '=', $page->id)
304 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
310 * Gets a single revision via it's id.
314 public function getRevisionById($id)
316 return $this->pageRevision->findOrFail($id);
320 * Checks if a slug exists within a book already.
323 * @param bool|false $currentId
326 public function doesSlugExist($slug, $bookId, $currentId = false)
328 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
329 if ($currentId) $query = $query->where('id', '!=', $currentId);
330 return $query->count() > 0;
334 * Changes the related book for the specified page.
335 * Changes the book id of any relations to the page that store the book id.
340 public function changeBook($bookId, Page $page)
342 $page->book_id = $bookId;
343 foreach ($page->activity as $activity) {
344 $activity->book_id = $bookId;
347 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
353 * Gets a suitable slug for the resource
356 * @param bool|false $currentId
359 public function findSuitableSlug($name, $bookId, $currentId = false)
361 $slug = Str::slug($name);
362 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
363 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
369 * Destroy a given page along with its dependencies.
372 public function destroy($page)
374 Activity::removeEntity($page);
375 $page->views()->delete();
376 $page->revisions()->delete();
377 $page->restrictions()->delete();
382 * Get the latest pages added to the system.
385 public function getRecentlyCreatedPaginated($count = 20)
387 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
391 * Get the latest pages added to the system.
394 public function getRecentlyUpdatedPaginated($count = 20)
396 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);