Create a standard type discussion list renderer.

@param forum_entity $forum The forum that the discussions belong to
@return discussion_list_renderer
774907
public function get_discussion_list_renderer(
        forum_entity $forum
    ) : discussion_list_renderer {

        $capabilitymanager = $this->managerfactory->get_capability_manager($forum);
        $rendererbase = $this->rendererbase;
        $notifications = [];

        switch ($forum->get_type()) {
            case 'news':
                if (SITEID == $forum->get_course_id()) {
                    $template = 'mod_forum/frontpage_news_discussion_list';
                } else {
                    $template = 'mod_forum/news_discussion_list';
                }
                break;
            case 'qanda':
                $template = 'mod_forum/qanda_discussion_list';
                break;
            default:
                $template = 'mod_forum/discussion_list';
        }

        return new discussion_list_renderer(
            $forum,
            $rendererbase,
            $this->legacydatamapperfactory,
            $this->exporterfactory,
            $this->vaultfactory,
            $this->builderfactory,
            $capabilitymanager,
            $this->urlfactory,
            $template,
            $notifications,
            function($discussions, $user, $forum) {

                $exporteddiscussionsummarybuilder = $this->builderfactory->get_exported_discussion_summaries_builder();
                return $exporteddiscussionsummarybuilder->build(
                    $user,
                    $forum,
                    $discussions
                );
            }
        );
    }
236803
public function get_first_discussion_in_forum(forum_entity $forum) : ?discussion_entity {
        $records = $this->get_db()->get_records(self::TABLE, [
            'forum' => $forum->get_id(),
        ], 'timemodified ASC', '*', 0, 1);

        $records = $this->transform_db_records_to_entities($records);
        return count($records) ? array_shift($records) : null;
    }
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;
    }
888442
protected function add_discussion_footer($discussion) {
        global $CFG;

        if ($this->allowhtml) {
            $footerlinks = [];

            $forum = $this->forums[$discussion->forum];
            if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
                // This forum is force subscribed. The user cannot unsubscribe.
                $footerlinks[] = get_string("everyoneissubscribed", "forum");
            } else {
                $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" .
                    get_string("unsubscribe", "forum") . "</a>";
            }
            $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" .
                    get_string("digestmailpost", "forum") . '</a>';

            $this->discussionhtml .= "\n<div class='mdl-right'><font size=\"1\">" .
                    implode('&nbsp;', $footerlinks) . '</font></div>';
            $this->discussionhtml .= '<hr size="1" noshade="noshade" /></p>';
        }
    }
1141510
public function get_discussion_from_stdclass(stdClass $record) : discussion_entity {
        return new discussion_entity(
            $record->id,
            $record->course,
            $record->forum,
            $record->name,
            $record->firstpost,
            $record->userid,
            $record->groupid,
            $record->assessed,
            $record->timemodified,
            $record->usermodified,
            $record->timestart,
            $record->timeend,
            $record->pinned,
            $record->timelocked
        );
    }
1374789
def create
      @discussion = Discussion.new(params[:discussion])

      # assign user if signed in
      if current_cornerstone_user
        @discussion.user = current_cornerstone_user
        @discussion.posts.first.user = current_cornerstone_user
      end

      respond_with(@discussion.category, @discussion) do |format|
        if @discussion.save
          flash[:notice] = 'Discussion was successfully created.'
          format.html {redirect_to category_discussion_path(@discussion.category, @discussion)}
        else
          @categories = Category.discussions
          format.html {render :new}
        end
      end
    end
994116
public function can_split_post(stdClass $user, discussion_entity $discussion, post_entity $post) : bool {
        if ($post->is_private_reply()) {
            // It is not possible to create a private discussion.
            return false;
        }

        return $this->can_split_discussions($user) && $post->has_parent();
    }
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;
    }
180364
public static function get_forum_discussions_paginated_returns() {
        return new external_single_structure(
            array(
                'discussions' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id' => new external_value(PARAM_INT, 'Post id'),
                                'name' => new external_value(PARAM_TEXT, 'Discussion name'),
                                'groupid' => new external_value(PARAM_INT, 'Group id'),
                                'timemodified' => new external_value(PARAM_INT, 'Time modified'),
                                'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
                                'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
                                'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
                                'discussion' => new external_value(PARAM_INT, 'Discussion id'),
                                'parent' => new external_value(PARAM_INT, 'Parent id'),
                                'userid' => new external_value(PARAM_INT, 'User who started the discussion 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?'),
                                'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
                                'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
                                'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
                                'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
                                'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
                                'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
                                'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
                                'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
                                'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
                                'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
                            ), 'post'
                        )
                    ),
                'warnings' => new external_warnings()
            )
        );
    }
208400
protected function add_discussion_header($discussion, $forum, $course) {
        global $CFG;

        $shortname = format_string($course->shortname, true, [
                'context' => \context_course::instance($course->id),
            ]);

        $strforums = get_string('forums', 'forum');

        $this->discussiontext .= "\n=====================================================================\n\n";
        $this->discussiontext .= "$shortname -> $strforums -> " . format_string($forum->name, true);
        if ($discussion->name != $forum->name) {
            $this->discussiontext  .= " -> " . format_string($discussion->name, true);
        }
        $this->discussiontext .= "\n";
        $this->discussiontext .= new \moodle_url('/mod/forum/discuss.php', [
                'd' => $discussion->id,
            ]);
        $this->discussiontext .= "\n";

        if ($this->allowhtml) {
            $this->discussionhtml .= "<p><font face=\"sans-serif\">".
                "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
                "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
                "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">" .
                        format_string($forum->name, true)."</a>";
            if ($discussion->name == $forum->name) {
                $this->discussionhtml .= "</font></p>";
            } else {
                $this->discussionhtml .=
                        " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">" .
                        format_string($discussion->name, true)."</a></font></p>";
            }
            $this->discussionhtml .= '<p>';
        }

    }
1176455
def forum_topic(self):
        
        if self.api and self.forum_topic_id:
            return self.api._get_topic(self.forum_topic_id)
422448
public function indexNew()
    {
        $threads = $this->api('thread.index-new')->get();

        event(new UserViewingNew($threads));

        return view('forum::thread.index-new', compact('threads'));
    }
1034648
protected function export_for_template_html(\mod_forum_renderer $renderer) {
        $data = $this->export_for_template_shared($renderer);
        return $data + array(
            'id'                            => $this->post->id,
            'coursename'                    => $this->get_coursename(),
            'courselink'                    => $this->get_courselink(),
            'forumname'                     => $this->get_forumname(),
            'showdiscussionname'            => $this->get_showdiscussionname(),
            'discussionname'                => $this->get_discussionname(),
            'subject'                       => $this->get_subject(),
            'authorfullname'                => $this->get_author_fullname(),
            'postdate'                      => $this->get_postdate(),

            // Format some components according to the renderer.
            'message'                       => $renderer->format_message_text($this->cm, $this->post),
            'attachments'                   => $renderer->format_message_attachments($this->cm, $this->post),
        );
    }
1298563
public function get_mark_post_as_read_url_from_post(post_entity $post, int $displaymode = FORUM_MODE_THREADED) : moodle_url {
        $params = [
            'd' => $post->get_discussion_id(),
            'postid' => $post->get_id(),
            'mark' => 'read'
        ];

        $url = new moodle_url('/mod/forum/discuss.php', $params);

        if ($displaymode == FORUM_MODE_THREADED) {
            $url->param('parent', $post->get_parent_id());
        } else {
            $url->set_anchor('p' . $post->get_id());
        }

        return $url;
    }
443459
private function get_move_discussion_html() : ?string {
        global $DB;

        $forum = $this->forum;
        $discussion = $this->discussion;
        $courseid = $forum->get_course_id();

        // Popup menu to move discussions to other forums. The discussion in a
        // single discussion forum can't be moved.
        $modinfo = get_fast_modinfo($courseid);
        if (isset($modinfo->instances['forum'])) {
            $forummenu = [];
            // Check forum types and eliminate simple discussions.
            $forumcheck = $DB->get_records('forum', ['course' => $courseid], '', 'id, type');
            foreach ($modinfo->instances['forum'] as $forumcm) {
                if (!$forumcm->uservisible || !has_capability('mod/forum:startdiscussion',
                    context_module::instance($forumcm->id))) {
                    continue;
                }
                $section = $forumcm->sectionnum;
                $sectionname = get_section_name($courseid, $section);
                if (empty($forummenu[$section])) {
                    $forummenu[$section] = [$sectionname => []];
                }
                $forumidcompare = $forumcm->instance != $forum->get_id();
                $forumtypecheck = $forumcheck[$forumcm->instance]->type !== 'single';

                if ($forumidcompare and $forumtypecheck) {
                    $url = "/mod/forum/discuss.php?d={$discussion->get_id()}&move=$forumcm->instance&sesskey=".sesskey();
                    $forummenu[$section][$sectionname][$url] = format_string($forumcm->name);
                }
            }
            if (!empty($forummenu)) {
                $html = '<div class="movediscussionoption">';
                $select = new url_select($forummenu, '',
                        ['/mod/forum/discuss.php?d=' . $discussion->get_id() => get_string("movethisdiscussionto", "forum")],
                        'forummenu', get_string('move'));
                $html .= $this->renderer->render($select);
                $html .= "</div>";
                return $html;
            }
        }

        return null;
    }
122093
public function actionEditForum($cid = null, $id = null)
    {
        $model = Forum::find()->where(['id' => $id, 'category_id' => $cid])->limit(1)->one();
        if (empty($model)) {
            $this->error(Yii::t('podium/flash', 'Sorry! We can not find Forum with this ID.'));
            return $this->redirect(['admin/forums', 'cid' => $cid]);
        }
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Log::info('Forum updated', $model->id, __METHOD__);
                $this->success(Yii::t('podium/flash', 'Forum has been updated.'));
                return $this->refresh();
            }
            $this->error(Yii::t('podium/flash', 'Sorry! There was an error while updating the forum.'));
        }
        return $this->render('forum', [
            'model' => $model,
            'forums' => Forum::find()->where(['category_id' => $cid])->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all(),
            'categories' => Category::find()->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all()
        ]);
    }
1124931
public function can_create_discussions(stdClass $user, int $groupid = null) : bool {
        if (isguestuser($user) or !isloggedin()) {
            return false;
        }

        if ($this->forum->is_cutoff_date_reached()) {
            if (!has_capability('mod/forum:canoverridecutoff', $this->get_context())) {
                return false;
            }
        }

        switch ($this->forum->get_type()) {
            case 'news':
                $capability = 'mod/forum:addnews';
                break;
            case 'qanda':
                $capability = 'mod/forum:addquestion';
                break;
            default:
                $capability = 'mod/forum:startdiscussion';
        }

        if (!has_capability($capability, $this->forum->get_context(), $user)) {
            return false;
        }

        if ($this->forum->get_type() == 'eachuser') {
            if (forum_user_has_posted_discussion($this->forum->get_id(), $user->id, $groupid)) {
                return false;
            }
        }

        if ($this->forum->is_in_group_mode()) {
            return $groupid ? $this->can_access_group($user, $groupid) : $this->can_access_all_groups($user);
        } else {
            return true;
        }
    }