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 libxml_use_internal_errors(true);
124 $doc = new \DOMDocument();
125 $doc->loadHTML($htmlText);
127 $container = $doc->documentElement;
128 $body = $container->childNodes->item(0);
129 $childNodes = $body->childNodes;
131 // Ensure no duplicate ids are used
135 foreach ($childNodes as $index => $childNode) {
136 /** @var \DOMElement $childNode */
137 if (get_class($childNode) !== 'DOMElement') continue;
139 // Overwrite id if not a bookstack custom id
140 if ($childNode->hasAttribute('id')) {
141 $id = $childNode->getAttribute('id');
142 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
148 // Create an unique id for the element
150 $id = 'bkmrk-' . substr(uniqid(), -5);
151 } while ($id == $lastId);
154 $childNode->setAttribute('id', $id);
158 // Generate inner html as a string
160 foreach ($childNodes as $childNode) {
161 $html .= $doc->saveHTML($childNode);
169 * Gets pages by a search term.
170 * Highlights page content for showing in results.
171 * @param string $term
172 * @param array $whereTerms
175 public function getBySearch($term, $whereTerms = [])
177 $terms = explode(' ', preg_quote(trim($term)));
178 $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
180 // Add highlights to page text.
181 $words = join('|', $terms);
182 //lookahead/behind assertions ensures cut between words
183 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
185 foreach ($pages as $page) {
186 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
187 //delimiter between occurrences
189 foreach ($matches as $line) {
190 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
193 if (count($results) > $matchLimit) {
194 $results = array_slice($results, 0, $matchLimit);
196 $result = join('... ', $results);
199 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
200 if (strlen($result) < 5) {
201 $result = $page->getExcerpt(80);
203 $page->searchSnippet = $result;
209 * Search for image usage.
210 * @param $imageString
213 public function searchForImage($imageString)
215 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
216 foreach ($pages as $page) {
217 $page->url = $page->getUrl();
221 return count($pages) > 0 ? $pages : false;
225 * Updates a page with any fillable data and saves it into the database.
227 * @param int $book_id
228 * @param string $input
231 public function updatePage(Page $page, $book_id, $input)
233 // Save a revision before updating
234 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
235 $this->saveRevision($page);
238 // Update with new details
240 $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
241 $page->html = $this->formatHtml($input['html']);
242 $page->text = strip_tags($page->html);
243 $page->updated_by = auth()->user()->id;
249 * Restores a revision's content back into a page.
252 * @param int $revisionId
255 public function restoreRevision(Page $page, Book $book, $revisionId)
257 $this->saveRevision($page);
258 $revision = $this->getRevisionById($revisionId);
259 $page->fill($revision->toArray());
260 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
261 $page->text = strip_tags($page->html);
262 $page->updated_by = auth()->user()->id;
268 * Saves a page revision into the system.
272 private function saveRevision(Page $page)
274 $revision = $this->pageRevision->fill($page->toArray());
275 $revision->page_id = $page->id;
276 $revision->created_by = auth()->user()->id;
277 $revision->created_at = $page->updated_at;
279 // Clear old revisions
280 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
281 $this->pageRevision->where('page_id', '=', $page->id)
282 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
288 * Gets a single revision via it's id.
292 public function getRevisionById($id)
294 return $this->pageRevision->findOrFail($id);
298 * Checks if a slug exists within a book already.
301 * @param bool|false $currentId
304 public function doesSlugExist($slug, $bookId, $currentId = false)
306 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
307 if ($currentId) $query = $query->where('id', '!=', $currentId);
308 return $query->count() > 0;
312 * Changes the related book for the specified page.
313 * Changes the book id of any relations to the page that store the book id.
318 public function changeBook($bookId, Page $page)
320 $page->book_id = $bookId;
321 foreach ($page->activity as $activity) {
322 $activity->book_id = $bookId;
325 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
331 * Gets a suitable slug for the resource
334 * @param bool|false $currentId
337 public function findSuitableSlug($name, $bookId, $currentId = false)
339 $slug = Str::slug($name);
340 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
341 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
347 * Destroy a given page along with its dependencies.
350 public function destroy($page)
352 Activity::removeEntity($page);
353 $page->views()->delete();
354 $page->revisions()->delete();