+ * Search for image usage.
+ * @param $imageString
+ * @return mixed
+ */
+ public function searchForImage($imageString)
+ {
+ $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
+ foreach ($pages as $page) {
+ $page->url = $page->getUrl();
+ $page->html = '';
+ $page->text = '';
+ }
+ return count($pages) > 0 ? $pages : false;
+ }
+
+ /**
+ * Updates a page with any fillable data and saves it into the database.
+ * @param Page $page
+ * @param int $book_id
+ * @param string $input
+ * @return Page
+ */
+ public function updatePage(Page $page, $book_id, $input)
+ {
+ // Hold the old details to compare later
+ $oldHtml = $page->html;
+ $oldName = $page->name;
+
+ // Prevent slug being updated if no name change
+ if ($page->name !== $input['name']) {
+ $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
+ }
+
+ // Save page tags if present
+ if (isset($input['tags'])) {
+ $this->tagRepo->saveTagsToEntity($page, $input['tags']);
+ }
+
+ // Update with new details
+ $userId = user()->id;
+ $page->fill($input);
+ $page->html = $this->formatHtml($input['html']);
+ $page->text = strip_tags($page->html);
+ if (setting('app-editor') !== 'markdown') $page->markdown = '';
+ $page->updated_by = $userId;
+ $page->save();
+
+ // Remove all update drafts for this user & page.
+ $this->userUpdateDraftsQuery($page, $userId)->delete();
+
+ // Save a revision after updating
+ if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
+ $this->saveRevision($page, $input['summary']);
+ }
+
+ return $page;
+ }
+
+ /**
+ * Restores a revision's content back into a page.
+ * @param Page $page
+ * @param Book $book
+ * @param int $revisionId
+ * @return Page
+ */
+ public function restoreRevision(Page $page, Book $book, $revisionId)
+ {
+ $this->saveRevision($page);
+ $revision = $this->getRevisionById($revisionId);
+ $page->fill($revision->toArray());
+ $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
+ $page->text = strip_tags($page->html);
+ $page->updated_by = user()->id;
+ $page->save();
+ return $page;
+ }
+
+ /**
+ * Saves a page revision into the system.
+ * @param Page $page
+ * @param null|string $summary
+ * @return $this
+ */
+ public function saveRevision(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->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;
+ }
+
+ /**
+ * Save a page update draft.
+ * @param Page $page
+ * @param array $data
+ * @return PageRevision
+ */
+ public function saveUpdateDraft(Page $page, $data = [])
+ {
+ $userId = user()->id;
+ $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
+
+ if ($drafts->count() > 0) {
+ $draft = $drafts->first();
+ } else {
+ $draft = $this->pageRevision->newInstance();
+ $draft->page_id = $page->id;
+ $draft->slug = $page->slug;
+ $draft->book_slug = $page->book->slug;
+ $draft->created_by = $userId;
+ $draft->type = 'update_draft';
+ }
+
+ $draft->fill($data);
+ if (setting('app-editor') !== 'markdown') $draft->markdown = '';
+
+ $draft->save();
+ return $draft;
+ }
+
+ /**
+ * Update a draft page.
+ * @param Page $page
+ * @param array $data
+ * @return Page
+ */
+ public function updateDraftPage(Page $page, $data = [])
+ {
+ $page->fill($data);
+
+ if (isset($data['html'])) {
+ $page->text = strip_tags($data['html']);
+ }
+
+ $page->save();
+ return $page;
+ }
+
+ /**
+ * The base query for getting user update drafts.
+ * @param Page $page
+ * @param $userId
+ * @return mixed
+ */
+ private function userUpdateDraftsQuery(Page $page, $userId)
+ {
+ return $this->pageRevision->where('created_by', '=', $userId)
+ ->where('type', 'update_draft')
+ ->where('page_id', '=', $page->id)
+ ->orderBy('created_at', 'desc');
+ }
+
+ /**
+ * Checks whether a user has a draft version of a particular page or not.
+ * @param Page $page
+ * @param $userId
+ * @return bool
+ */
+ public function hasUserGotPageDraft(Page $page, $userId)
+ {
+ return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
+ }
+
+ /**
+ * Get the latest updated draft revision for a particular page and user.
+ * @param Page $page
+ * @param $userId
+ * @return mixed
+ */
+ public function getUserPageDraft(Page $page, $userId)
+ {
+ return $this->userUpdateDraftsQuery($page, $userId)->first();
+ }
+
+ /**
+ * Get the notification message that informs the user that they are editing a draft page.
+ * @param PageRevision $draft
+ * @return string
+ */
+ public function getUserPageDraftMessage(PageRevision $draft)
+ {
+ $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
+ if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
+ $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
+ }
+ return $message;
+ }
+
+ /**
+ * Check if a page is being actively editing.
+ * Checks for edits since last page updated.
+ * Passing in a minuted range will check for edits
+ * within the last x minutes.
+ * @param Page $page
+ * @param null $minRange
+ * @return bool
+ */
+ public function isPageEditingActive(Page $page, $minRange = null)
+ {
+ $draftSearch = $this->activePageEditingQuery($page, $minRange);
+ return $draftSearch->count() > 0;
+ }
+
+ /**
+ * Get a notification message concerning the editing activity on
+ * a particular page.
+ * @param Page $page
+ * @param null $minRange
+ * @return string
+ */
+ public function getPageEditingActiveMessage(Page $page, $minRange = null)
+ {
+ $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
+ $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
+ $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
+ $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
+ return sprintf($message, $userMessage, $timeMessage);
+ }
+
+ /**
+ * A query to check for active update drafts on a particular page.
+ * @param Page $page
+ * @param null $minRange
+ * @return mixed
+ */
+ private function activePageEditingQuery(Page $page, $minRange = null)
+ {
+ $query = $this->pageRevision->where('type', '=', 'update_draft')
+ ->where('page_id', '=', $page->id)
+ ->where('updated_at', '>', $page->updated_at)
+ ->where('created_by', '!=', user()->id)
+ ->with('createdBy');
+
+ if ($minRange !== null) {
+ $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
+ }
+
+ return $query;
+ }
+
+ /**
+ * Gets a single revision via it's id.
+ * @param $id
+ * @return PageRevision
+ */
+ public function getRevisionById($id)
+ {
+ return $this->pageRevision->findOrFail($id);
+ }
+
+ /**
+ * Checks if a slug exists within a book already.
+ * @param $slug
+ * @param $bookId
+ * @param bool|false $currentId
+ * @return bool
+ */
+ public function doesSlugExist($slug, $bookId, $currentId = false)
+ {
+ $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
+ if ($currentId) $query = $query->where('id', '!=', $currentId);
+ return $query->count() > 0;
+ }
+
+ /**
+ * Changes the related book for the specified page.
+ * Changes the book id of any relations to the page that store the book id.
+ * @param int $bookId
+ * @param Page $page
+ * @return Page
+ */
+ public function changeBook($bookId, Page $page)
+ {
+ $page->book_id = $bookId;
+ foreach ($page->activity as $activity) {
+ $activity->book_id = $bookId;
+ $activity->save();
+ }
+ $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
+ $page->save();
+ return $page;
+ }
+
+
+ /**
+ * Change the page's parent to the given entity.
+ * @param Page $page
+ * @param Entity $parent
+ */
+ public function changePageParent(Page $page, Entity $parent)
+ {
+ $book = $parent->isA('book') ? $parent : $parent->book;
+ $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
+ $page->save();
+ $page = $this->changeBook($book->id, $page);
+ $page->load('book');
+ $this->permissionService->buildJointPermissionsForEntity($book);
+ }
+
+ /**
+ * Gets a suitable slug for the resource
+ * @param string $name
+ * @param int $bookId
+ * @param bool|false $currentId
+ * @return string
+ */
+ public function findSuitableSlug($name, $bookId, $currentId = false)
+ {
+ $slug = Str::slug($name);
+ if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
+ while ($this->doesSlugExist($slug, $bookId, $currentId)) {
+ $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
+ }
+ return $slug;
+ }
+
+ /**
+ * Destroy a given page along with its dependencies.
+ * @param $page
+ */
+ public function destroy(Page $page)
+ {
+ Activity::removeEntity($page);
+ $page->views()->delete();
+ $page->tags()->delete();
+ $page->revisions()->delete();
+ $page->permissions()->delete();
+ $this->permissionService->deleteJointPermissionsForEntity($page);
+
+ // Delete AttachedFiles
+ $fileService = app(FileService::class);
+ foreach ($page->files as $file) {
+ $fileService->deleteFile($file);
+ }
+
+ $page->delete();
+ }
+
+ /**
+ * Get the latest pages added to the system.
+ * @param $count
+ */
+ public function getRecentlyCreatedPaginated($count = 20)
+ {
+ return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
+ }
+
+ /**
+ * Get the latest pages added to the system.
+ * @param $count