Get the author's groups for a list of posts.

@param post_entity[] $posts The list of posts
@param forum_entity $forum The forum entity
@return array Author groups indexed by author id
19667
private function get_author_groups_from_posts(array $posts, $forum) : array {
        $course = $forum->get_course_record();
        $coursemodule = $forum->get_course_module_record();
        $authorids = array_reduce($posts, function($carry, $post) {
            $carry[$post->get_author_id()] = true;
            return $carry;
        }, []);
        $authorgroups = groups_get_all_groups($course->id, array_keys($authorids), $coursemodule->groupingid,
                'g.*, gm.id, gm.groupid, gm.userid');

        $authorgroups = array_reduce($authorgroups, function($carry, $group) {
            // Clean up data returned from groups_get_all_groups.
            $userid = $group->userid;
            $groupid = $group->groupid;

            unset($group->userid);
            unset($group->groupid);
            $group->id = $groupid;

            if (!isset($carry[$userid])) {
                $carry[$userid] = [$group];
            } else {
                $carry[$userid][] = $group;
            }

            return $carry;
        }, []);

        foreach (array_diff(array_keys($authorids), array_keys($authorgroups)) as $authorid) {
            $authorgroups[$authorid] = [];
        }

        return $authorgroups;
    }
354341
public function get_context_ids_for_author_ids(array $authorids) : array {
        $db = $this->get_db();
        [$insql, $params] = $db->get_in_or_equal($authorids);
        $sql = "SELECT instanceid, id FROM {context} WHERE contextlevel = ? AND instanceid {$insql}";
        $records = $db->get_records_sql($sql, array_merge([CONTEXT_USER], $params));
        return array_reduce($authorids, function($carry, $id) use ($records) {
            $carry[$id] = isset($records[$id]) ? (int) $records[$id]->id : null;
            return $carry;
        }, []);
    }
457112
public function get_capability_manager(forum_entity $forum) {
        return new capability_manager(
            $forum,
            $this->legacydatamapperfactory->get_forum_data_mapper(),
            $this->legacydatamapperfactory->get_discussion_data_mapper(),
            $this->legacydatamapperfactory->get_post_data_mapper()
        );
    }
116562
public static function get_forum_discussion_posts_returns() {
        return new external_single_structure(
            array(
                'posts' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id' => new external_value(PARAM_INT, 'Post id'),
                                'discussion' => new external_value(PARAM_INT, 'Discussion id'),
                                'parent' => new external_value(PARAM_INT, 'Parent id'),
                                'userid' => new external_value(PARAM_INT, 'User id'),
                                'created' => new external_value(PARAM_INT, 'Creation time'),
                                'modified' => new external_value(PARAM_INT, 'Time modified'),
                                'mailed' => new external_value(PARAM_INT, 'Mailed?'),
                                'subject' => new external_value(PARAM_TEXT, 'The post subject'),
                                'message' => new external_value(PARAM_RAW, 'The post message'),
                                'messageformat' => new external_format_value('message'),
                                'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
                                'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
                                'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
                                'attachments' => new external_files('attachments', VALUE_OPTIONAL),
                                'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
                                'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
                                'children' => new external_multiple_structure(new external_value(PARAM_INT, 'children post id')),
                                'canreply' => new external_value(PARAM_BOOL, 'The user can reply to posts?'),
                                'postread' => new external_value(PARAM_BOOL, 'The post was read'),
                                'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
                                'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.', VALUE_OPTIONAL),
                                'deleted' => new external_value(PARAM_BOOL, 'This post has been removed.'),
                                'isprivatereply' => new external_value(PARAM_BOOL, 'The post is a private reply'),
                                'tags' => new external_multiple_structure(
                                    \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags', VALUE_OPTIONAL
                                ),
                            ), 'post'
                        )
                    ),
                'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
                'warnings' => new external_warnings()
            )
        );
    }
938173
public function getVotes(string $author, string $permalink)
    {
        $request = self::getContent($author, $permalink);

        if(isset($request['active_votes']) && is_array($request['active_votes']))
        {
            return $request['active_votes'];
        }

        return [];
    }
1070314
def _get_hidden_forum_ids(self, forums, user):
        
        visible_forums = self._get_forums_for_user(
            user, ['can_see_forum', 'can_read_forum', ], use_tree_hierarchy=True,
        )
        return forums.exclude(id__in=[f.id for f in visible_forums])
992066
public function search($forumId = null, $filters = null)
    {
        $query = static::find();
        if ($forumId) {
            $query->where(['forum_id' => (int)$forumId]);
        }
        if (!empty($filters)) {
            $loggedId = User::loggedId();
            if (!empty($filters['pin']) && $filters['pin'] == 1) {
                $query->andWhere(['pinned' => 1]);
            }
            if (!empty($filters['lock']) && $filters['lock'] == 1) {
                $query->andWhere(['locked' => 1]);
            }
            if (!empty($filters['hot']) && $filters['hot'] == 1) {
                $query->andWhere(['>=', 'posts', Podium::getInstance()->podiumConfig->get('hot_minimum')]);
            }
            if (!empty($filters['new']) && $filters['new'] == 1 && !Podium::getInstance()->user->isGuest) {
                $query->joinWith(['threadView tvn' => function ($q) use ($loggedId) {
                    $q->onCondition(['tvn.user_id' => $loggedId]);
                    $q->andWhere(['or',
                            new Expression('tvn.new_last_seen < new_post_at'),
                            ['tvn.new_last_seen' => null]
                        ]);
                }], false);
            }
            if (!empty($filters['edit']) && $filters['edit'] == 1 && !Podium::getInstance()->user->isGuest) {
                $query->joinWith(['threadView tve' => function ($q) use ($loggedId) {
                    $q->onCondition(['tve.user_id' => $loggedId]);
                    $q->andWhere(['or',
                            new Expression('tve.edited_last_seen < edited_post_at'),
                            ['tve.edited_last_seen' => null]
                        ]);
                }], false);
            }
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
        ]);
        $dataProvider->sort->defaultOrder = [
            'pinned' => SORT_DESC,
            'updated_at' => SORT_DESC,
            'id' => SORT_ASC
        ];

        return $dataProvider;
    }
624261
public function search($forumId, $threadId)
    {
        $dataProvider = new ActiveDataProvider([
            'query' => static::find()->where(['forum_id' => $forumId, 'thread_id' => $threadId]),
            'pagination' => [
                'defaultPageSize' => 10,
                'pageSizeLimit' => false,
                'forcePageParam' => false
            ],
        ]);
        $dataProvider->sort->defaultOrder = ['id' => SORT_ASC];
        return $dataProvider;
    }
920255
public function groupRecords($records)
    {
        if (!is_array($records) || empty($records)) {
            return;
        }

        $groups = array($this->get('element_name') => array());

        foreach ($records as $r) {
            $data = $r->getData($this->get('id'));
            $author_id = !isset($data['author_id']) ? 0 : $data['author_id'];

            if (!isset($groups[$this->get('element_name')][$author_id])) {
                $author = AuthorManager::fetchByID($author_id);
                // If there is an author, use those values, otherwise just blank it.
                if ($author instanceof Author) {
                    $username = $author->get('username');
                    $full_name = $author->getFullName();
                } else {
                    $username = '';
                    $full_name = '';
                }

                $groups[$this->get('element_name')][$author_id] = array(
                    'attr' => array('author-id' => $author_id, 'username' => $username, 'full-name' => $full_name),
                    'records' => array(),
                    'groups' => array()
                );
            }

            $groups[$this->get('element_name')][$author_id]['records'][] = $r;
        }

        return $groups;
    }
1232276
public function subscriber_overview($users, $forum , $course) {
        $output = '';
        $modinfo = get_fast_modinfo($course);
        if (!$users || !is_array($users) || count($users)===0) {
            $output .= $this->output->heading(get_string("nosubscribers", "forum"));
        } else if (!isset($modinfo->instances['forum'][$forum->id])) {
            $output .= $this->output->heading(get_string("invalidmodule", "error"));
        } else {
            $cm = $modinfo->instances['forum'][$forum->id];
            $canviewemail = in_array('email', get_extra_user_fields(context_module::instance($cm->id)));
            $strparams = new stdclass();
            $strparams->name = format_string($forum->name);
            $strparams->count = count($users);
            $output .= $this->output->heading(get_string("subscriberstowithcount", "forum", $strparams));
            $table = new html_table();
            $table->cellpadding = 5;
            $table->cellspacing = 5;
            $table->tablealign = 'center';
            $table->data = array();
            foreach ($users as $user) {
                $info = array($this->output->user_picture($user, array('courseid'=>$course->id)), fullname($user));
                if ($canviewemail) {
                    array_push($info, $user->email);
                }
                $table->data[] = $info;
            }
            $output .= html_writer::table($table);
        }
        return $output;
    }
1059008
protected function getNewPosts()
    {
        Container::get('hooks')->fire('model.index.get_new_posts_start');

        $query['select'] = ['f.id', 'f.last_post'];
        $query['where'] = [
            ['fp.read_forum' => 'IS NULL'],
            ['fp.read_forum' => '1']
        ];
        $query = DB::forTable('forums')
            ->table_alias('f')
            ->select_many($query['select'])
            ->left_outer_join(
                DB::prefix().'forum_perms',
                '(`fp`.`forum_id`=`f`.`id` AND `fp`.`group_id`='.User::get()->g_id.')',
                'fp'
            )
//            ->left_outer_join(DB::prefix().'forum_perms', array('fp.forum_id', '=', 'f.id'), 'fp')
//            ->left_outer_join(DB::prefix().'forum_perms', array('fp.group_id', '=',
// User::get()->g_id), null, true)
//            ->where_any_is($query['where'])
            ->where_raw('(fp.read_forum IS NULL OR fp.read_forum = 1)')
            ->where_gt('f.last_post', User::get()->last_visit);

        $query = Container::get('hooks')->fireDB('model.index.query_get_new_posts', $query);

        $query = $query->find_result_set();

        $forums = $new_topics = [];
        $tracked_topics = Track::getTrackedTopics();

        foreach ($query as $cur_forum) {
            if (!isset($tracked_topics['forums'][$cur_forum->id]) ||
                $tracked_topics['forums'][$cur_forum->id] < $cur_forum->last_post) {
                $forums[$cur_forum->id] = $cur_forum->last_post;
            }
        }

        if (!empty($forums)) {
            if (empty($tracked_topics['topics'])) {
                $new_topics = $forums;
            } else {
                $query['select'] = ['forum_id', 'id', 'last_post'];

                $query = DB::forTable('topics')
                    ->select_many($query['select'])
                    ->where_in('forum_id', array_keys($forums))
                    ->where_gt('last_post', User::get()->last_visit)
                    ->where_null('moved_to');

                $query = Container::get('hooks')->fireDB('model.index.get_new_posts_query', $query);

                $query = $query->find_result_set();

                foreach ($query as $cur_topic) {
                    if (!isset($new_topics[$cur_topic->forum_id]) &&
                        (!isset($tracked_topics['forums'][$cur_topic->forum_id]) ||
                            $tracked_topics['forums'][$cur_topic->forum_id] < $forums[$cur_topic->forum_id]) &&
                        (!isset($tracked_topics['topics'][$cur_topic->id]) ||
                            $tracked_topics['topics'][$cur_topic->id] < $cur_topic->last_post)) {
                        $new_topics[$cur_topic->forum_id] = $forums[$cur_topic->forum_id];
                    }
                }
            }
        }

        $new_topics = Container::get('hooks')->fire('model.index.get_new_posts', $new_topics);

        return $new_topics;
    }
987593
public function getPosts($blogId, $filters, $publication = self::GET_PUBLISHED_POSTS, $abstract = true)
    {
        if (!isset($filters['hiddenFilters'])) {
            $filters['hiddenFilters'] = [];
        }
        //filter on current blog
        $filters['hiddenFilters'] = [
            'blog' => $blogId,
        ];
        $publicationOptions = [];
        if (self::GET_PUBLISHED_POSTS === $publication) {
            $publicationOptions = ['published' => true];
        } elseif (self::GET_UNPUBLISHED_POSTS === $publication) {
            $publicationOptions = ['published' => false];
        }
        $filters['hiddenFilters'] = array_merge($filters['hiddenFilters'], $publicationOptions);

        return $this->finder->search('Icap\BlogBundle\Entity\Post', $filters, [
            'abstract' => $abstract,
        ]);
    }
1020025
public function get_from_post_id(int $id) : ?forum_entity {
        $alias = $this->get_table_alias();
        $thistable = new dml_table(self::TABLE, $alias, $alias);
        $coursemoduletable = new dml_table('course_modules', 'cm', 'cm_');
        $coursetable = new dml_table('course', 'c', 'c_');

        $tablefields = $thistable->get_field_select();
        $coursemodulefields = $coursemoduletable->get_field_select();
        $coursefields = $coursetable->get_field_select();

        $fields = implode(', ', [
            $tablefields,
            context_helper::get_preload_record_columns_sql('ctx'),
            $coursemodulefields,
            $coursefields,
        ]);

        $tables = "{forum_posts} p";
        $tables .= " JOIN {forum_discussions} d ON d.id = p.discussion";
        $tables .= ' JOIN {' . self::TABLE . "} {$alias} ON {$alias}.id = d.forum";
        $tables .= " JOIN {modules} m ON m.name = 'forum'";
        $tables .= " JOIN {course_modules} cm ON cm.module = m.id AND cm.instance = {$alias}.id";
        $tables .= ' JOIN {context} ctx ON ctx.contextlevel = ' . CONTEXT_MODULE .  ' AND ctx.instanceid = cm.id';
        $tables .= " JOIN {course} c ON c.id = {$alias}.course";

        $sql = "SELECT {$fields} FROM {$tables} WHERE p.id = :postid";
        $records = $this->get_db()->get_records_sql($sql, [
            'postid' => $id,
        ]);

        $records = $this->transform_db_records_to_entities($records);
        return count($records) ? array_shift($records) : null;
    }
1034175
public static function get_forum_access_information($forumid) {
        global $DB;

        $params = self::validate_parameters(self::get_forum_access_information_parameters(), array('forumid' => $forumid));

        // Request and permission validation.
        $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
        $cm = get_coursemodule_from_instance('forum', $forum->id);

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        $result = array();
        // Return all the available capabilities.
        $capabilities = load_capability_def('mod_forum');
        foreach ($capabilities as $capname => $capdata) {
            // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
            $field = 'can' . str_replace('mod/forum:', '', $capname);
            $result[$field] = has_capability($capname, $context);
        }

        $result['warnings'] = array();
        return $result;
    }
1177979
public function render_forum_post_email(\mod_forum\output\forum_post_email $post) {
        $data = $post->export_for_template($this, $this->target === RENDERER_TARGET_TEXTEMAIL);
        return $this->render_from_template('mod_forum/' . $this->forum_post_template(), $data);
    }
1356119
public function to_legacy_objects(array $posts) : array {
        return array_map(function(post_entity $post) {
            return (object) [
                'id' => $post->get_id(),
                'discussion' => $post->get_discussion_id(),
                'parent' => $post->get_parent_id(),
                'userid' => $post->get_author_id(),
                'created' => $post->get_time_created(),
                'modified' => $post->get_time_modified(),
                'mailed' => $post->has_been_mailed(),
                'subject' => $post->get_subject(),
                'message' => $post->get_message(),
                'messageformat' => $post->get_message_format(),
                'messagetrust' => $post->is_message_trusted(),
                'attachment' => $post->has_attachments(),
                'totalscore' => $post->get_total_score(),
                'mailnow' => $post->should_mail_now(),
                'deleted' => $post->is_deleted(),
                'privatereplyto' => $post->get_private_reply_recipient_id(),
            ];
        }, $posts);
    }
272037
public function lastReply()
    {
        try {
            $replies = ForumReply::where('post_id', $this->id)->get();

            if ($replies->isEmpty()) {
                return null;
            }

            $reply = $replies->last();

            return [
                'author' => $reply->author->name,
                'date' => $reply->created_at
            ];
        } catch (Exception $e) {
            return null;
        }
    }