protected static function discover_endpoints($issuer) {
        $curl = new curl();

        if (empty($issuer->get('baseurl'))) {
            return 0;
        }

        $url = $issuer->get_endpoint_url('discovery');
        if (!$url) {
            $url = $issuer->get('baseurl') . '/.well-known/openid-configuration';
        }

        if (!$json = $curl->get($url)) {
            $msg = 'Could not discover end points for identity issuer' . $issuer->get('name');
            throw new moodle_exception($msg);
        }

        if ($msg = $curl->error) {
            throw new moodle_exception('Could not discover service endpoints: ' . $msg);
        }

        $info = json_decode($json);
        if (empty($info)) {
            $msg = 'Could not discover end points for identity issuer' . $issuer->get('name');
            throw new moodle_exception($msg);
        }

        foreach (endpoint::get_records(['issuerid' => $issuer->get('id')]) as $endpoint) {
            if ($endpoint->get('name') != 'discovery_endpoint') {
                $endpoint->delete();
            }
        }

        foreach ($info as $key => $value) {
            if (substr_compare($key, '_endpoint', - strlen('_endpoint')) === 0) {
                $record = new stdClass();
                $record->issuerid = $issuer->get('id');
                $record->name = $key;
                $record->url = $value;

                $endpoint = new endpoint(0, $record);
                $endpoint->create();
            }

            if ($key == 'scopes_supported') {
                $issuer->set('scopessupported', implode(' ', $value));
                $issuer->update();
            }
        }

        // We got to here - must be a decent OpenID connect service. Add the default user field mapping list.
        foreach (user_field_mapping::get_records(['issuerid' => $issuer->get('id')]) as $userfieldmapping) {
            $userfieldmapping->delete();
        }

        // Create the field mappings.
        $mapping = [
            'given_name' => 'firstname',
            'middle_name' => 'middlename',
            'family_name' => 'lastname',
            'email' => 'email',
            'website' => 'url',
            'nickname' => 'alternatename',
            'picture' => 'picture',
            'address' => 'address',
            'phone' => 'phone1',
            'locale' => 'lang'
        ];
        foreach ($mapping as $external => $internal) {
            $record = (object) [
                'issuerid' => $issuer->get('id'),
                'externalfield' => $external,
                'internalfield' => $internal
            ];
            $userfieldmapping = new user_field_mapping(0, $record);
            $userfieldmapping->create();
        }

        return endpoint::count_records(['issuerid' => $issuer->get('id')]);
    }