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 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
74 public function newFromInput($input)
76 $page = $this->page->fill($input);
81 * Count the pages with a particular slug within a book.
86 public function countBySlug($slug, $bookId)
88 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
92 * Save a new page into the system.
93 * Input validation must be done beforehand.
96 * @param int $chapterId
99 public function saveNew(array $input, Book $book, $chapterId = null)
101 $page = $this->newFromInput($input);
102 $page->slug = $this->findSuitableSlug($page->name, $book->id);
104 if ($chapterId) $page->chapter_id = $chapterId;
106 $page->html = $this->formatHtml($input['html']);
107 $page->text = strip_tags($page->html);
108 $page->created_by = auth()->user()->id;
109 $page->updated_by = auth()->user()->id;
111 $book->pages()->save($page);
116 * Formats a page's html to be tagged correctly
118 * @param string $htmlText
121 protected function formatHtml($htmlText)
123 if($htmlText == '') return $htmlText;
124 libxml_use_internal_errors(true);
125 $doc = new \DOMDocument();
126 $doc->loadHTML($htmlText);
128 $container = $doc->documentElement;
129 $body = $container->childNodes->item(0);
130 $childNodes = $body->childNodes;
132 // Ensure no duplicate ids are used
136 foreach ($childNodes as $index => $childNode) {
137 /** @var \DOMElement $childNode */
138 if (get_class($childNode) !== 'DOMElement') continue;
140 // Overwrite id if not a bookstack custom id
141 if ($childNode->hasAttribute('id')) {
142 $id = $childNode->getAttribute('id');
143 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
149 // Create an unique id for the element
151 $id = 'bkmrk-' . substr(uniqid(), -5);
152 } while ($id == $lastId);
155 $childNode->setAttribute('id', $id);
159 // Generate inner html as a string
161 foreach ($childNodes as $childNode) {
162 $html .= $doc->saveHTML($childNode);
170 * Gets pages by a search term.
171 * Highlights page content for showing in results.
172 * @param string $term
173 * @param array $whereTerms
176 public function getBySearch($term, $whereTerms = [])
178 $terms = explode(' ', preg_quote(trim($term)));
179 $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
181 // Add highlights to page text.
182 $words = join('|', $terms);
183 //lookahead/behind assertions ensures cut between words
184 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
186 foreach ($pages as $page) {
187 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
188 //delimiter between occurrences
190 foreach ($matches as $line) {
191 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
194 if (count($results) > $matchLimit) {
195 $results = array_slice($results, 0, $matchLimit);
197 $result = join('... ', $results);
200 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
201 if (strlen($result) < 5) {
202 $result = $page->getExcerpt(80);
204 $page->searchSnippet = $result;
210 * Search for image usage.
211 * @param $imageString
214 public function searchForImage($imageString)
216 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
217 foreach ($pages as $page) {
218 $page->url = $page->getUrl();
222 return count($pages) > 0 ? $pages : false;
226 * Updates a page with any fillable data and saves it into the database.
228 * @param int $book_id
229 * @param string $input
232 public function updatePage(Page $page, $book_id, $input)
234 // Save a revision before updating
235 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
236 $this->saveRevision($page);
239 // Update with new details
241 $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
242 $page->html = $this->formatHtml($input['html']);
243 $page->text = strip_tags($page->html);
244 $page->updated_by = auth()->user()->id;
250 * Restores a revision's content back into a page.
253 * @param int $revisionId
256 public function restoreRevision(Page $page, Book $book, $revisionId)
258 $this->saveRevision($page);
259 $revision = $this->getRevisionById($revisionId);
260 $page->fill($revision->toArray());
261 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
262 $page->text = strip_tags($page->html);
263 $page->updated_by = auth()->user()->id;
269 * Saves a page revision into the system.
273 public function saveRevision(Page $page)
275 $revision = $this->pageRevision->fill($page->toArray());
276 $revision->page_id = $page->id;
277 $revision->created_by = auth()->user()->id;
278 $revision->created_at = $page->updated_at;
280 // Clear old revisions
281 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
282 $this->pageRevision->where('page_id', '=', $page->id)
283 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
289 * Gets a single revision via it's id.
293 public function getRevisionById($id)
295 return $this->pageRevision->findOrFail($id);
299 * Checks if a slug exists within a book already.
302 * @param bool|false $currentId
305 public function doesSlugExist($slug, $bookId, $currentId = false)
307 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
308 if ($currentId) $query = $query->where('id', '!=', $currentId);
309 return $query->count() > 0;
313 * Changes the related book for the specified page.
314 * Changes the book id of any relations to the page that store the book id.
319 public function changeBook($bookId, Page $page)
321 $page->book_id = $bookId;
322 foreach ($page->activity as $activity) {
323 $activity->book_id = $bookId;
326 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
332 * Gets a suitable slug for the resource
335 * @param bool|false $currentId
338 public function findSuitableSlug($name, $bookId, $currentId = false)
340 $slug = Str::slug($name);
341 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
342 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
348 * Destroy a given page along with its dependencies.
351 public function destroy($page)
353 Activity::removeEntity($page);
354 $page->views()->delete();
355 $page->revisions()->delete();