PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/social-connect/openid/openid.php

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