public static function get_contexts_for_userid(int $userid) : contextlist {
        global $DB;

        $contextlist = new contextlist();

        // The role_capabilities table contains user data.
        $contexts = [
            CONTEXT_SYSTEM,
            CONTEXT_USER,
            CONTEXT_COURSECAT,
            CONTEXT_COURSE,
            CONTEXT_MODULE,
            CONTEXT_BLOCK
        ];
        list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
        $sql = "SELECT ctx.id
                  FROM {context} ctx
                  JOIN {role_capabilities} rc
                    ON rc.contextid = ctx.id
                   AND ((ctx.contextlevel {$insql} AND rc.modifierid = :modifierid)
                    OR (ctx.contextlevel = :contextlevel AND ctx.instanceid = :userid))";
        $params = [
            'modifierid' => $userid,
            'contextlevel' => CONTEXT_USER,
            'userid' => $userid
         ];
        $params += $inparams;

        $contextlist->add_from_sql($sql, $params);

        // The role_assignments table contains user data.
        $contexts = [
            CONTEXT_SYSTEM,
            CONTEXT_USER,
            CONTEXT_COURSECAT,
            CONTEXT_COURSE,
            CONTEXT_MODULE,
            CONTEXT_BLOCK
        ];
        list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
        $params = [
            'userid' => $userid,
            'modifierid' => $userid
         ];
        $params += $inparams;
        $sql = "SELECT ctx.id
                  FROM {role_assignments} ra
                  JOIN {context} ctx
                    ON ctx.id = ra.contextid
                   AND ctx.contextlevel {$insql}
                 WHERE (ra.userid = :userid
                    OR ra.modifierid = :modifierid)
                   AND ra.component != 'tool_cohortroles'";
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }