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.
8 * Sign-on with OpenID is a two step process:
9 * Step one is authentication with the provider:
11 * $openid = new LightOpenID;
12 * $openid->identity = 'ID supplied by user';
13 * header('Location: ' . $openid->authUrl());
15 * The provider then sends various parameters via GET, one of them is openid_mode.
16 * Step two is verification:
18 * if ($this->data['openid_mode']) {
19 * $openid = new LightOpenID;
20 * echo $openid->validate() ? 'Logged in.' : 'Failed';
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.
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).
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.
39 * To get the values, use $openid->getAttributes().
42 * The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled..
44 * @copyright Copyright (c) 2010, Mewp
45 * @license http://www.opensource.org/licenses/mit-license.php MIT
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',
62 'person/gender' => 'gender',
63 'contact/postalCode/home' => 'postcode',
64 'contact/country/home' => 'country',
65 'pref/language' => 'language',
66 'pref/timezone' => 'timezone',
69 function __construct()
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;
76 $this->data = $_POST + $_GET; # OPs may send data as POST or GET.
79 function __set($name, $value)
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";
89 if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
93 $this->$name = $this->claimed_id = $value;
97 $this->trustRoot = trim($value);
101 function __get($name)
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;
111 return $this->trustRoot;
116 * Checks if the server specified in the url exists.
118 * @param $url url to check
119 * @return true, if the server exists; false otherwise
121 function hostExists($url)
123 if (strpos($url, '/') === false) {
126 $server = @parse_url($url, PHP_URL_HOST);
133 return !!gethostbynamel($server);
136 protected function request_curl($url, $method='GET', $params=array())
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, */*'));
146 if($this->verify_perr !== null) {
147 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
149 curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
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);
160 curl_setopt($curl, CURLOPT_HTTPGET, true);
162 $response = curl_exec($curl);
164 if($method == 'HEAD') {
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));
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;
181 if (curl_errno($curl)) {
182 throw new ErrorException(curl_error($curl), curl_errno($curl));
188 protected function request_streams($url, $method='GET', $params=array())
190 if(!$this->hostExists($url)) {
191 throw new ErrorException('Invalid request.');
194 $params = http_build_query($params, '', '&');
200 'header' => 'Accept: application/xrds+xml, */*',
201 'ignore_errors' => true,
204 $url = $url . ($params ? '?' . $params : '');
210 'header' => 'Content-type: application/x-www-form-urlencoded',
211 'content' => $params,
212 'ignore_errors' => true,
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(
224 'header' => 'Accept: application/xrds+xml, */*',
225 'ignore_errors' => true,
229 $url = $url . ($params ? '?' . $params : '');
230 $headers_tmp = get_headers ($url);
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));
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);
253 $this->claimed_id = $parsed_url['scheme'] . '://'
254 . $parsed_url['host']
261 stream_context_get_default($default);
265 if($this->verify_peer) {
266 $opts += array('ssl' => array(
267 'verify_peer' => true,
268 'capath' => $this->capath,
272 $context = stream_context_create ($opts);
274 return file_get_contents($url, false, $context);
277 protected function request($url, $method='GET', $params=array())
279 if(function_exists('curl_init') && !ini_get('safe_mode') && (! strlen(ini_get('open_basedir')))) {
280 return $this->request_curl($url, $method, $params);
282 return $this->request_streams($url, $method, $params);
285 protected function build_url($url, $parts)
287 if (isset($url['query'], $parts['query'])) {
288 $parts['query'] = $url['query'] . '&' . $parts['query'];
291 $url = $parts + $url;
292 $url = $url['scheme'] . '://'
293 . (empty($url['username'])?''
294 :(empty($url['password'])? "{$url['username']}@"
295 :"{$url['username']}:{$url['password']}@"))
297 . (empty($url['port'])?'':":{$url['port']}")
298 . (empty($url['path'])?'':$url['path'])
299 . (empty($url['query'])?'':"?{$url['query']}")
300 . (empty($url['fragment'])?'':":{$url['fragment']}");
305 * Helper function used to scan for <meta>/<link> tags and extract information
308 protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
310 preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
311 preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
313 $result = array_merge($matches1[1], $matches2[1]);
314 return empty($result)?false:$result[0];
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
323 function discover($url)
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";
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.
336 # A flag to disable yadis discovery in case of failure in headers.
339 # We'll jump a maximum of 5 times, to avoid endless redirections.
340 for ($i = 0; $i < 5; $i ++) {
342 $headers = $this->request($url, 'HEAD');
345 if (isset($headers['x-xrds-location'])) {
346 $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
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');
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.
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;
365 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
366 preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
367 if (empty($server)) {
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>');
375 $server = $server[1];
376 if (isset($delegate[2])) $this->identity = trim($delegate[2]);
378 #logger('Server: ' . $server);
379 $this->server = $server;
384 $ns = preg_quote('http://openid.net/signon/1.1');
385 if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
387 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
388 preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
389 if (empty($server)) {
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>');
396 $server = $server[1];
397 if (isset($delegate[1])) $this->identity = $delegate[1];
400 $this->server = $server;
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));
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');
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');
437 # We found an OpenID2 OP Endpoint
439 # We have also found an OP-Local ID.
440 $this->identity = $delegate;
442 $this->server = $server;
446 throw new ErrorException('No servers found!');
448 throw new ErrorException('Endless redirection!');
451 protected function sregParams()
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];
464 $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
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];
473 $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
478 protected function axParams()
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();
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;
497 foreach ($this->aliases as $alias => $ns) {
498 $params['openid.ax.type.' . $alias] = $ns;
500 foreach ($counts as $alias => $count) {
501 if ($count == 1) continue;
502 $params['openid.ax.count.' . $alias] = $count;
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.
508 $params['openid.ax.required'] = implode(',', $required);
511 $params['openid.ax.if_available'] = implode(',', $optional);
517 protected function authUrl_v1()
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;
528 'openid.return_to' => $returnUrl,
529 'openid.mode' => 'checkid_setup',
530 'openid.identity' => $this->identity,
531 'openid.trust_root' => $this->trustRoot,
532 ) + $this->sregParams();
534 return $this->build_url(parse_url($this->server)
535 , array('query' => http_build_query($params, '', '&')));
538 protected function authUrl_v2($identifier_select)
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,
547 $params += $this->axParams();
550 $params += $this->sregParams();
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();
558 if ($identifier_select) {
559 $params['openid.identity'] = $params['openid.claimed_id']
560 = 'http://specs.openid.net/auth/2.0/identifier_select';
562 $params['openid.identity'] = $this->identity;
563 $params['openid.claimed_id'] = $this->claimed_id;
566 return $this->build_url(parse_url($this->server)
567 , array('query' => http_build_query($params, '', '&')));
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
576 function authUrl($identifier_select = null)
578 if (!$this->server) $this->discover($this->identity);
580 if ($this->version == 2) {
581 if ($identifier_select === null) {
582 return $this->authUrl_v2($this->identifier_select);
584 return $this->authUrl_v2($identifier_select);
586 return $this->authUrl_v1();
590 * Performs OpenID verification with the OP.
591 * @return Bool Whether the verification was successful.
592 * @throws ErrorException
596 $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
598 'openid.assoc_handle' => $this->data['openid_assoc_handle'],
599 'openid.signed' => $this->data['openid_signed'],
600 'openid.sig' => $this->data['openid_sig'],
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;
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.
621 $server = $this->discover($this->claimed_id);
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;
635 $params['openid.mode'] = 'check_authentication';
637 $response = $this->request($server, 'POST', $params);
639 return preg_match('/is_valid\s*:\s*true/i', $response);
642 protected function getAxAttributes()
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
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'
656 $alias = substr($key, strlen('openid_ns_'));
662 # An alias for AX schema has not been found,
663 # so there is no AX data in the OP's response
667 $attributes = array();
668 foreach ($this->data as $key => $value) {
669 $keyMatch = 'openid_' . $alias . '_value_';
670 if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
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.
680 $key = substr($this->data['openid_' . $alias . '_type_' . $key],
681 strlen('http://axschema.org/'));
682 $attributes[$key] = $value;
687 protected function getSregAttributes()
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) {
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.
701 $attributes[$sreg_to_ax[$key]] = $value;
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/
715 function getAttributes()
717 if (isset($this->data['openid_ns'])
718 && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
720 # We search for both AX and SREG attributes, with AX taking precedence.
721 return $this->getAxAttributes() + $this->getSregAttributes();
723 return $this->getSregAttributes();