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 $terms = explode(' ', $term);
205 $pages = $this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)
206 ->paginate($count)->appends($paginationAppends);
208 // Add highlights to page text.
209 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
210 //lookahead/behind assertions ensures cut between words
211 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
213 foreach ($pages as $page) {
214 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
215 //delimiter between occurrences
217 foreach ($matches as $line) {
218 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
221 if (count($results) > $matchLimit) {
222 $results = array_slice($results, 0, $matchLimit);
224 $result = join('... ', $results);
227 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
228 if (strlen($result) < 5) {
229 $result = $page->getExcerpt(80);
231 $page->searchSnippet = $result;
237 * Search for image usage.
238 * @param $imageString
241 public function searchForImage($imageString)
243 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
244 foreach ($pages as $page) {
245 $page->url = $page->getUrl();
249 return count($pages) > 0 ? $pages : false;
253 * Updates a page with any fillable data and saves it into the database.
255 * @param int $book_id
256 * @param string $input
259 public function updatePage(Page $page, $book_id, $input)
261 // Save a revision before updating
262 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
263 $this->saveRevision($page);
266 // Prevent slug being updated if no name change
267 if ($page->name !== $input['name']) {
268 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
271 // Update with new details
273 $page->html = $this->formatHtml($input['html']);
274 $page->text = strip_tags($page->html);
275 $page->updated_by = auth()->user()->id;
281 * Restores a revision's content back into a page.
284 * @param int $revisionId
287 public function restoreRevision(Page $page, Book $book, $revisionId)
289 $this->saveRevision($page);
290 $revision = $this->getRevisionById($revisionId);
291 $page->fill($revision->toArray());
292 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
293 $page->text = strip_tags($page->html);
294 $page->updated_by = auth()->user()->id;
300 * Saves a page revision into the system.
304 public function saveRevision(Page $page)
306 $revision = $this->pageRevision->fill($page->toArray());
307 $revision->page_id = $page->id;
308 $revision->slug = $page->slug;
309 $revision->book_slug = $page->book->slug;
310 $revision->created_by = auth()->user()->id;
311 $revision->created_at = $page->updated_at;
313 // Clear old revisions
314 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
315 $this->pageRevision->where('page_id', '=', $page->id)
316 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
322 * Gets a single revision via it's id.
326 public function getRevisionById($id)
328 return $this->pageRevision->findOrFail($id);
332 * Checks if a slug exists within a book already.
335 * @param bool|false $currentId
338 public function doesSlugExist($slug, $bookId, $currentId = false)
340 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
341 if ($currentId) $query = $query->where('id', '!=', $currentId);
342 return $query->count() > 0;
346 * Changes the related book for the specified page.
347 * Changes the book id of any relations to the page that store the book id.
352 public function changeBook($bookId, Page $page)
354 $page->book_id = $bookId;
355 foreach ($page->activity as $activity) {
356 $activity->book_id = $bookId;
359 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
365 * Gets a suitable slug for the resource
368 * @param bool|false $currentId
371 public function findSuitableSlug($name, $bookId, $currentId = false)
373 $slug = Str::slug($name);
374 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
375 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
381 * Destroy a given page along with its dependencies.
384 public function destroy($page)
386 Activity::removeEntity($page);
387 $page->views()->delete();
388 $page->revisions()->delete();
393 * Get the latest pages added to the system.
396 public function getRecentlyCreatedPaginated($count = 20)
398 return $this->page->orderBy('created_at', 'desc')->paginate($count);
402 * Get the latest pages added to the system.
405 public function getRecentlyUpdatedPaginated($count = 20)
407 return $this->page->orderBy('updated_at', 'desc')->paginate($count);