openid.php 31 KB

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