+ $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;
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Create a copy of a page in a new location with a new name.
+ * @param Page $page
+ * @param Entity $newParent
+ * @param string $newName
+ * @return Page
+ */
+ public function copyPage(Page $page, Entity $newParent, $newName = '')
+ {
+ $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
+ $newChapter = $newParent->isA('chapter') ? $newParent : null;
+ $copyPage = $this->getDraftPage($newBook, $newChapter);
+ $pageData = $page->getAttributes();
+
+ // Update name
+ if (!empty($newName)) {
+ $pageData['name'] = $newName;
+ }
+
+ // Copy tags from previous page if set
+ if ($page->tags) {
+ $pageData['tags'] = [];
+ foreach ($page->tags as $tag) {
+ $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
+ }
+ }
+
+ // Set priority
+ if ($newParent->isA('chapter')) {
+ $pageData['priority'] = $this->getNewChapterPriority($newParent);
+ } else {
+ $pageData['priority'] = $this->getNewBookPriority($newParent);
+ }
+
+ return $this->publishPageDraft($copyPage, $pageData);
+ }
+
+ /**
+ * 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;
+ if (!config('app.allow_content_scripts')) {
+ $content = $this->escapeScripts($content);
+ }
+
+ $matches = [];
+ preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
+ if (count($matches[0]) === 0) {
+ return $content;
+ }
+
+ $topLevelTags = ['table', 'ul', 'ol'];
+ foreach ($matches[1] as $index => $includeId) {
+ $splitInclude = explode('#', $includeId, 2);
+ $pageId = intval($splitInclude[0]);
+ if (is_nan($pageId)) {
+ continue;
+ }
+
+ $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
+ if ($matchedPage === null) {
+ $content = str_replace($matches[0][$index], '', $content);
+ continue;
+ }
+
+ if (count($splitInclude) === 1) {
+ $content = str_replace($matches[0][$index], $matchedPage->html, $content);
+ continue;
+ }
+
+ $doc = new DOMDocument();
+ $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
+ $matchingElem = $doc->getElementById($splitInclude[1]);
+ if ($matchingElem === null) {
+ $content = str_replace($matches[0][$index], '', $content);
+ continue;