3 namespace BookStack\Http\Controllers;
5 use BookStack\Auth\Permissions\PermissionApplicator;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Entity;
10 use BookStack\Entities\Models\Page;
11 use Illuminate\Database\Eloquent\Collection;
12 use Illuminate\Database\Eloquent\Relations\Relation;
14 class ReferenceController extends Controller
17 protected PermissionApplicator $permissions;
19 public function __construct(PermissionApplicator $permissions)
21 $this->permissions = $permissions;
25 * Display the references to a given page.
27 public function page(string $bookSlug, string $pageSlug)
29 /** @var Page $page */
30 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->firstOrFail();
31 $references = $this->getEntityReferences($page);
33 return view('pages.references', [
35 'references' => $references,
40 * Display the references to a given chapter.
42 public function chapter(string $bookSlug, string $chapterSlug)
44 /** @var Chapter $chapter */
45 $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
46 $references = $this->getEntityReferences($chapter);
48 return view('chapters.references', [
49 'chapter' => $chapter,
50 'references' => $references,
55 * Display the references to a given book.
57 public function book(string $slug)
59 $book = Book::visible()->where('slug', '=', $slug)->firstOrFail();
60 $references = $this->getEntityReferences($book);
62 return view('books.references', [
64 'references' => $references,
69 * Display the references to a given shelf.
71 public function shelf(string $slug)
73 $shelf = Bookshelf::visible()->where('slug', '=', $slug)->firstOrFail();
74 $references = $this->getEntityReferences($shelf);
76 return view('shelves.references', [
78 'references' => $references,
83 * Query the references for the given entities.
84 * Loads the commonly required relations while taking permissions into account.
86 protected function getEntityReferences(Entity $entity): Collection
88 $baseQuery = $entity->referencesTo()
89 ->where('from_type', '=', (new Page())->getMorphClass())
91 'from' => fn(Relation $query) => $query->select(Page::$listAttributes),
92 'from.book' => fn(Relation $query) => $query->scopes('visible'),
93 'from.chapter' => fn(Relation $query) => $query->scopes('visible')
96 $references = $this->permissions->restrictEntityRelationQuery(