1 <?php namespace BookStack\Repos;
6 use Illuminate\Http\Request;
7 use Illuminate\Support\Facades\Auth;
8 use Illuminate\Support\Facades\Log;
9 use Illuminate\Support\Str;
11 use BookStack\PageRevision;
16 protected $pageRevision;
19 * PageRepo constructor.
21 * @param PageRevision $pageRevision
23 public function __construct(Page $page, PageRevision $pageRevision)
26 $this->pageRevision = $pageRevision;
29 public function idExists($id)
31 return $this->page->where('page_id', '=', $id)->count() > 0;
34 public function getById($id)
36 return $this->page->findOrFail($id);
39 public function getAll()
41 return $this->page->all();
44 public function getBySlug($slug, $bookId)
46 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
53 public function newFromInput($input)
55 $page = $this->page->fill($input);
59 public function countBySlug($slug, $bookId)
61 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
65 * Save a new page into the system.
66 * Input validation must be done beforehand.
69 * @param int $chapterId
72 public function saveNew(array $input, Book $book, $chapterId = null)
74 $page = $this->newFromInput($input);
75 $page->slug = $this->findSuitableSlug($page->name, $book->id);
77 if ($chapterId) $page->chapter_id = $chapterId;
79 $page->html = $this->formatHtml($input['html']);
80 $page->text = strip_tags($page->html);
81 $page->created_by = auth()->user()->id;
82 $page->updated_by = auth()->user()->id;
84 $book->pages()->save($page);
89 * Formats a page's html to be tagged correctly
91 * @param string $htmlText
94 protected function formatHtml($htmlText)
96 libxml_use_internal_errors(true);
97 $doc = new \DOMDocument();
98 $doc->loadHTML($htmlText);
100 $container = $doc->documentElement;
101 $body = $container->childNodes->item(0);
102 $childNodes = $body->childNodes;
104 // Ensure no duplicate ids are used
108 foreach ($childNodes as $index => $childNode) {
109 /** @var \DOMElement $childNode */
110 if (get_class($childNode) !== 'DOMElement') continue;
112 // Overwrite id if not a bookstack custom id
113 if ($childNode->hasAttribute('id')) {
114 $id = $childNode->getAttribute('id');
115 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
121 // Create an unique id for the element
123 $id = 'bkmrk-' . substr(uniqid(), -5);
124 } while ($id == $lastId);
127 $childNode->setAttribute('id', $id);
131 // Generate inner html as a string
133 foreach ($childNodes as $childNode) {
134 $html .= $doc->saveHTML($childNode);
140 public function destroyById($id)
142 $page = $this->getById($id);
146 public function getBySearch($term, $whereTerms = [])
148 $terms = explode(' ', preg_quote(trim($term)));
149 $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
151 // Add highlights to page text.
152 $words = join('|', $terms);
153 //lookahead/behind assertions ensures cut between words
154 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
156 foreach ($pages as $page) {
157 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
158 //delimiter between occurrences
160 foreach ($matches as $line) {
161 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
164 if (count($results) > $matchLimit) {
165 $results = array_slice($results, 0, $matchLimit);
167 $result = join('... ', $results);
170 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
171 if (strlen($result) < 5) {
172 $result = $page->getExcerpt(80);
174 $page->searchSnippet = $result;
180 * Search for image usage.
181 * @param $imageString
184 public function searchForImage($imageString)
186 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
187 foreach ($pages as $page) {
188 $page->url = $page->getUrl();
192 return count($pages) > 0 ? $pages : false;
196 * Updates a page with any fillable data and saves it into the database.
198 * @param int $book_id
199 * @param string $input
202 public function updatePage(Page $page, $book_id, $input)
204 // Save a revision before updating
205 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
206 $this->saveRevision($page);
209 // Update with new details
211 $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
212 $page->html = $this->formatHtml($input['html']);
213 $page->text = strip_tags($page->html);
214 $page->updated_by = auth()->user()->id;
220 * Restores a revision's content back into a page.
223 * @param int $revisionId
226 public function restoreRevision(Page $page, Book $book, $revisionId)
228 $this->saveRevision($page);
229 $revision = $this->getRevisionById($revisionId);
230 $page->fill($revision->toArray());
231 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
232 $page->text = strip_tags($page->html);
233 $page->updated_by = auth()->user()->id;
239 * Saves a page revision into the system.
243 private function saveRevision(Page $page)
245 $revision = $this->pageRevision->fill($page->toArray());
246 $revision->page_id = $page->id;
247 $revision->created_by = auth()->user()->id;
248 $revision->created_at = $page->updated_at;
250 // Clear old revisions
251 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
252 $this->pageRevision->where('page_id', '=', $page->id)
253 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
259 * Gets a single revision via it's id.
263 public function getRevisionById($id)
265 return $this->pageRevision->findOrFail($id);
269 * Checks if a slug exists within a book already.
272 * @param bool|false $currentId
275 public function doesSlugExist($slug, $bookId, $currentId = false)
277 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
278 if ($currentId) $query = $query->where('id', '!=', $currentId);
279 return $query->count() > 0;
283 * Sets the book id for the specified page.
284 * Changes the book id of any relations to the page that store the book id.
289 public function setBookId($bookId, Page $page)
291 $page->book_id = $bookId;
292 foreach ($page->activity as $activity) {
293 $activity->book_id = $bookId;
301 * Gets a suitable slug for the resource
305 * @param bool|false $currentId
308 public function findSuitableSlug($name, $bookId, $currentId = false)
310 $slug = Str::slug($name);
311 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
312 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);