public static function can_send_message_to_conversation(int $userid, int $conversationid) : bool {
        global $DB;

        $systemcontext = \context_system::instance();
        if (!has_capability('moodle/site:sendmessage', $systemcontext, $userid)) {
            return false;
        }

        if (!self::is_user_in_conversation($userid, $conversationid)) {
            return false;
        }

        // User can post messages and is in the conversation, but we need to check the conversation type to
        // know whether or not to check the user privacy settings via can_contact_user().
        $conversation = $DB->get_record('message_conversations', ['id' => $conversationid], '*', MUST_EXIST);
        if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_GROUP ||
            $conversation->type == self::MESSAGE_CONVERSATION_TYPE_SELF) {
            return true;
        } else if ($conversation->type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
            // Get the other user in the conversation.
            $members = self::get_conversation_members($userid, $conversationid);
            $otheruser = array_filter($members, function($member) use($userid) {
                return $member->id != $userid;
            });
            $otheruser = reset($otheruser);

            return self::can_contact_user($otheruser->id, $userid);
        } else {
            throw new \moodle_exception("Invalid conversation type '$conversation->type'.");
        }
    }