- public function bookChildrenQuery($book_id, $filterDrafts = false) {
-
- // Draft setup
- $params = [
- 'userId' => $this->currentUser()->id,
- 'bookIdPage' => $book_id,
- 'bookIdChapter' => $book_id
- ];
- if (!$filterDrafts) {
- $params['userIdDrafts'] = $this->currentUser()->id;
- }
- // Role setup
- $userRoles = $this->getRoles();
- $roleBindings = [];
- $roleValues = [];
- foreach ($userRoles as $index => $roleId) {
- $roleBindings[':role'.$index] = $roleId;
- $roleValues['role'.$index] = $roleId;
+ /**
+ * Get the children of a book in an efficient single query, Filtered by the permission system.
+ * @param integer $book_id
+ * @param bool $filterDrafts
+ * @param bool $fetchPageContent
+ * @return \Illuminate\Database\Query\Builder
+ */
+ public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false) {
+ $pageContentSelect = $fetchPageContent ? 'html' : "''";
+ $pageSelect = $this->db->table('pages')->selectRaw("'BookStack\\\\Page' as entity_type, id, slug, name, text, {$pageContentSelect} as description, book_id, priority, chapter_id, draft")->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
+ $query->where('draft', '=', 0);
+ if (!$filterDrafts) {
+ $query->orWhere(function($query) {
+ $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
+ });
+ }
+ });
+ $chapterSelect = $this->db->table('chapters')->selectRaw("'BookStack\\\\Chapter' as entity_type, id, slug, name, '' as text, description, book_id, priority, 0 as chapter_id, 0 as draft")->where('book_id', '=', $book_id);
+ $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
+ ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
+
+ if (!$this->isAdmin()) {
+ $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
+ ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
+ ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
+ ->where(function($query) {
+ $query->where('jp.has_permission', '=', 1)->orWhere(function($query) {
+ $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
+ });
+ });
+ $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);