1 <?php namespace BookStack\Repos;
7 use Illuminate\Http\Request;
8 use Illuminate\Support\Facades\Auth;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
12 use BookStack\PageRevision;
13 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
18 protected $pageRevision;
21 * PageRepo constructor.
23 * @param PageRevision $pageRevision
25 public function __construct(Page $page, PageRevision $pageRevision)
28 $this->pageRevision = $pageRevision;
32 * Check if a page id exists.
36 public function idExists($id)
38 return $this->page->where('page_id', '=', $id)->count() > 0;
42 * Get a page via a specific ID.
46 public function getById($id)
48 return $this->page->findOrFail($id);
53 * @return \Illuminate\Database\Eloquent\Collection|static[]
55 public function getAll()
57 return $this->page->all();
61 * Get a page identified by the given slug.
66 public function getBySlug($slug, $bookId)
68 $page = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
69 if ($page === null) throw new NotFoundHttpException('Page not found');
74 * Search through page revisions and retrieve
75 * the last page in the current book that
76 * has a slug equal to the one given.
81 public function findPageUsingOldSlug($pageSlug, $bookSlug)
83 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
84 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
85 ->with('page')->first();
86 return $revision !== null ? $revision->page : null;
90 * Get a new Page instance from the given input.
94 public function newFromInput($input)
96 $page = $this->page->fill($input);
101 * Count the pages with a particular slug within a book.
106 public function countBySlug($slug, $bookId)
108 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
112 * Save a new page into the system.
113 * Input validation must be done beforehand.
114 * @param array $input
116 * @param int $chapterId
119 public function saveNew(array $input, Book $book, $chapterId = null)
121 $page = $this->newFromInput($input);
122 $page->slug = $this->findSuitableSlug($page->name, $book->id);
124 if ($chapterId) $page->chapter_id = $chapterId;
126 $page->html = $this->formatHtml($input['html']);
127 $page->text = strip_tags($page->html);
128 $page->created_by = auth()->user()->id;
129 $page->updated_by = auth()->user()->id;
131 $book->pages()->save($page);
136 * Formats a page's html to be tagged correctly
138 * @param string $htmlText
141 protected function formatHtml($htmlText)
143 if($htmlText == '') return $htmlText;
144 libxml_use_internal_errors(true);
145 $doc = new \DOMDocument();
146 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
148 $container = $doc->documentElement;
149 $body = $container->childNodes->item(0);
150 $childNodes = $body->childNodes;
152 // Ensure no duplicate ids are used
155 foreach ($childNodes as $index => $childNode) {
156 /** @var \DOMElement $childNode */
157 if (get_class($childNode) !== 'DOMElement') continue;
159 // Overwrite id if not a BookStack custom id
160 if ($childNode->hasAttribute('id')) {
161 $id = $childNode->getAttribute('id');
162 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
168 // Create an unique id for the element
169 // Uses the content as a basis to ensure output is the same every time
170 // the same content is passed through.
171 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
172 $newId = urlencode($contentId);
174 while (in_array($newId, $idArray)) {
175 $newId = urlencode($contentId . '-' . $loopIndex);
179 $childNode->setAttribute('id', $newId);
183 // Generate inner html as a string
185 foreach ($childNodes as $childNode) {
186 $html .= $doc->saveHTML($childNode);
194 * Gets pages by a search term.
195 * Highlights page content for showing in results.
196 * @param string $term
197 * @param array $whereTerms
199 * @param array $paginationAppends
202 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
204 preg_match_all('/"(.*?)"/', $term, $matches);
205 if (count($matches[1]) > 0) {
206 $terms = $matches[1];
207 $term = trim(preg_replace('/"(.*?)"/', '', $term));
212 $terms = array_merge($terms, explode(' ', $term));
214 $pages = $this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)
215 ->paginate($count)->appends($paginationAppends);
217 // Add highlights to page text.
218 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
219 //lookahead/behind assertions ensures cut between words
220 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
222 foreach ($pages as $page) {
223 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
224 //delimiter between occurrences
226 foreach ($matches as $line) {
227 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
230 if (count($results) > $matchLimit) {
231 $results = array_slice($results, 0, $matchLimit);
233 $result = join('... ', $results);
236 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
237 if (strlen($result) < 5) {
238 $result = $page->getExcerpt(80);
240 $page->searchSnippet = $result;
246 * Search for image usage.
247 * @param $imageString
250 public function searchForImage($imageString)
252 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
253 foreach ($pages as $page) {
254 $page->url = $page->getUrl();
258 return count($pages) > 0 ? $pages : false;
262 * Updates a page with any fillable data and saves it into the database.
264 * @param int $book_id
265 * @param string $input
268 public function updatePage(Page $page, $book_id, $input)
270 // Save a revision before updating
271 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
272 $this->saveRevision($page);
275 // Prevent slug being updated if no name change
276 if ($page->name !== $input['name']) {
277 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
280 // Update with new details
282 $page->html = $this->formatHtml($input['html']);
283 $page->text = strip_tags($page->html);
284 $page->updated_by = auth()->user()->id;
290 * Restores a revision's content back into a page.
293 * @param int $revisionId
296 public function restoreRevision(Page $page, Book $book, $revisionId)
298 $this->saveRevision($page);
299 $revision = $this->getRevisionById($revisionId);
300 $page->fill($revision->toArray());
301 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
302 $page->text = strip_tags($page->html);
303 $page->updated_by = auth()->user()->id;
309 * Saves a page revision into the system.
313 public function saveRevision(Page $page)
315 $revision = $this->pageRevision->fill($page->toArray());
316 $revision->page_id = $page->id;
317 $revision->slug = $page->slug;
318 $revision->book_slug = $page->book->slug;
319 $revision->created_by = auth()->user()->id;
320 $revision->created_at = $page->updated_at;
322 // Clear old revisions
323 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
324 $this->pageRevision->where('page_id', '=', $page->id)
325 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
331 * Gets a single revision via it's id.
335 public function getRevisionById($id)
337 return $this->pageRevision->findOrFail($id);
341 * Checks if a slug exists within a book already.
344 * @param bool|false $currentId
347 public function doesSlugExist($slug, $bookId, $currentId = false)
349 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
350 if ($currentId) $query = $query->where('id', '!=', $currentId);
351 return $query->count() > 0;
355 * Changes the related book for the specified page.
356 * Changes the book id of any relations to the page that store the book id.
361 public function changeBook($bookId, Page $page)
363 $page->book_id = $bookId;
364 foreach ($page->activity as $activity) {
365 $activity->book_id = $bookId;
368 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
374 * Gets a suitable slug for the resource
377 * @param bool|false $currentId
380 public function findSuitableSlug($name, $bookId, $currentId = false)
382 $slug = Str::slug($name);
383 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
384 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
390 * Destroy a given page along with its dependencies.
393 public function destroy($page)
395 Activity::removeEntity($page);
396 $page->views()->delete();
397 $page->revisions()->delete();
402 * Get the latest pages added to the system.
405 public function getRecentlyCreatedPaginated($count = 20)
407 return $this->page->orderBy('created_at', 'desc')->paginate($count);
411 * Get the latest pages added to the system.
414 public function getRecentlyUpdatedPaginated($count = 20)
416 return $this->page->orderBy('updated_at', 'desc')->paginate($count);