3 namespace BookStack\Activity\Tools;
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Permissions\Permission;
12 * The built nested tree structure array.
13 * @var CommentTreeNode[]
15 protected array $tree;
16 protected array $comments;
18 public function __construct(
21 $this->comments = $this->loadComments();
22 $this->tree = $this->createTree($this->comments);
25 public function enabled(): bool
27 return !setting('app-disable-comments');
30 public function empty(): bool
32 return count($this->getActive()) === 0;
35 public function count(): int
37 return count($this->comments);
40 public function getActive(): array
42 return array_filter($this->tree, fn (CommentTreeNode $node) => !$node->comment->archived);
45 public function activeThreadCount(): int
47 return count($this->getActive());
50 public function getArchived(): array
52 return array_filter($this->tree, fn (CommentTreeNode $node) => $node->comment->archived);
55 public function archivedThreadCount(): int
57 return count($this->getArchived());
60 public function getCommentNodeForId(int $commentId): ?CommentTreeNode
62 foreach ($this->tree as $node) {
63 if ($node->comment->id === $commentId) {
71 public function canUpdateAny(): bool
73 foreach ($this->comments as $comment) {
74 if (userCan(Permission::CommentUpdate, $comment)) {
83 * @param Comment[] $comments
84 * @return CommentTreeNode[]
86 protected function createTree(array $comments): array
89 foreach ($comments as $comment) {
90 $byId[$comment->local_id] = $comment;
94 foreach ($comments as $comment) {
95 $parent = $comment->parent_id;
96 if (is_null($parent) || !isset($byId[$parent])) {
100 if (!isset($childMap[$parent])) {
101 $childMap[$parent] = [];
103 $childMap[$parent][] = $comment->local_id;
107 foreach ($childMap[0] ?? [] as $childId) {
108 $tree[] = $this->createTreeNodeForId($childId, 0, $byId, $childMap);
114 protected function createTreeNodeForId(int $id, int $depth, array &$byId, array &$childMap): CommentTreeNode
116 $childIds = $childMap[$id] ?? [];
119 foreach ($childIds as $childId) {
120 $children[] = $this->createTreeNodeForId($childId, $depth + 1, $byId, $childMap);
123 return new CommentTreeNode($byId[$id], $depth, $children);
126 protected function loadComments(): array
128 if (!$this->enabled()) {
132 return $this->page->comments()