+/**
+ * @brief Add comments to top level entries that had been fetched before
+ *
+ * The system will fetch the comments for the local user whenever possible.
+ * This behaviour is currently needed to allow commenting on Friendica posts.
+ *
+ * @param array $parents Parent items
+ *
+ * @return array items with parents and comments
+ */
+function community_add_items($parents) {
+ $max_comments = Config::get("system", "max_comments", 100);
+
+ $items = [];
+
+ foreach ($parents AS $parent) {
+ $thread_items = dba::p(item_query()." AND `item`.`uid` = ?
+ AND `item`.`parent-uri` = ?
+ ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
+ local_user(),
+ $parent['uri']
+ );
+ $comments = dba::inArray($thread_items);
+
+ // Check if the original item is in the result.
+ // When commenting from the community page there can be incomplete threads
+ if (count($comments) > 0) {
+ $parent_found = false;
+ foreach ($comments as $comment) {
+ if ($comment['uri'] == $comment['parent-uri']) {
+ $parent_found = true;
+ break;
+ }
+ }
+ if (!$parent_found) {
+ $comments = [];
+ }
+ }
+
+ if (count($comments) == 0) {
+ $thread_items = dba::p(item_query()." AND `item`.`uid` = 0
+ AND `item`.`parent-uri` = ?
+ ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
+ $parent['uri']
+ );
+ $comments = dba::inArray($thread_items);
+ }
+
+ if (count($comments) != 0) {
+ $items = array_merge($items, $comments);
+ }
+ }
+
+ foreach ($items as $index => $item) {
+ if ($item['uid'] == 0) {
+ $items[$index]['writable'] = in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
+ }
+ }
+
+ $items = conv_sort($items, "`commented`");
+
+ return $items;
+}
+