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);
85 $this->saveRevision($page);
90 * Formats a page's html to be tagged correctly
92 * @param string $htmlText
95 protected function formatHtml($htmlText)
97 libxml_use_internal_errors(true);
98 $doc = new \DOMDocument();
99 $doc->loadHTML($htmlText);
101 $container = $doc->documentElement;
102 $body = $container->childNodes->item(0);
103 $childNodes = $body->childNodes;
105 // Ensure no duplicate ids are used
109 foreach ($childNodes as $index => $childNode) {
110 /** @var \DOMElement $childNode */
111 if (get_class($childNode) !== 'DOMElement') continue;
113 // Overwrite id if not a bookstack custom id
114 if ($childNode->hasAttribute('id')) {
115 $id = $childNode->getAttribute('id');
116 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
122 // Create an unique id for the element
124 $id = 'bkmrk-' . substr(uniqid(), -5);
125 } while ($id == $lastId);
128 $childNode->setAttribute('id', $id);
132 // Generate inner html as a string
134 foreach ($childNodes as $childNode) {
135 $html .= $doc->saveHTML($childNode);
141 public function destroyById($id)
143 $page = $this->getById($id);
147 public function getBySearch($term, $whereTerms = [])
149 $terms = explode(' ', preg_quote(trim($term)));
150 $pages = $this->page->fullTextSearch(['name', 'text'], $terms, $whereTerms);
152 // Add highlights to page text.
153 $words = join('|', $terms);
154 //lookahead/behind assertions ensures cut between words
155 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
157 foreach ($pages as $page) {
158 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
159 //delimiter between occurrences
161 foreach ($matches as $line) {
162 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
165 if (count($results) > $matchLimit) {
166 $results = array_slice($results, 0, $matchLimit);
168 $result = join('... ', $results);
171 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
172 if (strlen($result) < 5) {
173 $result = $page->getExcerpt(80);
175 $page->searchSnippet = $result;
181 * Search for image usage.
182 * @param $imageString
185 public function searchForImage($imageString)
187 $pages = $this->page->where('html', 'like', '%' . $imageString . '%')->get();
188 foreach ($pages as $page) {
189 $page->url = $page->getUrl();
193 return count($pages) > 0 ? $pages : false;
197 * Updates a page with any fillable data and saves it into the database.
199 * @param int $book_id
200 * @param string $input
203 public function updatePage(Page $page, $book_id, $input)
206 $page->slug = $this->findSuitableSlug($page->name, $book_id, $page->id);
207 $page->html = $this->formatHtml($input['html']);
208 $page->text = strip_tags($page->html);
209 $page->updated_by = Auth::user()->id;
211 $this->saveRevision($page);
216 * Saves a page revision into the system.
220 public function saveRevision(Page $page)
222 $lastRevision = $this->getLastRevision($page);
223 if ($lastRevision && ($lastRevision->html === $page->html && $lastRevision->name === $page->name)) {
226 $revision = $this->pageRevision->fill($page->toArray());
227 $revision->page_id = $page->id;
228 $revision->created_by = Auth::user()->id;
230 // Clear old revisions
231 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
232 $this->pageRevision->where('page_id', '=', $page->id)
233 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
239 * Gets the most recent revision for a page.
243 public function getLastRevision(Page $page)
245 return $this->pageRevision->where('page_id', '=', $page->id)
246 ->orderBy('created_at', 'desc')->first();
250 * Gets a single revision via it's id.
254 public function getRevisionById($id)
256 return $this->pageRevision->findOrFail($id);
260 * Checks if a slug exists within a book already.
263 * @param bool|false $currentId
266 public function doesSlugExist($slug, $bookId, $currentId = false)
268 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
270 $query = $query->where('id', '!=', $currentId);
272 return $query->count() > 0;
275 public function setBookId($bookId, Page $page)
277 $page->book_id = $bookId;
278 foreach ($page->activity as $activity) {
279 $activity->book_id = $bookId;
287 * Gets a suitable slug for the resource
291 * @param bool|false $currentId
294 public function findSuitableSlug($name, $bookId, $currentId = false)
296 $slug = Str::slug($name);
297 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
298 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);