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));
211 $terms = array_merge($terms, explode(' ', $term));
212 $pages = $this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)
213 ->paginate($count)->appends($paginationAppends);
215 // Add highlights to page text.
216 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
217 //lookahead/behind assertions ensures cut between words
218 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
220 foreach ($pages as $page) {
221 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
222 //delimiter between occurrences
224 foreach ($matches as $line) {
225 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
228 if (count($results) > $matchLimit) {
229 $results = array_slice($results, 0, $matchLimit);
231 $result = join('... ', $results);
234 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
235 if (strlen($result) < 5) {
236 $result = $page->getExcerpt(80);
238 $page->searchSnippet = $result;
244 * Search for image usage.
245 * @param $imageString
248 public function searchForImage($imageString)
250 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
251 foreach ($pages as $page) {
252 $page->url = $page->getUrl();
256 return count($pages) > 0 ? $pages : false;
260 * Updates a page with any fillable data and saves it into the database.
262 * @param int $book_id
263 * @param string $input
266 public function updatePage(Page $page, $book_id, $input)
268 // Save a revision before updating
269 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
270 $this->saveRevision($page);
273 // Prevent slug being updated if no name change
274 if ($page->name !== $input['name']) {
275 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
278 // Update with new details
280 $page->html = $this->formatHtml($input['html']);
281 $page->text = strip_tags($page->html);
282 $page->updated_by = auth()->user()->id;
288 * Restores a revision's content back into a page.
291 * @param int $revisionId
294 public function restoreRevision(Page $page, Book $book, $revisionId)
296 $this->saveRevision($page);
297 $revision = $this->getRevisionById($revisionId);
298 $page->fill($revision->toArray());
299 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
300 $page->text = strip_tags($page->html);
301 $page->updated_by = auth()->user()->id;
307 * Saves a page revision into the system.
311 public function saveRevision(Page $page)
313 $revision = $this->pageRevision->fill($page->toArray());
314 $revision->page_id = $page->id;
315 $revision->slug = $page->slug;
316 $revision->book_slug = $page->book->slug;
317 $revision->created_by = auth()->user()->id;
318 $revision->created_at = $page->updated_at;
320 // Clear old revisions
321 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
322 $this->pageRevision->where('page_id', '=', $page->id)
323 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
329 * Gets a single revision via it's id.
333 public function getRevisionById($id)
335 return $this->pageRevision->findOrFail($id);
339 * Checks if a slug exists within a book already.
342 * @param bool|false $currentId
345 public function doesSlugExist($slug, $bookId, $currentId = false)
347 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
348 if ($currentId) $query = $query->where('id', '!=', $currentId);
349 return $query->count() > 0;
353 * Changes the related book for the specified page.
354 * Changes the book id of any relations to the page that store the book id.
359 public function changeBook($bookId, Page $page)
361 $page->book_id = $bookId;
362 foreach ($page->activity as $activity) {
363 $activity->book_id = $bookId;
366 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
372 * Gets a suitable slug for the resource
375 * @param bool|false $currentId
378 public function findSuitableSlug($name, $bookId, $currentId = false)
380 $slug = Str::slug($name);
381 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
382 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
388 * Destroy a given page along with its dependencies.
391 public function destroy($page)
393 Activity::removeEntity($page);
394 $page->views()->delete();
395 $page->revisions()->delete();
400 * Get the latest pages added to the system.
403 public function getRecentlyCreatedPaginated($count = 20)
405 return $this->page->orderBy('created_at', 'desc')->paginate($count);
409 * Get the latest pages added to the system.
412 public function getRecentlyUpdatedPaginated($count = 20)
414 return $this->page->orderBy('updated_at', 'desc')->paginate($count);