]> git.mxchange.org Git - friendica.git/blob - library/openid.php
update of fullcalender to v1.6.4
[friendica.git] / library / openid.php
1 <?php
2 /**
3  * This class provides a simple interface for OpenID (1.1 and 2.0) authentication.
4  * Supports Yadis discovery.
5  * The authentication process is stateless/dumb.
6  *
7  * Usage:
8  * Sign-on with OpenID is a two step process:
9  * Step one is authentication with the provider:
10  * <code>
11  * $openid = new LightOpenID;
12  * $openid->identity = 'ID supplied by user';
13  * header('Location: ' . $openid->authUrl());
14  * </code>
15  * The provider then sends various parameters via GET, one of them is openid_mode.
16  * Step two is verification:
17  * <code>
18  * if ($this->data['openid_mode']) {
19  *     $openid = new LightOpenID;
20  *     echo $openid->validate() ? 'Logged in.' : 'Failed';
21  * }
22  * </code>
23  *
24  * Optionally, you can set $returnUrl and $realm (or $trustRoot, which is an alias).
25  * The default values for those are:
26  * $openid->realm     = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
27  * $openid->returnUrl = $openid->realm . $_SERVER['REQUEST_URI']; # without the query part, if present
28  * If you don't know their meaning, refer to any openid tutorial, or specification. Or just guess.
29  *
30  * AX and SREG extensions are supported.
31  * To use them, specify $openid->required and/or $openid->optional before calling $openid->authUrl().
32  * These are arrays, with values being AX schema paths (the 'path' part of the URL).
33  * For example:
34  *   $openid->required = array('namePerson/friendly', 'contact/email');
35  *   $openid->optional = array('namePerson/first');
36  * If the server supports only SREG or OpenID 1.1, these are automaticaly
37  * mapped to SREG names, so that user doesn't have to know anything about the server.
38  *
39  * To get the values, use $openid->getAttributes().
40  *
41  *
42  * The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled..
43  * @author Mewp
44  * @copyright Copyright (c) 2010, Mewp
45  * @license http://www.opensource.org/licenses/mit-license.php MIT
46  */
47 class LightOpenID
48 {
49     public $returnUrl
50          , $required = array()
51          , $optional = array()
52          , $verify_perr = null
53          , $capath = null;
54     private $identity, $claimed_id;
55     protected $server, $version, $trustRoot, $aliases, $identifier_select = false
56             , $ax = false, $sreg = false, $data;
57     static protected $ax_to_sreg = array(
58         'namePerson/friendly'     => 'nickname',
59         'contact/email'           => 'email',
60         'namePerson'              => 'fullname',
61         'birthDate'               => 'dob',
62         'person/gender'           => 'gender',
63         'contact/postalCode/home' => 'postcode',
64         'contact/country/home'    => 'country',
65         'pref/language'           => 'language',
66         'pref/timezone'           => 'timezone',
67         );
68
69     function __construct()
70     {
71         $this->trustRoot = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
72         $uri = $_SERVER['REQUEST_URI'];
73         $uri = strpos($uri, '?') ? substr($uri, 0, strpos($uri, '?')) : $uri;
74         $this->returnUrl = $this->trustRoot . $uri;
75
76         $this->data = $_POST + $_GET; # OPs may send data as POST or GET.
77     }
78
79     function __set($name, $value)
80     {
81         switch ($name) {
82         case 'identity':
83             if (strlen($value = trim((String) $value))) {
84                 if (preg_match('#^xri:/*#i', $value, $m)) {
85                     $value = substr($value, strlen($m[0]));
86                 } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
87                     $value = "http://$value";
88                 }
89                 if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
90                     $value .= '/';
91                 }
92             }
93             $this->$name = $this->claimed_id = $value;
94             break;
95         case 'trustRoot':
96         case 'realm':
97             $this->trustRoot = trim($value);
98         }
99     }
100
101     function __get($name)
102     {
103         switch ($name) {
104         case 'identity':
105             # We return claimed_id instead of identity,
106             # because the developer should see the claimed identifier,
107             # i.e. what he set as identity, not the op-local identifier (which is what we verify)
108             return $this->claimed_id;
109         case 'trustRoot':
110         case 'realm':
111             return $this->trustRoot;
112         }
113     }
114
115     /**
116      * Checks if the server specified in the url exists.
117      *
118      * @param $url url to check
119      * @return true, if the server exists; false otherwise
120      */
121     function hostExists($url)
122     {
123         if (strpos($url, '/') === false) {
124             $server = $url;
125         } else {
126             $server = @parse_url($url, PHP_URL_HOST);
127         }
128
129         if (!$server) {
130             return false;
131         }
132
133         return !!gethostbynamel($server);
134     }
135
136     protected function request_curl($url, $method='GET', $params=array())
137     {
138         $params = http_build_query($params, '', '&');
139         $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
140         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
141         curl_setopt($curl, CURLOPT_HEADER, false);
142         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
143         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
144         curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
145
146         if($this->verify_perr !== null) {
147             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
148             if($this->capath) {
149                 curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
150             }
151         }
152
153         if ($method == 'POST') {
154             curl_setopt($curl, CURLOPT_POST, true);
155             curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
156         } elseif ($method == 'HEAD') {
157             curl_setopt($curl, CURLOPT_HEADER, true);
158             curl_setopt($curl, CURLOPT_NOBODY, true);
159         } else {
160             curl_setopt($curl, CURLOPT_HTTPGET, true);
161         }
162         $response = curl_exec($curl);
163
164         if($method == 'HEAD') {
165             $headers = array();
166             foreach(explode("\n", $response) as $header) {
167                 $pos = strpos($header,':');
168                 $name = strtolower(trim(substr($header, 0, $pos)));
169                 $headers[$name] = trim(substr($header, $pos+1));
170             }
171
172             # Updating claimed_id in case of redirections.
173             $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
174             if($effective_url != $url) {
175                 $this->identity = $this->claimed_id = $effective_url;
176             }
177
178             return $headers;
179         }
180
181         if (curl_errno($curl)) {
182             throw new ErrorException(curl_error($curl), curl_errno($curl));
183         }
184
185         return $response;
186     }
187
188     protected function request_streams($url, $method='GET', $params=array())
189     {
190         if(!$this->hostExists($url)) {
191             throw new ErrorException('Invalid request.');
192         }
193
194         $params = http_build_query($params, '', '&');
195         switch($method) {
196         case 'GET':
197             $opts = array(
198                 'http' => array(
199                     'method' => 'GET',
200                     'header' => 'Accept: application/xrds+xml, */*',
201                     'ignore_errors' => true,
202                 )
203             );
204             $url = $url . ($params ? '?' . $params : '');
205             break;
206         case 'POST':
207             $opts = array(
208                 'http' => array(
209                     'method' => 'POST',
210                     'header'  => 'Content-type: application/x-www-form-urlencoded',
211                     'content' => $params,
212                     'ignore_errors' => true,
213                 )
214             );
215             break;
216         case 'HEAD':
217             # We want to send a HEAD request,
218             # but since get_headers doesn't accept $context parameter,
219             # we have to change the defaults.
220             $default = stream_context_get_options(stream_context_get_default());
221             stream_context_get_default(
222                 array('http' => array(
223                     'method' => 'HEAD',
224                     'header' => 'Accept: application/xrds+xml, */*',
225                     'ignore_errors' => true,
226                 ))
227             );
228
229             $url = $url . ($params ? '?' . $params : '');
230             $headers_tmp = get_headers ($url);
231             if(!$headers_tmp) {
232                 return array();
233             }
234
235             # Parsing headers.
236             $headers = array();
237             foreach($headers_tmp as $header) {
238                 $pos = strpos($header,':');
239                 $name = strtolower(trim(substr($header, 0, $pos)));
240                 $headers[$name] = trim(substr($header, $pos+1));
241
242                 # Following possible redirections. The point is just to have
243                 # claimed_id change with them, because get_headers() will
244                 # follow redirections automatically.
245                 # We ignore redirections with relative paths.
246                 # If any known provider uses them, file a bug report.
247                 if($name == 'location') {
248                     if(strpos($headers[$name], 'http') === 0) {
249                         $this->identity = $this->claimed_id = $headers[$name];
250                     } elseif($headers[$name][0] == '/') {
251                         $parsed_url = parse_url($this->claimed_id);
252                         $this->identity =
253                         $this->claimed_id = $parsed_url['scheme'] . '://'
254                                           . $parsed_url['host']
255                                           . $headers[$name];
256                     }
257                 }
258             }
259
260             # And restore them.
261             stream_context_get_default($default);
262             return $headers;
263         }
264
265         if($this->verify_peer) {
266             $opts += array('ssl' => array(
267                 'verify_peer' => true,
268                 'capath'      => $this->capath,
269             ));
270         }
271
272         $context = stream_context_create ($opts);
273
274         return file_get_contents($url, false, $context);
275     }
276
277     protected function request($url, $method='GET', $params=array())
278     {
279         if(function_exists('curl_init') && !ini_get('safe_mode') && (! strlen(ini_get('open_basedir')))) {
280             return $this->request_curl($url, $method, $params);
281         }
282         return $this->request_streams($url, $method, $params);
283     }
284
285     protected function build_url($url, $parts)
286     {
287         if (isset($url['query'], $parts['query'])) {
288             $parts['query'] = $url['query'] . '&' . $parts['query'];
289         }
290
291         $url = $parts + $url;
292         $url = $url['scheme'] . '://'
293              . (empty($url['username'])?''
294                  :(empty($url['password'])? "{$url['username']}@"
295                  :"{$url['username']}:{$url['password']}@"))
296              . $url['host']
297              . (empty($url['port'])?'':":{$url['port']}")
298              . (empty($url['path'])?'':$url['path'])
299              . (empty($url['query'])?'':"?{$url['query']}")
300              . (empty($url['fragment'])?'':":{$url['fragment']}");
301         return $url;
302     }
303
304     /**
305      * Helper function used to scan for <meta>/<link> tags and extract information
306      * from them
307      */
308     protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
309     {
310         preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
311         preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
312
313         $result = array_merge($matches1[1], $matches2[1]);
314         return empty($result)?false:$result[0];
315     }
316
317     /**
318      * Performs Yadis and HTML discovery. Normally not used.
319      * @param $url Identity URL.
320      * @return String OP Endpoint (i.e. OpenID provider address).
321      * @throws ErrorException
322      */
323     function discover($url)
324     {
325         if (!$url) throw new ErrorException('No identity supplied.');
326         # Use xri.net proxy to resolve i-name identities
327         if (!preg_match('#^https?:#', $url)) {
328             $url = "https://xri.net/$url";
329         }
330
331         # We save the original url in case of Yadis discovery failure.
332         # It can happen when we'll be lead to an XRDS document
333         # which does not have any OpenID2 services.
334         $originalUrl = $url;
335
336         # A flag to disable yadis discovery in case of failure in headers.
337         $yadis = true;
338
339         # We'll jump a maximum of 5 times, to avoid endless redirections.
340         for ($i = 0; $i < 5; $i ++) {
341             if ($yadis) {
342                 $headers = $this->request($url, 'HEAD');
343
344                 $next = false;
345                     if (isset($headers['x-xrds-location'])) {
346                         $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
347                         $next = true;
348                     }
349
350                     if (isset($headers['content-type'])
351                         && ((strpos($headers['content-type'], 'application/xrds+xml') !== false
352                     ) || (strpos($headers['content-type'], 'text/xml') !== false))) {
353                         # Found an XRDS document, now let's find the server, and optionally delegate.
354                         $content = $this->request($url, 'GET');
355
356                         preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
357                         foreach($m[1] as $content) {
358                             $content = ' ' . $content; # The space is added, so that strpos doesn't return 0.
359
360                             # OpenID 2
361                             $ns = preg_quote('http://specs.openid.net/auth/2.0/');
362                             if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
363                                 if ($type[1] == 'server') $this->identifier_select = true;
364
365                                 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
366                                 preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
367                                 if (empty($server)) {
368                                     return false;
369                                 }
370                                 # Does the server advertise support for either AX or SREG?
371                                 $this->ax   = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
372                                 $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
373                                            || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
374
375                                 $server = $server[1];
376                                 if (isset($delegate[2])) $this->identity = trim($delegate[2]);
377                                 $this->version = 2;
378 logger('Server: ' . $server);
379                                 $this->server = $server;
380                                 return $server;
381                             }
382
383                             # OpenID 1.1
384                             $ns = preg_quote('http://openid.net/signon/1.1');
385                             if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
386
387                                 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
388                                 preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
389                                 if (empty($server)) {
390                                     return false;
391                                 }
392                                 # AX can be used only with OpenID 2.0, so checking only SREG
393                                 $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
394                                            || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
395
396                                 $server = $server[1];
397                                 if (isset($delegate[1])) $this->identity = $delegate[1];
398                                 $this->version = 1;
399
400                                 $this->server = $server;
401                                 return $server;
402                             }
403                         }
404
405                         $next = true;
406                         $yadis = false;
407                         $url = $originalUrl;
408                         $content = null;
409                         break;
410                     }
411                 if ($next) continue;
412
413                 # There are no relevant information in headers, so we search the body.
414                 $content = $this->request($url, 'GET');
415                 if ($location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content')) {
416                     $url = $this->build_url(parse_url($url), parse_url($location));
417                     continue;
418                 }
419             }
420
421             if (!$content) $content = $this->request($url, 'GET');
422 logger('openid' . $content);
423             # At this point, the YADIS Discovery has failed, so we'll switch
424             # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
425             $server   = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
426             $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
427             $this->version = 2;
428
429             if (!$server) {
430                 # The same with openid 1.1
431                 $server   = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
432                 $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
433                 $this->version = 1;
434             }
435
436             if ($server) {
437                 # We found an OpenID2 OP Endpoint
438                 if ($delegate) {
439                     # We have also found an OP-Local ID.
440                     $this->identity = $delegate;
441                 }
442                 $this->server = $server;
443                 return $server;
444             }
445
446             throw new ErrorException('No servers found!');
447         }
448         throw new ErrorException('Endless redirection!');
449     }
450
451     protected function sregParams()
452     {
453         $params = array();
454         # We always use SREG 1.1, even if the server is advertising only support for 1.0.
455         # That's because it's fully backwards compatibile with 1.0, and some providers
456         # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
457         $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
458         if ($this->required) {
459             $params['openid.sreg.required'] = array();
460             foreach ($this->required as $required) {
461                 if (!isset(self::$ax_to_sreg[$required])) continue;
462                 $params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
463             }
464             $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
465         }
466
467         if ($this->optional) {
468             $params['openid.sreg.optional'] = array();
469             foreach ($this->optional as $optional) {
470                 if (!isset(self::$ax_to_sreg[$optional])) continue;
471                 $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
472             }
473             $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
474         }
475         return $params;
476     }
477
478     protected function axParams()
479     {
480         $params = array();
481         if ($this->required || $this->optional) {
482             $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
483             $params['openid.ax.mode'] = 'fetch_request';
484             $this->aliases  = array();
485             $counts   = array();
486             $required = array();
487             $optional = array();
488             foreach (array('required','optional') as $type) {
489                 foreach ($this->$type as $alias => $field) {
490                     if (is_int($alias)) $alias = strtr($field, '/', '_');
491                     $this->aliases[$alias] = 'http://axschema.org/' . $field;
492                     if (empty($counts[$alias])) $counts[$alias] = 0;
493                     $counts[$alias] += 1;
494                     ${$type}[] = $alias;
495                 }
496             }
497             foreach ($this->aliases as $alias => $ns) {
498                 $params['openid.ax.type.' . $alias] = $ns;
499             }
500             foreach ($counts as $alias => $count) {
501                 if ($count == 1) continue;
502                 $params['openid.ax.count.' . $alias] = $count;
503             }
504
505             # Don't send empty ax.requied and ax.if_available.
506             # Google and possibly other providers refuse to support ax when one of these is empty.
507             if($required) {
508                 $params['openid.ax.required'] = implode(',', $required);
509             }
510             if($optional) {
511                 $params['openid.ax.if_available'] = implode(',', $optional);
512             }
513         }
514         return $params;
515     }
516
517     protected function authUrl_v1()
518     {
519         $returnUrl = $this->returnUrl;
520         # If we have an openid.delegate that is different from our claimed id,
521         # we need to somehow preserve the claimed id between requests.
522         # The simplest way is to just send it along with the return_to url.
523         if($this->identity != $this->claimed_id) {
524             $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
525         }
526
527         $params = array(
528             'openid.return_to'  => $returnUrl,
529             'openid.mode'       => 'checkid_setup',
530             'openid.identity'   => $this->identity,
531             'openid.trust_root' => $this->trustRoot,
532             ) + $this->sregParams();
533
534         return $this->build_url(parse_url($this->server)
535                                , array('query' => http_build_query($params, '', '&')));
536     }
537
538     protected function authUrl_v2($identifier_select)
539     {
540         $params = array(
541             'openid.ns'          => 'http://specs.openid.net/auth/2.0',
542             'openid.mode'        => 'checkid_setup',
543             'openid.return_to'   => $this->returnUrl,
544             'openid.realm'       => $this->trustRoot,
545         );
546         if ($this->ax) {
547             $params += $this->axParams();
548         }
549         if ($this->sreg) {
550             $params += $this->sregParams();
551         }
552         if (!$this->ax && !$this->sreg) {
553             # If OP doesn't advertise either SREG, nor AX, let's send them both
554             # in worst case we don't get anything in return.
555             $params += $this->axParams() + $this->sregParams();
556         }
557
558         if ($identifier_select) {
559             $params['openid.identity'] = $params['openid.claimed_id']
560                  = 'http://specs.openid.net/auth/2.0/identifier_select';
561         } else {
562             $params['openid.identity'] = $this->identity;
563             $params['openid.claimed_id'] = $this->claimed_id;
564         }
565
566         return $this->build_url(parse_url($this->server)
567                                , array('query' => http_build_query($params, '', '&')));
568     }
569
570     /**
571      * Returns authentication url. Usually, you want to redirect your user to it.
572      * @return String The authentication url.
573      * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1.
574      * @throws ErrorException
575      */
576     function authUrl($identifier_select = null)
577     {
578         if (!$this->server) $this->discover($this->identity);
579
580         if ($this->version == 2) {
581             if ($identifier_select === null) {
582                 return $this->authUrl_v2($this->identifier_select);
583             }
584             return $this->authUrl_v2($identifier_select);
585         }
586         return $this->authUrl_v1();
587     }
588
589     /**
590      * Performs OpenID verification with the OP.
591      * @return Bool Whether the verification was successful.
592      * @throws ErrorException
593      */
594     function validate()
595     {
596         $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
597         $params = array(
598             'openid.assoc_handle' => $this->data['openid_assoc_handle'],
599             'openid.signed'       => $this->data['openid_signed'],
600             'openid.sig'          => $this->data['openid_sig'],
601             );
602
603         if (isset($this->data['openid_ns'])) {
604             # We're dealing with an OpenID 2.0 server, so let's set an ns
605             # Even though we should know location of the endpoint,
606             # we still need to verify it by discovery, so $server is not set here
607             $params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
608         } elseif(isset($this->data['openid_claimed_id'])) {
609             # If it's an OpenID 1 provider, and we've got claimed_id,
610             # we have to append it to the returnUrl, like authUrl_v1 does.
611             $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
612                              .  'openid.claimed_id=' . $this->claimed_id;
613         }
614
615         if ($this->data['openid_return_to'] != $this->returnUrl) {
616             # The return_to url must match the url of current request.
617             # I'm assuing that noone will set the returnUrl to something that doesn't make sense.
618             return false;
619         }
620
621         $server = $this->discover($this->claimed_id);
622
623         foreach (explode(',', $this->data['openid_signed']) as $item) {
624             # Checking whether magic_quotes_gpc is turned on, because
625             # the function may fail if it is. For example, when fetching
626             # AX namePerson, it might containg an apostrophe, which will be escaped.
627             # In such case, validation would fail, since we'd send different data than OP
628             # wants to verify. stripslashes() should solve that problem, but we can't
629             # use it when magic_quotes is off.
630             $value = $this->data['openid_' . str_replace('.','_',$item)];
631             $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value;
632
633         }
634
635         $params['openid.mode'] = 'check_authentication';
636
637         $response = $this->request($server, 'POST', $params);
638
639         return preg_match('/is_valid\s*:\s*true/i', $response);
640     }
641
642     protected function getAxAttributes()
643     {
644         $alias = null;
645         if (isset($this->data['openid_ns_ax'])
646             && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0'
647         ) { # It's the most likely case, so we'll check it before
648             $alias = 'ax';
649         } else {
650             # 'ax' prefix is either undefined, or points to another extension,
651             # so we search for another prefix
652             foreach ($this->data as $key => $val) {
653                 if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_'
654                     && $val == 'http://openid.net/srv/ax/1.0'
655                 ) {
656                     $alias = substr($key, strlen('openid_ns_'));
657                     break;
658                 }
659             }
660         }
661         if (!$alias) {
662             # An alias for AX schema has not been found,
663             # so there is no AX data in the OP's response
664             return array();
665         }
666
667         $attributes = array();
668         foreach ($this->data as $key => $value) {
669             $keyMatch = 'openid_' . $alias . '_value_';
670             if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
671                 continue;
672             }
673             $key = substr($key, strlen($keyMatch));
674             if (!isset($this->data['openid_' . $alias . '_type_' . $key])) {
675                 # OP is breaking the spec by returning a field without
676                 # associated ns. This shouldn't happen, but it's better
677                 # to check, than cause an E_NOTICE.
678                 continue;
679             }
680             $key = substr($this->data['openid_' . $alias . '_type_' . $key],
681                           strlen('http://axschema.org/'));
682             $attributes[$key] = $value;
683         }
684         return $attributes;
685     }
686
687     protected function getSregAttributes()
688     {
689         $attributes = array();
690         $sreg_to_ax = array_flip(self::$ax_to_sreg);
691         foreach ($this->data as $key => $value) {
692             $keyMatch = 'openid_sreg_';
693             if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
694                 continue;
695             }
696             $key = substr($key, strlen($keyMatch));
697             if (!isset($sreg_to_ax[$key])) {
698                 # The field name isn't part of the SREG spec, so we ignore it.
699                 continue;
700             }
701             $attributes[$sreg_to_ax[$key]] = $value;
702         }
703         return $attributes;
704     }
705
706     /**
707      * Gets AX/SREG attributes provided by OP. should be used only after successful validaton.
708      * Note that it does not guarantee that any of the required/optional parameters will be present,
709      * or that there will be no other attributes besides those specified.
710      * In other words. OP may provide whatever information it wants to.
711      *     * SREG names will be mapped to AX names.
712      *     * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email'
713      * @see http://www.axschema.org/types/
714      */
715     function getAttributes()
716     {
717         if (isset($this->data['openid_ns'])
718             && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
719         ) { # OpenID 2.0
720             # We search for both AX and SREG attributes, with AX taking precedence.
721             return $this->getAxAttributes() + $this->getSregAttributes();
722         }
723         return $this->getSregAttributes();
724     }
725 }