public static function set_subscription_state($forumid, $discussionid, $targetstate) {
        global $PAGE, $USER;

        $params = self::validate_parameters(self::set_subscription_state_parameters(), [
            'forumid' => $forumid,
            'discussionid' => $discussionid,
            'targetstate' => $targetstate
        ]);

        $vaultfactory = mod_forum\local\container::get_vault_factory();
        $forumvault = $vaultfactory->get_forum_vault();
        $forum = $forumvault->get_from_id($params['forumid']);
        $coursemodule = $forum->get_course_module_record();
        $context = $forum->get_context();

        self::validate_context($context);

        $discussionvault = $vaultfactory->get_discussion_vault();
        $discussion = $discussionvault->get_from_id($params['discussionid']);
        $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();

        $forumrecord = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
        $discussionrecord = $legacydatamapperfactory->get_discussion_data_mapper()->to_legacy_object($discussion);

        if (!\mod_forum\subscriptions::is_subscribable($forumrecord)) {
            // Nothing to do. We won't actually output any content here though.
            throw new \moodle_exception('cannotsubscribe', 'mod_forum');
        }

        $issubscribed = \mod_forum\subscriptions::is_subscribed(
            $USER->id,
            $forumrecord,
            $discussion->get_id(),
            $coursemodule
        );

        // If the current state doesn't equal the desired state then update the current
        // state to the desired state.
        if ($issubscribed != (bool) $params['targetstate']) {
            if ($params['targetstate']) {
                \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussionrecord, $context);
            } else {
                \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussionrecord, $context);
            }
        }

        $exporterfactory = mod_forum\local\container::get_exporter_factory();
        $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
        return $exporter->export($PAGE->get_renderer('mod_forum'));
    }