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'];
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
55 private $identity, $claimed_id;
56 protected $server, $version, $trustRoot, $aliases, $identifier_select = false
57 , $ax = false, $sreg = false, $data;
58 static protected $ax_to_sreg = array(
59 'namePerson/friendly' => 'nickname',
60 'contact/email' => 'email',
61 'namePerson' => 'fullname',
63 'person/gender' => 'gender',
64 'contact/postalCode/home' => 'postcode',
65 'contact/country/home' => 'country',
66 'pref/language' => 'language',
67 'pref/timezone' => 'timezone',
70 function __construct()
72 $this->trustRoot = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
73 $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
74 $this->returnUrl = $this->trustRoot . $uri;
76 $this->data = $_POST + $_GET; # OPs may send data as POST or GET.
78 if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) {
79 throw new ErrorException('You must have either https wrappers or curl enabled.');
83 function __set($name, $value)
87 if (strlen($value = trim((String) $value))) {
88 if (preg_match('#^xri:/*#i', $value, $m)) {
89 $value = substr($value, strlen($m[0]));
90 } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
91 $value = "http://$value";
93 if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
97 $this->$name = $this->claimed_id = $value;
101 $this->trustRoot = trim($value);
105 function __get($name)
109 # We return claimed_id instead of identity,
110 # because the developer should see the claimed identifier,
111 # i.e. what he set as identity, not the op-local identifier (which is what we verify)
112 return $this->claimed_id;
115 return $this->trustRoot;
117 return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
122 * Checks if the server specified in the url exists.
124 * @param $url url to check
125 * @return true, if the server exists; false otherwise
127 function hostExists($url)
129 if (strpos($url, '/') === false) {
132 $server = @parse_url($url, PHP_URL_HOST);
139 return !!gethostbynamel($server);
142 protected function request_curl($url, $method='GET', $params=array())
144 $params = http_build_query($params, '', '&');
145 $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
146 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
147 curl_setopt($curl, CURLOPT_HEADER, false);
148 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
149 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
150 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
152 if($this->verify_peer !== null) {
153 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
155 curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
159 curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
163 if ($method == 'POST') {
164 curl_setopt($curl, CURLOPT_POST, true);
165 curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
166 } elseif ($method == 'HEAD') {
167 curl_setopt($curl, CURLOPT_HEADER, true);
168 curl_setopt($curl, CURLOPT_NOBODY, true);
170 curl_setopt($curl, CURLOPT_HTTPGET, true);
172 $response = curl_exec($curl);
174 if($method == 'HEAD') {
176 foreach(explode("\n", $response) as $header) {
177 $pos = strpos($header,':');
178 $name = strtolower(trim(substr($header, 0, $pos)));
179 $headers[$name] = trim(substr($header, $pos+1));
182 # Updating claimed_id in case of redirections.
183 $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
184 if($effective_url != $url) {
185 $this->identity = $this->claimed_id = $effective_url;
191 if (curl_errno($curl)) {
192 throw new ErrorException(curl_error($curl), curl_errno($curl));
198 protected function request_streams($url, $method='GET', $params=array())
200 if(!$this->hostExists($url)) {
201 throw new ErrorException('Invalid request.');
204 $params = http_build_query($params, '', '&');
210 'header' => 'Accept: application/xrds+xml, */*',
211 'ignore_errors' => true,
214 $url = $url . ($params ? '?' . $params : '');
220 'header' => 'Content-type: application/x-www-form-urlencoded',
221 'content' => $params,
222 'ignore_errors' => true,
227 # We want to send a HEAD request,
228 # but since get_headers doesn't accept $context parameter,
229 # we have to change the defaults.
230 $default = stream_context_get_options(stream_context_get_default());
231 stream_context_get_default(
232 array('http' => array(
234 'header' => 'Accept: application/xrds+xml, */*',
235 'ignore_errors' => true,
239 $url = $url . ($params ? '?' . $params : '');
240 $headers_tmp = get_headers ($url);
247 foreach($headers_tmp as $header) {
248 $pos = strpos($header,':');
249 $name = strtolower(trim(substr($header, 0, $pos)));
250 $headers[$name] = trim(substr($header, $pos+1));
252 # Following possible redirections. The point is just to have
253 # claimed_id change with them, because get_headers() will
254 # follow redirections automatically.
255 # We ignore redirections with relative paths.
256 # If any known provider uses them, file a bug report.
257 if($name == 'location') {
258 if(strpos($headers[$name], 'http') === 0) {
259 $this->identity = $this->claimed_id = $headers[$name];
260 } elseif($headers[$name][0] == '/') {
261 $parsed_url = parse_url($this->claimed_id);
263 $this->claimed_id = $parsed_url['scheme'] . '://'
264 . $parsed_url['host']
271 stream_context_get_default($default);
275 if($this->verify_peer) {
276 $opts += array('ssl' => array(
277 'verify_peer' => true,
278 'capath' => $this->capath,
279 'cafile' => $this->cainfo,
283 $context = stream_context_create ($opts);
285 return file_get_contents($url, false, $context);
288 protected function request($url, $method='GET', $params=array())
290 if(function_exists('curl_init') && !ini_get('safe_mode') && !ini_get('open_basedir')) {
291 return $this->request_curl($url, $method, $params);
293 return $this->request_streams($url, $method, $params);
296 protected function build_url($url, $parts)
298 if (isset($url['query'], $parts['query'])) {
299 $parts['query'] = $url['query'] . '&' . $parts['query'];
302 $url = $parts + $url;
303 $url = $url['scheme'] . '://'
304 . (empty($url['username'])?''
305 :(empty($url['password'])? "{$url['username']}@"
306 :"{$url['username']}:{$url['password']}@"))
308 . (empty($url['port'])?'':":{$url['port']}")
309 . (empty($url['path'])?'':$url['path'])
310 . (empty($url['query'])?'':"?{$url['query']}")
311 . (empty($url['fragment'])?'':"#{$url['fragment']}");
316 * Helper function used to scan for <meta>/<link> tags and extract information
319 protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
321 preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
322 preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
324 $result = array_merge($matches1[1], $matches2[1]);
325 return empty($result)?false:$result[0];
329 * Performs Yadis and HTML discovery. Normally not used.
330 * @param $url Identity URL.
331 * @return String OP Endpoint (i.e. OpenID provider address).
332 * @throws ErrorException
334 function discover($url)
336 if (!$url) throw new ErrorException('No identity supplied.');
337 # Use xri.net proxy to resolve i-name identities
338 if (!preg_match('#^https?:#', $url)) {
339 $url = "https://xri.net/$url";
342 # We save the original url in case of Yadis discovery failure.
343 # It can happen when we'll be lead to an XRDS document
344 # which does not have any OpenID2 services.
347 # A flag to disable yadis discovery in case of failure in headers.
350 # We'll jump a maximum of 5 times, to avoid endless redirections.
351 for ($i = 0; $i < 5; $i ++) {
353 $headers = $this->request($url, 'HEAD');
356 if (isset($headers['x-xrds-location'])) {
357 $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
361 if (isset($headers['content-type'])
362 && (strpos($headers['content-type'], 'application/xrds+xml') !== false
363 || strpos($headers['content-type'], 'text/xml') !== false)
365 # Apparently, some providers return XRDS documents as text/html.
366 # While it is against the spec, allowing this here shouldn't break
367 # compatibility with anything.
369 # Found an XRDS document, now let's find the server, and optionally delegate.
370 $content = $this->request($url, 'GET');
372 preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
373 foreach($m[1] as $content) {
374 $content = ' ' . $content; # The space is added, so that strpos doesn't return 0.
377 $ns = preg_quote('http://specs.openid.net/auth/2.0/');
378 if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
379 if ($type[1] == 'server') $this->identifier_select = true;
381 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
382 preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
383 if (empty($server)) {
386 # Does the server advertise support for either AX or SREG?
387 $this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
388 $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
389 || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
391 $server = $server[1];
392 if (isset($delegate[2])) $this->identity = trim($delegate[2]);
395 $this->server = $server;
400 $ns = preg_quote('http://openid.net/signon/1.1');
401 if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
403 preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
404 preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
405 if (empty($server)) {
408 # AX can be used only with OpenID 2.0, so checking only SREG
409 $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
410 || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
412 $server = $server[1];
413 if (isset($delegate[1])) $this->identity = $delegate[1];
416 $this->server = $server;
429 # There are no relevant information in headers, so we search the body.
430 $content = $this->request($url, 'GET');
431 $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
433 $url = $this->build_url(parse_url($url), parse_url($location));
438 if (!$content) $content = $this->request($url, 'GET');
440 # At this point, the YADIS Discovery has failed, so we'll switch
441 # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
442 $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
443 $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
447 # The same with openid 1.1
448 $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
449 $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
454 # We found an OpenID2 OP Endpoint
456 # We have also found an OP-Local ID.
457 $this->identity = $delegate;
459 $this->server = $server;
463 throw new ErrorException('No servers found!');
465 throw new ErrorException('Endless redirection!');
468 protected function sregParams()
471 # We always use SREG 1.1, even if the server is advertising only support for 1.0.
472 # That's because it's fully backwards compatibile with 1.0, and some providers
473 # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
474 $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
475 if ($this->required) {
476 $params['openid.sreg.required'] = array();
477 foreach ($this->required as $required) {
478 if (!isset(self::$ax_to_sreg[$required])) continue;
479 $params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
481 $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
484 if ($this->optional) {
485 $params['openid.sreg.optional'] = array();
486 foreach ($this->optional as $optional) {
487 if (!isset(self::$ax_to_sreg[$optional])) continue;
488 $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
490 $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
495 protected function axParams()
498 if ($this->required || $this->optional) {
499 $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
500 $params['openid.ax.mode'] = 'fetch_request';
501 $this->aliases = array();
505 foreach (array('required','optional') as $type) {
506 foreach ($this->$type as $alias => $field) {
507 if (is_int($alias)) $alias = strtr($field, '/', '_');
508 $this->aliases[$alias] = 'http://axschema.org/' . $field;
509 if (empty($counts[$alias])) $counts[$alias] = 0;
510 $counts[$alias] += 1;
514 foreach ($this->aliases as $alias => $ns) {
515 $params['openid.ax.type.' . $alias] = $ns;
517 foreach ($counts as $alias => $count) {
518 if ($count == 1) continue;
519 $params['openid.ax.count.' . $alias] = $count;
522 # Don't send empty ax.requied and ax.if_available.
523 # Google and possibly other providers refuse to support ax when one of these is empty.
525 $params['openid.ax.required'] = implode(',', $required);
528 $params['openid.ax.if_available'] = implode(',', $optional);
534 protected function authUrl_v1()
536 $returnUrl = $this->returnUrl;
537 # If we have an openid.delegate that is different from our claimed id,
538 # we need to somehow preserve the claimed id between requests.
539 # The simplest way is to just send it along with the return_to url.
540 if($this->identity != $this->claimed_id) {
541 $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
545 'openid.return_to' => $returnUrl,
546 'openid.mode' => 'checkid_setup',
547 'openid.identity' => $this->identity,
548 'openid.trust_root' => $this->trustRoot,
549 ) + $this->sregParams();
551 return $this->build_url(parse_url($this->server)
552 , array('query' => http_build_query($params, '', '&')));
555 protected function authUrl_v2($identifier_select)
558 'openid.ns' => 'http://specs.openid.net/auth/2.0',
559 'openid.mode' => 'checkid_setup',
560 'openid.return_to' => $this->returnUrl,
561 'openid.realm' => $this->trustRoot,
564 $params += $this->axParams();
567 $params += $this->sregParams();
569 if (!$this->ax && !$this->sreg) {
570 # If OP doesn't advertise either SREG, nor AX, let's send them both
571 # in worst case we don't get anything in return.
572 $params += $this->axParams() + $this->sregParams();
575 if ($identifier_select) {
576 $params['openid.identity'] = $params['openid.claimed_id']
577 = 'http://specs.openid.net/auth/2.0/identifier_select';
579 $params['openid.identity'] = $this->identity;
580 $params['openid.claimed_id'] = $this->claimed_id;
583 return $this->build_url(parse_url($this->server)
584 , array('query' => http_build_query($params, '', '&')));
588 * Returns authentication url. Usually, you want to redirect your user to it.
589 * @return String The authentication url.
590 * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1.
591 * @throws ErrorException
593 function authUrl($identifier_select = null)
595 if (!$this->server) $this->discover($this->identity);
597 if ($this->version == 2) {
598 if ($identifier_select === null) {
599 return $this->authUrl_v2($this->identifier_select);
601 return $this->authUrl_v2($identifier_select);
603 return $this->authUrl_v1();
607 * Performs OpenID verification with the OP.
608 * @return Bool Whether the verification was successful.
609 * @throws ErrorException
613 $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
615 'openid.assoc_handle' => $this->data['openid_assoc_handle'],
616 'openid.signed' => $this->data['openid_signed'],
617 'openid.sig' => $this->data['openid_sig'],
620 if (isset($this->data['openid_ns'])) {
621 # We're dealing with an OpenID 2.0 server, so let's set an ns
622 # Even though we should know location of the endpoint,
623 # we still need to verify it by discovery, so $server is not set here
624 $params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
625 } elseif (isset($this->data['openid_claimed_id'])
626 && $this->data['openid_claimed_id'] != $this->data['openid_identity']
628 # If it's an OpenID 1 provider, and we've got claimed_id,
629 # we have to append it to the returnUrl, like authUrl_v1 does.
630 $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
631 . 'openid.claimed_id=' . $this->claimed_id;
634 if ($this->data['openid_return_to'] != $this->returnUrl) {
635 # The return_to url must match the url of current request.
636 # I'm assuing that noone will set the returnUrl to something that doesn't make sense.
640 $server = $this->discover($this->claimed_id);
642 foreach (explode(',', $this->data['openid_signed']) as $item) {
643 # Checking whether magic_quotes_gpc is turned on, because
644 # the function may fail if it is. For example, when fetching
645 # AX namePerson, it might containg an apostrophe, which will be escaped.
646 # In such case, validation would fail, since we'd send different data than OP
647 # wants to verify. stripslashes() should solve that problem, but we can't
648 # use it when magic_quotes is off.
649 $value = $this->data['openid_' . str_replace('.','_',$item)];
650 $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value;
654 $params['openid.mode'] = 'check_authentication';
656 $response = $this->request($server, 'POST', $params);
658 return preg_match('/is_valid\s*:\s*true/i', $response);
661 protected function getAxAttributes()
664 if (isset($this->data['openid_ns_ax'])
665 && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0'
666 ) { # It's the most likely case, so we'll check it before
669 # 'ax' prefix is either undefined, or points to another extension,
670 # so we search for another prefix
671 foreach ($this->data as $key => $val) {
672 if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_'
673 && $val == 'http://openid.net/srv/ax/1.0'
675 $alias = substr($key, strlen('openid_ns_'));
681 # An alias for AX schema has not been found,
682 # so there is no AX data in the OP's response
686 $attributes = array();
687 foreach ($this->data as $key => $value) {
688 $keyMatch = 'openid_' . $alias . '_value_';
689 if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
692 $key = substr($key, strlen($keyMatch));
693 if (!isset($this->data['openid_' . $alias . '_type_' . $key])) {
694 # OP is breaking the spec by returning a field without
695 # associated ns. This shouldn't happen, but it's better
696 # to check, than cause an E_NOTICE.
699 $key = substr($this->data['openid_' . $alias . '_type_' . $key],
700 strlen('http://axschema.org/'));
701 $attributes[$key] = $value;
706 protected function getSregAttributes()
708 $attributes = array();
709 $sreg_to_ax = array_flip(self::$ax_to_sreg);
710 foreach ($this->data as $key => $value) {
711 $keyMatch = 'openid_sreg_';
712 if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
715 $key = substr($key, strlen($keyMatch));
716 if (!isset($sreg_to_ax[$key])) {
717 # The field name isn't part of the SREG spec, so we ignore it.
720 $attributes[$sreg_to_ax[$key]] = $value;
726 * Gets AX/SREG attributes provided by OP. should be used only after successful validaton.
727 * Note that it does not guarantee that any of the required/optional parameters will be present,
728 * or that there will be no other attributes besides those specified.
729 * In other words. OP may provide whatever information it wants to.
730 * * SREG names will be mapped to AX names.
731 * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email'
732 * @see http://www.axschema.org/types/
734 function getAttributes()
736 if (isset($this->data['openid_ns'])
737 && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
739 # We search for both AX and SREG attributes, with AX taking precedence.
740 return $this->getAxAttributes() + $this->getSregAttributes();
742 return $this->getSregAttributes();