readMetadata.php 20.2 KB
Newer Older
Lukas Haemmerle's avatar
Lukas Haemmerle committed
1
<?php // Copyright (c) 2018, SWITCH
haemmer's avatar
haemmer committed
2

3 4 5 6
function updateMetadata() {
	global $metadataLockFile, $metadataIDPFile, $metadataSPFile;
	global $metadataFile, $defaultLanguage;
	global $SAML2MetaOverLocalConf, $includeLocalConfEntries;
7
	global $verbose, $IDProviders, $SProviders;
8
	
9 10 11
	// Open the metadata lock file.
	if (($lockFp = fopen($metadataLockFile, 'a+')) === false) {
		$errorMsg = 'Could not open lock file '.$metadataLockFile;
haemmer's avatar
haemmer committed
12
		logError($errorMsg);
13
		return false;
14
	}
haemmer's avatar
haemmer committed
15 16 17 18 19 20
	
	// Check that $IDProviders exists
	if (!isset($IDProviders) or !is_array($IDProviders)){
		$IDProviders = array();
	}
	
21 22 23 24 25 26 27 28 29 30 31 32 33
	if (!file_exists($metadataIDPFile) or filemtime($metadataFile) > filemtime($metadataIDPFile)) {

		// Get an exclusive lock to regenerate the IdP and SP files
		// from the metadata file.
		if (flock($lockFp, LOCK_EX) === false) {
			$errorMsg = 'Could not get exclusive lock on '.$metadataLockFile;
			logError($errorMsg);
			fclose($lockFp);
			return false;
		}

		// parse metadata file
		list($metadataIDProviders, $metadataSProviders) = parseMetadata($metadataFile, $defaultLanguage);
haemmer's avatar
haemmer committed
34
	
35 36
		if ($metadataIDProviders != false && is_array($metadataIDProviders)){
			dumpFile($metadataIDPFile, $metadataIDProviders, 'metadataIDProviders');
37
		}
haemmer's avatar
haemmer committed
38
	
39 40 41 42 43 44
		if ($metadataSProviders != false && is_array($metadataSProviders)){
			dumpFile($metadataSPFile, $metadataSProviders, 'metadataSProviders');
		}

		// release the exclusive lock
		flock($lockFp, LOCK_UN);
haemmer's avatar
haemmer committed
45 46
		
		// Now merge IDPs from metadata and static file
47 48
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
49 50
		// There is no static file for SPs, use metadata only
		$SProviders = $metadataSProviders;
51 52 53

	} elseif (file_exists($metadataIDPFile)) {

54 55
		// Get a shared lock to read the IdP and SP files
		// generated from the metadata file.
56 57 58 59 60
		if (flock($lockFp, LOCK_SH) === false) {
			$errorMsg = 'Could not lock file '.$metadataLockFile;
			logError($errorMsg);
			fclose($lockFp);
			return false;
61
		}
haemmer's avatar
haemmer committed
62
		
63
		// Read SP and IDP files generated with metadata
haemmer's avatar
haemmer committed
64
		require($metadataIDPFile);
65
		require($metadataSPFile);
66
		
67
		// Release the lock.
68
		flock($lockFp, LOCK_UN);
haemmer's avatar
haemmer committed
69
		
70 71 72
		// Now merge IDPs from metadata and static file
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
73 74
		// There is no static file for SPs, use metadata only
		$SProviders = $metadataSProviders;
75
	}
haemmer's avatar
haemmer committed
76
	
77
	// Close the metadata lock file.
78
	fclose($lockFp);
haemmer's avatar
haemmer committed
79 80
}

81 82
// Function parseMetadata, parses metadata file and returns Array($IdPs, SPs)  or
// Array(false, false) if error occurs while parsing metadata file
haemmer's avatar
haemmer committed
83
function parseMetadata($metadataFile, $defaultLanguage){
84
	global $supportHideFromDiscoveryEntityCategory;
haemmer's avatar
haemmer committed
85
	
86
	if(!file_exists($metadataFile)){
haemmer's avatar
haemmer committed
87
		$errorMsg = 'File '.$metadataFile." does not exist"; 
88
		if (isRunViaCLI()){
haemmer's avatar
haemmer committed
89
			echo $errorMsg."\n";
90
		} else {
haemmer's avatar
haemmer committed
91
			logError($errorMsg);
92 93 94 95 96
		}
		return Array(false, false);
	}

	if(!is_readable($metadataFile)){
haemmer's avatar
haemmer committed
97 98 99 100
		$errorMsg = 'File '.$metadataFile." cannot be read due to insufficient permissions"; 
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
haemmer's avatar
haemmer committed
101
			logError($errorMsg);
haemmer's avatar
haemmer committed
102
		}
103 104
		return Array(false, false);
	}
haemmer's avatar
haemmer committed
105
	
haemmer's avatar
haemmer committed
106 107
	$CurrentXMLReaderNode = new XMLReader();
	if(!$CurrentXMLReaderNode->open($metadataFile, null, LIBXML_PARSEHUGE | LIBXML_NOERROR | LIBXML_NOWARNING | 1)){
haemmer's avatar
haemmer committed
108 109 110 111
		$errorMsg = 'Could not parse metadata file '.$metadataFile; 
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
haemmer's avatar
haemmer committed
112
			logError($errorMsg);
haemmer's avatar
haemmer committed
113
		}
114 115 116
		return Array(false, false);
	}
	
haemmer's avatar
haemmer committed
117 118 119
	// Go to first element and check it is named 'EntitiesDescriptor'
	// If not it's probably not a valid SAML metadata file
	$CurrentXMLReaderNode->read();
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	
	// Often there are comments at the beginning of the metadata,
	// this will eat/skip a max #(3) of comments and then hit the 
	// evaluation of the EntitiesDescriptor tweak if necessary
	$maxCommentCount=3;    
	$commentCount=0;
	while ($CurrentXMLReaderNode->localName  == '#comment') {
			$CurrentXMLReaderNode->read();
			// Always have an way to punch out of a while loop & inform the user why
			if ($commentCount++ >=$maxCommentCount){
					$errorMsg= 'This file has exceeded the max # comments of'. $maxCommentCount;
					$errorMsg .=' XML comments before an EntityDescriptor. Are you sure this is a well formed Metadata file?';
					if (isRunViaCLI()){
							echo $errorMsg."\n";
					} else {
							logError($errorMsg);
					}
					return Array(false, false);
			}
	}
	
	// If we arrive here, we have read the first node at very 
	// least and if it's not a comment, it should be an 
	// EntityDescriptor
	// If it WAS 1 or more comments, we will have eaten then up 
	// and the NEXT read will have occurred
	// If this next read of the XML nodes is NOT an 
	// EntitiesDescriptor, (note the plural), we should fail.
	// If the next read of the XML nodes IS an 
	// EntitiesDescriptor, we should proceed stead of 'read again'
haemmer's avatar
haemmer committed
150 151 152 153 154 155 156 157 158 159
	if ($CurrentXMLReaderNode->localName  !== 'EntitiesDescriptor') {
		$errorMsg = 'Metadata file '.$metadataFile.' does not include a root node EntitiesDescriptor'; 
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
			logError($errorMsg);
		}
		return Array(false, false);
	}
	
Lukas Haemmerle's avatar
Lukas Haemmerle committed
160
	// Init variables
161
	$hiddenIdPs = 0;
Lukas Haemmerle's avatar
Lukas Haemmerle committed
162 163
	$metadataIDProviders = array();
	$metadataSProviders = array();
164
	
haemmer's avatar
haemmer committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	// Process individual EntityDescriptors
	while( $CurrentXMLReaderNode->read() ) {
		if($CurrentXMLReaderNode->nodeType == XMLReader::ELEMENT && $CurrentXMLReaderNode->localName  === 'EntityDescriptor') {
			$entityID = $CurrentXMLReaderNode->getAttribute('entityID');
			$EntityDescriptorXML = $CurrentXMLReaderNode->readOuterXML();
			$EntityDescriptorDOM = new DOMDocument();
			$EntityDescriptorDOM->loadXML($EntityDescriptorXML);
			
			// Check role descriptors
			foreach($EntityDescriptorDOM->documentElement->childNodes as $RoleDescriptor) {
				$nodeName = $RoleDescriptor->localName;
				switch($nodeName){
					case 'IDPSSODescriptor':
						$IDP = processIDPRoleDescriptor($RoleDescriptor);
						if ($IDP){
							$metadataIDProviders[$entityID] = $IDP;
181 182
						} else {
							$hiddenIdPs++;
haemmer's avatar
haemmer committed
183 184 185 186 187 188
						}
						break;
					case 'SPSSODescriptor':
						$SP = processSPRoleDescriptor($RoleDescriptor);
						if ($SP){
							$metadataSProviders[$entityID] = $SP;
haemmer's avatar
haemmer committed
189
						} else {
haemmer's avatar
haemmer committed
190 191 192 193 194 195
							$errorMsg = "Failed to load SP with entityID $entityID from metadata file $metadataFile";
							if (isRunViaCLI()){
								echo $errorMsg."\n";
							} else {
								logWarning($errorMsg);
							}
haemmer's avatar
haemmer committed
196
						}
haemmer's avatar
haemmer committed
197 198 199
						break;
					default:
				}
haemmer's avatar
haemmer committed
200 201 202 203
			}
		}
	}
	
204 205 206 207 208 209
	// log result when called by the web application
	if (!isRunViaCLI()){
		$infoMsg = "Successfully parsed metadata file ".$metadataFile. " ";
		$infoMsg .= "(".count($metadataIDProviders)." IdPs, ";
		$infoMsg .= " ".count($metadataSProviders)." SPs, ";
		$infoMsg .=  ($hiddenIdPs > 0) ? $hiddenIdPs." IdPs are hidden)" : "no hidden IdPs)" ;
haemmer's avatar
haemmer committed
210
		logInfo($infoMsg);
haemmer's avatar
haemmer committed
211 212
	}
	
213
	return Array($metadataIDProviders, $metadataSProviders);
haemmer's avatar
haemmer committed
214 215
}

216 217 218
// Processes an IDPRoleDescriptor XML node and returns an IDP entry or false if 
// something went wrong
function processIDPRoleDescriptor($IDPRoleDescriptorNode){
219
	global $defaultLanguage, $supportHideFromDiscoveryEntityCategory;
haemmer's avatar
haemmer committed
220
	
221
	$IDP = Array();
haemmer's avatar
haemmer committed
222
	$Profiles = Array();
223 224 225 226 227 228 229 230 231
	
	// Skip Idp if it has the Hide-From-Discovery entity 
	// category attribute
	if (!isset($supportHideFromDiscoveryEntityCategory) || $supportHideFromDiscoveryEntityCategory){
		if (hasHideFromDiscoveryEntityCategory($IDPRoleDescriptorNode)){
			return false;
		}
	}
	
232 233 234
	// Get SSO URL
	$SSOServices = $IDPRoleDescriptorNode->getElementsByTagNameNS( 'urn:oasis:names:tc:SAML:2.0:metadata', 'SingleSignOnService' );
	foreach( $SSOServices as $SSOService ){
haemmer's avatar
haemmer committed
235
	  $Profiles[$SSOService->getAttribute('Binding')] = $SSOService->getAttribute('Location');
236 237
	}
	
haemmer's avatar
haemmer committed
238
	// Set SAML1 SSO URL
haemmer's avatar
haemmer committed
239
	if (isset($Profiles['urn:mace:shibboleth:1.0:profiles:AuthnRequest'])) {
haemmer's avatar
haemmer committed
240
		$IDP['SSO'] = $Profiles['urn:mace:shibboleth:1.0:profiles:AuthnRequest'];
haemmer's avatar
haemmer committed
241
	} else if (isset($Profiles['urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'])) {
haemmer's avatar
haemmer committed
242 243
		$IDP['SSO'] = $Profiles['urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'];
	} else {
244
		$IDP['SSO'] = 'https://no.saml1.or.saml2.sso.url.defined.com/error';
245 246
	}
	
247 248 249 250 251 252 253 254
	// First get MDUI name
	$MDUIDisplayNames = getMDUIDisplayNames($IDPRoleDescriptorNode);
	if (count($MDUIDisplayNames)){
		$IDP['Name'] = current($MDUIDisplayNames);
	}
	foreach ($MDUIDisplayNames as $lang => $value){
		$IDP[$lang]['Name'] = $value;
	}
255
	
256 257 258 259
	// Then try organization names 
	if (empty($IDP['Name'])){
		$OrgnizationNames = getOrganizationNames($IDPRoleDescriptorNode);
		$IDP['Name'] = current($OrgnizationNames);
haemmer's avatar
haemmer committed
260
		
261 262
		foreach ($OrgnizationNames as $lang => $value){
			$IDP[$lang]['Name'] = $value;
263
		}
264 265 266 267
	} 
	
	// As last resort, use entityID
	if (empty($IDP['Name'])){
268 269 270
		$IDP['Name'] = $IDPRoleDescriptorNode->parentNode->getAttribute('entityID');
	}
	
271 272 273 274 275 276 277 278 279 280 281
	// Set default name
	if (isset($IDP[$defaultLanguage])){
		$IDP['Name'] = $IDP[$defaultLanguage]['Name'];
	} elseif (isset($IDP['en'])){
		$IDP['Name'] = $IDP['en']['Name'];
	}
	
	// Get supported protocols
	$protocols = $IDPRoleDescriptorNode->getAttribute('protocolSupportEnumeration');
	$IDP['Protocols'] = $protocols;
	
282 283 284 285 286 287
	// Get keywords
	$MDUIKeywords = getMDUIKeywords($IDPRoleDescriptorNode);
	foreach ($MDUIKeywords as $lang => $keywords){
		$IDP[$lang]['Keywords'] = $keywords;
	}
	
haemmer's avatar
haemmer committed
288 289 290 291
	// Get Logos
	$MDUILogos = getMDUILogos($IDPRoleDescriptorNode);
	foreach ($MDUILogos as $Logo){
		// Skip non-favicon logos
haemmer's avatar
haemmer committed
292
		if ($Logo['Height'] != 16 || $Logo['Width'] != 16 ){
haemmer's avatar
haemmer committed
293 294 295
			continue;
		}
		
haemmer's avatar
haemmer committed
296 297 298 299 300 301
		// Strip height and width
		unset($Logo['Height']);
		unset($Logo['Width']);
		
		if ($Logo['Lang'] == ''){
			unset($Logo['Lang']);
haemmer's avatar
haemmer committed
302 303
			$IDP['Logo'] = $Logo;
		} else {
haemmer's avatar
haemmer committed
304 305
			$lang = $Logo['Lang'];
			unset($Logo['Lang']);
haemmer's avatar
haemmer committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
			$IDP[$lang]['Logo'] = $Logo;
		}
	}
	
	// Get AttributeValue 
	$SAMLAttributeValues = getSAMLAttributeValues($IDPRoleDescriptorNode);
	if ($SAMLAttributeValues){
		$IDP['AttributeValue'] = $SAMLAttributeValues;
	}
	
	// Get IPHints 
	$MDUIIPHints = getMDUIIPHints($IDPRoleDescriptorNode);
	if ($MDUIIPHints){
		$IDP['IPHint'] = $MDUIIPHints;
	}
	
	// Get DomainHints 
	$MDUIDomainHints = getMDUIDomainHints($IDPRoleDescriptorNode);
	if ($MDUIDomainHints){
		$IDP['DomainHint'] = $MDUIDomainHints;
	}
	
	// Get GeolocationHints 
	$MDUIGeolocationHints = getMDUIGeolocationHints($IDPRoleDescriptorNode);
	if ($MDUIGeolocationHints){
		$IDP['GeolocationHint'] = $MDUIGeolocationHints;
	}
	
334 335 336 337 338 339
	return $IDP;
}

// Processes an SPRoleDescriptor XML node and returns an SP entry or false if 
// something went wrong
function processSPRoleDescriptor($SPRoleDescriptorNode){
haemmer's avatar
haemmer committed
340 341
	global $defaultLanguage;

342 343 344 345 346 347 348 349 350 351
	$SP = Array();
	
	// Get <idpdisc:DiscoveryResponse> extensions
	$DResponses = $SPRoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol', 'DiscoveryResponse');
	foreach( $DResponses as $DResponse ){
		if ($DResponse->getAttribute('Binding') == 'urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol'){
			$SP['DSURL'][] =  $DResponse->getAttribute('Location');
		}
	}
	
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
	// First get MDUI name
	$MDUIDisplayNames = getMDUIDisplayNames($SPRoleDescriptorNode);
	if (count($MDUIDisplayNames)){
		$SP['Name'] = current($MDUIDisplayNames);
	}
	foreach ($MDUIDisplayNames as $lang => $value){
		$SP[$lang]['Name'] = $value;
	}
	
	// Then try attribute consuming service
	if (empty($SP['Name'])){
		$ConsumingServiceNames = getAttributeConsumingServiceNames($SPRoleDescriptorNode);
		$SP['Name'] = current($ConsumingServiceNames);
		
		foreach ($ConsumingServiceNames as $lang => $value){
			$SP[$lang]['Name'] = $value;
		}
	} 
	
	// As last resort, use entityID
	if (empty($SP['Name'])){
		$SP['Name'] = $SPRoleDescriptorNode->parentNode->getAttribute('entityID');
	}
	
	// Set default name
	if (isset($SP[$defaultLanguage])){
		$SP['Name'] = $SP[$defaultLanguage]['Name'];
	} elseif (isset($SP['en'])){
		$SP['Name'] = $SP['en']['Name'];
	}
	
383 384 385 386 387 388
	// Get Assertion Consumer Services and store their hostnames
	$ACServices = $SPRoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'AssertionConsumerService');
	foreach( $ACServices as $ACService ){
		$SP['ACURL'][] =  $ACService->getAttribute('Location');
	}
	
389 390 391 392
	// Get supported protocols
	$protocols = $SPRoleDescriptorNode->getAttribute('protocolSupportEnumeration');
	$SP['Protocols'] = $protocols;
	
393 394 395 396 397 398
	// Get keywords
	$MDUIKeywords = getMDUIKeywords($SPRoleDescriptorNode);
	foreach ($MDUIKeywords as $lang => $keywords){
		$SP[$lang]['Keywords'] = $keywords;
	}
	
399 400 401 402 403 404 405
	return $SP;
}

// Dump variable to a file 
function dumpFile($dumpFile, $providers, $variableName){
	 
	if(($fp = fopen($dumpFile, 'w')) !== false){
406 407 408
		fwrite($fp, "<?php\n\n");
		fwrite($fp, "// This file was automatically generated by readMetadata.php\n");
		fwrite($fp, "// Don't edit!\n\n");
haemmer's avatar
haemmer committed
409
		
410 411 412 413 414
		fwrite($fp, '$'.$variableName.' = ');
		fwrite($fp, var_export($providers,true));
		
		fwrite($fp, "\n?>");
			
415
		fclose($fp);
haemmer's avatar
haemmer committed
416
	} else {
haemmer's avatar
haemmer committed
417 418 419 420
		$errorMsg = 'Could not open file '.$dumpFile.' for writting';
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
haemmer's avatar
haemmer committed
421
			logInfo($errorMsg);
haemmer's avatar
haemmer committed
422
		}
haemmer's avatar
haemmer committed
423 424 425 426 427 428 429 430 431 432 433 434
	}
}

// Function mergeInfo is used to create the effective $IDProviders array.
// For each IDP found in the metadata, merge the values from IDProvider.conf.php.
// If an IDP is found in IDProvider.conf as well as in metadata, use metadata  
// information if $SAML2MetaOverLocalConf is true or else use IDProvider.conf data
function mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries){

	// If $includeLocalConfEntries parameter is set to true, mergeInfo() will also consider IDPs
	// not listed in metadataIDProviders but defined in IDProviders file
	// This is required if you need to add local exceptions over the federation metadata
435 436
	$allIDPS = $metadataIDProviders;
	$mergedArray = Array();
haemmer's avatar
haemmer committed
437
	if ($includeLocalConfEntries) {
haemmer's avatar
haemmer committed
438
		$allIDPS = array_merge($metadataIDProviders, $IDProviders);
haemmer's avatar
haemmer committed
439
	}
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
	
	foreach ($allIDPS as $allIDPsKey => $allIDPsEntry){
		if(isset($IDProviders[$allIDPsKey])){
			// Entry exists also in local IDProviders.conf.php
			if (isset($metadataIDProviders[$allIDPsKey]) && is_array($metadataIDProviders[$allIDPsKey])) {
				
				// Remove IdP if there is a removal rule in local IDProviders.conf.php 
				if (!is_array($IDProviders[$allIDPsKey])){
					unset($metadataIDProviders[$allIDPsKey]);
					continue;
				}
				
				// Entry exists in both IDProviders sources and is an array
				if($SAML2MetaOverLocalConf){
					// Metadata entry overwrite local conf
					$mergedArray[$allIDPsKey] = array_merge($IDProviders[$allIDPsKey], $metadataIDProviders[$allIDPsKey]);
				} else {
					// Local conf overwrites metada entry
					$mergedArray[$allIDPsKey] = array_merge($metadataIDProviders[$allIDPsKey], $IDProviders[$allIDPsKey]);
				}
haemmer's avatar
haemmer committed
460
			} else {
461 462
					// Entry only exists in local IDProviders file
					$mergedArray[$allIDPsKey] = $IDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
463
			}
haemmer's avatar
haemmer committed
464
		} else {
465 466
			// Entry doesnt exist in in local IDProviders.conf.php
			$mergedArray[$allIDPsKey] = $metadataIDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
467 468 469 470 471 472
		}
	}
	
	return $mergedArray;
}

473 474 475 476 477 478 479 480
// Get MD Display Names from RoleDescriptor
function getMDUIDisplayNames($RoleDescriptorNode){
	
	$Entity = Array();
	
	$MDUIDisplayNames = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'DisplayName');
	foreach( $MDUIDisplayNames as $MDUIDisplayName ){
		$lang = $MDUIDisplayName->getAttributeNodeNS('http://www.w3.org/XML/1998/namespace', 'lang')->nodeValue;
haemmer's avatar
haemmer committed
481
		$Entity[$lang] = trimToSingleLine($MDUIDisplayName->nodeValue);
482 483 484 485 486
	}
	
	return $Entity;
}

487 488 489 490 491 492 493 494
// Get MD Keywords from RoleDescriptor
function getMDUIKeywords($RoleDescriptorNode){
	
	$Entity = Array();
	
	$MDUIKeywords = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'Keywords');
	foreach( $MDUIKeywords as $MDUIKeywordEntry ){
		$lang = $MDUIKeywordEntry->getAttributeNodeNS('http://www.w3.org/XML/1998/namespace', 'lang')->nodeValue;
haemmer's avatar
haemmer committed
495
		$Entity[$lang] = trimToSingleLine($MDUIKeywordEntry->nodeValue);
496 497 498 499
	}
	
	return $Entity;
}
haemmer's avatar
haemmer committed
500 501 502 503 504 505 506 507

// Get MD Logos from RoleDescriptor. Prefer the favicon logos
function getMDUILogos($RoleDescriptorNode){
	
	$Logos = Array();
	$MDUILogos = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'Logo');
	foreach( $MDUILogos as $MDUILogoEntry ){
		$Logo = Array();
haemmer's avatar
haemmer committed
508 509 510 511
		$Logo['URL'] = trimToSingleLine($MDUILogoEntry->nodeValue);
		$Logo['Height'] = ($MDUILogoEntry->getAttribute('height') != '') ? trimToSingleLine($MDUILogoEntry->getAttribute('height')) : '16';
		$Logo['Width'] = ($MDUILogoEntry->getAttribute('width') != '') ? trimToSingleLine($MDUILogoEntry->getAttribute('width')) : '16';
		$Logo['Lang'] = ($MDUILogoEntry->getAttribute('lang') != '') ? trimToSingleLine($MDUILogoEntry->getAttribute('lang')) : '';
haemmer's avatar
haemmer committed
512 513 514 515 516 517 518 519 520 521 522 523 524
		$Logos[] = $Logo;
	}
	
	return $Logos;
}

// Get MD Attribute Value(kind) from RoleDescriptor
function getSAMLAttributeValues($RoleDescriptorNode){
	
	$Entity = Array();
	
	$SAMLAttributeValues = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AttributeValue');
	foreach( $SAMLAttributeValues as $SAMLAttributeValuesEntry ){
haemmer's avatar
haemmer committed
525
		$Entity[] = trimToSingleLine($SAMLAttributeValuesEntry->nodeValue);
haemmer's avatar
haemmer committed
526 527 528 529 530 531 532 533 534 535 536 537
	}
	
	return $Entity;
}

// Get MD IP Address Hints from RoleDescriptor
function getMDUIIPHints($RoleDescriptorNode){
	
	$Entity = Array();
	
	$MDUIIPHints = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'IPHint');
	foreach( $MDUIIPHints as $MDUIIPHintEntry ){
haemmer's avatar
haemmer committed
538 539 540 541
		if (preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}$/", trimToSingleLine($MDUIIPHintEntry->nodeValue), $splitIP)){
			$Entity[] = trimToSingleLine($splitIP[0]);
		} elseif (preg_match("/^.*\:.*\/[0-9]{1,2}$/", trimToSingleLine($MDUIIPHintEntry->nodeValue), $splitIP)){ 
			$Entity[] = trimToSingleLine($splitIP[0]);
haemmer's avatar
haemmer committed
542 543 544 545 546 547 548 549 550 551 552 553 554
		}
	}
	
	return $Entity;
}

// Get MD Domain Hints from RoleDescriptor
function getMDUIDomainHints($RoleDescriptorNode){
	
	$Entity = Array();
	
	$MDUIDomainHints = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'DomainHint');
	foreach( $MDUIDomainHints as $MDUIDomainHintEntry ){
haemmer's avatar
haemmer committed
555
		$Entity[] = trimToSingleLine($MDUIDomainHintEntry->nodeValue);
haemmer's avatar
haemmer committed
556 557 558 559 560 561 562 563 564 565 566 567
	}
	
	return $Entity;
}

// Get MD Geolocation Hints from RoleDescriptor
function getMDUIGeolocationHints($RoleDescriptorNode){
	
	$Entity = Array();
	
	$MDUIGeolocationHints = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:metadata:ui', 'GeolocationHint');
	foreach( $MDUIGeolocationHints as $MDUIGeolocationHintEntry ){
haemmer's avatar
haemmer committed
568 569
		if (preg_match("/^geo:([0-9]+\.{0,1}[0-9]*,[0-9]+\.{0,1}[0-9]*)$/", trimToSingleLine($MDUIGeolocationHintEntry->nodeValue), $splitGeo)){
			$Entity[] = trimToSingleLine($splitGeo[1]);
haemmer's avatar
haemmer committed
570 571 572 573 574 575
		}
	}
	
	return $Entity;
}

576 577 578 579 580 581 582 583 584 585
// Get Organization Names from RoleDescriptor
function getOrganizationNames($RoleDescriptorNode){
	
	$Entity = Array();
	
	$Orgnization = $RoleDescriptorNode->parentNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'Organization' )->item(0);
	if ($Orgnization){
		$DisplayNames = $Orgnization->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'OrganizationDisplayName');
		foreach ($DisplayNames as $DisplayName){
			$lang = $DisplayName->getAttributeNodeNS('http://www.w3.org/XML/1998/namespace', 'lang')->nodeValue;
haemmer's avatar
haemmer committed
586
			$Entity[$lang] = trimToSingleLine($DisplayName->nodeValue);
587 588 589 590 591 592
		}
	}
	
	return $Entity;
}

haemmer's avatar
haemmer committed
593
// Get Attribute Consuming Service
594 595 596 597
function getAttributeConsumingServiceNames($RoleDescriptorNode){
	
	$Entity = Array();
	
598 599 600
	$ServiceNames = $RoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'ServiceName' );
	foreach ($ServiceNames as $ServiceName){
		$lang = $ServiceName->getAttributeNodeNS('http://www.w3.org/XML/1998/namespace', 'lang')->nodeValue;
haemmer's avatar
haemmer committed
601
		$Entity[$lang] = trimToSingleLine($ServiceName->nodeValue);
602 603 604 605 606
	}
	
	return $Entity;
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
// Returns true if IdP has Hide-From-Discovery entity category attribute
function hasHideFromDiscoveryEntityCategory($IDPRoleDescriptorNode){
	// Get SAML Attributes for this entity
	$AttributeValues = $IDPRoleDescriptorNode->parentNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AttributeValue');
	
	if (!$AttributeValues || $AttributeValues->length < 1){
		return false;
	}
	
	foreach( $AttributeValues as $AttributeValue ){
		if (trim($AttributeValue->nodeValue) == 'http://refeds.org/category/hide-from-discovery'){
			return true;
		}
	}
	
	return false;
}