public static function link_login($userinfo, $issuer, $userid = false, $skippermissions = false) {
        global $USER;

        if ($userid === false) {
            $userid = $USER->id;
        }

        if (linked_login::has_existing_issuer_match($issuer, $userinfo['username'])) {
            throw new moodle_exception('alreadylinked', 'auth_oauth2');
        }

        if (\core\session\manager::is_loggedinas()) {
            throw new moodle_exception('notwhileloggedinas', 'auth_oauth2');
        }

        $context = context_user::instance($userid);
        if (!$skippermissions) {
            require_capability('auth/oauth2:managelinkedlogins', $context);
        }

        $record = new stdClass();
        $record->issuerid = $issuer->get('id');
        $record->username = $userinfo['username'];
        $record->userid = $userid;
        $existing = linked_login::get_record((array)$record);
        if ($existing) {
            $existing->set('confirmtoken', '');
            $existing->update();
            return $existing;
        }
        $record->email = $userinfo['email'];
        $record->confirmtoken = '';
        $record->confirmtokenexpires = 0;
        $linkedlogin = new linked_login(0, $record);
        return $linkedlogin->create();
    }