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 = [])
194 preg_match_all('/"(.*?)"/', $term, $matches);
195 if (count($matches[1]) > 0) {
196 $terms = $matches[1];
197 $term = trim(preg_replace('/"(.*?)"/', '', $term));
202 $terms = array_merge($terms, explode(' ', $term));
204 $pages = $this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)
206 $terms = explode(' ', $term);
207 $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
208 >>>>>>> custom_role_system
209 ->paginate($count)->appends($paginationAppends);
211 // Add highlights to page text.
212 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
213 //lookahead/behind assertions ensures cut between words
214 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
216 foreach ($pages as $page) {
217 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
218 //delimiter between occurrences
220 foreach ($matches as $line) {
221 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
224 if (count($results) > $matchLimit) {
225 $results = array_slice($results, 0, $matchLimit);
227 $result = join('... ', $results);
230 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
231 if (strlen($result) < 5) {
232 $result = $page->getExcerpt(80);
234 $page->searchSnippet = $result;
240 * Search for image usage.
241 * @param $imageString
244 public function searchForImage($imageString)
246 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
247 foreach ($pages as $page) {
248 $page->url = $page->getUrl();
252 return count($pages) > 0 ? $pages : false;
256 * Updates a page with any fillable data and saves it into the database.
258 * @param int $book_id
259 * @param string $input
262 public function updatePage(Page $page, $book_id, $input)
264 // Save a revision before updating
265 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
266 $this->saveRevision($page);
269 // Prevent slug being updated if no name change
270 if ($page->name !== $input['name']) {
271 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
274 // Update with new details
276 $page->html = $this->formatHtml($input['html']);
277 $page->text = strip_tags($page->html);
278 $page->updated_by = auth()->user()->id;
284 * Restores a revision's content back into a page.
287 * @param int $revisionId
290 public function restoreRevision(Page $page, Book $book, $revisionId)
292 $this->saveRevision($page);
293 $revision = $this->getRevisionById($revisionId);
294 $page->fill($revision->toArray());
295 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
296 $page->text = strip_tags($page->html);
297 $page->updated_by = auth()->user()->id;
303 * Saves a page revision into the system.
307 public function saveRevision(Page $page)
309 $revision = $this->pageRevision->fill($page->toArray());
310 $revision->page_id = $page->id;
311 $revision->slug = $page->slug;
312 $revision->book_slug = $page->book->slug;
313 $revision->created_by = auth()->user()->id;
314 $revision->created_at = $page->updated_at;
316 // Clear old revisions
317 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
318 $this->pageRevision->where('page_id', '=', $page->id)
319 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
325 * Gets a single revision via it's id.
329 public function getRevisionById($id)
331 return $this->pageRevision->findOrFail($id);
335 * Checks if a slug exists within a book already.
338 * @param bool|false $currentId
341 public function doesSlugExist($slug, $bookId, $currentId = false)
343 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
344 if ($currentId) $query = $query->where('id', '!=', $currentId);
345 return $query->count() > 0;
349 * Changes the related book for the specified page.
350 * Changes the book id of any relations to the page that store the book id.
355 public function changeBook($bookId, Page $page)
357 $page->book_id = $bookId;
358 foreach ($page->activity as $activity) {
359 $activity->book_id = $bookId;
362 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
368 * Gets a suitable slug for the resource
371 * @param bool|false $currentId
374 public function findSuitableSlug($name, $bookId, $currentId = false)
376 $slug = Str::slug($name);
377 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
378 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
384 * Destroy a given page along with its dependencies.
387 public function destroy($page)
389 Activity::removeEntity($page);
390 $page->views()->delete();
391 $page->revisions()->delete();
392 $page->restrictions()->delete();
397 * Get the latest pages added to the system.
400 public function getRecentlyCreatedPaginated($count = 20)
402 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
406 * Get the latest pages added to the system.
409 public function getRecentlyUpdatedPaginated($count = 20)
411 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);
415 * Updates pages restrictions from a request
419 public function updateRestrictionsFromRequest($request, $page)
421 // TODO - extract into shared repo
422 $page->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
423 $page->restrictions()->delete();
424 if ($request->has('restrictions')) {
425 foreach($request->get('restrictions') as $roleId => $restrictions) {
426 foreach ($restrictions as $action => $value) {
427 $page->restrictions()->create([
428 'role_id' => $roleId,
429 'action' => strtolower($action)