OpenId.php 28.4 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\authclient;
9

10 11
use yii\base\Exception;
use yii\base\NotSupportedException;
12
use Yii;
13 14

/**
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 * OpenId provides a simple interface for OpenID (1.1 and 2.0) authentication.
 * Supports Yadis and HTML discovery.
 *
 * Usage:
 *
 * ~~~
 * use yii\authclient\OpenId;
 *
 * $client = new OpenId();
 * $client->authUrl = 'https://open.id.provider.url'; // Setup provider endpoint
 * $url = $client->buildAuthUrl(); // Get authentication URL
 * return Yii::$app->getResponse()->redirect($url); // Redirect to authentication URL
 * // After user returns at our site:
 * if ($client->validate()) { // validate response
 *     $userAttributes = $client->getUserAttributes(); // get account info
 *     ...
 * }
 * ~~~
 *
 * AX and SREG extensions are supported.
 * To use them, specify [[requiredAttributes]] and/or [[optionalAttributes]].
36 37 38
 *
 * @see http://openid.net/
 *
Qiang Xue committed
39 40 41
 * @property string $claimedId Claimed identifier (identity).
 * @property string $returnUrl Authentication return URL.
 * @property string $trustRoot Client trust root (realm).
42
 *
43 44 45
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
46
class OpenId extends BaseClient implements ClientInterface
47
{
48 49 50 51 52
	/**
	 * @var string authentication base URL, which should be used to compose actual authentication URL
	 * by [[buildAuthUrl()]] method.
	 */
	public $authUrl;
53
	/**
54
	 * @var array list of attributes, which always should be returned from server.
55 56 57 58 59
	 * Attribute names should be always specified in AX format.
	 * For example:
	 * ~~~
	 * ['namePerson/friendly', 'contact/email']
	 * ~~~
60 61
	 */
	public $requiredAttributes = [];
62 63
	/**
	 * @var array list of attributes, which could be returned from server.
64 65 66 67 68
	 * Attribute names should be always specified in AX format.
	 * For example:
	 * ~~~
	 * ['namePerson/first', 'namePerson/last']
	 * ~~~
69 70 71 72 73 74 75 76 77 78 79
	 */
	public $optionalAttributes = [];

	/**
	 * @var boolean whether to verify the peer's certificate.
	 */
	public $verifyPeer;
	/**
	 * @var string directory that holds multiple CA certificates.
	 * This value will take effect only if [[verifyPeer]] is set.
	 */
80
	public $capath;
81 82 83 84
	/**
	 * @var string the name of a file holding one or more certificates to verify the peer with.
	 * This value will take effect only if [[verifyPeer]] is set.
	 */
85 86
	public $cainfo;

87 88 89
	/**
	 * @var string authentication return URL.
	 */
90
	private $_returnUrl;
91 92 93
	/**
	 * @var string claimed identifier (identity)
	 */
94
	private $_claimedId;
95 96 97
	/**
	 * @var string client trust root (realm), by default [[\yii\web\Request::hostInfo]] value will be used.
	 */
98
	private $_trustRoot;
99 100 101 102 103
	/**
	 * @var array data, which should be used to retrieve the OpenID response.
	 * If not set combination of GET and POST will be used.
	 */
	public $data;
104 105 106 107 108 109 110 111 112
	/**
	 * @var array map of matches between AX and SREG attribute names in format: axAttributeName => sregAttributeName
	 */
	public $axToSregMap = [
		'namePerson/friendly' => 'nickname',
		'contact/email' => 'email',
		'namePerson' => 'fullname',
		'birthDate' => 'dob',
		'person/gender' => 'gender',
113
		'contact/postalCode/home' => 'postcode',
114 115 116
		'contact/country/home' => 'country',
		'pref/language' => 'language',
		'pref/timezone' => 'timezone',
117 118 119 120 121 122 123
	];

	/**
	 * @inheritdoc
	 */
	public function init()
	{
124 125 126
		if ($this->data === null) {
			$this->data = array_merge($_GET, $_POST); // OPs may send data as POST or GET.
		}
127 128
	}

129 130 131 132
	/**
	 * @param string $claimedId claimed identifier (identity).
	 */
	public function setClaimedId($claimedId)
133
	{
134
		$this->_claimedId = $claimedId;
135 136
	}

137 138 139 140
	/**
	 * @return string claimed identifier (identity).
	 */
	public function getClaimedId()
141
	{
142 143 144 145 146 147 148
		if ($this->_claimedId === null) {
			if (isset($this->data['openid_claimed_id'])) {
				$this->_claimedId = $this->data['openid_claimed_id'];
			} elseif (isset($this->data['openid_identity'])) {
				$this->_claimedId = $this->data['openid_identity'];
			}
		}
149
		return $this->_claimedId;
150 151
	}

152 153 154
	/**
	 * @param string $returnUrl authentication return URL.
	 */
155 156 157 158 159
	public function setReturnUrl($returnUrl)
	{
		$this->_returnUrl = $returnUrl;
	}

160 161 162
	/**
	 * @return string authentication return URL.
	 */
163 164 165
	public function getReturnUrl()
	{
		if ($this->_returnUrl === null) {
166
			$this->_returnUrl = $this->defaultReturnUrl();
167 168 169 170
		}
		return $this->_returnUrl;
	}

171 172 173
	/**
	 * @param string $value client trust root (realm).
	 */
174 175
	public function setTrustRoot($value)
	{
176
		$this->_trustRoot = $value;
177 178
	}

179 180 181
	/**
	 * @return string client trust root (realm).
	 */
182 183 184
	public function getTrustRoot()
	{
		if ($this->_trustRoot === null) {
185
			$this->_trustRoot = Yii::$app->getRequest()->getHostInfo();
186 187 188 189
		}
		return $this->_trustRoot;
	}

190 191 192 193 194
	/**
	 * Generates default [[returnUrl]] value.
	 * @return string default authentication return URL.
	 */
	protected function defaultReturnUrl()
195
	{
196 197 198 199 200 201 202 203
		$params = $_GET;
		foreach ($params as $name => $value) {
			if (strncmp('openid', $name, 6) === 0) {
				unset($params[$name]);
			}
		}
		$url = Yii::$app->getUrlManager()->createUrl(Yii::$app->requestedRoute, $params);
		return $this->getTrustRoot() . $url;
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
	}

	/**
	 * Checks if the server specified in the url exists.
	 * @param string $url URL to check
	 * @return boolean true, if the server exists; false otherwise
	 */
	public function hostExists($url)
	{
		if (strpos($url, '/') === false) {
			$server = $url;
		} else {
			$server = @parse_url($url, PHP_URL_HOST);
		}
		if (!$server) {
			return false;
		}
		$ips = gethostbynamel($server);
		return !empty($ips);
	}

225 226 227 228 229 230 231 232
	/**
	 * Sends HTTP request.
	 * @param string $url request URL.
	 * @param string $method request method.
	 * @param array $params request params.
	 * @return array|string response.
	 * @throws \yii\base\Exception on failure.
	 */
233 234 235 236 237 238 239 240 241 242
	protected function sendCurlRequest($url, $method = 'GET', $params = [])
	{
		$params = http_build_query($params, '', '&');
		$curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));

243 244
		if ($this->verifyPeer !== null) {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
			if($this->capath) {
				curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
			}
			if($this->cainfo) {
				curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
			}
		}

		if ($method == 'POST') {
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
		} elseif ($method == 'HEAD') {
			curl_setopt($curl, CURLOPT_HEADER, true);
			curl_setopt($curl, CURLOPT_NOBODY, true);
		} else {
			curl_setopt($curl, CURLOPT_HTTPGET, true);
		}
		$response = curl_exec($curl);

		if ($method == 'HEAD') {
			$headers = [];
			foreach (explode("\n", $response) as $header) {
267
				$pos = strpos($header, ':');
268 269 270 271 272 273 274 275 276 277 278 279 280
				$name = strtolower(trim(substr($header, 0, $pos)));
				$headers[$name] = trim(substr($header, $pos+1));
			}
			return $headers;
		}

		if (curl_errno($curl)) {
			throw new Exception(curl_error($curl), curl_errno($curl));
		}

		return $response;
	}

281 282 283 284 285 286 287 288 289
	/**
	 * Sends HTTP request.
	 * @param string $url request URL.
	 * @param string $method request method.
	 * @param array $params request params.
	 * @return array|string response.
	 * @throws \yii\base\Exception on failure.
	 * @throws \yii\base\NotSupportedException if request method is not supported.
	 */
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	protected function sendStreamRequest($url, $method = 'GET', $params = [])
	{
		if (!$this->hostExists($url)) {
			throw new Exception('Invalid request.');
		}

		$params = http_build_query($params, '', '&');
		switch ($method) {
			case 'GET':
				$options = [
					'http' => [
						'method' => 'GET',
						'header' => 'Accept: application/xrds+xml, */*',
						'ignore_errors' => true,
					]
				];
				$url = $url . ($params ? '?' . $params : '');
				break;
			case 'POST':
				$options = [
					'http' => [
						'method' => 'POST',
						'header'  => 'Content-type: application/x-www-form-urlencoded',
						'content' => $params,
						'ignore_errors' => true,
					]
				];
				break;
			case 'HEAD':
319 320 321
				/* We want to send a HEAD request,
				but since get_headers doesn't accept $context parameter,
				we have to change the defaults.*/
322 323 324 325 326 327 328 329 330 331
				$default = stream_context_get_options(stream_context_get_default());
				stream_context_get_default([
					'http' => [
						'method' => 'HEAD',
						'header' => 'Accept: application/xrds+xml, */*',
						'ignore_errors' => true,
					]
				]);

				$url = $url . ($params ? '?' . $params : '');
332 333
				$headersTmp = get_headers($url);
				if (empty($headersTmp)) {
334 335 336
					return [];
				}

337
				// Parsing headers.
338
				$headers = [];
339
				foreach ($headersTmp as $header) {
340 341
					$pos = strpos($header, ':');
					$name = strtolower(trim(substr($header, 0, $pos)));
342
					$headers[$name] = trim(substr($header, $pos + 1));
343 344
				}

345
				// and restore them
346 347 348 349 350 351
				stream_context_get_default($default);
				return $headers;
			default:
				throw new NotSupportedException("Method {$method} not supported");
		}

352
		if ($this->verifyPeer) {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
			$options = array_merge(
				$options,
				[
					'ssl' => [
						'verify_peer' => true,
						'capath' => $this->capath,
						'cafile' => $this->cainfo,
					]
				]
			);
		}

		$context = stream_context_create($options);
		return file_get_contents($url, false, $context);
	}

369 370 371 372 373 374 375
	/**
	 * Sends request to the server
	 * @param string $url request URL.
	 * @param string $method request method.
	 * @param array $params request parameters.
	 * @return array|string response.
	 */
376 377 378 379 380 381 382 383
	protected function sendRequest($url, $method = 'GET', $params = [])
	{
		if (function_exists('curl_init') && !ini_get('safe_mode')) {
			return $this->sendCurlRequest($url, $method, $params);
		}
		return $this->sendStreamRequest($url, $method, $params);
	}

384 385 386 387 388 389 390
	/**
	 * Combines given URLs into single one.
	 * @param string $baseUrl base URL.
	 * @param string|array $additionalUrl additional URL string or information array.
	 * @return string composed URL.
	 */
	protected function buildUrl($baseUrl, $additionalUrl)
391
	{
392 393 394 395 396 397 398
		$baseUrl = parse_url($baseUrl);
		if (!is_array($additionalUrl)) {
			$additionalUrl = parse_url($additionalUrl);
		}

		if (isset($baseUrl['query'], $additionalUrl['query'])) {
			$additionalUrl['query'] = $baseUrl['query'] . '&' . $additionalUrl['query'];
399 400
		}

401 402 403 404 405 406 407 408 409 410
		$urlInfo = array_merge($baseUrl, $additionalUrl);
		$url = $urlInfo['scheme'] . '://'
			. (empty($urlInfo['username']) ? ''
				:(empty($urlInfo['password']) ? "{$urlInfo['username']}@"
					:"{$urlInfo['username']}:{$urlInfo['password']}@"))
			. $urlInfo['host']
			. (empty($urlInfo['port']) ? '' : ":{$urlInfo['port']}")
			. (empty($urlInfo['path']) ? '' : $urlInfo['path'])
			. (empty($urlInfo['query']) ? '' : "?{$urlInfo['query']}")
			. (empty($urlInfo['fragment']) ? '' : "#{$urlInfo['fragment']}");
411 412 413 414
		return $url;
	}

	/**
415 416 417 418 419 420 421 422 423
	 * Scans content for <meta>/<link> tags and extract information from them.
	 * @param string $content HTML content to be be parsed.
	 * @param string $tag name of the source tag.
	 * @param string $matchAttributeName name of the source tag attribute, which should contain $matchAttributeValue
	 * @param string $matchAttributeValue required value of $matchAttributeName
	 * @param string $valueAttributeName name of the source tag attribute, which should contain searched value.
	 * @return string|boolean searched value, "false" on failure.
	 */
	protected function extractHtmlTagValue($content, $tag, $matchAttributeName, $matchAttributeValue, $valueAttributeName)
424
	{
425 426
		preg_match_all("#<{$tag}[^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*$valueAttributeName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
		preg_match_all("#<{$tag}[^>]*$valueAttributeName=['\"](.+?)['\"][^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*/?>#i", $content, $matches2);
427 428 429 430 431
		$result = array_merge($matches1[1], $matches2[1]);
		return empty($result) ? false : $result[0];
	}

	/**
432
	 * Performs Yadis and HTML discovery.
433
	 * @param string $url Identity URL.
434 435 436
	 * @return array OpenID provider info, following keys will be available:
	 * - 'url' - string OP Endpoint (i.e. OpenID provider address).
	 * - 'version' - integer OpenID protocol version used by provider.
437 438
	 * - 'identity' - string identity value.
	 * - 'identifier_select' - boolean whether to request OP to select identity for an user in OpenID 2, does not affect OpenID 1.
439 440
	 * - 'ax' - boolean whether AX attributes should be used.
	 * - 'sreg' - boolean whether SREG attributes should be used.
441
	 * @throws Exception on failure.
442 443 444
	 */
	public function discover($url)
	{
445
		if (empty($url)) {
446 447
			throw new Exception('No identity supplied.');
		}
448 449 450
		$result = [
			'url' => null,
			'version' => null,
451 452
			'identity' => $url,
			'identifier_select' => false,
453 454 455 456
			'ax' => false,
			'sreg' => false,
		];

457 458 459 460 461
		// Use xri.net proxy to resolve i-name identities
		if (!preg_match('#^https?:#', $url)) {
			$url = 'https://xri.net/' . $url;
		}

462 463 464
		/* We save the original url in case of Yadis discovery failure.
		It can happen when we'll be lead to an XRDS document
		which does not have any OpenID2 services.*/
465 466
		$originalUrl = $url;

467
		// A flag to disable yadis discovery in case of failure in headers.
468 469
		$yadis = true;

470
		// We'll jump a maximum of 5 times, to avoid endless redirections.
471 472 473 474 475 476
		for ($i = 0; $i < 5; $i ++) {
			if ($yadis) {
				$headers = $this->sendRequest($url, 'HEAD');

				$next = false;
				if (isset($headers['x-xrds-location'])) {
477
					$url = $this->buildUrl($url, trim($headers['x-xrds-location']));
478 479 480 481 482 483 484
					$next = true;
				}

				if (isset($headers['content-type'])
					&& (strpos($headers['content-type'], 'application/xrds+xml') !== false
						|| strpos($headers['content-type'], 'text/xml') !== false)
				) {
485 486 487 488 489
					/* Apparently, some providers return XRDS documents as text/html.
					While it is against the spec, allowing this here shouldn't break
					compatibility with anything.
					---
					Found an XRDS document, now let's find the server, and optionally delegate.*/
490 491 492 493
					$content = $this->sendRequest($url, 'GET');

					preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
					foreach ($m[1] as $content) {
494
						$content = ' ' . $content; // The space is added, so that strpos doesn't return 0.
495

496
						// OpenID 2
497 498 499
						$ns = preg_quote('http://specs.openid.net/auth/2.0/');
						if (preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
							if ($type[1] == 'server') {
500
								$result['identifier_select'] = true;
501 502 503 504 505
							}

							preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
							preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
							if (empty($server)) {
506
								throw new Exception('No servers found!');
507
							}
508
							// Does the server advertise support for either AX or SREG?
509 510
							$result['ax'] = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
							$result['sreg'] = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
511 512 513

							$server = $server[1];
							if (isset($delegate[2])) {
514
								$result['identity'] = trim($delegate[2]);
515 516
							}

517 518 519
							$result['url'] = $server;
							$result['version'] = 2;
							return $result;
520 521
						}

522
						// OpenID 1.1
523 524 525 526 527
						$ns = preg_quote('http://openid.net/signon/1.1');
						if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
							preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
							preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
							if (empty($server)) {
528
								throw new Exception('No servers found!');
529
							}
530
							// AX can be used only with OpenID 2.0, so checking only SREG
531
							$result['sreg'] = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
532 533 534

							$server = $server[1];
							if (isset($delegate[1])) {
535
								$result['identity'] = $delegate[1];
536 537
							}

538 539 540
							$result['url'] = $server;
							$result['version'] = 1;
							return $result;
541 542 543 544 545 546 547 548 549 550 551 552 553
						}
					}

					$next = true;
					$yadis = false;
					$url = $originalUrl;
					$content = null;
					break;
				}
				if ($next) {
					continue;
				}

554
				// There are no relevant information in headers, so we search the body.
555 556 557
				$content = $this->sendRequest($url, 'GET');
				$location = $this->extractHtmlTagValue($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
				if ($location) {
558
					$url = $this->buildUrl($url, $location);
559 560 561 562 563 564 565 566
					continue;
				}
			}

			if (!isset($content)) {
				$content = $this->sendRequest($url, 'GET');
			}

567
			// At this point, the YADIS Discovery has failed, so we'll switch to openid2 HTML discovery, then fallback to openid 1.1 discovery.
568 569
			$server = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid2.provider', 'href');
			if (!$server) {
570
				// The same with openid 1.1
571
				$server = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid.server', 'href');
572
				$delegate = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid.delegate', 'href');
573 574 575 576
				$version = 1;
			} else {
				$delegate = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid2.local_id', 'href');
				$version = 2;
577 578 579
			}

			if ($server) {
580
				// We found an OpenID2 OP Endpoint
581
				if ($delegate) {
582
					// We have also found an OP-Local ID.
583
					$result['identity'] = $delegate;
584
				}
585 586 587
				$result['url'] = $server;
				$result['version'] = $version;
				return $result;
588 589 590 591 592 593
			}
			throw new Exception('No servers found!');
		}
		throw new Exception('Endless redirection!');
	}

594 595 596 597 598
	/**
	 * Composes SREG request parameters.
	 * @return array SREG parameters.
	 */
	protected function buildSregParams()
599 600
	{
		$params = [];
601
		/* We always use SREG 1.1, even if the server is advertising only support for 1.0.
munawer-t committed
602
		That's because it's fully backwards compatible with 1.0, and some providers
603
		advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com */
604
		$params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
605
		if (!empty($this->requiredAttributes)) {
606
			$params['openid.sreg.required'] = [];
607
			foreach ($this->requiredAttributes as $required) {
608
				if (!isset($this->axToSregMap[$required])) {
609 610
					continue;
				}
611
				$params['openid.sreg.required'][] = $this->axToSregMap[$required];
612 613 614 615
			}
			$params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
		}

616
		if (!empty($this->optionalAttributes)) {
617
			$params['openid.sreg.optional'] = [];
618 619
			foreach ($this->optionalAttributes as $optional) {
				if (!isset($this->axToSregMap[$optional])) {
620 621
					continue;
				}
622
				$params['openid.sreg.optional'][] = $this->axToSregMap[$optional];
623 624 625 626 627 628
			}
			$params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
		}
		return $params;
	}

629 630 631 632 633
	/**
	 * Composes AX request parameters.
	 * @return array AX parameters.
	 */
	protected function buildAxParams()
634 635
	{
		$params = [];
636
		if (!empty($this->requiredAttributes) || !empty($this->optionalAttributes)) {
637 638
			$params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
			$params['openid.ax.mode'] = 'fetch_request';
639
			$aliases = [];
640
			$counts = [];
641 642
			$requiredAttributes = [];
			$optionalAttributes = [];
643
			foreach (['requiredAttributes', 'optionalAttributes'] as $type) {
644 645 646 647
				foreach ($this->$type as $alias => $field) {
					if (is_int($alias)) {
						$alias = strtr($field, '/', '_');
					}
648
					$aliases[$alias] = 'http://axschema.org/' . $field;
649 650 651 652 653 654 655
					if (empty($counts[$alias])) {
						$counts[$alias] = 0;
					}
					$counts[$alias] += 1;
					${$type}[] = $alias;
				}
			}
656
			foreach ($aliases as $alias => $ns) {
657 658 659 660 661 662 663 664 665
				$params['openid.ax.type.' . $alias] = $ns;
			}
			foreach ($counts as $alias => $count) {
				if ($count == 1) {
					continue;
				}
				$params['openid.ax.count.' . $alias] = $count;
			}

munawer-t committed
666
			// Don't send empty ax.required and ax.if_available.
667
			// Google and possibly other providers refuse to support ax when one of these is empty.
668 669
			if (!empty($requiredAttributes)) {
				$params['openid.ax.required'] = implode(',', $requiredAttributes);
670
			}
671 672
			if (!empty($optionalAttributes)) {
				$params['openid.ax.if_available'] = implode(',', $optionalAttributes);
673 674 675 676 677
			}
		}
		return $params;
	}

678 679
	/**
	 * Builds authentication URL for the protocol version 1.
680
	 * @param array $serverInfo OpenID server info.
681 682
	 * @return string authentication URL.
	 */
683
	protected function buildAuthUrlV1($serverInfo)
684
	{
685
		$returnUrl = $this->getReturnUrl();
686 687 688
		/* If we have an openid.delegate that is different from our claimed id,
		we need to somehow preserve the claimed id between requests.
		The simplest way is to just send it along with the return_to url.*/
689 690
		if ($serverInfo['identity'] != $this->getClaimedId()) {
			$returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->getClaimedId();
691 692 693 694 695 696
		}

		$params = array_merge(
			[
				'openid.return_to' => $returnUrl,
				'openid.mode' => 'checkid_setup',
697
				'openid.identity' => $serverInfo['identity'],
698
				'openid.trust_root' => $this->trustRoot,
699 700
			],
			$this->buildSregParams()
701 702
		);

703
		return $this->buildUrl($serverInfo['url'], ['query' => http_build_query($params, '', '&')]);
704 705
	}

706 707
	/**
	 * Builds authentication URL for the protocol version 2.
708
	 * @param array $serverInfo OpenID server info.
709 710
	 * @return string authentication URL.
	 */
711
	protected function buildAuthUrlV2($serverInfo)
712 713 714 715
	{
		$params = [
			'openid.ns' => 'http://specs.openid.net/auth/2.0',
			'openid.mode' => 'checkid_setup',
716 717
			'openid.return_to' => $this->getReturnUrl(),
			'openid.realm' => $this->getTrustRoot(),
718
		];
719
		if ($serverInfo['ax']) {
720
			$params = array_merge($params, $this->buildAxParams());
721
		}
722
		if ($serverInfo['sreg']) {
723
			$params = array_merge($params, $this->buildSregParams());
724
		}
725
		if (!$serverInfo['ax'] && !$serverInfo['sreg']) {
726
			// If OP doesn't advertise either SREG, nor AX, let's send them both in worst case we don't get anything in return.
727
			$params = array_merge($this->buildSregParams(), $this->buildAxParams(), $params);
728 729
		}

730
		if ($serverInfo['identifier_select']) {
731 732 733 734
			$url = 'http://specs.openid.net/auth/2.0/identifier_select';
			$params['openid.identity'] = $url;
			$params['openid.claimed_id']= $url;
		} else {
735
			$params['openid.identity'] = $serverInfo['identity'];
736
			$params['openid.claimed_id'] = $this->getClaimedId();
737
		}
738
		return $this->buildUrl($serverInfo['url'], ['query' => http_build_query($params, '', '&')]);
739 740 741 742
	}

	/**
	 * Returns authentication URL. Usually, you want to redirect your user to it.
743
	 * @param boolean $identifierSelect whether to request OP to select identity for an user in OpenID 2, does not affect OpenID 1.
744
	 * @return string the authentication URL.
745
	 * @throws Exception on failure.
746
	 */
747
	public function buildAuthUrl($identifierSelect = null)
748
	{
749 750 751 752 753 754
		$authUrl = $this->authUrl;
		$claimedId = $this->getClaimedId();
		if (empty($claimedId)) {
			$this->setClaimedId($authUrl);
		}
		$serverInfo = $this->discover($authUrl);
755 756
		if ($serverInfo['version'] == 2) {
			if ($identifierSelect !== null) {
757
				$serverInfo['identifier_select'] = $identifierSelect;
758
			}
759
			return $this->buildAuthUrlV2($serverInfo);
760
		}
761
		return $this->buildAuthUrlV1($serverInfo);
762 763 764 765
	}

	/**
	 * Performs OpenID verification with the OP.
766
	 * @param boolean $validateRequiredAttributes whether to validate required attributes.
767 768
	 * @return boolean whether the verification was successful.
	 */
769
	public function validate($validateRequiredAttributes = true)
770
	{
771 772 773 774
		$claimedId = $this->getClaimedId();
		if (empty($claimedId)) {
			return false;
		}
775 776 777 778 779 780 781
		$params = [
			'openid.assoc_handle' => $this->data['openid_assoc_handle'],
			'openid.signed' => $this->data['openid_signed'],
			'openid.sig' => $this->data['openid_sig'],
		];

		if (isset($this->data['openid_ns'])) {
782 783 784
			/* We're dealing with an OpenID 2.0 server, so let's set an ns
			Even though we should know location of the endpoint,
			we still need to verify it by discovery, so $server is not set here*/
785
			$params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
786
		} elseif (isset($this->data['openid_claimed_id']) && $this->data['openid_claimed_id'] != $this->data['openid_identity']) {
787
			// If it's an OpenID 1 provider, and we've got claimed_id,
788 789
			// we have to append it to the returnUrl, like authUrlV1 does.
			$this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $claimedId;
790 791 792
		}

		if ($this->data['openid_return_to'] != $this->returnUrl) {
793
			// The return_to url must match the url of current request.
794 795 796
			return false;
		}

797
		$serverInfo = $this->discover($claimedId);
798 799 800

		foreach (explode(',', $this->data['openid_signed']) as $item) {
			$value = $this->data['openid_' . str_replace('.', '_', $item)];
801
			$params['openid.' . $item] = $value;
802 803 804 805
		}

		$params['openid.mode'] = 'check_authentication';

806
		$response = $this->sendRequest($serverInfo['url'], 'POST', $params);
807

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
		if (preg_match('/is_valid\s*:\s*true/i', $response)) {
			if ($validateRequiredAttributes) {
				return $this->validateRequiredAttributes();
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

	/**
	 * Checks if all required attributes are present in the server response.
	 * @return boolean whether all required attributes are present.
	 */
	protected function validateRequiredAttributes()
	{
		if (!empty($this->requiredAttributes)) {
			$attributes = $this->fetchAttributes();
			foreach ($this->requiredAttributes as $openIdAttributeName) {
				if (!isset($attributes[$openIdAttributeName])) {
					return false;
				}
			}
		}
		return true;
834 835
	}

836 837 838 839 840
	/**
	 * Gets AX attributes provided by OP.
	 * @return array array of attributes.
	 */
	protected function fetchAxAttributes()
841 842 843
	{
		$alias = null;
		if (isset($this->data['openid_ns_ax']) && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0') {
844
			// It's the most likely case, so we'll check it before
845 846
			$alias = 'ax';
		} else {
847
			// 'ax' prefix is either undefined, or points to another extension, so we search for another prefix
848 849 850 851 852 853 854 855
			foreach ($this->data as $key => $value) {
				if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_' && $value == 'http://openid.net/srv/ax/1.0') {
					$alias = substr($key, strlen('openid_ns_'));
					break;
				}
			}
		}
		if (!$alias) {
856
			// An alias for AX schema has not been found, so there is no AX data in the OP's response
857 858 859 860 861 862 863 864 865 866 867
			return [];
		}

		$attributes = [];
		foreach ($this->data as $key => $value) {
			$keyMatch = 'openid_' . $alias . '_value_';
			if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
				continue;
			}
			$key = substr($key, strlen($keyMatch));
			if (!isset($this->data['openid_' . $alias . '_type_' . $key])) {
868 869 870
				/* OP is breaking the spec by returning a field without
				associated ns. This shouldn't happen, but it's better
				to check, than cause an E_NOTICE.*/
871 872 873 874 875 876 877 878
				continue;
			}
			$key = substr($this->data['openid_' . $alias . '_type_' . $key], strlen('http://axschema.org/'));
			$attributes[$key] = $value;
		}
		return $attributes;
	}

879 880 881 882 883
	/**
	 * Gets SREG attributes provided by OP. SREG names will be mapped to AX names.
	 * @return array array of attributes with keys being the AX schema names, e.g. 'contact/email'
	 */
	protected function fetchSregAttributes()
884
	{
885
		$attributes = [];
886
		$sregToAx = array_flip($this->axToSregMap);
887 888 889 890 891 892 893
		foreach ($this->data as $key => $value) {
			$keyMatch = 'openid_sreg_';
			if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
				continue;
			}
			$key = substr($key, strlen($keyMatch));
			if (!isset($sregToAx[$key])) {
894
				// The field name isn't part of the SREG spec, so we ignore it.
895 896 897 898 899 900
				continue;
			}
			$attributes[$sregToAx[$key]] = $value;
		}
		return $attributes;
	}
901

902
	/**
903
	 * Gets AX/SREG attributes provided by OP. Should be used only after successful validation.
904 905 906 907 908 909 910
	 * Note that it does not guarantee that any of the required/optional parameters will be present,
	 * or that there will be no other attributes besides those specified.
	 * In other words. OP may provide whatever information it wants to.
	 * SREG names will be mapped to AX names.
	 * @return array array of attributes with keys being the AX schema names, e.g. 'contact/email'
	 * @see http://www.axschema.org/types/
	 */
911
	public function fetchAttributes()
912 913
	{
		if (isset($this->data['openid_ns']) && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0') {
914 915
			// OpenID 2.0
			// We search for both AX and SREG attributes, with AX taking precedence.
916
			return array_merge($this->fetchSregAttributes(), $this->fetchAxAttributes());
917
		}
918
		return $this->fetchSregAttributes();
919
	}
920 921 922 923 924 925 926 927

	/**
	 * @inheritdoc
	 */
	protected function initUserAttributes()
	{
		return array_merge(['id' => $this->getClaimedId()], $this->fetchAttributes());
	}
928
}