PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/protected/extensions/lightopenid/LightOpenID.php

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