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;
17 protected $pageRevision;
20 * PageRepo constructor.
22 * @param PageRevision $pageRevision
24 public function __construct(Page $page, PageRevision $pageRevision)
27 $this->pageRevision = $pageRevision;
31 * Check if a page id exists.
35 public function idExists($id)
37 return $this->page->where('page_id', '=', $id)->count() > 0;
41 * Get a page via a specific ID.
45 public function getById($id)
47 return $this->page->findOrFail($id);
52 * @return \Illuminate\Database\Eloquent\Collection|static[]
54 public function getAll()
56 return $this->page->all();
60 * Get a page identified by the given slug.
65 public function getBySlug($slug, $bookId)
67 $page = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
68 if ($page === null) abort(404);
76 public function newFromInput($input)
78 $page = $this->page->fill($input);
83 * Count the pages with a particular slug within a book.
88 public function countBySlug($slug, $bookId)
90 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
94 * Save a new page into the system.
95 * Input validation must be done beforehand.
98 * @param int $chapterId
101 public function saveNew(array $input, Book $book, $chapterId = null)
103 $page = $this->newFromInput($input);
104 $page->slug = $this->findSuitableSlug($page->name, $book->id);
106 if ($chapterId) $page->chapter_id = $chapterId;
108 $page->html = $this->formatHtml($input['html']);
109 $page->text = strip_tags($page->html);
110 $page->created_by = auth()->user()->id;
111 $page->updated_by = auth()->user()->id;
113 $book->pages()->save($page);
118 * Formats a page's html to be tagged correctly
120 * @param string $htmlText
123 protected function formatHtml($htmlText)
125 if($htmlText == '') return $htmlText;
126 libxml_use_internal_errors(true);
127 $doc = new \DOMDocument();
128 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
130 $container = $doc->documentElement;
131 $body = $container->childNodes->item(0);
132 $childNodes = $body->childNodes;
134 // Ensure no duplicate ids are used
137 foreach ($childNodes as $index => $childNode) {
138 /** @var \DOMElement $childNode */
139 if (get_class($childNode) !== 'DOMElement') continue;
141 // Overwrite id if not a BookStack custom id
142 if ($childNode->hasAttribute('id')) {
143 $id = $childNode->getAttribute('id');
144 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
150 // Create an unique id for the element
151 // Uses the content as a basis to ensure output is the same every time
152 // the same content is passed through.
153 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
154 $newId = urlencode($contentId);
156 while (in_array($newId, $idArray)) {
157 $newId = urlencode($contentId . '-' . $loopIndex);
161 $childNode->setAttribute('id', $newId);
165 // Generate inner html as a string
167 foreach ($childNodes as $childNode) {
168 $html .= $doc->saveHTML($childNode);
176 * Gets pages by a search term.
177 * Highlights page content for showing in results.
178 * @param string $term
179 * @param array $whereTerms
182 public function getBySearch($term, $whereTerms = [])
184 $terms = explode(' ', $term);
185 $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
187 // Add highlights to page text.
188 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
189 //lookahead/behind assertions ensures cut between words
190 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
192 foreach ($pages as $page) {
193 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
194 //delimiter between occurrences
196 foreach ($matches as $line) {
197 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
200 if (count($results) > $matchLimit) {
201 $results = array_slice($results, 0, $matchLimit);
203 $result = join('... ', $results);
206 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
207 if (strlen($result) < 5) {
208 $result = $page->getExcerpt(80);
210 $page->searchSnippet = $result;
216 * Search for image usage.
217 * @param $imageString
220 public function searchForImage($imageString)
222 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
223 foreach ($pages as $page) {
224 $page->url = $page->getUrl();
228 return count($pages) > 0 ? $pages : false;
232 * Updates a page with any fillable data and saves it into the database.
234 * @param int $book_id
235 * @param string $input
238 public function updatePage(Page $page, $book_id, $input)
240 // Save a revision before updating
241 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
242 $this->saveRevision($page);
245 // Update with new details
247 $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
248 $page->html = $this->formatHtml($input['html']);
249 $page->text = strip_tags($page->html);
250 $page->updated_by = auth()->user()->id;
256 * Restores a revision's content back into a page.
259 * @param int $revisionId
262 public function restoreRevision(Page $page, Book $book, $revisionId)
264 $this->saveRevision($page);
265 $revision = $this->getRevisionById($revisionId);
266 $page->fill($revision->toArray());
267 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
268 $page->text = strip_tags($page->html);
269 $page->updated_by = auth()->user()->id;
275 * Saves a page revision into the system.
279 public function saveRevision(Page $page)
281 $revision = $this->pageRevision->fill($page->toArray());
282 $revision->page_id = $page->id;
283 $revision->created_by = auth()->user()->id;
284 $revision->created_at = $page->updated_at;
286 // Clear old revisions
287 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
288 $this->pageRevision->where('page_id', '=', $page->id)
289 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
295 * Gets a single revision via it's id.
299 public function getRevisionById($id)
301 return $this->pageRevision->findOrFail($id);
305 * Checks if a slug exists within a book already.
308 * @param bool|false $currentId
311 public function doesSlugExist($slug, $bookId, $currentId = false)
313 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
314 if ($currentId) $query = $query->where('id', '!=', $currentId);
315 return $query->count() > 0;
319 * Changes the related book for the specified page.
320 * Changes the book id of any relations to the page that store the book id.
325 public function changeBook($bookId, Page $page)
327 $page->book_id = $bookId;
328 foreach ($page->activity as $activity) {
329 $activity->book_id = $bookId;
332 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
338 * Gets a suitable slug for the resource
341 * @param bool|false $currentId
344 public function findSuitableSlug($name, $bookId, $currentId = false)
346 $slug = Str::slug($name);
347 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
348 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
354 * Destroy a given page along with its dependencies.
357 public function destroy($page)
359 Activity::removeEntity($page);
360 $page->views()->delete();
361 $page->revisions()->delete();
366 * Get the latest pages added to the system.
369 public function getRecentlyCreatedPaginated($count = 20)
371 return $this->page->orderBy('created_at', 'desc')->paginate($count);
375 * Get the latest pages added to the system.
378 public function getRecentlyUpdatedPaginated($count = 20)
380 return $this->page->orderBy('updated_at', 'desc')->paginate($count);