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
		$params = $_GET;
		foreach ($params as $name => $value) {
			if (strncmp('openid', $name, 6) === 0) {
				unset($params[$name]);
			}
		}
202 203
		$params[0] = Yii::$app->requestedRoute;
		$url = Yii::$app->getUrlManager()->createUrl($params);
204
		return $this->getTrustRoot() . $url;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
	}

	/**
	 * 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);
	}

226 227 228 229 230 231 232 233
	/**
	 * 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.
	 */
234 235 236 237 238 239 240 241
	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);
AlexGx committed
242
		curl_setopt($curl, CURLOPT_HTTPHEADER, ['Accept: application/xrds+xml, */*']);
243

244 245
		if ($this->verifyPeer !== null) {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer);
AlexGx committed
246
			if ($this->capath) {
247 248
				curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
			}
AlexGx committed
249
			if ($this->cainfo) {
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
				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) {
268
				$pos = strpos($header, ':');
269 270 271 272 273 274 275 276 277 278 279 280 281
				$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;
	}

282 283 284 285 286 287 288 289 290
	/**
	 * 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.
	 */
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 319
	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':
320 321 322
				/* We want to send a HEAD request,
				but since get_headers doesn't accept $context parameter,
				we have to change the defaults.*/
323 324 325 326 327 328 329 330 331 332
				$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 : '');
333 334
				$headersTmp = get_headers($url);
				if (empty($headersTmp)) {
335 336 337
					return [];
				}

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

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

353
		if ($this->verifyPeer) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
			$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);
	}

370 371 372 373 374 375 376
	/**
	 * Sends request to the server
	 * @param string $url request URL.
	 * @param string $method request method.
	 * @param array $params request parameters.
	 * @return array|string response.
	 */
377 378 379 380 381 382 383 384
	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);
	}

385 386 387 388 389 390 391
	/**
	 * 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)
392
	{
393 394 395 396 397 398 399
		$baseUrl = parse_url($baseUrl);
		if (!is_array($additionalUrl)) {
			$additionalUrl = parse_url($additionalUrl);
		}

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

402 403 404 405 406 407 408 409 410 411
		$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']}");
412 413 414 415
		return $url;
	}

	/**
416 417 418 419 420 421 422 423 424
	 * 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)
425
	{
426 427
		preg_match_all("#<{$tag}[^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*$valueAttributeName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
		preg_match_all("#<{$tag}[^>]*$valueAttributeName=['\"](.+?)['\"][^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*/?>#i", $content, $matches2);
428 429 430 431 432
		$result = array_merge($matches1[1], $matches2[1]);
		return empty($result) ? false : $result[0];
	}

	/**
433
	 * Performs Yadis and HTML discovery.
434
	 * @param string $url Identity URL.
435 436 437
	 * @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.
438 439
	 * - '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.
440 441
	 * - 'ax' - boolean whether AX attributes should be used.
	 * - 'sreg' - boolean whether SREG attributes should be used.
442
	 * @throws Exception on failure.
443 444 445
	 */
	public function discover($url)
	{
446
		if (empty($url)) {
447 448
			throw new Exception('No identity supplied.');
		}
449 450 451
		$result = [
			'url' => null,
			'version' => null,
452 453
			'identity' => $url,
			'identifier_select' => false,
454 455 456 457
			'ax' => false,
			'sreg' => false,
		];

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

463 464 465
		/* 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.*/
466 467
		$originalUrl = $url;

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

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

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

				if (isset($headers['content-type'])
					&& (strpos($headers['content-type'], 'application/xrds+xml') !== false
						|| strpos($headers['content-type'], 'text/xml') !== false)
				) {
486 487 488 489 490
					/* 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.*/
491 492 493 494
					$content = $this->sendRequest($url, 'GET');

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

497
						// OpenID 2
498 499 500
						$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') {
501
								$result['identifier_select'] = true;
502 503 504 505 506
							}

							preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
							preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
							if (empty($server)) {
507
								throw new Exception('No servers found!');
508
							}
509
							// Does the server advertise support for either AX or SREG?
510 511
							$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>');
512 513 514

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

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

523
						// OpenID 1.1
524 525 526 527 528
						$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)) {
529
								throw new Exception('No servers found!');
530
							}
531
							// AX can be used only with OpenID 2.0, so checking only SREG
532
							$result['sreg'] = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
533 534 535

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

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

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

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

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

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

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

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

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

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

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

679 680
	/**
	 * Builds authentication URL for the protocol version 1.
681
	 * @param array $serverInfo OpenID server info.
682 683
	 * @return string authentication URL.
	 */
684
	protected function buildAuthUrlV1($serverInfo)
685
	{
686
		$returnUrl = $this->getReturnUrl();
687 688 689
		/* 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.*/
690 691
		if ($serverInfo['identity'] != $this->getClaimedId()) {
			$returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->getClaimedId();
692 693 694 695 696 697
		}

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

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

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

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

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

	/**
	 * Performs OpenID verification with the OP.
767
	 * @param boolean $validateRequiredAttributes whether to validate required attributes.
768 769
	 * @return boolean whether the verification was successful.
	 */
770
	public function validate($validateRequiredAttributes = true)
771
	{
772 773 774 775
		$claimedId = $this->getClaimedId();
		if (empty($claimedId)) {
			return false;
		}
776 777 778 779 780 781 782
		$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'])) {
783 784 785
			/* 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*/
786
			$params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
787
		} elseif (isset($this->data['openid_claimed_id']) && $this->data['openid_claimed_id'] != $this->data['openid_identity']) {
788
			// If it's an OpenID 1 provider, and we've got claimed_id,
789 790
			// we have to append it to the returnUrl, like authUrlV1 does.
			$this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $claimedId;
791 792 793
		}

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

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

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

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

807
		$response = $this->sendRequest($serverInfo['url'], 'POST', $params);
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 834
		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;
835 836
	}

837 838 839 840 841
	/**
	 * Gets AX attributes provided by OP.
	 * @return array array of attributes.
	 */
	protected function fetchAxAttributes()
842 843 844
	{
		$alias = null;
		if (isset($this->data['openid_ns_ax']) && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0') {
845
			// It's the most likely case, so we'll check it before
846 847
			$alias = 'ax';
		} else {
848
			// 'ax' prefix is either undefined, or points to another extension, so we search for another prefix
849 850 851 852 853 854 855 856
			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) {
857
			// An alias for AX schema has not been found, so there is no AX data in the OP's response
858 859 860 861 862 863 864 865 866 867 868
			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])) {
869 870 871
				/* 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.*/
872 873 874 875 876 877 878 879
				continue;
			}
			$key = substr($this->data['openid_' . $alias . '_type_' . $key], strlen('http://axschema.org/'));
			$attributes[$key] = $value;
		}
		return $attributes;
	}

880 881 882 883 884
	/**
	 * 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()
885
	{
886
		$attributes = [];
887
		$sregToAx = array_flip($this->axToSregMap);
888 889 890 891 892 893 894
		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])) {
895
				// The field name isn't part of the SREG spec, so we ignore it.
896 897 898 899 900 901
				continue;
			}
			$attributes[$sregToAx[$key]] = $value;
		}
		return $attributes;
	}
902

903
	/**
904
	 * Gets AX/SREG attributes provided by OP. Should be used only after successful validation.
905 906 907 908 909 910 911
	 * 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/
	 */
912
	public function fetchAttributes()
913 914
	{
		if (isset($this->data['openid_ns']) && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0') {
915 916
			// OpenID 2.0
			// We search for both AX and SREG attributes, with AX taking precedence.
917
			return array_merge($this->fetchSregAttributes(), $this->fetchAxAttributes());
918
		}
919
		return $this->fetchSregAttributes();
920
	}
921 922 923 924 925 926 927 928

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