1 <?php namespace BookStack\Repos;
7 use BookStack\Exceptions\NotFoundException;
8 use BookStack\Services\RestrictionService;
9 use Illuminate\Http\Request;
10 use Illuminate\Support\Facades\Auth;
11 use Illuminate\Support\Facades\Log;
12 use Illuminate\Support\Str;
14 use BookStack\PageRevision;
15 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
20 protected $pageRevision;
21 protected $restrictionService;
24 * PageRepo constructor.
26 * @param PageRevision $pageRevision
27 * @param RestrictionService $restrictionService
29 public function __construct(Page $page, PageRevision $pageRevision, RestrictionService $restrictionService)
32 $this->pageRevision = $pageRevision;
33 $this->restrictionService = $restrictionService;
37 * Base query for getting pages, Takes restrictions into account.
40 private function pageQuery()
42 return $this->restrictionService->enforcePageRestrictions($this->page, 'view');
46 * Get a page via a specific ID.
50 public function getById($id)
52 return $this->pageQuery()->findOrFail($id);
56 * Get a page identified by the given slug.
60 * @throws NotFoundException
62 public function getBySlug($slug, $bookId)
64 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
65 if ($page === null) throw new NotFoundException('Page not found');
70 * Search through page revisions and retrieve
71 * the last page in the current book that
72 * has a slug equal to the one given.
77 public function findPageUsingOldSlug($pageSlug, $bookSlug)
79 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
80 ->whereHas('page', function($query) {
81 $this->restrictionService->enforcePageRestrictions($query);
83 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
84 ->with('page')->first();
85 return $revision !== null ? $revision->page : null;
89 * Get a new Page instance from the given input.
93 public function newFromInput($input)
95 $page = $this->page->fill($input);
101 * Save a new page into the system.
102 * Input validation must be done beforehand.
103 * @param array $input
105 * @param int $chapterId
108 public function saveNew(array $input, Book $book, $chapterId = null)
110 $page = $this->newFromInput($input);
111 $page->slug = $this->findSuitableSlug($page->name, $book->id);
113 if ($chapterId) $page->chapter_id = $chapterId;
115 $page->html = $this->formatHtml($input['html']);
116 $page->text = strip_tags($page->html);
117 $page->created_by = auth()->user()->id;
118 $page->updated_by = auth()->user()->id;
120 $book->pages()->save($page);
125 * Formats a page's html to be tagged correctly
127 * @param string $htmlText
130 protected function formatHtml($htmlText)
132 if($htmlText == '') return $htmlText;
133 libxml_use_internal_errors(true);
134 $doc = new \DOMDocument();
135 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
137 $container = $doc->documentElement;
138 $body = $container->childNodes->item(0);
139 $childNodes = $body->childNodes;
141 // Ensure no duplicate ids are used
144 foreach ($childNodes as $index => $childNode) {
145 /** @var \DOMElement $childNode */
146 if (get_class($childNode) !== 'DOMElement') continue;
148 // Overwrite id if not a BookStack custom id
149 if ($childNode->hasAttribute('id')) {
150 $id = $childNode->getAttribute('id');
151 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
157 // Create an unique id for the element
158 // Uses the content as a basis to ensure output is the same every time
159 // the same content is passed through.
160 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
161 $newId = urlencode($contentId);
163 while (in_array($newId, $idArray)) {
164 $newId = urlencode($contentId . '-' . $loopIndex);
168 $childNode->setAttribute('id', $newId);
172 // Generate inner html as a string
174 foreach ($childNodes as $childNode) {
175 $html .= $doc->saveHTML($childNode);
183 * Gets pages by a search term.
184 * Highlights page content for showing in results.
185 * @param string $term
186 * @param array $whereTerms
188 * @param array $paginationAppends
191 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
193 $terms = explode(' ', $term);
194 $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
195 ->paginate($count)->appends($paginationAppends);
197 // Add highlights to page text.
198 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
199 //lookahead/behind assertions ensures cut between words
200 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
202 foreach ($pages as $page) {
203 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
204 //delimiter between occurrences
206 foreach ($matches as $line) {
207 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
210 if (count($results) > $matchLimit) {
211 $results = array_slice($results, 0, $matchLimit);
213 $result = join('... ', $results);
216 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
217 if (strlen($result) < 5) {
218 $result = $page->getExcerpt(80);
220 $page->searchSnippet = $result;
226 * Search for image usage.
227 * @param $imageString
230 public function searchForImage($imageString)
232 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
233 foreach ($pages as $page) {
234 $page->url = $page->getUrl();
238 return count($pages) > 0 ? $pages : false;
242 * Updates a page with any fillable data and saves it into the database.
244 * @param int $book_id
245 * @param string $input
248 public function updatePage(Page $page, $book_id, $input)
250 // Save a revision before updating
251 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
252 $this->saveRevision($page);
255 // Prevent slug being updated if no name change
256 if ($page->name !== $input['name']) {
257 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
260 // Update with new details
262 $page->html = $this->formatHtml($input['html']);
263 $page->text = strip_tags($page->html);
264 $page->updated_by = auth()->user()->id;
270 * Restores a revision's content back into a page.
273 * @param int $revisionId
276 public function restoreRevision(Page $page, Book $book, $revisionId)
278 $this->saveRevision($page);
279 $revision = $this->getRevisionById($revisionId);
280 $page->fill($revision->toArray());
281 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
282 $page->text = strip_tags($page->html);
283 $page->updated_by = auth()->user()->id;
289 * Saves a page revision into the system.
293 public function saveRevision(Page $page)
295 $revision = $this->pageRevision->fill($page->toArray());
296 $revision->page_id = $page->id;
297 $revision->slug = $page->slug;
298 $revision->book_slug = $page->book->slug;
299 $revision->created_by = auth()->user()->id;
300 $revision->created_at = $page->updated_at;
302 // Clear old revisions
303 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
304 $this->pageRevision->where('page_id', '=', $page->id)
305 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
311 * Gets a single revision via it's id.
315 public function getRevisionById($id)
317 return $this->pageRevision->findOrFail($id);
321 * Checks if a slug exists within a book already.
324 * @param bool|false $currentId
327 public function doesSlugExist($slug, $bookId, $currentId = false)
329 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
330 if ($currentId) $query = $query->where('id', '!=', $currentId);
331 return $query->count() > 0;
335 * Changes the related book for the specified page.
336 * Changes the book id of any relations to the page that store the book id.
341 public function changeBook($bookId, Page $page)
343 $page->book_id = $bookId;
344 foreach ($page->activity as $activity) {
345 $activity->book_id = $bookId;
348 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
354 * Gets a suitable slug for the resource
357 * @param bool|false $currentId
360 public function findSuitableSlug($name, $bookId, $currentId = false)
362 $slug = Str::slug($name);
363 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
364 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
370 * Destroy a given page along with its dependencies.
373 public function destroy($page)
375 Activity::removeEntity($page);
376 $page->views()->delete();
377 $page->revisions()->delete();
378 $page->restrictions()->delete();
383 * Get the latest pages added to the system.
386 public function getRecentlyCreatedPaginated($count = 20)
388 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
392 * Get the latest pages added to the system.
395 public function getRecentlyUpdatedPaginated($count = 20)
397 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
401 * Updates pages restrictions from a request
405 public function updateRestrictionsFromRequest($request, $page)
407 // TODO - extract into shared repo
408 $page->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
409 $page->restrictions()->delete();
410 if ($request->has('restrictions')) {
411 foreach($request->get('restrictions') as $roleId => $restrictions) {
412 foreach ($restrictions as $action => $value) {
413 $page->restrictions()->create([
414 'role_id' => $roleId,
415 'action' => strtolower($action)