PageRenderTime 53ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Thirdparty/OpenID/LightOpenID.php

http://github.com/hybridauth/hybridauth
PHP | 1256 lines | 827 code | 148 blank | 281 comment | 171 complexity | fb36e7576ad2f2e94bca1444323893c7 MD5 | raw file
  1. <?php
  2. /*!
  3. * This file is part of the LightOpenID PHP Library (https://github.com/iignatov/LightOpenID)
  4. *
  5. * LightOpenID is an open source software available under the MIT License.
  6. *
  7. * Updated: 52f9910 on 4 Mar 2016.
  8. */
  9. namespace Hybridauth\Thirdparty\OpenID;
  10. use Hybridauth\Exception\Exception;
  11. use Hybridauth\Exception\ExceptionInterface;
  12. /**
  13. * Class ErrorException
  14. *
  15. * @package Hybridauth\Thirdparty\OpenID
  16. */
  17. class ErrorException extends Exception implements ExceptionInterface
  18. {
  19. }
  20. /**
  21. * This class provides a simple interface for OpenID 1.1/2.0 authentication.
  22. *
  23. * It requires PHP >= 5.1.2 with cURL or HTTP/HTTPS stream wrappers enabled.
  24. *
  25. * @version v1.3.1 (2016-03-04)
  26. * @link https://code.google.com/p/lightopenid/ Project URL
  27. * @link https://github.com/iignatov/LightOpenID GitHub Repo
  28. * @author Mewp <mewp151 at gmail dot com>
  29. * @copyright Copyright (c) 2013 Mewp
  30. * @license http://opensource.org/licenses/mit-license.php MIT License
  31. */
  32. class LightOpenID
  33. {
  34. public $returnUrl
  35. ;
  36. public $required = array()
  37. ;
  38. public $optional = array()
  39. ;
  40. public $verify_peer = null
  41. ;
  42. public $capath = null
  43. ;
  44. public $cainfo = null
  45. ;
  46. public $cnmatch = null
  47. ;
  48. public $data
  49. ;
  50. public $oauth = array()
  51. ;
  52. public $curl_time_out = 30 // in seconds
  53. ;
  54. public $curl_connect_time_out = 30; // in seconds
  55. private $identity;
  56. private $claimed_id;
  57. protected $server;
  58. protected $version;
  59. protected $trustRoot;
  60. protected $aliases;
  61. protected $identifier_select = false
  62. ;
  63. protected $ax = false;
  64. protected $sreg = false;
  65. protected $setup_url = null;
  66. protected $headers = array()
  67. ;
  68. protected $proxy = null;
  69. protected $user_agent = 'LightOpenID'
  70. ;
  71. protected $xrds_override_pattern = null;
  72. protected $xrds_override_replacement = null;
  73. protected static $ax_to_sreg = array(
  74. 'namePerson/friendly' => 'nickname',
  75. 'contact/email' => 'email',
  76. 'namePerson' => 'fullname',
  77. 'birthDate' => 'dob',
  78. 'person/gender' => 'gender',
  79. 'contact/postalCode/home' => 'postcode',
  80. 'contact/country/home' => 'country',
  81. 'pref/language' => 'language',
  82. 'pref/timezone' => 'timezone',
  83. );
  84. /**
  85. * LightOpenID constructor.
  86. *
  87. * @param $host
  88. * @param null $proxy
  89. *
  90. * @throws ErrorException
  91. */
  92. public function __construct($host, $proxy = null)
  93. {
  94. $this->set_realm($host);
  95. $this->set_proxy($proxy);
  96. $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
  97. $this->returnUrl = $this->trustRoot . $uri;
  98. $this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;
  99. if (!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) {
  100. throw new ErrorException('You must have either https wrappers or curl enabled.');
  101. }
  102. }
  103. /**
  104. * @param $name
  105. *
  106. * @return bool
  107. */
  108. public function __isset($name)
  109. {
  110. return in_array($name, array('identity', 'trustRoot', 'realm', 'xrdsOverride', 'mode'));
  111. }
  112. /**
  113. * @param $name
  114. * @param $value
  115. */
  116. public function __set($name, $value)
  117. {
  118. switch ($name) {
  119. case 'identity':
  120. if (strlen($value = trim((String) $value))) {
  121. if (preg_match('#^xri:/*#i', $value, $m)) {
  122. $value = substr($value, strlen($m[0]));
  123. } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
  124. $value = "http://$value";
  125. }
  126. if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
  127. $value .= '/';
  128. }
  129. }
  130. $this->$name = $this->claimed_id = $value;
  131. break;
  132. case 'trustRoot':
  133. case 'realm':
  134. $this->trustRoot = trim($value);
  135. break;
  136. case 'xrdsOverride':
  137. if (is_array($value)) {
  138. list($pattern, $replacement) = $value;
  139. $this->xrds_override_pattern = $pattern;
  140. $this->xrds_override_replacement = $replacement;
  141. } else {
  142. trigger_error('Invalid value specified for "xrdsOverride".', E_USER_ERROR);
  143. }
  144. break;
  145. }
  146. }
  147. /**
  148. * @param $name
  149. *
  150. * @return |null
  151. */
  152. public function __get($name)
  153. {
  154. switch ($name) {
  155. case 'identity':
  156. # We return claimed_id instead of identity,
  157. # because the developer should see the claimed identifier,
  158. # i.e. what he set as identity, not the op-local identifier (which is what we verify)
  159. return $this->claimed_id;
  160. case 'trustRoot':
  161. case 'realm':
  162. return $this->trustRoot;
  163. case 'mode':
  164. return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
  165. }
  166. }
  167. /**
  168. * @param $proxy
  169. *
  170. * @throws ErrorException
  171. */
  172. public function set_proxy($proxy)
  173. {
  174. if (!empty($proxy)) {
  175. // When the proxy is a string - try to parse it.
  176. if (!is_array($proxy)) {
  177. $proxy = parse_url($proxy);
  178. }
  179. // Check if $proxy is valid after the parsing.
  180. if ($proxy && !empty($proxy['host'])) {
  181. // Make sure that a valid port number is specified.
  182. if (array_key_exists('port', $proxy)) {
  183. if (!is_int($proxy['port'])) {
  184. $proxy['port'] = is_numeric($proxy['port']) ? intval($proxy['port']) : 0;
  185. }
  186. if ($proxy['port'] <= 0) {
  187. throw new ErrorException('The specified proxy port number is invalid.');
  188. }
  189. }
  190. $this->proxy = $proxy;
  191. }
  192. }
  193. }
  194. /**
  195. * Checks if the server specified in the url exists.
  196. *
  197. * @param $url string url to check
  198. * @return true, if the server exists; false otherwise
  199. */
  200. public function hostExists($url)
  201. {
  202. if (strpos($url, '/') === false) {
  203. $server = $url;
  204. } else {
  205. $server = @parse_url($url, PHP_URL_HOST);
  206. }
  207. if (!$server) {
  208. return false;
  209. }
  210. return !!gethostbynamel($server);
  211. }
  212. /**
  213. * @param $uri
  214. */
  215. protected function set_realm($uri)
  216. {
  217. $realm = '';
  218. # Set a protocol, if not specified.
  219. $realm .= (($offset = strpos($uri, '://')) === false) ? $this->get_realm_protocol() : '';
  220. # Set the offset properly.
  221. $offset = (($offset !== false) ? $offset + 3 : 0);
  222. # Get only the root, without the path.
  223. $realm .= (($end = strpos($uri, '/', $offset)) === false) ? $uri : substr($uri, 0, $end);
  224. $this->trustRoot = $realm;
  225. }
  226. /**
  227. * @return string
  228. */
  229. protected function get_realm_protocol()
  230. {
  231. if (!empty($_SERVER['HTTPS'])) {
  232. $use_secure_protocol = ($_SERVER['HTTPS'] !== 'off');
  233. } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  234. $use_secure_protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
  235. } elseif (isset($_SERVER['HTTP__WSSC'])) {
  236. $use_secure_protocol = ($_SERVER['HTTP__WSSC'] == 'https');
  237. } else {
  238. $use_secure_protocol = false;
  239. }
  240. return $use_secure_protocol ? 'https://' : 'http://';
  241. }
  242. /**
  243. * @param $url
  244. * @param string $method
  245. * @param array $params
  246. * @param $update_claimed_id
  247. *
  248. * @return array|bool|string
  249. * @throws ErrorException
  250. */
  251. protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id=false)
  252. {
  253. $params = http_build_query($params, '', '&');
  254. $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
  255. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  256. curl_setopt($curl, CURLOPT_HEADER, false);
  257. curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
  258. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  259. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  260. if ($method == 'POST') {
  261. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
  262. } else {
  263. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
  264. }
  265. curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_time_out); // defaults to infinite
  266. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out); // defaults to 300s
  267. if (!empty($this->proxy)) {
  268. curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']);
  269. if (!empty($this->proxy['port'])) {
  270. curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']);
  271. }
  272. if (!empty($this->proxy['user'])) {
  273. curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']);
  274. }
  275. }
  276. if ($this->verify_peer !== null) {
  277. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
  278. if ($this->capath) {
  279. curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
  280. }
  281. if ($this->cainfo) {
  282. curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
  283. }
  284. }
  285. if ($method == 'POST') {
  286. curl_setopt($curl, CURLOPT_POST, true);
  287. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  288. } elseif ($method == 'HEAD') {
  289. curl_setopt($curl, CURLOPT_HEADER, true);
  290. curl_setopt($curl, CURLOPT_NOBODY, true);
  291. } else {
  292. curl_setopt($curl, CURLOPT_HEADER, true);
  293. curl_setopt($curl, CURLOPT_HTTPGET, true);
  294. }
  295. $response = curl_exec($curl);
  296. if ($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) {
  297. curl_setopt($curl, CURLOPT_HTTPGET, true);
  298. $response = curl_exec($curl);
  299. $response = substr($response, 0, strpos($response, "\r\n\r\n"));
  300. }
  301. if ($method == 'HEAD' || $method == 'GET') {
  302. $header_response = $response;
  303. # If it's a GET request, we want to only parse the header part.
  304. if ($method == 'GET') {
  305. $header_response = substr($response, 0, strpos($response, "\r\n\r\n"));
  306. }
  307. $headers = array();
  308. foreach (explode("\n", $header_response) as $header) {
  309. $pos = strpos($header, ':');
  310. if ($pos !== false) {
  311. $name = strtolower(trim(substr($header, 0, $pos)));
  312. $headers[$name] = trim(substr($header, $pos+1));
  313. }
  314. }
  315. if ($update_claimed_id) {
  316. # Update the claimed_id value in case of redirections.
  317. $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
  318. # Ignore the fragment (some cURL versions don't handle it well).
  319. if (strtok($effective_url, '#') != strtok($url, '#')) {
  320. $this->identity = $this->claimed_id = $effective_url;
  321. }
  322. }
  323. if ($method == 'HEAD') {
  324. return $headers;
  325. } else {
  326. $this->headers = $headers;
  327. }
  328. }
  329. if (curl_errno($curl)) {
  330. throw new ErrorException(curl_error($curl), curl_errno($curl));
  331. }
  332. return $response;
  333. }
  334. /**
  335. * @param $array
  336. * @param $update_claimed_id
  337. *
  338. * @return array
  339. */
  340. protected function parse_header_array($array, $update_claimed_id)
  341. {
  342. $headers = array();
  343. foreach ($array as $header) {
  344. $pos = strpos($header, ':');
  345. if ($pos !== false) {
  346. $name = strtolower(trim(substr($header, 0, $pos)));
  347. $headers[$name] = trim(substr($header, $pos+1));
  348. # Following possible redirections. The point is just to have
  349. # claimed_id change with them, because the redirections
  350. # are followed automatically.
  351. # We ignore redirections with relative paths.
  352. # If any known provider uses them, file a bug report.
  353. if ($name == 'location' && $update_claimed_id) {
  354. if (strpos($headers[$name], 'http') === 0) {
  355. $this->identity = $this->claimed_id = $headers[$name];
  356. } elseif ($headers[$name][0] == '/') {
  357. $parsed_url = parse_url($this->claimed_id);
  358. $this->identity =
  359. $this->claimed_id = $parsed_url['scheme'] . '://'
  360. . $parsed_url['host']
  361. . $headers[$name];
  362. }
  363. }
  364. }
  365. }
  366. return $headers;
  367. }
  368. /**
  369. * @param $url
  370. * @param string $method
  371. * @param array $params
  372. * @param $update_claimed_id
  373. *
  374. * @return array|false|string
  375. * @throws ErrorException
  376. */
  377. protected function request_streams($url, $method='GET', $params=array(), $update_claimed_id=false)
  378. {
  379. if (!$this->hostExists($url)) {
  380. throw new ErrorException("Could not connect to $url.", 404);
  381. }
  382. if (empty($this->cnmatch)) {
  383. $this->cnmatch = parse_url($url, PHP_URL_HOST);
  384. }
  385. $params = http_build_query($params, '', '&');
  386. switch ($method) {
  387. case 'GET':
  388. $opts = array(
  389. 'http' => array(
  390. 'method' => 'GET',
  391. 'header' => 'Accept: application/xrds+xml, */*',
  392. 'user_agent' => $this->user_agent,
  393. 'ignore_errors' => true,
  394. ),
  395. 'ssl' => array(
  396. 'CN_match' => $this->cnmatch
  397. )
  398. );
  399. $url = $url . ($params ? '?' . $params : '');
  400. if (!empty($this->proxy)) {
  401. $opts['http']['proxy'] = $this->proxy_url();
  402. }
  403. break;
  404. case 'POST':
  405. $opts = array(
  406. 'http' => array(
  407. 'method' => 'POST',
  408. 'header' => 'Content-type: application/x-www-form-urlencoded',
  409. 'user_agent' => $this->user_agent,
  410. 'content' => $params,
  411. 'ignore_errors' => true,
  412. ),
  413. 'ssl' => array(
  414. 'CN_match' => $this->cnmatch
  415. )
  416. );
  417. if (!empty($this->proxy)) {
  418. $opts['http']['proxy'] = $this->proxy_url();
  419. }
  420. break;
  421. case 'HEAD':
  422. // We want to send a HEAD request, but since get_headers() doesn't
  423. // accept $context parameter, we have to change the defaults.
  424. $default = stream_context_get_options(stream_context_get_default());
  425. // PHP does not reset all options. Instead, it just sets the options
  426. // available in the passed array, therefore set the defaults manually.
  427. $default += array(
  428. 'http' => array(),
  429. 'ssl' => array()
  430. );
  431. $default['http'] += array(
  432. 'method' => 'GET',
  433. 'header' => '',
  434. 'user_agent' => '',
  435. 'ignore_errors' => false
  436. );
  437. $default['ssl'] += array(
  438. 'CN_match' => ''
  439. );
  440. $opts = array(
  441. 'http' => array(
  442. 'method' => 'HEAD',
  443. 'header' => 'Accept: application/xrds+xml, */*',
  444. 'user_agent' => $this->user_agent,
  445. 'ignore_errors' => true,
  446. ),
  447. 'ssl' => array(
  448. 'CN_match' => $this->cnmatch
  449. )
  450. );
  451. // Enable validation of the SSL certificates.
  452. if ($this->verify_peer) {
  453. $default['ssl'] += array(
  454. 'verify_peer' => false,
  455. 'capath' => '',
  456. 'cafile' => ''
  457. );
  458. $opts['ssl'] += array(
  459. 'verify_peer' => true,
  460. 'capath' => $this->capath,
  461. 'cafile' => $this->cainfo
  462. );
  463. }
  464. // Change the stream context options.
  465. stream_context_get_default($opts);
  466. $headers = get_headers($url . ($params ? '?' . $params : ''));
  467. // Restore the stream context options.
  468. stream_context_get_default($default);
  469. if (!empty($headers)) {
  470. if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) {
  471. // The server doesn't support HEAD - emulate it with a GET.
  472. $args = func_get_args();
  473. $args[1] = 'GET';
  474. call_user_func_array(array($this, 'request_streams'), $args);
  475. $headers = $this->headers;
  476. } else {
  477. $headers = $this->parse_header_array($headers, $update_claimed_id);
  478. }
  479. } else {
  480. $headers = array();
  481. }
  482. return $headers;
  483. }
  484. if ($this->verify_peer) {
  485. $opts['ssl'] += array(
  486. 'verify_peer' => true,
  487. 'capath' => $this->capath,
  488. 'cafile' => $this->cainfo
  489. );
  490. }
  491. $context = stream_context_create($opts);
  492. $data = file_get_contents($url, false, $context);
  493. # This is a hack for providers who don't support HEAD requests.
  494. # It just creates the headers array for the last request in $this->headers.
  495. if (isset($http_response_header)) {
  496. $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id);
  497. }
  498. return $data;
  499. }
  500. /**
  501. * @param $url
  502. * @param string $method
  503. * @param array $params
  504. * @param bool $update_claimed_id
  505. *
  506. * @return array|bool|false|string
  507. * @throws ErrorException
  508. */
  509. protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
  510. {
  511. $use_curl = false;
  512. if (function_exists('curl_init')) {
  513. if (!$use_curl) {
  514. # When allow_url_fopen is disabled, PHP streams will not work.
  515. $use_curl = !ini_get('allow_url_fopen');
  516. }
  517. if (!$use_curl) {
  518. # When there is no HTTPS wrapper, PHP streams cannott be used.
  519. $use_curl = !in_array('https', stream_get_wrappers());
  520. }
  521. if (!$use_curl) {
  522. # With open_basedir or safe_mode set, cURL can't follow redirects.
  523. $use_curl = !(ini_get('safe_mode') || ini_get('open_basedir'));
  524. }
  525. }
  526. return
  527. $use_curl
  528. ? $this->request_curl($url, $method, $params, $update_claimed_id)
  529. : $this->request_streams($url, $method, $params, $update_claimed_id);
  530. }
  531. /**
  532. * @return string
  533. */
  534. protected function proxy_url()
  535. {
  536. $result = '';
  537. if (!empty($this->proxy)) {
  538. $result = $this->proxy['host'];
  539. if (!empty($this->proxy['port'])) {
  540. $result = $result . ':' . $this->proxy['port'];
  541. }
  542. if (!empty($this->proxy['user'])) {
  543. $result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result;
  544. }
  545. $result = 'http://' . $result;
  546. }
  547. return $result;
  548. }
  549. /**
  550. * @param $url
  551. * @param $parts
  552. *
  553. * @return string
  554. */
  555. protected function build_url($url, $parts)
  556. {
  557. if (isset($url['query'], $parts['query'])) {
  558. $parts['query'] = $url['query'] . '&' . $parts['query'];
  559. }
  560. $url = $parts + $url;
  561. $url = $url['scheme'] . '://'
  562. . (empty($url['username'])?''
  563. :(empty($url['password'])? "{$url['username']}@"
  564. :"{$url['username']}:{$url['password']}@"))
  565. . $url['host']
  566. . (empty($url['port'])?'':":{$url['port']}")
  567. . (empty($url['path'])?'':$url['path'])
  568. . (empty($url['query'])?'':"?{$url['query']}")
  569. . (empty($url['fragment'])?'':"#{$url['fragment']}");
  570. return $url;
  571. }
  572. /**
  573. * Helper function used to scan for <meta>/<link> tags and extract information
  574. * from them
  575. *
  576. * @param $content
  577. * @param $tag
  578. * @param $attrName
  579. * @param $attrValue
  580. * @param $valueName
  581. *
  582. * @return bool
  583. */
  584. protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
  585. {
  586. preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
  587. preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
  588. $result = array_merge($matches1[1], $matches2[1]);
  589. return empty($result)?false:$result[0];
  590. }
  591. /**
  592. * Performs Yadis and HTML discovery. Normally not used.
  593. * @param $url Identity URL.
  594. * @return String OP Endpoint (i.e. OpenID provider address).
  595. * @throws ErrorException
  596. */
  597. public function discover($url)
  598. {
  599. if (!$url) {
  600. throw new ErrorException('No identity supplied.');
  601. }
  602. # Use xri.net proxy to resolve i-name identities
  603. if (!preg_match('#^https?:#', $url)) {
  604. $url = "https://xri.net/$url";
  605. }
  606. # We save the original url in case of Yadis discovery failure.
  607. # It can happen when we'll be lead to an XRDS document
  608. # which does not have any OpenID2 services.
  609. $originalUrl = $url;
  610. # A flag to disable yadis discovery in case of failure in headers.
  611. $yadis = true;
  612. # Allows optional regex replacement of the URL, e.g. to use Google Apps
  613. # as an OpenID provider without setting up XRDS on the domain hosting.
  614. if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) {
  615. $url = preg_replace($this->xrds_override_pattern, $this->xrds_override_replacement, $url);
  616. }
  617. # We'll jump a maximum of 5 times, to avoid endless redirections.
  618. for ($i = 0; $i < 5; $i ++) {
  619. if ($yadis) {
  620. $headers = $this->request($url, 'HEAD', array(), true);
  621. $next = false;
  622. if (isset($headers['x-xrds-location'])) {
  623. $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
  624. $next = true;
  625. }
  626. if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) {
  627. # Found an XRDS document, now let's find the server, and optionally delegate.
  628. $content = $this->request($url, 'GET');
  629. preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
  630. foreach ($m[1] as $content) {
  631. $content = ' ' . $content; # The space is added, so that strpos doesn't return 0.
  632. # OpenID 2
  633. $ns = preg_quote('http://specs.openid.net/auth/2.0/', '#');
  634. if (preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
  635. if ($type[1] == 'server') {
  636. $this->identifier_select = true;
  637. }
  638. preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
  639. preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
  640. if (empty($server)) {
  641. return false;
  642. }
  643. # Does the server advertise support for either AX or SREG?
  644. $this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
  645. $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
  646. || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
  647. $server = $server[1];
  648. if (isset($delegate[2])) {
  649. $this->identity = trim($delegate[2]);
  650. }
  651. $this->version = 2;
  652. $this->server = $server;
  653. return $server;
  654. }
  655. # OpenID 1.1
  656. $ns = preg_quote('http://openid.net/signon/1.1', '#');
  657. if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
  658. preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
  659. preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
  660. if (empty($server)) {
  661. return false;
  662. }
  663. # AX can be used only with OpenID 2.0, so checking only SREG
  664. $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
  665. || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
  666. $server = $server[1];
  667. if (isset($delegate[1])) {
  668. $this->identity = $delegate[1];
  669. }
  670. $this->version = 1;
  671. $this->server = $server;
  672. return $server;
  673. }
  674. }
  675. $next = true;
  676. $yadis = false;
  677. $url = $originalUrl;
  678. $content = null;
  679. break;
  680. }
  681. if ($next) {
  682. continue;
  683. }
  684. # There are no relevant information in headers, so we search the body.
  685. $content = $this->request($url, 'GET', array(), true);
  686. if (isset($this->headers['x-xrds-location'])) {
  687. $url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location'])));
  688. continue;
  689. }
  690. $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
  691. if ($location) {
  692. $url = $this->build_url(parse_url($url), parse_url($location));
  693. continue;
  694. }
  695. }
  696. if (!$content) {
  697. $content = $this->request($url, 'GET');
  698. }
  699. # At this point, the YADIS Discovery has failed, so we'll switch
  700. # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
  701. $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
  702. $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
  703. $this->version = 2;
  704. if (!$server) {
  705. # The same with openid 1.1
  706. $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
  707. $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
  708. $this->version = 1;
  709. }
  710. if ($server) {
  711. # We found an OpenID2 OP Endpoint
  712. if ($delegate) {
  713. # We have also found an OP-Local ID.
  714. $this->identity = $delegate;
  715. }
  716. $this->server = $server;
  717. return $server;
  718. }
  719. throw new ErrorException("No OpenID Server found at $url", 404);
  720. }
  721. throw new ErrorException('Endless redirection!', 500);
  722. }
  723. /**
  724. * @param $content_type
  725. *
  726. * @return bool
  727. */
  728. protected function is_allowed_type($content_type)
  729. {
  730. # Apparently, some providers return XRDS documents as text/html.
  731. # While it is against the spec, allowing this here shouldn't break
  732. # compatibility with anything.
  733. $allowed_types = array('application/xrds+xml', 'text/xml');
  734. # Only allow text/html content type for the Yahoo logins, since
  735. # it might cause an endless redirection for the other providers.
  736. if ($this->get_provider_name($this->claimed_id) == 'yahoo') {
  737. $allowed_types[] = 'text/html';
  738. }
  739. foreach ($allowed_types as $type) {
  740. if (strpos($content_type, $type) !== false) {
  741. return true;
  742. }
  743. }
  744. return false;
  745. }
  746. /**
  747. * @param $provider_url
  748. *
  749. * @return string
  750. */
  751. protected function get_provider_name($provider_url)
  752. {
  753. $result = '';
  754. if (!empty($provider_url)) {
  755. $tokens = array_reverse(
  756. explode('.', parse_url($provider_url, PHP_URL_HOST))
  757. );
  758. $result = strtolower(
  759. (count($tokens) > 1 && strlen($tokens[1]) > 3)
  760. ? $tokens[1]
  761. : (count($tokens) > 2 ? $tokens[2] : '')
  762. );
  763. }
  764. return $result;
  765. }
  766. /**
  767. * @return array
  768. */
  769. protected function sregParams()
  770. {
  771. $params = array();
  772. # We always use SREG 1.1, even if the server is advertising only support for 1.0.
  773. # That's because it's fully backwards compatible with 1.0, and some providers
  774. # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
  775. $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
  776. if ($this->required) {
  777. $params['openid.sreg.required'] = array();
  778. foreach ($this->required as $required) {
  779. if (!isset(self::$ax_to_sreg[$required])) {
  780. continue;
  781. }
  782. $params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
  783. }
  784. $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
  785. }
  786. if ($this->optional) {
  787. $params['openid.sreg.optional'] = array();
  788. foreach ($this->optional as $optional) {
  789. if (!isset(self::$ax_to_sreg[$optional])) {
  790. continue;
  791. }
  792. $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
  793. }
  794. $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
  795. }
  796. return $params;
  797. }
  798. /**
  799. * @return array
  800. */
  801. protected function axParams()
  802. {
  803. $params = array();
  804. if ($this->required || $this->optional) {
  805. $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
  806. $params['openid.ax.mode'] = 'fetch_request';
  807. $this->aliases = array();
  808. $counts = array();
  809. $required = array();
  810. $optional = array();
  811. foreach (array('required','optional') as $type) {
  812. foreach ($this->$type as $alias => $field) {
  813. if (is_int($alias)) {
  814. $alias = strtr($field, '/', '_');
  815. }
  816. $this->aliases[$alias] = 'http://axschema.org/' . $field;
  817. if (empty($counts[$alias])) {
  818. $counts[$alias] = 0;
  819. }
  820. $counts[$alias] += 1;
  821. ${$type}[] = $alias;
  822. }
  823. }
  824. foreach ($this->aliases as $alias => $ns) {
  825. $params['openid.ax.type.' . $alias] = $ns;
  826. }
  827. foreach ($counts as $alias => $count) {
  828. if ($count == 1) {
  829. continue;
  830. }
  831. $params['openid.ax.count.' . $alias] = $count;
  832. }
  833. # Don't send empty ax.required and ax.if_available.
  834. # Google and possibly other providers refuse to support ax when one of these is empty.
  835. if ($required) {
  836. $params['openid.ax.required'] = implode(',', $required);
  837. }
  838. if ($optional) {
  839. $params['openid.ax.if_available'] = implode(',', $optional);
  840. }
  841. }
  842. return $params;
  843. }
  844. /**
  845. * @param $immediate
  846. *
  847. * @return string
  848. */
  849. protected function authUrl_v1($immediate)
  850. {
  851. $returnUrl = $this->returnUrl;
  852. # If we have an openid.delegate that is different from our claimed id,
  853. # we need to somehow preserve the claimed id between requests.
  854. # The simplest way is to just send it along with the return_to url.
  855. if ($this->identity != $this->claimed_id) {
  856. $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
  857. }
  858. $params = array(
  859. 'openid.return_to' => $returnUrl,
  860. 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
  861. 'openid.identity' => $this->identity,
  862. 'openid.trust_root' => $this->trustRoot,
  863. ) + $this->sregParams();
  864. return $this->build_url(parse_url($this->server), array('query' => http_build_query($params, '', '&')));
  865. }
  866. /**
  867. * @param $immediate
  868. *
  869. * @return string
  870. */
  871. protected function authUrl_v2($immediate)
  872. {
  873. $params = array(
  874. 'openid.ns' => 'http://specs.openid.net/auth/2.0',
  875. 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
  876. 'openid.return_to' => $this->returnUrl,
  877. 'openid.realm' => $this->trustRoot,
  878. );
  879. if ($this->ax) {
  880. $params += $this->axParams();
  881. }
  882. if ($this->sreg) {
  883. $params += $this->sregParams();
  884. }
  885. if (!$this->ax && !$this->sreg) {
  886. # If OP doesn't advertise either SREG, nor AX, let's send them both
  887. # in worst case we don't get anything in return.
  888. $params += $this->axParams() + $this->sregParams();
  889. }
  890. if (!empty($this->oauth) && is_array($this->oauth)) {
  891. $params['openid.ns.oauth'] = 'http://specs.openid.net/extensions/oauth/1.0';
  892. $params['openid.oauth.consumer'] = str_replace(array('http://', 'https://'), '', $this->trustRoot);
  893. $params['openid.oauth.scope'] = implode(' ', $this->oauth);
  894. }
  895. if ($this->identifier_select) {
  896. $params['openid.identity'] = $params['openid.claimed_id']
  897. = 'http://specs.openid.net/auth/2.0/identifier_select';
  898. } else {
  899. $params['openid.identity'] = $this->identity;
  900. $params['openid.claimed_id'] = $this->claimed_id;
  901. }
  902. return $this->build_url(parse_url($this->server), array('query' => http_build_query($params, '', '&')));
  903. }
  904. /**
  905. * Returns authentication url. Usually, you want to redirect your user to it.
  906. * @param bool $immediate
  907. * @return String The authentication url.
  908. * @throws ErrorException
  909. */
  910. public function authUrl($immediate = false)
  911. {
  912. if ($this->setup_url && !$immediate) {
  913. return $this->setup_url;
  914. }
  915. if (!$this->server) {
  916. $this->discover($this->identity);
  917. }
  918. if ($this->version == 2) {
  919. return $this->authUrl_v2($immediate);
  920. }
  921. return $this->authUrl_v1($immediate);
  922. }
  923. /**
  924. * Performs OpenID verification with the OP.
  925. * @return Bool Whether the verification was successful.
  926. * @throws ErrorException
  927. */
  928. public function validate()
  929. {
  930. # If the request was using immediate mode, a failure may be reported
  931. # by presenting user_setup_url (for 1.1) or reporting
  932. # mode 'setup_needed' (for 2.0). Also catching all modes other than
  933. # id_res, in order to avoid throwing errors.
  934. if (isset($this->data['openid_user_setup_url'])) {
  935. $this->setup_url = $this->data['openid_user_setup_url'];
  936. return false;
  937. }
  938. if ($this->mode != 'id_res') {
  939. return false;
  940. }
  941. $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
  942. $params = array(
  943. 'openid.assoc_handle' => $this->data['openid_assoc_handle'],
  944. 'openid.signed' => $this->data['openid_signed'],
  945. 'openid.sig' => $this->data['openid_sig'],
  946. );
  947. if (isset($this->data['openid_ns'])) {
  948. # We're dealing with an OpenID 2.0 server, so let's set an ns
  949. # Even though we should know location of the endpoint,
  950. # we still need to verify it by discovery, so $server is not set here
  951. $params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
  952. } elseif (isset($this->data['openid_claimed_id'])
  953. && $this->data['openid_claimed_id'] != $this->data['openid_identity']
  954. ) {
  955. # If it's an OpenID 1 provider, and we've got claimed_id,
  956. # we have to append it to the returnUrl, like authUrl_v1 does.
  957. $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
  958. . 'openid.claimed_id=' . $this->claimed_id;
  959. }
  960. if ($this->data['openid_return_to'] != $this->returnUrl) {
  961. # The return_to url must match the url of current request.
  962. # I'm assuming that no one will set the returnUrl to something that doesn't make sense.
  963. return false;
  964. }
  965. $server = $this->discover($this->claimed_id);
  966. foreach (explode(',', $this->data['openid_signed']) as $item) {
  967. $value = $this->data['openid_' . str_replace('.', '_', $item)];
  968. $params['openid.' . $item] = $value;
  969. }
  970. $params['openid.mode'] = 'check_authentication';
  971. $response = $this->request($server, 'POST', $params);
  972. return preg_match('/is_valid\s*:\s*true/i', $response);
  973. }
  974. /**
  975. * @return array
  976. */
  977. protected function getAxAttributes()
  978. {
  979. $result = array();
  980. if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) {
  981. $prefix = 'openid_' . $alias;
  982. $length = strlen('http://axschema.org/');
  983. foreach (explode(',', $this->data['openid_signed']) as $key) {
  984. $keyMatch = $alias . '.type.';
  985. if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
  986. continue;
  987. }
  988. $key = substr($key, strlen($keyMatch));
  989. $idv = $prefix . '_value_' . $key;
  990. $idc = $prefix . '_count_' . $key;
  991. $key = substr($this->getItem($prefix . '_type_' . $key), $length);
  992. if (!empty($key)) {
  993. if (($count = intval($this->getItem($idc))) > 0) {
  994. $value = array();
  995. for ($i = 1; $i <= $count; $i++) {
  996. $value[] = $this->getItem($idv . '_' . $i);
  997. }
  998. $value = ($count == 1) ? reset($value) : $value;
  999. } else {
  1000. $value = $this->getItem($idv);
  1001. }
  1002. if (!is_null($value)) {
  1003. $result[$key] = $value;
  1004. }
  1005. }
  1006. }
  1007. } else {
  1008. // No alias for the AX schema has been found,
  1009. // so there is no AX data in the OP's response.
  1010. }
  1011. return $result;
  1012. }
  1013. /**
  1014. * @return array
  1015. */
  1016. protected function getSregAttributes()
  1017. {
  1018. $attributes = array();
  1019. $sreg_to_ax = array_flip(self::$ax_to_sreg);
  1020. if ($alias = $this->getNamespaceAlias('http://openid.net/extensions/sreg/1.1', 'sreg')) {
  1021. foreach (explode(',', $this->data['openid_signed']) as $key) {
  1022. $keyMatch = $alias . '.';
  1023. if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
  1024. continue;
  1025. }
  1026. $key = substr($key, strlen($keyMatch));
  1027. if (!isset($sreg_to_ax[$key])) {
  1028. # The field name isn't part of the SREG spec, so we ignore it.
  1029. continue;
  1030. }
  1031. $attributes[$sreg_to_ax[$key]] = $this->data['openid_' . $alias . '_' . $key];
  1032. }
  1033. }
  1034. return $attributes;
  1035. }
  1036. /**
  1037. * Gets AX/SREG attributes provided by OP. should be used only after successful validation.
  1038. * Note that it does not guarantee that any of the required/optional parameters will be present,
  1039. * or that there will be no other attributes besides those specified.
  1040. * In other words. OP may provide whatever information it wants to.
  1041. * * SREG names will be mapped to AX names.
  1042. * *
  1043. * @return array Array of attributes with keys being the AX schema names, e.g. 'contact/email' @see http://www.axschema.org/types/
  1044. */
  1045. public function getAttributes()
  1046. {
  1047. if (isset($this->data['openid_ns'])
  1048. && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
  1049. ) { # OpenID 2.0
  1050. # We search for both AX and SREG attributes, with AX taking precedence.
  1051. return $this->getAxAttributes() + $this->getSregAttributes();
  1052. }
  1053. return $this->getSregAttributes();
  1054. }
  1055. /**
  1056. * Gets an OAuth request token if the OpenID+OAuth hybrid protocol has been used.
  1057. *
  1058. * In order to use the OpenID+OAuth hybrid protocol, you need to add at least one
  1059. * scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.:
  1060. * $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me';
  1061. *
  1062. * Furthermore the registered consumer name must fit the OpenID realm.
  1063. * To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains
  1064. *
  1065. * @return string|bool OAuth request token on success, FALSE if no token was provided.
  1066. */
  1067. public function getOAuthRequestToken()
  1068. {
  1069. $alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0');
  1070. return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false;
  1071. }
  1072. /**
  1073. * Gets the alias for the specified namespace, if it's present.
  1074. *
  1075. * @param string $namespace The namespace for which an alias is needed.
  1076. * @param string $hint Common alias of this namespace, used for optimization.
  1077. * @return string|null The namespace alias if found, otherwise - NULL.
  1078. */
  1079. private function getNamespaceAlias($namespace, $hint = null)
  1080. {
  1081. $result = null;
  1082. if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) {
  1083. // The common alias is either undefined or points to
  1084. // some other extension - search for another alias..
  1085. $prefix = 'openid_ns_';
  1086. $length = strlen($prefix);
  1087. foreach ($this->data as $key => $val) {
  1088. if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) {
  1089. $result = trim(substr($key, $length));
  1090. break;
  1091. }
  1092. }
  1093. } else {
  1094. $result = $hint;
  1095. }
  1096. return $result;
  1097. }
  1098. /**
  1099. * Gets an item from the $data array by the specified id.
  1100. *
  1101. * @param string $id The id of the desired item.
  1102. * @return string|null The item if found, otherwise - NULL.
  1103. */
  1104. private function getItem($id)
  1105. {
  1106. return isset($this->data[$id]) ? $this->data[$id] : null;
  1107. }
  1108. }