1 <?php namespace BookStack\Repos;
7 use BookStack\Services\RestrictionService;
8 use Illuminate\Http\Request;
9 use Illuminate\Support\Facades\Auth;
10 use Illuminate\Support\Facades\Log;
11 use Illuminate\Support\Str;
13 use BookStack\PageRevision;
14 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19 protected $pageRevision;
20 protected $restrictionService;
23 * PageRepo constructor.
25 * @param PageRevision $pageRevision
26 * @param RestrictionService $restrictionService
28 public function __construct(Page $page, PageRevision $pageRevision, RestrictionService $restrictionService)
31 $this->pageRevision = $pageRevision;
32 $this->restrictionService = $restrictionService;
36 * Base query for getting pages, Takes restrictions into account.
39 private function pageQuery()
41 return $this->restrictionService->enforcePageRestrictions($this->page, 'view');
45 * Get a page via a specific ID.
49 public function getById($id)
51 return $this->pageQuery()->findOrFail($id);
55 * Get a page identified by the given slug.
60 public function getBySlug($slug, $bookId)
62 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
63 if ($page === null) throw new NotFoundHttpException('Page not found');
68 * Search through page revisions and retrieve
69 * the last page in the current book that
70 * has a slug equal to the one given.
75 public function findPageUsingOldSlug($pageSlug, $bookSlug)
77 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
78 ->whereHas('page', function($query) {
79 $this->restrictionService->enforcePageRestrictions($query);
81 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
82 ->with('page')->first();
83 return $revision !== null ? $revision->page : null;
87 * Get a new Page instance from the given input.
91 public function newFromInput($input)
93 $page = $this->page->fill($input);
99 * Save a new page into the system.
100 * Input validation must be done beforehand.
101 * @param array $input
103 * @param int $chapterId
106 public function saveNew(array $input, Book $book, $chapterId = null)
108 $page = $this->newFromInput($input);
109 $page->slug = $this->findSuitableSlug($page->name, $book->id);
111 if ($chapterId) $page->chapter_id = $chapterId;
113 $page->html = $this->formatHtml($input['html']);
114 $page->text = strip_tags($page->html);
115 $page->created_by = auth()->user()->id;
116 $page->updated_by = auth()->user()->id;
118 $book->pages()->save($page);
123 * Formats a page's html to be tagged correctly
125 * @param string $htmlText
128 protected function formatHtml($htmlText)
130 if($htmlText == '') return $htmlText;
131 libxml_use_internal_errors(true);
132 $doc = new \DOMDocument();
133 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
135 $container = $doc->documentElement;
136 $body = $container->childNodes->item(0);
137 $childNodes = $body->childNodes;
139 // Ensure no duplicate ids are used
142 foreach ($childNodes as $index => $childNode) {
143 /** @var \DOMElement $childNode */
144 if (get_class($childNode) !== 'DOMElement') continue;
146 // Overwrite id if not a BookStack custom id
147 if ($childNode->hasAttribute('id')) {
148 $id = $childNode->getAttribute('id');
149 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
155 // Create an unique id for the element
156 // Uses the content as a basis to ensure output is the same every time
157 // the same content is passed through.
158 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
159 $newId = urlencode($contentId);
161 while (in_array($newId, $idArray)) {
162 $newId = urlencode($contentId . '-' . $loopIndex);
166 $childNode->setAttribute('id', $newId);
170 // Generate inner html as a string
172 foreach ($childNodes as $childNode) {
173 $html .= $doc->saveHTML($childNode);
181 * Gets pages by a search term.
182 * Highlights page content for showing in results.
183 * @param string $term
184 * @param array $whereTerms
186 * @param array $paginationAppends
189 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
191 $terms = explode(' ', $term);
192 $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
193 ->paginate($count)->appends($paginationAppends);
195 // Add highlights to page text.
196 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
197 //lookahead/behind assertions ensures cut between words
198 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
200 foreach ($pages as $page) {
201 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
202 //delimiter between occurrences
204 foreach ($matches as $line) {
205 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
208 if (count($results) > $matchLimit) {
209 $results = array_slice($results, 0, $matchLimit);
211 $result = join('... ', $results);
214 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
215 if (strlen($result) < 5) {
216 $result = $page->getExcerpt(80);
218 $page->searchSnippet = $result;
224 * Search for image usage.
225 * @param $imageString
228 public function searchForImage($imageString)
230 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
231 foreach ($pages as $page) {
232 $page->url = $page->getUrl();
236 return count($pages) > 0 ? $pages : false;
240 * Updates a page with any fillable data and saves it into the database.
242 * @param int $book_id
243 * @param string $input
246 public function updatePage(Page $page, $book_id, $input)
248 // Save a revision before updating
249 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
250 $this->saveRevision($page);
253 // Prevent slug being updated if no name change
254 if ($page->name !== $input['name']) {
255 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
258 // Update with new details
260 $page->html = $this->formatHtml($input['html']);
261 $page->text = strip_tags($page->html);
262 $page->updated_by = auth()->user()->id;
268 * Restores a revision's content back into a page.
271 * @param int $revisionId
274 public function restoreRevision(Page $page, Book $book, $revisionId)
276 $this->saveRevision($page);
277 $revision = $this->getRevisionById($revisionId);
278 $page->fill($revision->toArray());
279 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
280 $page->text = strip_tags($page->html);
281 $page->updated_by = auth()->user()->id;
287 * Saves a page revision into the system.
291 public function saveRevision(Page $page)
293 $revision = $this->pageRevision->fill($page->toArray());
294 $revision->page_id = $page->id;
295 $revision->slug = $page->slug;
296 $revision->book_slug = $page->book->slug;
297 $revision->created_by = auth()->user()->id;
298 $revision->created_at = $page->updated_at;
300 // Clear old revisions
301 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
302 $this->pageRevision->where('page_id', '=', $page->id)
303 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
309 * Gets a single revision via it's id.
313 public function getRevisionById($id)
315 return $this->pageRevision->findOrFail($id);
319 * Checks if a slug exists within a book already.
322 * @param bool|false $currentId
325 public function doesSlugExist($slug, $bookId, $currentId = false)
327 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
328 if ($currentId) $query = $query->where('id', '!=', $currentId);
329 return $query->count() > 0;
333 * Changes the related book for the specified page.
334 * Changes the book id of any relations to the page that store the book id.
339 public function changeBook($bookId, Page $page)
341 $page->book_id = $bookId;
342 foreach ($page->activity as $activity) {
343 $activity->book_id = $bookId;
346 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
352 * Gets a suitable slug for the resource
355 * @param bool|false $currentId
358 public function findSuitableSlug($name, $bookId, $currentId = false)
360 $slug = Str::slug($name);
361 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
362 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
368 * Destroy a given page along with its dependencies.
371 public function destroy($page)
373 Activity::removeEntity($page);
374 $page->views()->delete();
375 $page->revisions()->delete();
380 * Get the latest pages added to the system.
383 public function getRecentlyCreatedPaginated($count = 20)
385 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
389 * Get the latest pages added to the system.
392 public function getRecentlyUpdatedPaginated($count = 20)
394 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
398 * Updates pages restrictions from a request
402 public function updateRestrictionsFromRequest($request, $page)
404 // TODO - extract into shared repo
405 $page->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
406 $page->restrictions()->delete();
407 if ($request->has('restrictions')) {
408 foreach($request->get('restrictions') as $roleId => $restrictions) {
409 foreach ($restrictions as $action => $value) {
410 $page->restrictions()->create([
411 'role_id' => $roleId,
412 'action' => strtolower($action)