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
			}
		}
	}
	
haemmer's avatar
haemmer committed
204
	// Output result
205 206 207 208
	$infoMsg = "Successfully parsed metadata file ".$metadataFile. " ";
	$infoMsg .= "(".count($metadataIDProviders)." IdPs, ";
	$infoMsg .= " ".count($metadataSProviders)." SPs, ";
	$infoMsg .=  ($hiddenIdPs > 0) ? $hiddenIdPs." IdPs are hidden)" : "no hidden IdPs)" ;
209
	
210
	if (isRunViaCLI() && isset($verbose) && $verbose){
haemmer's avatar
haemmer committed
211 212
		echo $infoMsg."\n";
	} else {
haemmer's avatar
haemmer committed
213
		logInfo($infoMsg);
haemmer's avatar
haemmer committed
214 215
	}
	
216
	return Array($metadataIDProviders, $metadataSProviders);
haemmer's avatar
haemmer committed
217 218
}

219 220 221
// Processes an IDPRoleDescriptor XML node and returns an IDP entry or false if 
// something went wrong
function processIDPRoleDescriptor($IDPRoleDescriptorNode){
222
	global $defaultLanguage, $supportHideFromDiscoveryEntityCategory;
haemmer's avatar
haemmer committed
223
	
224
	$IDP = Array();
haemmer's avatar
haemmer committed
225
	$Profiles = Array();
226 227 228 229 230 231 232 233 234
	
	// Skip Idp if it has the Hide-From-Discovery entity 
	// category attribute
	if (!isset($supportHideFromDiscoveryEntityCategory) || $supportHideFromDiscoveryEntityCategory){
		if (hasHideFromDiscoveryEntityCategory($IDPRoleDescriptorNode)){
			return false;
		}
	}
	
235 236 237
	// Get SSO URL
	$SSOServices = $IDPRoleDescriptorNode->getElementsByTagNameNS( 'urn:oasis:names:tc:SAML:2.0:metadata', 'SingleSignOnService' );
	foreach( $SSOServices as $SSOService ){
haemmer's avatar
haemmer committed
238
	  $Profiles[$SSOService->getAttribute('Binding')] = $SSOService->getAttribute('Location');
239 240
	}
	
haemmer's avatar
haemmer committed
241
	// Set SAML1 SSO URL
haemmer's avatar
haemmer committed
242
	if (isset($Profiles['urn:mace:shibboleth:1.0:profiles:AuthnRequest'])) {
haemmer's avatar
haemmer committed
243
		$IDP['SSO'] = $Profiles['urn:mace:shibboleth:1.0:profiles:AuthnRequest'];
haemmer's avatar
haemmer committed
244
	} else if (isset($Profiles['urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'])) {
haemmer's avatar
haemmer committed
245 246
		$IDP['SSO'] = $Profiles['urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'];
	} else {
247
		$IDP['SSO'] = 'https://no.saml1.or.saml2.sso.url.defined.com/error';
248 249
	}
	
250 251 252 253 254 255 256 257
	// First get MDUI name
	$MDUIDisplayNames = getMDUIDisplayNames($IDPRoleDescriptorNode);
	if (count($MDUIDisplayNames)){
		$IDP['Name'] = current($MDUIDisplayNames);
	}
	foreach ($MDUIDisplayNames as $lang => $value){
		$IDP[$lang]['Name'] = $value;
	}
258
	
259 260 261 262
	// Then try organization names 
	if (empty($IDP['Name'])){
		$OrgnizationNames = getOrganizationNames($IDPRoleDescriptorNode);
		$IDP['Name'] = current($OrgnizationNames);
haemmer's avatar
haemmer committed
263
		
264 265
		foreach ($OrgnizationNames as $lang => $value){
			$IDP[$lang]['Name'] = $value;
266
		}
267 268 269 270
	} 
	
	// As last resort, use entityID
	if (empty($IDP['Name'])){
271 272 273
		$IDP['Name'] = $IDPRoleDescriptorNode->parentNode->getAttribute('entityID');
	}
	
274 275 276 277 278 279 280 281 282 283 284
	// 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;
	
285 286 287 288 289 290
	// Get keywords
	$MDUIKeywords = getMDUIKeywords($IDPRoleDescriptorNode);
	foreach ($MDUIKeywords as $lang => $keywords){
		$IDP[$lang]['Keywords'] = $keywords;
	}
	
haemmer's avatar
haemmer committed
291 292 293 294
	// Get Logos
	$MDUILogos = getMDUILogos($IDPRoleDescriptorNode);
	foreach ($MDUILogos as $Logo){
		// Skip non-favicon logos
haemmer's avatar
haemmer committed
295
		if ($Logo['Height'] != 16 || $Logo['Width'] != 16 ){
haemmer's avatar
haemmer committed
296 297 298
			continue;
		}
		
haemmer's avatar
haemmer committed
299 300 301 302 303 304
		// Strip height and width
		unset($Logo['Height']);
		unset($Logo['Width']);
		
		if ($Logo['Lang'] == ''){
			unset($Logo['Lang']);
haemmer's avatar
haemmer committed
305 306
			$IDP['Logo'] = $Logo;
		} else {
haemmer's avatar
haemmer committed
307 308
			$lang = $Logo['Lang'];
			unset($Logo['Lang']);
haemmer's avatar
haemmer committed
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 334 335 336
			$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;
	}
	
337 338 339 340 341 342
	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
343 344
	global $defaultLanguage;

345 346 347 348 349 350 351 352 353 354
	$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');
		}
	}
	
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 383 384 385
	// 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'];
	}
	
386 387 388 389 390 391
	// 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');
	}
	
392 393 394 395
	// Get supported protocols
	$protocols = $SPRoleDescriptorNode->getAttribute('protocolSupportEnumeration');
	$SP['Protocols'] = $protocols;
	
396 397 398 399 400 401
	// Get keywords
	$MDUIKeywords = getMDUIKeywords($SPRoleDescriptorNode);
	foreach ($MDUIKeywords as $lang => $keywords){
		$SP[$lang]['Keywords'] = $keywords;
	}
	
402 403 404 405 406 407 408
	return $SP;
}

// Dump variable to a file 
function dumpFile($dumpFile, $providers, $variableName){
	 
	if(($fp = fopen($dumpFile, 'w')) !== false){
409 410 411
		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
412
		
413 414 415 416 417
		fwrite($fp, '$'.$variableName.' = ');
		fwrite($fp, var_export($providers,true));
		
		fwrite($fp, "\n?>");
			
418
		fclose($fp);
haemmer's avatar
haemmer committed
419
	} else {
haemmer's avatar
haemmer committed
420 421 422 423
		$errorMsg = 'Could not open file '.$dumpFile.' for writting';
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
haemmer's avatar
haemmer committed
424
			logInfo($errorMsg);
haemmer's avatar
haemmer committed
425
		}
haemmer's avatar
haemmer committed
426 427 428 429 430 431 432 433 434 435 436 437
	}
}

// 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
438 439
	$allIDPS = $metadataIDProviders;
	$mergedArray = Array();
haemmer's avatar
haemmer committed
440
	if ($includeLocalConfEntries) {
haemmer's avatar
haemmer committed
441
		$allIDPS = array_merge($metadataIDProviders, $IDProviders);
haemmer's avatar
haemmer committed
442
	}
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	
	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
463
			} else {
464 465
					// Entry only exists in local IDProviders file
					$mergedArray[$allIDPsKey] = $IDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
466
			}
haemmer's avatar
haemmer committed
467
		} else {
468 469
			// Entry doesnt exist in in local IDProviders.conf.php
			$mergedArray[$allIDPsKey] = $metadataIDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
470 471 472 473 474 475
		}
	}
	
	return $mergedArray;
}

476 477 478 479 480 481 482 483
// 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
484
		$Entity[$lang] = trimToSingleLine($MDUIDisplayName->nodeValue);
485 486 487 488 489
	}
	
	return $Entity;
}

490 491 492 493 494 495 496 497
// 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
498
		$Entity[$lang] = trimToSingleLine($MDUIKeywordEntry->nodeValue);
499 500 501 502
	}
	
	return $Entity;
}
haemmer's avatar
haemmer committed
503 504 505 506 507 508 509 510

// 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
511 512 513 514
		$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
515 516 517 518 519 520 521 522 523 524 525 526 527
		$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
528
		$Entity[] = trimToSingleLine($SAMLAttributeValuesEntry->nodeValue);
haemmer's avatar
haemmer committed
529 530 531 532 533 534 535 536 537 538 539 540
	}
	
	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
541 542 543 544
		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
545 546 547 548 549 550 551 552 553 554 555 556 557
		}
	}
	
	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
558
		$Entity[] = trimToSingleLine($MDUIDomainHintEntry->nodeValue);
haemmer's avatar
haemmer committed
559 560 561 562 563 564 565 566 567 568 569 570
	}
	
	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
571 572
		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
573 574 575 576 577 578
		}
	}
	
	return $Entity;
}

579 580 581 582 583 584 585 586 587 588
// 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
589
			$Entity[$lang] = trimToSingleLine($DisplayName->nodeValue);
590 591 592 593 594 595
		}
	}
	
	return $Entity;
}

haemmer's avatar
haemmer committed
596
// Get Attribute Consuming Service
597 598 599 600
function getAttributeConsumingServiceNames($RoleDescriptorNode){
	
	$Entity = Array();
	
601 602 603
	$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
604
		$Entity[$lang] = trimToSingleLine($ServiceName->nodeValue);
605 606 607 608 609
	}
	
	return $Entity;
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
// 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;
}