+ $this->permissionService->buildJointPermissionsForEntity($entity);
+ }
+
+
+
+ /**
+ * Create a new entity from request input.
+ * Used for books and chapters.
+ * @param string $type
+ * @param array $input
+ * @param bool|Book $book
+ * @return Entity
+ */
+ public function createFromInput($type, $input = [], $book = false)
+ {
+ $isChapter = strtolower($type) === 'chapter';
+ $entity = $this->getEntity($type)->newInstance($input);
+ $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
+ $entity->created_by = user()->id;
+ $entity->updated_by = user()->id;
+ $isChapter ? $book->chapters()->save($entity) : $entity->save();
+ $this->permissionService->buildJointPermissionsForEntity($entity);
+ $this->searchService->indexEntity($entity);
+ return $entity;
+ }
+
+ /**
+ * Update entity details from request input.
+ * Used for books and chapters
+ * @param string $type
+ * @param Entity $entityModel
+ * @param array $input
+ * @return Entity
+ */
+ public function updateFromInput($type, Entity $entityModel, $input = [])
+ {
+ if ($entityModel->name !== $input['name']) {
+ $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
+ }
+ $entityModel->fill($input);
+ $entityModel->updated_by = user()->id;
+ $entityModel->save();
+ $this->permissionService->buildJointPermissionsForEntity($entityModel);
+ $this->searchService->indexEntity($entityModel);
+ return $entityModel;
+ }
+
+ /**
+ * Change the book that an entity belongs to.
+ * @param string $type
+ * @param integer $newBookId
+ * @param Entity $entity
+ * @param bool $rebuildPermissions
+ * @return Entity
+ */
+ public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
+ {
+ $entity->book_id = $newBookId;
+ // Update related activity
+ foreach ($entity->activity as $activity) {
+ $activity->book_id = $newBookId;
+ $activity->save();
+ }
+ $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
+ $entity->save();
+
+ // Update all child pages if a chapter
+ if (strtolower($type) === 'chapter') {
+ foreach ($entity->pages as $page) {
+ $this->changeBook('page', $newBookId, $page, false);
+ }
+ }
+
+ // Update permissions if applicable
+ if ($rebuildPermissions) {
+ $entity->load('book');
+ $this->permissionService->buildJointPermissionsForEntity($entity->book);
+ }
+
+ return $entity;
+ }
+
+ /**
+ * Alias method to update the book jointPermissions in the PermissionService.
+ * @param Book $book
+ */
+ public function buildJointPermissionsForBook(Book $book)
+ {
+ $this->permissionService->buildJointPermissionsForEntity($book);
+ }
+
+ /**
+ * Format a name as a url slug.
+ * @param $name
+ * @return string
+ */
+ protected function nameToSlug($name)
+ {
+ $slug = str_replace(' ', '-', strtolower($name));
+ $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
+ if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
+ return $slug;
+ }
+
+ /**
+ * Publish a draft page to make it a normal page.
+ * Sets the slug and updates the content.
+ * @param Page $draftPage
+ * @param array $input
+ * @return Page
+ */
+ public function publishPageDraft(Page $draftPage, array $input)
+ {
+ $draftPage->fill($input);
+
+ // Save page tags if present
+ if (isset($input['tags'])) {
+ $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
+ }
+
+ $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
+ $draftPage->html = $this->formatHtml($input['html']);
+ $draftPage->text = $this->pageToPlainText($draftPage);
+ $draftPage->draft = false;
+ $draftPage->revision_count = 1;
+
+ $draftPage->save();
+ $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
+ $this->searchService->indexEntity($draftPage);
+ return $draftPage;
+ }
+
+ /**
+ * Saves a page revision into the system.
+ * @param Page $page
+ * @param null|string $summary
+ * @return PageRevision
+ */
+ public function savePageRevision(Page $page, $summary = null)
+ {
+ $revision = $this->pageRevision->newInstance($page->toArray());
+ if (setting('app-editor') !== 'markdown') $revision->markdown = '';
+ $revision->page_id = $page->id;
+ $revision->slug = $page->slug;
+ $revision->book_slug = $page->book->slug;
+ $revision->created_by = user()->id;
+ $revision->created_at = $page->updated_at;
+ $revision->type = 'version';
+ $revision->summary = $summary;
+ $revision->revision_number = $page->revision_count;
+ $revision->save();
+
+ // Clear old revisions
+ if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
+ $this->pageRevision->where('page_id', '=', $page->id)
+ ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
+ }
+
+ return $revision;
+ }
+
+ /**
+ * Formats a page's html to be tagged correctly
+ * within the system.
+ * @param string $htmlText
+ * @return string
+ */
+ protected function formatHtml($htmlText)
+ {
+ if ($htmlText == '') return $htmlText;
+ libxml_use_internal_errors(true);
+ $doc = new DOMDocument();
+ $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
+
+ $container = $doc->documentElement;
+ $body = $container->childNodes->item(0);
+ $childNodes = $body->childNodes;
+
+ // Ensure no duplicate ids are used
+ $idArray = [];
+
+ foreach ($childNodes as $index => $childNode) {
+ /** @var \DOMElement $childNode */
+ if (get_class($childNode) !== 'DOMElement') continue;
+
+ // Overwrite id if not a BookStack custom id
+ if ($childNode->hasAttribute('id')) {
+ $id = $childNode->getAttribute('id');
+ if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
+ $idArray[] = $id;
+ continue;
+ };
+ }
+
+ // Create an unique id for the element
+ // Uses the content as a basis to ensure output is the same every time
+ // the same content is passed through.
+ $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
+ $newId = urlencode($contentId);
+ $loopIndex = 0;
+ while (in_array($newId, $idArray)) {
+ $newId = urlencode($contentId . '-' . $loopIndex);
+ $loopIndex++;
+ }
+
+ $childNode->setAttribute('id', $newId);
+ $idArray[] = $newId;
+ }
+
+ // Generate inner html as a string
+ $html = '';
+ foreach ($childNodes as $childNode) {
+ $html .= $doc->saveHTML($childNode);
+ }
+
+ return $html;
+ }
+
+
+ /**
+ * Render the page for viewing, Parsing and performing features such as page transclusion.
+ * @param Page $page
+ * @param bool $ignorePermissions
+ * @return mixed|string
+ */
+ public function renderPage(Page $page, $ignorePermissions = false)
+ {
+ $content = $page->html;
+ $matches = [];
+ preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
+ if (count($matches[0]) === 0) return $content;
+
+ foreach ($matches[1] as $index => $includeId) {
+ $splitInclude = explode('#', $includeId, 2);
+ $pageId = intval($splitInclude[0]);
+ if (is_nan($pageId)) continue;
+
+ $page = $this->getById('page', $pageId, false, $ignorePermissions);
+ if ($page === null) {
+ $content = str_replace($matches[0][$index], '', $content);
+ continue;
+ }
+
+ if (count($splitInclude) === 1) {
+ $content = str_replace($matches[0][$index], $page->html, $content);
+ continue;
+ }
+
+ $doc = new DOMDocument();
+ $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
+ $matchingElem = $doc->getElementById($splitInclude[1]);
+ if ($matchingElem === null) {
+ $content = str_replace($matches[0][$index], '', $content);
+ continue;
+ }
+ $innerContent = '';
+ foreach ($matchingElem->childNodes as $childNode) {
+ $innerContent .= $doc->saveHTML($childNode);
+ }
+ $content = str_replace($matches[0][$index], trim($innerContent), $content);
+ }
+
+ $page->renderedHTML = $content;
+ return $content;
+ }
+
+ /**
+ * Get the plain text version of a page's content.
+ * @param Page $page
+ * @return string
+ */
+ public function pageToPlainText(Page $page)
+ {
+ $html = $this->renderPage($page);
+ return strip_tags($html);
+ }
+
+ /**
+ * Get a new draft page instance.
+ * @param Book $book
+ * @param Chapter|bool $chapter
+ * @return Page
+ */
+ public function getDraftPage(Book $book, $chapter = false)
+ {
+ $page = $this->page->newInstance();
+ $page->name = trans('entities.pages_initial_name');
+ $page->created_by = user()->id;
+ $page->updated_by = user()->id;
+ $page->draft = true;
+
+ if ($chapter) $page->chapter_id = $chapter->id;
+
+ $book->pages()->save($page);
+ $page = $this->page->find($page->id);
+ $this->permissionService->buildJointPermissionsForEntity($page);
+ return $page;
+ }
+
+ /**
+ * Search for image usage within page content.
+ * @param $imageString
+ * @return mixed
+ */
+ public function searchForImage($imageString)
+ {
+ $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
+ foreach ($pages as $page) {
+ $page->url = $page->getUrl();
+ $page->html = '';
+ $page->text = '';
+ }
+ return count($pages) > 0 ? $pages : false;