summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rwxr-xr-xbin/pwgen.php2
-rwxr-xr-xbin/translation.php6
-rw-r--r--composer.json7
-rw-r--r--composer.lock228
-rw-r--r--docs/simplesamlphp-install.txt14
-rw-r--r--docs/simplesamlphp-translation.txt12
-rw-r--r--lib/SimpleSAML/Auth/Default.php16
-rw-r--r--lib/SimpleSAML/Auth/LDAP.php4
-rw-r--r--lib/SimpleSAML/Auth/ProcessingChain.php4
-rw-r--r--lib/SimpleSAML/Auth/Simple.php13
-rw-r--r--lib/SimpleSAML/Auth/State.php32
-rw-r--r--lib/SimpleSAML/Auth/TimeLimitedToken.php13
-rw-r--r--lib/SimpleSAML/Bindings/Shib13/Artifact.php22
-rw-r--r--lib/SimpleSAML/Bindings/Shib13/HTTPPost.php18
-rw-r--r--lib/SimpleSAML/Configuration.php8
-rw-r--r--lib/SimpleSAML/Error/Error.php6
-rw-r--r--lib/SimpleSAML/Error/NotFound.php2
-rw-r--r--lib/SimpleSAML/IdP.php2
-rw-r--r--lib/SimpleSAML/IdP/LogoutIFrame.php2
-rw-r--r--lib/SimpleSAML/IdP/LogoutTraditional.php2
-rw-r--r--lib/SimpleSAML/Logger/LoggingHandlerFile.php2
-rw-r--r--lib/SimpleSAML/Logger/LoggingHandlerSyslog.php2
-rw-r--r--lib/SimpleSAML/Memcache.php2
-rw-r--r--lib/SimpleSAML/Metadata/MetaDataStorageHandler.php8
-rw-r--r--lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php6
-rw-r--r--lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php8
-rw-r--r--lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php15
-rw-r--r--lib/SimpleSAML/Metadata/MetaDataStorageSource.php4
-rw-r--r--lib/SimpleSAML/Metadata/SAMLBuilder.php23
-rw-r--r--lib/SimpleSAML/Metadata/SAMLParser.php16
-rw-r--r--lib/SimpleSAML/Metadata/Signer.php4
-rw-r--r--lib/SimpleSAML/Module.php4
-rw-r--r--lib/SimpleSAML/Session.php4
-rw-r--r--lib/SimpleSAML/SessionHandler.php2
-rw-r--r--lib/SimpleSAML/SessionHandlerCookie.php2
-rw-r--r--lib/SimpleSAML/SessionHandlerPHP.php6
-rw-r--r--lib/SimpleSAML/Stats.php2
-rw-r--r--lib/SimpleSAML/Store.php3
-rw-r--r--lib/SimpleSAML/Utilities.php1989
-rw-r--r--lib/SimpleSAML/Utils/Arrays.php104
-rw-r--r--lib/SimpleSAML/Utils/Auth.php72
-rw-r--r--lib/SimpleSAML/Utils/Config.php58
-rw-r--r--lib/SimpleSAML/Utils/Config/Metadata.php109
-rw-r--r--lib/SimpleSAML/Utils/Crypto.php464
-rw-r--r--lib/SimpleSAML/Utils/HTTP.php1027
-rw-r--r--lib/SimpleSAML/Utils/Net.php82
-rw-r--r--lib/SimpleSAML/Utils/Random.php25
-rw-r--r--lib/SimpleSAML/Utils/System.php199
-rw-r--r--lib/SimpleSAML/Utils/Time.php162
-rw-r--r--lib/SimpleSAML/Utils/XML.php428
-rw-r--r--lib/SimpleSAML/XHTML/EMail.php2
-rw-r--r--lib/SimpleSAML/XHTML/IdPDisco.php25
-rw-r--r--lib/SimpleSAML/XHTML/Template.php5
-rw-r--r--lib/SimpleSAML/XML/Parser.php5
-rw-r--r--lib/SimpleSAML/XML/Shib13/AuthnRequest.php2
-rw-r--r--lib/SimpleSAML/XML/Shib13/AuthnResponse.php57
-rw-r--r--lib/SimpleSAML/XML/Signer.php6
-rw-r--r--lib/SimpleSAML/XML/Validator.php129
-rw-r--r--modules/adfs/lib/IdP/ADFS.php26
-rw-r--r--modules/adfs/www/idp/metadata.php12
-rw-r--r--modules/aselect/lib/Auth/Source/aselect.php6
-rw-r--r--modules/authX509/templates/X509error.php2
-rw-r--r--modules/authYubiKey/lib/Auth/Source/YubiKey.php2
-rw-r--r--modules/authYubiKey/libextinc/Yubico.php2
-rw-r--r--modules/authcrypt/lib/Auth/Source/Hash.php4
-rw-r--r--modules/authcrypt/lib/Auth/Source/Htpasswd.php9
-rw-r--r--modules/authfacebook/extlibinc/base_facebook.php2
-rw-r--r--modules/authfacebook/lib/Auth/Source/Facebook.php2
-rw-r--r--modules/authmyspace/lib/Auth/Source/MySpace.php3
-rw-r--r--modules/authorize/lib/Auth/Process/Authorize.php2
-rw-r--r--modules/authtwitter/lib/Auth/Source/Twitter.php2
-rw-r--r--modules/authwindowslive/lib/Auth/Source/LiveID.php8
-rw-r--r--modules/cas/lib/Auth/Source/CAS.php12
-rw-r--r--modules/casserver/www/login.php6
-rw-r--r--modules/casserver/www/proxy.php2
-rw-r--r--modules/casserver/www/serviceValidate.php6
-rw-r--r--modules/cdc/lib/Server.php10
-rw-r--r--modules/consent/lib/Auth/Process/Consent.php18
-rw-r--r--modules/consent/lib/Consent/Store/Cookie.php6
-rw-r--r--modules/consent/lib/Consent/Store/Database.php7
-rw-r--r--modules/consent/lib/Logout.php2
-rw-r--r--modules/consent/templates/consentform.php4
-rw-r--r--modules/consentAdmin/templates/consentadmin.php3
-rw-r--r--modules/consentAdmin/www/consentAdmin.php538
-rw-r--r--modules/consentSimpleAdmin/www/consentAdmin.php178
-rw-r--r--modules/consentSimpleAdmin/www/consentStats.php2
-rw-r--r--modules/core/hooks/hook_sanitycheck.php5
-rw-r--r--modules/core/lib/ACL.php2
-rw-r--r--modules/core/lib/Auth/Process/TargetedID.php2
-rw-r--r--modules/core/lib/Auth/Process/WarnShortSSOInterval.php2
-rw-r--r--modules/core/lib/Auth/Source/AdminPassword.php2
-rw-r--r--modules/core/lib/Auth/UserPassBase.php2
-rw-r--r--modules/core/lib/Auth/UserPassOrgBase.php2
-rw-r--r--modules/core/lib/ModuleDefinition.php4
-rw-r--r--modules/core/lib/ModuleInstaller.php5
-rw-r--r--modules/core/lib/Storage/SQLPermanentStorage.php6
-rw-r--r--modules/core/templates/frontpage_federation.tpl.php8
-rw-r--r--modules/core/templates/show_metadata.tpl.php2
-rw-r--r--modules/core/www/as_login.php4
-rw-r--r--modules/core/www/as_logout.php2
-rw-r--r--modules/core/www/authenticate.php2
-rw-r--r--modules/core/www/cleardiscochoices.php6
-rw-r--r--modules/core/www/frontpage_auth.php6
-rw-r--r--modules/core/www/frontpage_config.php12
-rw-r--r--modules/core/www/frontpage_federation.php8
-rw-r--r--modules/core/www/frontpage_welcome.php6
-rw-r--r--modules/core/www/login-admin.php4
-rw-r--r--modules/core/www/loginuserpass.php2
-rw-r--r--modules/core/www/loginuserpassorg.php2
-rw-r--r--modules/core/www/no_cookie.php2
-rw-r--r--modules/core/www/postredirect.php2
-rw-r--r--modules/core/www/show_metadata.php6
-rw-r--r--modules/cron/www/cron.php2
-rw-r--r--modules/cron/www/croninfo.php2
-rw-r--r--modules/discojuice/templates/central.tpl.php3
-rw-r--r--modules/discojuice/www/central.php2
-rw-r--r--modules/discopower/lib/PowerIdPDisco.php11
-rw-r--r--modules/discopower/templates/disco-tpl.php30
-rw-r--r--modules/exampleauth/lib/Auth/Process/RedirectTest.php2
-rw-r--r--modules/exampleauth/lib/Auth/Source/External.php2
-rw-r--r--modules/exampleauth/lib/Auth/Source/Static.php2
-rw-r--r--modules/exampleauth/lib/Auth/Source/UserPass.php2
-rw-r--r--modules/exampleauth/www/authpage.php4
-rw-r--r--modules/expirycheck/lib/Auth/Process/ExpiryDate.php7
-rw-r--r--modules/expirycheck/templates/about2expire.php4
-rw-r--r--modules/logpeek/lib/File/reverseRead.php7
-rw-r--r--modules/logpeek/www/index.php2
-rw-r--r--modules/memcacheMonitor/templates/memcachestat.tpl.php10
-rw-r--r--modules/memcacheMonitor/www/memcachestat.php2
-rw-r--r--modules/metaedit/config-template/module_metaedit.php1
-rw-r--r--modules/metaedit/lib/MetaEditor.php10
-rw-r--r--modules/metaedit/templates/metalist.php6
-rw-r--r--modules/metaedit/templates/xmlimport.tpl.php10
-rw-r--r--modules/metaedit/www/edit.php8
-rwxr-xr-xmodules/metarefresh/bin/metarefresh.php7
-rw-r--r--modules/metarefresh/lib/ARP.php3
-rw-r--r--modules/metarefresh/lib/MetaLoader.php13
-rw-r--r--modules/metarefresh/www/fetch.php2
-rw-r--r--modules/multiauth/lib/Auth/Source/MultiAuth.php4
-rw-r--r--modules/negotiate/lib/Auth/Source/Negotiate.php12
-rw-r--r--modules/negotiate/www/disable.php2
-rw-r--r--modules/negotiate/www/enable.php2
-rwxr-xr-xmodules/oauth/bin/demo.php1
-rw-r--r--modules/oauth/lib/Consumer.php7
-rw-r--r--modules/oauth/lib/OAuthStore.php10
-rw-r--r--modules/oauth/lib/Registry.php21
-rw-r--r--modules/oauth/templates/registry.list.php6
-rw-r--r--modules/oauth/www/accessToken.php5
-rw-r--r--modules/oauth/www/authorize.php21
-rw-r--r--modules/oauth/www/registry.edit.php12
-rw-r--r--modules/oauth/www/registry.php6
-rw-r--r--modules/oauth/www/requestToken.php3
-rw-r--r--modules/portal/hooks/hook_htmlinject.php4
-rw-r--r--modules/portal/lib/Portal.php13
-rw-r--r--modules/preprodwarning/lib/Auth/Process/Warning.php2
-rw-r--r--modules/radius/lib/Auth/Source/Radius.php7
-rw-r--r--modules/saml/docs/sp.txt12
-rw-r--r--modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php2
-rw-r--r--modules/saml/lib/Auth/Process/PersistentNameID.php2
-rw-r--r--modules/saml/lib/Auth/Process/SQLPersistentNameID.php2
-rw-r--r--modules/saml/lib/Auth/Process/TransientNameID.php2
-rw-r--r--modules/saml/lib/Auth/Source/SP.php6
-rw-r--r--modules/saml/lib/IdP/SAML1.php8
-rw-r--r--modules/saml/lib/IdP/SAML2.php18
-rw-r--r--modules/saml/lib/Message.php21
-rw-r--r--modules/saml/lib/SP/LogoutStore.php2
-rw-r--r--modules/saml/www/idp/certs.php8
-rw-r--r--modules/saml/www/sp/metadata.php20
-rw-r--r--modules/saml/www/sp/saml1-acs.php2
-rw-r--r--modules/saml/www/sp/saml2-acs.php4
-rw-r--r--modules/saml/www/sp/saml2-logout.php2
-rw-r--r--modules/saml2debug/www/debug.php5
-rwxr-xr-xmodules/statistics/bin/loganalyzer.php2
-rw-r--r--modules/statistics/lib/AccessCheck.php4
-rw-r--r--modules/statistics/lib/Aggregator.php35
-rw-r--r--modules/statistics/lib/DateHandler.php16
-rw-r--r--modules/statistics/lib/DateHandlerMonth.php20
-rw-r--r--modules/statistics/lib/Graph/GoogleCharts.php11
-rw-r--r--modules/statistics/lib/LogCleaner.php16
-rw-r--r--modules/statistics/lib/LogParser.php3
-rw-r--r--modules/statistics/lib/RatioDataset.php13
-rw-r--r--modules/statistics/lib/Ruleset.php1
-rw-r--r--modules/statistics/lib/StatDataset.php26
-rw-r--r--modules/statistics/lib/Statistics/Rulesets/BaseRule.php1
-rw-r--r--modules/statistics/templates/statistics-tpl.php23
-rw-r--r--modules/statistics/www/showstats.php1
-rw-r--r--templates/includes/header.php2
-rw-r--r--templates/selectidp-links.php4
-rw-r--r--tests/Metadata/MetadataTest.php (renamed from tests/Utils/MetadataTest.php)47
-rw-r--r--tests/Metadata/SAMLBuilderTest.php137
-rw-r--r--tests/SimpleSAML/Metadata/SAMLBuilderTest.php137
-rw-r--r--tests/Utils/ArraysTest.php165
-rw-r--r--tests/Utils/NetTest.php42
-rw-r--r--tools/phpunit/phpunit.xml8
-rw-r--r--www/_include.php4
-rw-r--r--www/admin/hostnames.php16
-rw-r--r--www/admin/metadata-converter.php6
-rw-r--r--www/admin/phpinfo.php2
-rw-r--r--www/authmemcookie.php4
-rw-r--r--www/errorreport.php2
-rw-r--r--www/index.php3
-rw-r--r--www/logout.php2
-rw-r--r--www/saml2/idp/SingleLogoutService.php2
-rw-r--r--www/saml2/idp/initSLO.php2
-rw-r--r--www/saml2/idp/metadata.php18
-rw-r--r--www/shib13/idp/SSOService.php2
-rw-r--r--www/shib13/idp/metadata.php10
207 files changed, 4256 insertions, 3397 deletions
diff --git a/bin/pwgen.php b/bin/pwgen.php
index 83b4dfe..24fef6c 100755
--- a/bin/pwgen.php
+++ b/bin/pwgen.php
@@ -44,4 +44,4 @@ if(!in_array(strtolower($algo), hash_algos())) {
echo "Do you want to use a salt? (yes/no) [yes] ";
$s = (trim(fgets(STDIN)) == 'no') ? '' : 'S';
-echo "\n " . SimpleSAML_Utils_Crypto::pwHash($password, strtoupper( $s . $algo ) ). "\n\n";
+echo "\n " . SimpleSAML\Utils\Crypto::pwHash($password, strtoupper( $s . $algo ) ). "\n\n";
diff --git a/bin/translation.php b/bin/translation.php
index 0ffc820..f5bf452 100755
--- a/bin/translation.php
+++ b/bin/translation.php
@@ -40,14 +40,14 @@ echo 'File base: [' . $basefile . ']'. "\n";
switch($action) {
case 'pulldef':
- $content = SimpleSAML_Utilities::fetch($base . 'export.php?aid=' . $application . '&type=def&file=' . $basefile);
+ $content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=def&file=' . $basefile);
file_put_contents($fileWithoutExt . '.definition.json' , $content);
break;
case 'pull':
try {
- $content = SimpleSAML_Utilities::fetch($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
+ $content = \SimpleSAML\Utils\HTTP::fetch($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
file_put_contents($fileWithoutExt . '.translation.json' , $content);
}
catch (SimpleSAML_Error_Exception $e) {
@@ -58,8 +58,6 @@ switch($action) {
case 'push':
- #$content = file_get_contents($base . 'export.php?aid=' . $application . '&type=translation&file=' . $basefile);
- #file_put_contents($fileWithoutExt . '.translation.json' , $content);
push($file, $basefile, $application, $type);
break;
diff --git a/composer.json b/composer.json
index 1513187..5476a73 100644
--- a/composer.json
+++ b/composer.json
@@ -17,14 +17,15 @@
],
"autoload": {
"psr-0": {
- "SimpleSAML_": "lib/"
+ "SimpleSAML": "lib/"
},
"files": ["lib/_autoload_modules.php"]
},
"require": {
"php": "~5.3",
- "simplesamlphp/saml2": "~0.3",
- "simplesamlphp/xmlseclibs": "~1.3.2"
+ "simplesamlphp/saml2": "~1.5.3",
+ "simplesamlphp/xmlseclibs": "~1.3.2",
+ "whitehat101/apr1-md5": "~1.0"
},
"require-dev": {
"phpunit/phpunit": "~3.7",
diff --git a/composer.lock b/composer.lock
index bd2530d..7fe4801 100644
--- a/composer.lock
+++ b/composer.lock
@@ -1,10 +1,10 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
- "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
- "hash": "fc3fadc5fc728a0b64192750e916ada2",
+ "hash": "df47ca40f6c0e79c52c38b9e2bf01174",
"packages": [
{
"name": "psr/log",
@@ -46,16 +46,16 @@
},
{
"name": "simplesamlphp/saml2",
- "version": "v0.6.2",
+ "version": "v1.5.3",
"source": {
"type": "git",
"url": "https://github.com/simplesamlphp/saml2.git",
- "reference": "32fb4d416d065aa5c84505e274055de331ef286e"
+ "reference": "9617bd59c18d49b69fe315d5951cc51cdcb30e1b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/simplesamlphp/saml2/zipball/32fb4d416d065aa5c84505e274055de331ef286e",
- "reference": "32fb4d416d065aa5c84505e274055de331ef286e",
+ "url": "https://api.github.com/repos/simplesamlphp/saml2/zipball/9617bd59c18d49b69fe315d5951cc51cdcb30e1b",
+ "reference": "9617bd59c18d49b69fe315d5951cc51cdcb30e1b",
"shasum": ""
},
"require": {
@@ -92,7 +92,7 @@
}
],
"description": "SAML2 PHP library from SimpleSAMLphp",
- "time": "2014-12-22 09:42:36"
+ "time": "2015-05-12 13:52:00"
},
{
"name": "simplesamlphp/xmlseclibs",
@@ -144,21 +144,65 @@
"xmlsec"
],
"time": "2013-06-19 00:00:00"
+ },
+ {
+ "name": "whitehat101/apr1-md5",
+ "version": "v1.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/whitehat101/apr1-md5.git",
+ "reference": "8b261c9fc0481b4e9fa9d01c6ca70867b5d5e819"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/whitehat101/apr1-md5/zipball/8b261c9fc0481b4e9fa9d01c6ca70867b5d5e819",
+ "reference": "8b261c9fc0481b4e9fa9d01c6ca70867b5d5e819",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "4.0.*"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "WhiteHat101\\Crypt\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jeremy Ebler",
+ "email": "jebler@gmail.com"
+ }
+ ],
+ "description": "Apache's APR1-MD5 algorithm in pure PHP",
+ "homepage": "https://github.com/whitehat101/apr1-md5",
+ "keywords": [
+ "MD5",
+ "apr1"
+ ],
+ "time": "2015-02-11 11:06:42"
}
],
"packages-dev": [
{
"name": "guzzle/guzzle",
- "version": "v3.9.2",
+ "version": "v3.9.3",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle3.git",
- "reference": "54991459675c1a2924122afbb0e5609ade581155"
+ "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/54991459675c1a2924122afbb0e5609ade581155",
- "reference": "54991459675c1a2924122afbb0e5609ade581155",
+ "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/0645b70d953bc1c067bbc8d5bc53194706b628d9",
+ "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9",
"shasum": ""
},
"require": {
@@ -199,6 +243,9 @@
"zendframework/zend-cache": "2.*,<2.3",
"zendframework/zend-log": "2.*,<2.3"
},
+ "suggest": {
+ "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated."
+ },
"type": "library",
"extra": {
"branch-alias": {
@@ -226,7 +273,7 @@
"homepage": "https://github.com/guzzle/guzzle/contributors"
}
],
- "description": "Guzzle is a PHP HTTP client library and framework for building RESTful web service clients",
+ "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle",
"homepage": "http://guzzlephp.org/",
"keywords": [
"client",
@@ -237,7 +284,7 @@
"rest",
"web service"
],
- "time": "2014-08-11 04:32:36"
+ "time": "2015-03-18 18:23:50"
},
{
"name": "phpunit/php-code-coverage",
@@ -302,31 +349,33 @@
},
{
"name": "phpunit/php-file-iterator",
- "version": "1.3.4",
+ "version": "1.4.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
- "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb"
+ "reference": "a923bb15680d0089e2316f7a4af8f437046e96bb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb",
- "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/a923bb15680d0089e2316f7a4af8f437046e96bb",
+ "reference": "a923bb15680d0089e2316f7a4af8f437046e96bb",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.4.x-dev"
+ }
+ },
"autoload": {
"classmap": [
- "File/"
+ "src/"
]
},
"notification-url": "https://packagist.org/downloads/",
- "include-path": [
- ""
- ],
"license": [
"BSD-3-Clause"
],
@@ -343,7 +392,7 @@
"filesystem",
"iterator"
],
- "time": "2013-10-10 15:34:57"
+ "time": "2015-04-02 05:19:05"
},
{
"name": "phpunit/php-text-template",
@@ -682,23 +731,26 @@
},
{
"name": "symfony/config",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/Config",
"source": {
"type": "git",
"url": "https://github.com/symfony/Config.git",
- "reference": "d94f222eff99a22ce313555b78642b4873418d56"
+ "reference": "b6fddb4aa2daaa2b06f0040071ac131b4a1ecf25"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/Config/zipball/d94f222eff99a22ce313555b78642b4873418d56",
- "reference": "d94f222eff99a22ce313555b78642b4873418d56",
+ "url": "https://api.github.com/repos/symfony/Config/zipball/b6fddb4aa2daaa2b06f0040071ac131b4a1ecf25",
+ "reference": "b6fddb4aa2daaa2b06f0040071ac131b4a1ecf25",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"symfony/filesystem": "~2.3"
},
+ "require-dev": {
+ "symfony/phpunit-bridge": "~2.7"
+ },
"type": "library",
"extra": {
"branch-alias": {
@@ -716,31 +768,31 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Config Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-03 08:01:59"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-02 15:18:45"
},
{
"name": "symfony/console",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/Console",
"source": {
"type": "git",
"url": "https://github.com/symfony/Console.git",
- "reference": "6ac6491ff60c0e5a941db3ccdc75a07adbb61476"
+ "reference": "ebc5679854aa24ed7d65062e9e3ab0b18a917272"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/Console/zipball/6ac6491ff60c0e5a941db3ccdc75a07adbb61476",
- "reference": "6ac6491ff60c0e5a941db3ccdc75a07adbb61476",
+ "url": "https://api.github.com/repos/symfony/Console/zipball/ebc5679854aa24ed7d65062e9e3ab0b18a917272",
+ "reference": "ebc5679854aa24ed7d65062e9e3ab0b18a917272",
"shasum": ""
},
"require": {
@@ -749,6 +801,7 @@
"require-dev": {
"psr/log": "~1.0",
"symfony/event-dispatcher": "~2.1",
+ "symfony/phpunit-bridge": "~2.7",
"symfony/process": "~2.1"
},
"suggest": {
@@ -773,31 +826,31 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Console Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-06 17:50:02"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-02 15:18:45"
},
{
"name": "symfony/event-dispatcher",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/EventDispatcher",
"source": {
"type": "git",
"url": "https://github.com/symfony/EventDispatcher.git",
- "reference": "40ff70cadea3785d83cac1c8309514b36113064e"
+ "reference": "672593bc4b0043a0acf91903bb75a1c82d8f2e02"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/40ff70cadea3785d83cac1c8309514b36113064e",
- "reference": "40ff70cadea3785d83cac1c8309514b36113064e",
+ "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/672593bc4b0043a0acf91903bb75a1c82d8f2e02",
+ "reference": "672593bc4b0043a0acf91903bb75a1c82d8f2e02",
"shasum": ""
},
"require": {
@@ -808,6 +861,7 @@
"symfony/config": "~2.0,>=2.0.5",
"symfony/dependency-injection": "~2.6",
"symfony/expression-language": "~2.6",
+ "symfony/phpunit-bridge": "~2.7",
"symfony/stopwatch": "~2.3"
},
"suggest": {
@@ -831,36 +885,39 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony EventDispatcher Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-05 14:28:40"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-02 15:18:45"
},
{
"name": "symfony/filesystem",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/Filesystem",
"source": {
"type": "git",
"url": "https://github.com/symfony/Filesystem.git",
- "reference": "a1f566d1f92e142fa1593f4555d6d89e3044a9b7"
+ "reference": "f73904bd2dae525c42ea1f0340c7c98480ecacde"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/Filesystem/zipball/a1f566d1f92e142fa1593f4555d6d89e3044a9b7",
- "reference": "a1f566d1f92e142fa1593f4555d6d89e3044a9b7",
+ "url": "https://api.github.com/repos/symfony/Filesystem/zipball/f73904bd2dae525c42ea1f0340c7c98480ecacde",
+ "reference": "f73904bd2dae525c42ea1f0340c7c98480ecacde",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
+ "require-dev": {
+ "symfony/phpunit-bridge": "~2.7"
+ },
"type": "library",
"extra": {
"branch-alias": {
@@ -878,36 +935,39 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Filesystem Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-03 21:13:09"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-08 00:09:07"
},
{
"name": "symfony/stopwatch",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/Stopwatch",
"source": {
"type": "git",
"url": "https://github.com/symfony/Stopwatch.git",
- "reference": "e8da5286132ba75ce4b4275fbf0f4cd369bfd71c"
+ "reference": "b470f87c69837cb71115f1fa720388bb19b63635"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/e8da5286132ba75ce4b4275fbf0f4cd369bfd71c",
- "reference": "e8da5286132ba75ce4b4275fbf0f4cd369bfd71c",
+ "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/b470f87c69837cb71115f1fa720388bb19b63635",
+ "reference": "b470f87c69837cb71115f1fa720388bb19b63635",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
+ "require-dev": {
+ "symfony/phpunit-bridge": "~2.7"
+ },
"type": "library",
"extra": {
"branch-alias": {
@@ -925,36 +985,39 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Stopwatch Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-03 08:01:59"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-02 15:18:45"
},
{
"name": "symfony/yaml",
- "version": "v2.6.3",
+ "version": "v2.6.7",
"target-dir": "Symfony/Component/Yaml",
"source": {
"type": "git",
"url": "https://github.com/symfony/Yaml.git",
- "reference": "82462a90848a52c2533aa6b598b107d68076b018"
+ "reference": "f157ab074e453ecd4c0fa775f721f6e67a99d9e2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/Yaml/zipball/82462a90848a52c2533aa6b598b107d68076b018",
- "reference": "82462a90848a52c2533aa6b598b107d68076b018",
+ "url": "https://api.github.com/repos/symfony/Yaml/zipball/f157ab074e453ecd4c0fa775f721f6e67a99d9e2",
+ "reference": "f157ab074e453ecd4c0fa775f721f6e67a99d9e2",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
+ "require-dev": {
+ "symfony/phpunit-bridge": "~2.7"
+ },
"type": "library",
"extra": {
"branch-alias": {
@@ -972,17 +1035,17 @@
],
"authors": [
{
- "name": "Symfony Community",
- "homepage": "http://symfony.com/contributors"
- },
- {
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Yaml Component",
- "homepage": "http://symfony.com",
- "time": "2015-01-03 15:33:07"
+ "homepage": "https://symfony.com",
+ "time": "2015-05-02 15:18:45"
}
],
"aliases": [],
@@ -991,6 +1054,7 @@
"satooshi/php-coveralls": 20
},
"prefer-stable": false,
+ "prefer-lowest": false,
"platform": {
"php": "~5.3"
},
diff --git a/docs/simplesamlphp-install.txt b/docs/simplesamlphp-install.txt
index d0b82e5..76a5fb4 100644
--- a/docs/simplesamlphp-install.txt
+++ b/docs/simplesamlphp-install.txt
@@ -17,7 +17,7 @@ simpleSAMLphp news and documentation
This document is part of the simpleSAMLphp documentation suite.
* [List of all simpleSAMLphp documentation](http://simplesamlphp.org/docs)
- * [Latest news about simpleSAMLphp](http://rnd.feide.no/taxonomy/term/4). (Also conatins an RSS feed)
+ * [Latest news about simpleSAMLphp](http://rnd.feide.no/taxonomy/term/4). (Also contains an RSS feed)
* [simpleSAMLphp homepage](https://simplesamlphp.org)
@@ -48,7 +48,7 @@ What actual packages are required for the various extensions varies between diff
Download and install simpleSAMLphp
----------------------------------
-The most recent relase of simpleSAMLphp is found at [https://simplesamlphp.org/download](https://simplesamlphp.org/download).
+The most recent release of simpleSAMLphp is found at [https://simplesamlphp.org/download](https://simplesamlphp.org/download).
Go to the directory where you want to install simpleSAMLphp, and extract the archive file you just downloaded:
@@ -143,9 +143,9 @@ file, `config.php`, right away:
'technicalcontact_email' => 'andreas.solberg@uninett.no',
-
- If you use simpleSAMLphp in a country where english is not
+ If you use simpleSAMLphp in a country where English is not
widespread, you may want to change the default language from
- english to something else:
+ English to something else:
'language.default' => 'no',
@@ -191,7 +191,7 @@ After installing simpleSAMLphp, you can access the homepage of your installation
https://service.example.org/simplesaml/
-The exact link depends on how you set it up with Apache, and off course on your hostname.
+The exact link depends on how you set it up with Apache, and of course on your hostname.
### Warning
@@ -248,10 +248,10 @@ in an alternative way.
Still you can install simpleSAMLphp - keep on reading.
2. You have full permissions to the server, but cannot edit Apache
- configuration for some reason, polictics, policy or whatever.
+ configuration for some reason, politics, policy or whatever.
-The SimpleSAMLphp code contains one folder named `simplesamlphp`. In this folder there are a lot of subfolders for library, metadata, configuration and much more. One of these folders is named `www`. This and *only this* folder should be exposed on the web. The reccomended configuration is to put the whole `simplesamlphp` folder outside the webroot, and then link in the `www` folder by using the `Alias` directive, as described in [the section called “Configuring Apacheâ€](#sect.apacheconfig "Configuring Apache"). But this is not the only possible way.
+The SimpleSAMLphp code contains one folder named `simplesamlphp`. In this folder there are a lot of subfolders for library, metadata, configuration and much more. One of these folders is named `www`. This and *only this* folder should be exposed on the web. The recommended configuration is to put the whole `simplesamlphp` folder outside the webroot, and then link in the `www` folder by using the `Alias` directive, as described in [the section called “Configuring Apacheâ€](#sect.apacheconfig "Configuring Apache"). But this is not the only possible way.
As an example, let's see how you can install simpleSAMLphp in your home directory on a shared hosting server.
diff --git a/docs/simplesamlphp-translation.txt b/docs/simplesamlphp-translation.txt
index 794fa52..ae220ed 100644
--- a/docs/simplesamlphp-translation.txt
+++ b/docs/simplesamlphp-translation.txt
@@ -114,13 +114,13 @@ The script requires that the config file `translation.php` is copied from `confi
The script may be used to these tasks:
- * upload definition files
- * download defintion files
- * download translation files
+ * Uploading definition files
+ * Downloading definition files
+ * Downloading translation files
### Uploading defintion files
-You probably do not have access to upload definition files for the simpleSAMLphp application. But, from January 2010, the translation portal is generic to host multiple independent applications. What you may do is to contact Andreas to add your own application to the translation portal, where you off course have access to upload definition files.
+You probably do not have access to upload definition files for the simpleSAMLphp application. But, from January 2010, the translation portal is generic to host multiple independent applications. What you may do is to contact Andreas to add your own application to the translation portal, where you of course have access to upload definition files.
**Note**: an application may very well be a local simpleSAMLphp module that you run.
@@ -152,7 +152,7 @@ The script uses OAuth to connect your session on the command line client with th
-### Deleting defintion files
+### Deleting definition files
Is perfomed via the webbased translation portal.
@@ -162,7 +162,7 @@ Seldom used, as the defintion file is manually created locally. Anyway:
bin/translation.php pulldef modules/MODULENAME/dictionaries/BASENAME.definition.json
-Ooutput example:
+Output example:
Action: [pulldef]
Application: [simplesamlphp]
diff --git a/lib/SimpleSAML/Auth/Default.php b/lib/SimpleSAML/Auth/Default.php
index e3687bd..0498554 100644
--- a/lib/SimpleSAML/Auth/Default.php
+++ b/lib/SimpleSAML/Auth/Default.php
@@ -21,11 +21,11 @@ class SimpleSAML_Auth_Default {
* @param string|array $return The URL or function we should direct the
* user to after authentication. If using a URL obtained from user input,
* please make sure to check it by calling
- * SimpleSAML_Utilities::checkURLAllowed().
+ * \SimpleSAML\Utils\HTTP::checkURLAllowed().
* @param string|NULL $errorURL The URL we should direct the user to after
* failed authentication. Can be NULL, in which case a standard error page
* will be shown. If using a URL obtained from user input, please make sure
- * to check it by calling SimpleSAML_Utilities::checkURLAllowed().
+ * to check it by calling \SimpleSAML\Utils\HTTP::checkURLAllowed().
* @param array $params Extra information about the login. Different
* authentication requestors may provide different information. Optional,
* will default to an empty array.
@@ -128,7 +128,7 @@ class SimpleSAML_Auth_Default {
if (is_string($return)) {
/* Redirect... */
- SimpleSAML_Utilities::redirectTrustedURL($return);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($return);
} else {
call_user_func($return, $state);
assert('FALSE');
@@ -146,7 +146,7 @@ class SimpleSAML_Auth_Default {
* @param string $returnURL The URL we should redirect the user to after
* logging out. No checking is performed on the URL, so make sure to verify
* it on beforehand if the URL is obtained from user input. Refer to
- * SimpleSAML_Utilities::checkURLAllowed() for more information.
+ * \SimpleSAML\Utils\HTTP::checkURLAllowed() for more information.
* @param string $authority The authentication source we are logging
* out from.
*/
@@ -181,7 +181,7 @@ class SimpleSAML_Auth_Default {
* @param string $returnURL The URL we should redirect the user to after
* logging out. No checking is performed on the URL, so make sure to verify
* it on beforehand if the URL is obtained from user input. Refer to
- * SimpleSAML_Utilities::checkURLAllowed() for more information.
+ * \SimpleSAML\Utils\HTTP::checkURLAllowed() for more information.
* @param string|NULL $authority The authentication source we are logging
* out from.
* @return void This function never returns.
@@ -193,7 +193,7 @@ class SimpleSAML_Auth_Default {
self::initLogoutReturn($returnURL, $authority);
/* Redirect... */
- SimpleSAML_Utilities::redirectTrustedURL($returnURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnURL);
}
@@ -211,7 +211,7 @@ class SimpleSAML_Auth_Default {
$returnURL = $state['SimpleSAML_Auth_Default.ReturnURL'];
/* Redirect... */
- SimpleSAML_Utilities::redirectTrustedURL($returnURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnURL);
}
@@ -265,7 +265,7 @@ class SimpleSAML_Auth_Default {
$session = SimpleSAML_Session::getSessionFromRequest();
$session->doLogin($authId, self::extractPersistentAuthState($state));
- SimpleSAML_Utilities::redirectUntrustedURL($redirectTo);
+ \SimpleSAML\Utils\HTTP::redirectUntrustedURL($redirectTo);
}
}
diff --git a/lib/SimpleSAML/Auth/LDAP.php b/lib/SimpleSAML/Auth/LDAP.php
index 24e0a28..50cd5da 100644
--- a/lib/SimpleSAML/Auth/LDAP.php
+++ b/lib/SimpleSAML/Auth/LDAP.php
@@ -261,7 +261,7 @@ class SimpleSAML_Auth_LDAP {
public function searchfordn($base, $attribute, $value, $allowZeroHits = FALSE) {
// Traverse all search bases, returning DN if found.
- $bases = SimpleSAML_Utilities::arrayize($base);
+ $bases = SimpleSAML\Utils\Arrays::arrayize($base);
$result = NULL;
foreach ($bases AS $current) {
try {
@@ -586,7 +586,7 @@ class SimpleSAML_Auth_LDAP {
$dn = $this->searchfordn($config['searchbase'], $config['searchattributes'], $username);
}
- if ($password != null) { /* checking users credentials ... assuming below that she may read her own attributes ... */
+ if ($password !== null) { /* checking users credentials ... assuming below that she may read her own attributes ... */
if (!$this->bind($dn, $password)) {
SimpleSAML_Logger::info('Library - LDAP validate(): Failed to authenticate \''. $username . '\' using DN \'' . $dn . '\'');
return FALSE;
diff --git a/lib/SimpleSAML/Auth/ProcessingChain.php b/lib/SimpleSAML/Auth/ProcessingChain.php
index da75fcc..b034220 100644
--- a/lib/SimpleSAML/Auth/ProcessingChain.php
+++ b/lib/SimpleSAML/Auth/ProcessingChain.php
@@ -247,7 +247,7 @@ class SimpleSAML_Auth_ProcessingChain {
* in $state['ReturnURL'].
*/
$id = SimpleSAML_Auth_State::saveState($state, self::COMPLETED_STAGE);
- SimpleSAML_Utilities::redirectTrustedURL($state['ReturnURL'], array(self::AUTHPARAM => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($state['ReturnURL'], array(self::AUTHPARAM => $id));
} else {
/* Pass the state to the function defined in $state['ReturnCall']. */
@@ -302,7 +302,7 @@ class SimpleSAML_Auth_ProcessingChain {
* Retrieve a state which has finished processing.
*
* @param string $id The state identifier.
- * @see SimpleSAML_Utilities::parseStateID()
+ * @see SimpleSAML_Auth_State::parseStateID()
* @return Array The state referenced by the $id parameter.
*/
public static function fetchProcessedState($id) {
diff --git a/lib/SimpleSAML/Auth/Simple.php b/lib/SimpleSAML/Auth/Simple.php
index da0881d..a82419f 100644
--- a/lib/SimpleSAML/Auth/Simple.php
+++ b/lib/SimpleSAML/Auth/Simple.php
@@ -110,11 +110,11 @@ class SimpleSAML_Auth_Simple {
} else if (array_key_exists('ReturnCallback', $params)) {
$returnTo = (array)$params['ReturnCallback'];
} else {
- $returnTo = SimpleSAML_Utilities::selfURL();
+ $returnTo = \SimpleSAML\Utils\HTTP::getSelfURL();
}
if (is_string($returnTo) && $keepPost && $_SERVER['REQUEST_METHOD'] === 'POST') {
- $returnTo = SimpleSAML_Utilities::createPostRedirectLink($returnTo, $_POST);
+ $returnTo = \SimpleSAML\Utils\HTTP::getPOSTRedirectURL($returnTo, $_POST);
}
if (array_key_exists('ErrorURL', $params)) {
@@ -159,7 +159,7 @@ class SimpleSAML_Auth_Simple {
assert('is_array($params) || is_string($params) || is_null($params)');
if ($params === NULL) {
- $params = SimpleSAML_Utilities::selfURL();
+ $params = \SimpleSAML\Utils\HTTP::getSelfURL();
}
if (is_string($params)) {
@@ -217,8 +217,7 @@ class SimpleSAML_Auth_Simple {
$stateID = SimpleSAML_Auth_State::saveState($state, $state['ReturnStateStage']);
$params[$state['ReturnStateParam']] = $stateID;
}
-
- SimpleSAML_Utilities::redirectTrustedURL($state['ReturnTo'], $params);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($state['ReturnTo'], $params);
}
}
@@ -290,7 +289,7 @@ class SimpleSAML_Auth_Simple {
assert('is_null($returnTo) || is_string($returnTo)');
if ($returnTo === NULL) {
- $returnTo = SimpleSAML_Utilities::selfURL();
+ $returnTo = \SimpleSAML\Utils\HTTP::getSelfURL();
}
$login = SimpleSAML_Module::getModuleURL('core/as_login.php', array(
@@ -313,7 +312,7 @@ class SimpleSAML_Auth_Simple {
assert('is_null($returnTo) || is_string($returnTo)');
if ($returnTo === NULL) {
- $returnTo = SimpleSAML_Utilities::selfURL();
+ $returnTo = \SimpleSAML\Utils\HTTP::getSelfURL();
}
$logout = SimpleSAML_Module::getModuleURL('core/as_logout.php', array(
diff --git a/lib/SimpleSAML/Auth/State.php b/lib/SimpleSAML/Auth/State.php
index 4684f5d..4f5e263 100644
--- a/lib/SimpleSAML/Auth/State.php
+++ b/lib/SimpleSAML/Auth/State.php
@@ -105,7 +105,7 @@ class SimpleSAML_Auth_State {
assert('is_bool($rawId)');
if (!array_key_exists(self::ID, $state)) {
- $state[self::ID] = SimpleSAML_Utilities::generateID();
+ $state[self::ID] = SimpleSAML\Utils\Random::generateID();
}
$id = $state[self::ID];
@@ -210,7 +210,7 @@ class SimpleSAML_Auth_State {
assert('is_bool($allowMissing)');
SimpleSAML_Logger::debug('Loading state: ' . var_export($id, TRUE));
- $sid = SimpleSAML_Utilities::parseStateID($id);
+ $sid = self::parseStateID($id);
$session = SimpleSAML_Session::getSessionFromRequest();
$state = $session->getData('SimpleSAML_Auth_State', $sid['id']);
@@ -225,7 +225,7 @@ class SimpleSAML_Auth_State {
throw new SimpleSAML_Error_NoState();
}
- SimpleSAML_Utilities::redirectUntrustedURL($sid['url']);
+ \SimpleSAML\Utils\HTTP::redirectUntrustedURL($sid['url']);
}
$state = unserialize($state);
@@ -249,7 +249,7 @@ class SimpleSAML_Auth_State {
throw new Exception($msg);
}
- SimpleSAML_Utilities::redirectUntrustedURL($sid['url']);
+ \SimpleSAML\Utils\HTTP::redirectUntrustedURL($sid['url']);
}
return $state;
@@ -294,7 +294,7 @@ class SimpleSAML_Auth_State {
$id = self::saveState($state, self::EXCEPTION_STAGE);
/* Redirect to the exception handler. */
- SimpleSAML_Utilities::redirectTrustedURL($state[self::EXCEPTION_HANDLER_URL], array(self::EXCEPTION_PARAM => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($state[self::EXCEPTION_HANDLER_URL], array(self::EXCEPTION_PARAM => $id));
} elseif (array_key_exists(self::EXCEPTION_HANDLER_FUNC, $state)) {
/* Call the exception handler. */
@@ -337,4 +337,26 @@ class SimpleSAML_Auth_State {
return $state;
}
+
+ /**
+ * Get the ID and (optionally) a URL embedded in a StateID, in the form 'id:url'.
+ *
+ * @param string $stateId The state ID to use.
+ *
+ * @return array A hashed array with the ID and the URL (if any), in the 'id' and 'url' keys, respectively. If
+ * there's no URL in the input parameter, NULL will be returned as the value for the 'url' key.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function parseStateID($stateId) {
+ $tmp = explode(':', $stateId, 2);
+ $id = $tmp[0];
+ $url = null;
+ if (count($tmp) === 2) {
+ $url = $tmp[1];
+ }
+ return array('id' => $id, 'url' => $url);
+ }
+
}
diff --git a/lib/SimpleSAML/Auth/TimeLimitedToken.php b/lib/SimpleSAML/Auth/TimeLimitedToken.php
index 3c991ce..5a59b7a 100644
--- a/lib/SimpleSAML/Auth/TimeLimitedToken.php
+++ b/lib/SimpleSAML/Auth/TimeLimitedToken.php
@@ -14,7 +14,7 @@ class SimpleSAML_Auth_TimeLimitedToken {
*/
public function __construct( $lifetime = 900, $secretSalt = NULL, $skew = 1) {
if ($secretSalt === NULL) {
- $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+ $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
}
$this->secretSalt = $secretSalt;
@@ -39,9 +39,6 @@ class SimpleSAML_Auth_TimeLimitedToken {
* Calculate the given time slot for a given offset.
*/
private function calculate_time_slot($offset) {
-
- #echo 'lifetime is: ' . $this->lifetime;
-
$timeslot = floor( (time() - $offset) / ($this->lifetime + $this->skew) );
return $timeslot;
}
@@ -51,10 +48,6 @@ class SimpleSAML_Auth_TimeLimitedToken {
*/
private function calculate_tokenvalue($offset) {
// A secret salt that should be randomly generated for each installation.
- #echo 'Secret salt is: ' . $this->secretSalt;
-
- #echo '<p>Calculating sha1( ' . $this->calculate_time_slot($offset) . ':' . $this->secretSalt . ' )<br />';
-
return sha1( $this->calculate_time_slot($offset) . ':' . $this->secretSalt);
}
@@ -74,10 +67,6 @@ class SimpleSAML_Auth_TimeLimitedToken {
$splittedtoken = explode('-', $token);
$offset = hexdec($splittedtoken[0]);
$value = $splittedtoken[1];
-
-
- #echo 'compare [' . $this->calculate_tokenvalue($offset). '] with [' . $value . '] offset was [' . $offset. ']';
-
return ($this->calculate_tokenvalue($offset) === $value);
}
diff --git a/lib/SimpleSAML/Bindings/Shib13/Artifact.php b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
index 4eda10b..0b27c03 100644
--- a/lib/SimpleSAML/Bindings/Shib13/Artifact.php
+++ b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
@@ -48,9 +48,9 @@ class SimpleSAML_Bindings_Shib13_Artifact {
$msg = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">' .
'<SOAP-ENV:Body>' .
'<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"' .
- ' RequestID="' . SimpleSAML_Utilities::generateID() . '"' .
+ ' RequestID="' . SimpleSAML\Utils\Random::generateID() . '"' .
' MajorVersion="1" MinorVersion="1"' .
- ' IssueInstant="' . SimpleSAML_Utilities::generateTimestamp() . '"' .
+ ' IssueInstant="' . SimpleSAML\Utils\Time::generateTimestamp() . '"' .
'>';
foreach ($artifacts as $a) {
@@ -80,18 +80,18 @@ class SimpleSAML_Bindings_Shib13_Artifact {
}
$soapEnvelope = $doc->firstChild;
- if (!SimpleSAML_Utilities::isDOMElementOfType($soapEnvelope, 'Envelope', 'http://schemas.xmlsoap.org/soap/envelope/')) {
+ if (!SimpleSAML\Utils\XML::isDOMElementOfType($soapEnvelope, 'Envelope', 'http://schemas.xmlsoap.org/soap/envelope/')) {
throw new SimpleSAML_Error_Exception('Expected artifact response to contain a <soap:Envelope> element.');
}
- $soapBody = SimpleSAML_Utilities::getDOMChildren($soapEnvelope, 'Body', 'http://schemas.xmlsoap.org/soap/envelope/');
+ $soapBody = SimpleSAML\Utils\XML::getDOMChildren($soapEnvelope, 'Body', 'http://schemas.xmlsoap.org/soap/envelope/');
if (count($soapBody) === 0) {
throw new SimpleSAML_Error_Exception('Couldn\'t find <soap:Body> in <soap:Envelope>.');
}
$soapBody = $soapBody[0];
- $responseElement = SimpleSAML_Utilities::getDOMChildren($soapBody, 'Response', 'urn:oasis:names:tc:SAML:1.0:protocol');
+ $responseElement = SimpleSAML\Utils\XML::getDOMChildren($soapBody, 'Response', 'urn:oasis:names:tc:SAML:1.0:protocol');
if (count($responseElement) === 0) {
throw new SimpleSAML_Error_Exception('Couldn\'t find <saml1p:Response> in <soap:Body>.');
}
@@ -121,7 +121,7 @@ class SimpleSAML_Bindings_Shib13_Artifact {
$artifacts = self::getArtifacts();
$request = self::buildRequest($artifacts);
- SimpleSAML_Utilities::debugMessage($msgStr, 'out');
+ \SimpleSAML\Utils\XML::debugSAMLMessage($request, 'out');
$url = $idpMetadata->getDefaultEndpoint('ArtifactResolutionService', array('urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding'));
$url = $url['Location'];
@@ -137,12 +137,12 @@ class SimpleSAML_Bindings_Shib13_Artifact {
"-----END CERTIFICATE-----\n";
}
- $file = SimpleSAML_Utilities::getTempDir() . '/' . sha1($certData) . '.crt';
+ $file = SimpleSAML\Utils\System::getTempDir() . DIRECTORY_SEPARATOR . sha1($certData) . '.crt';
if (!file_exists($file)) {
- SimpleSAML_Utilities::writeFile($file, $certData);
+ SimpleSAML\Utils\System::writeFile($file, $certData);
}
- $spKeyCertFile = SimpleSAML_Utilities::resolveCert($spMetadata->getString('privatekey'));
+ $spKeyCertFile = \SimpleSAML\Utils\Config::getCertPath($spMetadata->getString('privatekey'));
$opts = array(
'ssl' => array(
@@ -161,12 +161,12 @@ class SimpleSAML_Bindings_Shib13_Artifact {
);
/* Fetch the artifact. */
- $response = SimpleSAML_Utilities::fetch($url, $opts);
+ $response = \SimpleSAML\Utils\HTTP::fetch($url, $opts);
if ($response === FALSE) {
throw new SimpleSAML_Error_Exception('Failed to retrieve assertion from IdP.');
}
- SimpleSAML_Utilities::debugMessage($response, 'in');
+ \SimpleSAML\Utils\XML::debugSAMLMessage($response, 'in');
/* Find the response in the SOAP message. */
$response = self::extractResponse($response);
diff --git a/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php b/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
index f9f5d8a..c97cf89 100644
--- a/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
+++ b/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
@@ -3,7 +3,7 @@
/**
* Implementation of the Shibboleth 1.3 HTTP-POST binding.
*
- * @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
+ * @author Andreas Ã…kre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @package simpleSAMLphp
*/
class SimpleSAML_Bindings_Shib13_HTTPPost {
@@ -27,10 +27,10 @@ class SimpleSAML_Bindings_Shib13_HTTPPost {
*/
public function sendResponse($response, SimpleSAML_Configuration $idpmd, SimpleSAML_Configuration $spmd, $relayState, $shire) {
- SimpleSAML_Utilities::validateXMLDocument($response, 'saml11');
+ \SimpleSAML\Utils\XML::checkSAMLMessage($response, 'saml11');
- $privatekey = SimpleSAML_Utilities::loadPrivateKey($idpmd, TRUE);
- $publickey = SimpleSAML_Utilities::loadPublicKey($idpmd, TRUE);
+ $privatekey = SimpleSAML\Utils\Crypto::loadPrivateKey($idpmd, TRUE);
+ $publickey = SimpleSAML\Utils\Crypto::loadPublicKey($idpmd, TRUE);
$responsedom = new DOMDocument();
$responsedom->loadXML(str_replace ("\r", "", $response));
@@ -67,7 +67,7 @@ class SimpleSAML_Bindings_Shib13_HTTPPost {
if ($signResponse) {
/* Sign the response - this must be done after encrypting the assertion. */
/* We insert the signature before the saml2p:Status element. */
- $statusElements = SimpleSAML_Utilities::getDOMChildren($responseroot, 'Status', '@saml1p');
+ $statusElements = SimpleSAML\Utils\XML::getDOMChildren($responseroot, 'Status', '@saml1p');
assert('count($statusElements) === 1');
$signer->sign($responseroot, $responseroot, $statusElements[0]);
@@ -78,9 +78,9 @@ class SimpleSAML_Bindings_Shib13_HTTPPost {
$response = $responsedom->saveXML();
- SimpleSAML_Utilities::debugMessage($response, 'out');
+ \SimpleSAML\Utils\XML::debugSAMLMessage($response, 'out');
- SimpleSAML_Utilities::postRedirect($shire, array(
+ \SimpleSAML\Utils\HTTP::submitPOSTData($shire, array(
'TARGET' => $relayState,
'SAMLResponse' => base64_encode($response),
));
@@ -103,9 +103,9 @@ class SimpleSAML_Bindings_Shib13_HTTPPost {
$rawResponse = $post['SAMLResponse'];
$samlResponseXML = base64_decode($rawResponse);
- SimpleSAML_Utilities::debugMessage($samlResponseXML, 'in');
+ \SimpleSAML\Utils\XML::debugSAMLMessage($samlResponseXML, 'in');
- SimpleSAML_Utilities::validateXMLDocument($samlResponseXML, 'saml11');
+ \SimpleSAML\Utils\XML::checkSAMLMessage($samlResponseXML, 'saml11');
$samlResponse = new SimpleSAML_XML_Shib13_AuthnResponse();
$samlResponse->setXML($samlResponseXML);
diff --git a/lib/SimpleSAML/Configuration.php b/lib/SimpleSAML/Configuration.php
index 40941d5..deff4a6 100644
--- a/lib/SimpleSAML/Configuration.php
+++ b/lib/SimpleSAML/Configuration.php
@@ -111,7 +111,7 @@ class SimpleSAML_Configuration {
$host = $_SERVER['HTTP_HOST'];
if (array_key_exists($host, $config['override.host'])) {
$ofs = $config['override.host'][$host];
- foreach (SimpleSAML_Utilities::arrayize($ofs) AS $of) {
+ foreach (SimpleSAML\Utils\Arrays::arrayize($ofs) AS $of) {
$overrideFile = dirname($filename) . '/' . $of;
if (!file_exists($overrideFile)) {
throw new Exception('Config file [' . $filename . '] requests override for host ' . $host . ' but file does not exists [' . $of . ']');
@@ -346,7 +346,7 @@ class SimpleSAML_Configuration {
if (preg_match('/^\*(.*)$/D', $baseURL, $matches)) {
/* deprecated behaviour, will be removed in the future */
- return SimpleSAML_Utilities::getFirstPathElement(false) . $matches[1];
+ return \SimpleSAML\Utils\HTTP::getFirstPathElement(false) . $matches[1];
}
if (preg_match('#^https?://[^/]*/(.*)$#', $baseURL, $matches)) {
@@ -1020,7 +1020,7 @@ class SimpleSAML_Configuration {
$endpoints = $this->getEndpoints($endpointType);
- $defaultEndpoint = SimpleSAML_Utilities::getDefaultEndpoint($endpoints, $bindings);
+ $defaultEndpoint = \SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint($endpoints, $bindings);
if ($defaultEndpoint !== NULL) {
return $defaultEndpoint;
}
@@ -1118,7 +1118,7 @@ class SimpleSAML_Configuration {
);
} elseif ($this->hasValue($prefix . 'certificate')) {
$file = $this->getString($prefix . 'certificate');
- $file = SimpleSAML_Utilities::resolveCert($file);
+ $file = \SimpleSAML\Utils\Config::getCertPath($file);
$data = @file_get_contents($file);
if ($data === FALSE) {
diff --git a/lib/SimpleSAML/Error/Error.php b/lib/SimpleSAML/Error/Error.php
index a08ffdd..a276d8f 100644
--- a/lib/SimpleSAML/Error/Error.php
+++ b/lib/SimpleSAML/Error/Error.php
@@ -202,7 +202,7 @@ class SimpleSAML_Error_Error extends SimpleSAML_Error_Exception {
$emsg = array_shift($data);
$etrace = implode("\n", $data);
- $reportId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(4));
+ $reportId = bin2hex(openssl_random_pseudo_bytes(4));
SimpleSAML_Logger::error('Error report with id ' . $reportId . ' generated.');
$config = SimpleSAML_Configuration::getInstance();
@@ -226,7 +226,7 @@ class SimpleSAML_Error_Error extends SimpleSAML_Error_Exception {
'exceptionTrace' => $etrace,
'reportId' => $reportId,
'trackId' => $session->getTrackID(),
- 'url' => SimpleSAML_Utilities::selfURLNoQuery(),
+ 'url' => \SimpleSAML\Utils\HTTP::getSelfURLNoQuery(),
'version' => $config->getVersion(),
'referer' => $referer,
);
@@ -265,7 +265,7 @@ class SimpleSAML_Error_Error extends SimpleSAML_Error_Exception {
if($config->getBoolean('errorreporting', TRUE) &&
$config->getString('technicalcontact_email', 'na@example.org') !== 'na@example.org') {
/* Enable error reporting. */
- $baseurl = SimpleSAML_Utilities::getBaseURL();
+ $baseurl = \SimpleSAML\Utils\HTTP::getBaseURL();
$data['errorReportAddress'] = $baseurl . 'errorreport.php';
}
diff --git a/lib/SimpleSAML/Error/NotFound.php b/lib/SimpleSAML/Error/NotFound.php
index cb868e8..251ff19 100644
--- a/lib/SimpleSAML/Error/NotFound.php
+++ b/lib/SimpleSAML/Error/NotFound.php
@@ -27,7 +27,7 @@ class SimpleSAML_Error_NotFound extends SimpleSAML_Error_Error {
assert('is_null($reason) || is_string($reason)');
- $url = SimpleSAML_Utilities::selfURL();
+ $url = \SimpleSAML\Utils\HTTP::getSelfURL();
if($reason === NULL) {
parent::__construct(array('NOTFOUND', '%URL%' => $url));
diff --git a/lib/SimpleSAML/IdP.php b/lib/SimpleSAML/IdP.php
index e5566b8..7ba6193 100644
--- a/lib/SimpleSAML/IdP.php
+++ b/lib/SimpleSAML/IdP.php
@@ -531,7 +531,7 @@ class SimpleSAML_IdP {
public static function finishLogoutRedirect(SimpleSAML_IdP $idp, array $state) {
assert('isset($state["core:Logout:URL"])');
- SimpleSAML_Utilities::redirectTrustedURL($state['core:Logout:URL']);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($state['core:Logout:URL']);
assert('FALSE');
}
diff --git a/lib/SimpleSAML/IdP/LogoutIFrame.php b/lib/SimpleSAML/IdP/LogoutIFrame.php
index 44c3b3d..e7fdc6e 100644
--- a/lib/SimpleSAML/IdP/LogoutIFrame.php
+++ b/lib/SimpleSAML/IdP/LogoutIFrame.php
@@ -48,7 +48,7 @@ class SimpleSAML_IdP_LogoutIFrame extends SimpleSAML_IdP_LogoutHandler {
}
$url = SimpleSAML_Module::getModuleURL('core/idp/logout-iframe.php', $params);
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
}
diff --git a/lib/SimpleSAML/IdP/LogoutTraditional.php b/lib/SimpleSAML/IdP/LogoutTraditional.php
index 4cd16dd..7632cab 100644
--- a/lib/SimpleSAML/IdP/LogoutTraditional.php
+++ b/lib/SimpleSAML/IdP/LogoutTraditional.php
@@ -29,7 +29,7 @@ class SimpleSAML_IdP_LogoutTraditional extends SimpleSAML_IdP_LogoutHandler {
try {
$idp = SimpleSAML_IdP::getByState($association);
$url = call_user_func(array($association['Handler'], 'getLogoutURL'), $idp, $association, $relayState);
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
} catch (Exception $e) {
SimpleSAML_Logger::warning('Unable to initialize logout to ' . var_export($id, TRUE) . '.');
$this->idp->terminateAssociation($id);
diff --git a/lib/SimpleSAML/Logger/LoggingHandlerFile.php b/lib/SimpleSAML/Logger/LoggingHandlerFile.php
index 9ed795e..feab437 100644
--- a/lib/SimpleSAML/Logger/LoggingHandlerFile.php
+++ b/lib/SimpleSAML/Logger/LoggingHandlerFile.php
@@ -56,7 +56,7 @@ class SimpleSAML_Logger_LoggingHandlerFile implements SimpleSAML_Logger_LoggingH
}
}
- SimpleSAML_Utilities::initTimezone();
+ SimpleSAML\Utils\Time::initTimezone();
}
diff --git a/lib/SimpleSAML/Logger/LoggingHandlerSyslog.php b/lib/SimpleSAML/Logger/LoggingHandlerSyslog.php
index f6d58b1..6b8abef 100644
--- a/lib/SimpleSAML/Logger/LoggingHandlerSyslog.php
+++ b/lib/SimpleSAML/Logger/LoggingHandlerSyslog.php
@@ -27,7 +27,7 @@ class SimpleSAML_Logger_LoggingHandlerSyslog implements SimpleSAML_Logger_Loggin
$processname = $config->getString('logging.processname', 'simpleSAMLphp');
// Setting facility to LOG_USER (only valid in Windows), enable log level rewrite on windows systems.
- if (SimpleSAML_Utilities::isWindowsOS()) {
+ if (SimpleSAML\Utils\System::getOS() === SimpleSAML\Utils\System::WINDOWS) {
$this->isWindows = TRUE;
$facility = LOG_USER;
}
diff --git a/lib/SimpleSAML/Memcache.php b/lib/SimpleSAML/Memcache.php
index 33d4584..791f43a 100644
--- a/lib/SimpleSAML/Memcache.php
+++ b/lib/SimpleSAML/Memcache.php
@@ -403,7 +403,7 @@ class SimpleSAML_Memcache {
throw new Exception('Failed to get memcache server status.');
}
- $stats = SimpleSAML_Utilities::transposeArray($stats);
+ $stats = SimpleSAML\Utils\Arrays::transpose($stats);
$ret = array_merge_recursive($ret, $stats);
}
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
index 3e08619..aa93416 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
@@ -89,7 +89,7 @@ class SimpleSAML_Metadata_MetaDataStorageHandler {
$config = SimpleSAML_Configuration::getInstance();
assert($config instanceof SimpleSAML_Configuration);
- $baseurl = SimpleSAML_Utilities::selfURLhost() . '/' .
+ $baseurl = \SimpleSAML\Utils\HTTP::getSelfURLHost() . '/' .
$config->getBaseURL();
if ($set == 'saml20-sp-hosted') {
@@ -144,7 +144,7 @@ class SimpleSAML_Metadata_MetaDataStorageHandler {
unset($srcList[$key]);
SimpleSAML_Logger::warning("Dropping metadata entity " .
var_export($key,true) . ", expired " .
- SimpleSAML_Utilities::generateTimestamp($le['expire']) .
+ SimpleSAML\Utils\Time::generateTimestamp($le['expire']) .
".");
}
}
@@ -187,7 +187,7 @@ class SimpleSAML_Metadata_MetaDataStorageHandler {
assert('is_string($set)');
/* First we look for the hostname/path combination. */
- $currenthostwithpath = SimpleSAML_Utilities::getSelfHostWithPath(); // sp.example.org/university
+ $currenthostwithpath = \SimpleSAML\Utils\HTTP::getSelfHostWithPath(); // sp.example.org/university
foreach($this->sources as $source) {
$index = $source->getEntityIdFromHostPath($currenthostwithpath, $set, $type);
@@ -198,7 +198,7 @@ class SimpleSAML_Metadata_MetaDataStorageHandler {
/* Then we look for the hostname. */
- $currenthost = SimpleSAML_Utilities::getSelfHost(); // sp.example.org
+ $currenthost = \SimpleSAML\Utils\HTTP::getSelfHost(); // sp.example.org
if(strpos($currenthost, ":") !== FALSE) {
$currenthostdecomposed = explode(":", $currenthost);
$currenthost = $currenthostdecomposed[0];
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
index 22688c2..656426b 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
@@ -116,16 +116,16 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerFlatFile extends SimpleSAML_Meta
private function generateDynamicHostedEntityID($set) {
/* Get the configuration. */
- $baseurl = SimpleSAML_Utilities::getBaseURL();
+ $baseurl = \SimpleSAML\Utils\HTTP::getBaseURL();
if ($set === 'saml20-idp-hosted') {
return $baseurl . 'saml2/idp/metadata.php';
} elseif($set === 'shib13-idp-hosted') {
return $baseurl . 'shib13/idp/metadata.php';
} elseif($set === 'wsfed-sp-hosted') {
- return 'urn:federation:' . SimpleSAML_Utilities::getSelfHost();
+ return 'urn:federation:' . \SimpleSAML\Utils\HTTP::getSelfHost();
} elseif($set === 'adfs-idp-hosted') {
- return 'urn:federation:' . SimpleSAML_Utilities::getSelfHost() . ':idp';
+ return 'urn:federation:' . \SimpleSAML\Utils\HTTP::getSelfHost() . ':idp';
} else {
throw new Exception('Can not generate dynamic EntityID for metadata of this type: [' . $set . ']');
}
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
index 7364a6f..7f61a62 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerMDX.php
@@ -140,8 +140,9 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerMDX extends SimpleSAML_Metadata_
$rawData = file_get_contents($cachefilename);
if (empty($rawData)) {
+ $error = error_get_last();
throw new Exception('Error reading metadata from cache file "' . $cachefilename . '": ' .
- SimpleSAML_Utilities::getLastError());
+ $error['message']);
}
$data = unserialize($rawData);
@@ -252,14 +253,15 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerMDX extends SimpleSAML_Metadata_
SimpleSAML_Logger::debug('MetaData - Handler.MDX: Downloading metadata for "'. $index .'" from [' . $mdx_url . ']' );
try {
- $xmldata = SimpleSAML_Utilities::fetch($mdx_url);
+ $xmldata = \SimpleSAML\Utils\HTTP::fetch($mdx_url);
} catch(Exception $e) {
SimpleSAML_Logger::warning('Fetching metadata for ' . $index . ': ' . $e->getMessage());
}
if (empty($xmldata)) {
+ $error = error_get_last();
throw new Exception('Error downloading metadata for "'. $index .'" from "' . $mdx_url . '": ' .
- SimpleSAML_Utilities::getLastError());
+ $error['message']);
}
$entity = SimpleSAML_Metadata_SAMLParser::parseString($xmldata);
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
index 3415cd5..fae34c9 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
@@ -164,8 +164,9 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerSerialize extends SimpleSAML_Met
$data = @file_get_contents($filePath);
if ($data === FALSE) {
+ $error = error_get_last();
SimpleSAML_Logger::warning('Error reading file ' . $filePath .
- ': ' . SimpleSAML_Utilities::getLastError());
+ ': ' . $error['message']);
return NULL;
}
@@ -199,8 +200,9 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerSerialize extends SimpleSAML_Met
SimpleSAML_Logger::info('Creating directory: ' . $dir);
$res = @mkdir($dir, 0777, TRUE);
if ($res === FALSE) {
+ $error = error_get_last();
SimpleSAML_Logger::error('Failed to create directory ' . $dir .
- ': ' . SimpleSAML_Utilities::getLastError());
+ ': ' . $error['message']);
return FALSE;
}
}
@@ -211,15 +213,17 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerSerialize extends SimpleSAML_Met
$res = file_put_contents($newPath, $data);
if ($res === FALSE) {
+ $error = error_get_last();
SimpleSAML_Logger::error('Error saving file ' . $newPath .
- ': ' . SimpleSAML_Utilities::getLastError());
+ ': ' . $error['message']);
return FALSE;
}
$res = rename($newPath, $filePath);
if ($res === FALSE) {
+ $error = error_get_last();
SimpleSAML_Logger::error('Error renaming ' . $newPath . ' to ' . $filePath .
- ': ' . SimpleSAML_Utilities::getLastError());
+ ': ' . $error['message']);
return FALSE;
}
@@ -248,8 +252,9 @@ class SimpleSAML_Metadata_MetaDataStorageHandlerSerialize extends SimpleSAML_Met
$res = unlink($filePath);
if ($res === FALSE) {
+ $error = error_get_last();
SimpleSAML_Logger::error('Failed to delete file ' . $filePath .
- ': ' . SimpleSAML_Utilities::getLastError());
+ ': ' . $error['message']);
}
}
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
index 549d920..1fc1160 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
@@ -152,7 +152,7 @@ abstract class SimpleSAML_Metadata_MetaDataStorageSource {
if(!is_array($entry['hint.cidr'])) continue;
foreach ($entry['hint.cidr'] AS $hint_entry) {
- if (SimpleSAML_Utilities::ipCIDRcheck($hint_entry, $ip)) {
+ if (SimpleSAML\Utils\Net::ipCIDRcheck($hint_entry, $ip)) {
if ($type === 'entityid') {
return $entry['entityid'];
} else {
@@ -178,7 +178,7 @@ abstract class SimpleSAML_Metadata_MetaDataStorageSource {
$metadataSet = $this->getMetadataSet($set);
/* Check for hostname. */
- $currenthost = SimpleSAML_Utilities::getSelfHost(); // sp.example.org
+ $currenthost = \SimpleSAML\Utils\HTTP::getSelfHost(); // sp.example.org
if(strpos($currenthost, ":") !== FALSE) {
$currenthostdecomposed = explode(":", $currenthost);
$currenthost = $currenthostdecomposed[0];
diff --git a/lib/SimpleSAML/Metadata/SAMLBuilder.php b/lib/SimpleSAML/Metadata/SAMLBuilder.php
index f684d82..703d28c 100644
--- a/lib/SimpleSAML/Metadata/SAMLBuilder.php
+++ b/lib/SimpleSAML/Metadata/SAMLBuilder.php
@@ -78,7 +78,7 @@ class SimpleSAML_Metadata_SAMLBuilder {
$xml = $this->getEntityDescriptor();
if ($formatted) {
- SimpleSAML_Utilities::formatDOMElement($xml);
+ SimpleSAML\Utils\XML::formatDOMElement($xml);
}
return $xml->ownerDocument->saveXML();
@@ -277,9 +277,9 @@ class SimpleSAML_Metadata_SAMLBuilder {
return;
}
- $orgName = SimpleSAML_Utilities::arrayize($metadata['OrganizationName'], 'en');
- $orgDisplayName = SimpleSAML_Utilities::arrayize($metadata['OrganizationDisplayName'], 'en');
- $orgURL = SimpleSAML_Utilities::arrayize($metadata['OrganizationURL'], 'en');
+ $orgName = SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationName'], 'en');
+ $orgDisplayName = SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationDisplayName'], 'en');
+ $orgURL = SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationURL'], 'en');
$this->addOrganization($orgName, $orgDisplayName, $orgURL);
}
@@ -441,6 +441,15 @@ class SimpleSAML_Metadata_SAMLBuilder {
$e = new SAML2_XML_md_SPSSODescriptor();
$e->protocolSupportEnumeration = $protocols;
+ if ($metadata->hasValue('saml20.sign.assertion')) {
+ $e->WantAssertionsSigned = $metadata->getBoolean('saml20.sign.assertion');
+ }
+
+ if ($metadata->hasValue('redirect.validate')) {
+ $e->AuthnRequestsSigned = $metadata->getBoolean('redirect.validate');
+ } elseif ($metadata->hasValue('validate.authnrequest')) {
+ $e->AuthnRequestsSigned = $metadata->getBoolean('validate.authnrequest');
+ }
$this->addExtensions($metadata, $e);
@@ -465,7 +474,7 @@ class SimpleSAML_Metadata_SAMLBuilder {
foreach ($metadata->getArray('contacts', array()) as $contact) {
if (array_key_exists('contactType', $contact) && array_key_exists('emailAddress', $contact)) {
- $this->addContact($contact['contactType'], SimpleSAML_Utils_Config_Metadata::getContact($contact));
+ $this->addContact($contact['contactType'], \SimpleSAML\Utils\Config\Metadata::getContact($contact));
}
}
@@ -511,7 +520,7 @@ class SimpleSAML_Metadata_SAMLBuilder {
foreach ($metadata->getArray('contacts', array()) as $contact) {
if (array_key_exists('contactType', $contact) && array_key_exists('emailAddress', $contact)) {
- $this->addContact($contact['contactType'], SimpleSAML_Utils_Config_Metadata::getContact($contact));
+ $this->addContact($contact['contactType'], \SimpleSAML\Utils\Config\Metadata::getContact($contact));
}
}
@@ -624,7 +633,7 @@ class SimpleSAML_Metadata_SAMLBuilder {
assert('in_array($type, array("technical", "support", "administrative", "billing", "other"), TRUE)');
// TODO: remove this check as soon as getContact() is called always before calling this function.
- $details = SimpleSAML_Utils_Config_Metadata::getContact($details);
+ $details = \SimpleSAML\Utils\Config\Metadata::getContact($details);
$e = new SAML2_XML_md_ContactPerson();
$e->contactType = $type;
diff --git a/lib/SimpleSAML/Metadata/SAMLParser.php b/lib/SimpleSAML/Metadata/SAMLParser.php
index cc5b84e..c141a5c 100644
--- a/lib/SimpleSAML/Metadata/SAMLParser.php
+++ b/lib/SimpleSAML/Metadata/SAMLParser.php
@@ -178,7 +178,7 @@ class SimpleSAML_Metadata_SAMLParser {
public static function parseFile($file) {
$doc = new DOMDocument();
- $data = SimpleSAML_Utilities::fetch($file);
+ $data = \SimpleSAML\Utils\HTTP::fetch($file);
$res = $doc->loadXML($data);
if($res !== TRUE) {
@@ -248,7 +248,7 @@ class SimpleSAML_Metadata_SAMLParser {
if ($file === NULL) throw new Exception('Cannot open file NULL. File name not specified.');
- $data = SimpleSAML_Utilities::fetch($file);
+ $data = \SimpleSAML\Utils\HTTP::fetch($file);
$doc = new DOMDocument();
$res = $doc->loadXML($data);
@@ -297,9 +297,9 @@ class SimpleSAML_Metadata_SAMLParser {
assert('$element instanceof DOMElement');
- if(SimpleSAML_Utilities::isDOMElementOfType($element, 'EntityDescriptor', '@md') === TRUE) {
+ if (SimpleSAML\Utils\XML::isDOMElementOfType($element, 'EntityDescriptor', '@md') === TRUE) {
return self::processDescriptorsElement(new SAML2_XML_md_EntityDescriptor($element));
- } elseif(SimpleSAML_Utilities::isDOMElementOfType($element, 'EntitiesDescriptor', '@md') === TRUE) {
+ } elseif (SimpleSAML\Utils\XML::isDOMElementOfType($element, 'EntitiesDescriptor', '@md') === TRUE) {
return self::processDescriptorsElement(new SAML2_XML_md_EntitiesDescriptor($element));
} else {
throw new Exception('Unexpected root node: [' . $element->namespaceURI . ']:' .
@@ -1016,8 +1016,8 @@ class SimpleSAML_Metadata_SAMLParser {
$name = $attribute->getAttribute('Name');
$values = array_map(
- array('SimpleSAML_Utilities', 'getDOMText'),
- SimpleSAML_Utilities::getDOMChildren($attribute, 'AttributeValue', '@saml2')
+ array('SimpleSAML\Utils\XML', 'getDOMText'),
+ SimpleSAML\Utils\XML::getDOMChildren($attribute, 'AttributeValue', '@saml2')
);
if ($name === 'tags') {
@@ -1293,7 +1293,7 @@ class SimpleSAML_Metadata_SAMLParser {
throw new Exception('Failed to load SAML metadata from empty XML document.');
}
- if(SimpleSAML_Utilities::isDOMElementOfType($ed, 'EntityDescriptor', '@md') === FALSE) {
+ if (SimpleSAML\Utils\XML::isDOMElementOfType($ed, 'EntityDescriptor', '@md') === FALSE) {
throw new Exception('Expected first element in the metadata document to be an EntityDescriptor element.');
}
@@ -1311,7 +1311,7 @@ class SimpleSAML_Metadata_SAMLParser {
public function validateSignature($certificates) {
foreach ($certificates as $cert) {
assert('is_string($cert)');
- $certFile = SimpleSAML_Utilities::resolveCert($cert);
+ $certFile = \SimpleSAML\Utils\Config::getCertPath($cert);
if (!file_exists($certFile)) {
throw new Exception('Could not find certificate file [' . $certFile . '], which is needed to validate signature');
}
diff --git a/lib/SimpleSAML/Metadata/Signer.php b/lib/SimpleSAML/Metadata/Signer.php
index 51c29d3..a53201b 100644
--- a/lib/SimpleSAML/Metadata/Signer.php
+++ b/lib/SimpleSAML/Metadata/Signer.php
@@ -142,13 +142,13 @@ class SimpleSAML_Metadata_Signer {
$keyCertFiles = self::findKeyCert($config, $entityMetadata, $type);
- $keyFile = SimpleSAML_Utilities::resolveCert($keyCertFiles['privatekey']);
+ $keyFile = \SimpleSAML\Utils\Config::getCertPath($keyCertFiles['privatekey']);
if (!file_exists($keyFile)) {
throw new Exception('Could not find private key file [' . $keyFile . '], which is needed to sign the metadata');
}
$keyData = file_get_contents($keyFile);
- $certFile = SimpleSAML_Utilities::resolveCert($keyCertFiles['certificate']);
+ $certFile = \SimpleSAML\Utils\Config::getCertPath($keyCertFiles['certificate']);
if (!file_exists($certFile)) {
throw new Exception('Could not find certificate file [' . $certFile . '], which is needed to sign the metadata');
}
diff --git a/lib/SimpleSAML/Module.php b/lib/SimpleSAML/Module.php
index b5d8f02..45b1ae6 100644
--- a/lib/SimpleSAML/Module.php
+++ b/lib/SimpleSAML/Module.php
@@ -155,9 +155,9 @@ class SimpleSAML_Module {
assert('is_string($resource)');
assert('$resource[0] !== "/"');
- $url = SimpleSAML_Utilities::getBaseURL() . 'module.php/' . $resource;
+ $url = \SimpleSAML\Utils\HTTP::getBaseURL() . 'module.php/' . $resource;
if (!empty($parameters)) {
- $url = SimpleSAML_Utilities::addURLparameter($url, $parameters);
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, $parameters);
}
return $url;
}
diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php
index 3f2af27..42f73b8 100644
--- a/lib/SimpleSAML/Session.php
+++ b/lib/SimpleSAML/Session.php
@@ -137,7 +137,7 @@ class SimpleSAML_Session
$sh = SimpleSAML_SessionHandler::getSessionHandler();
$this->sessionId = $sh->newSessionId();
- $this->trackid = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(5));
+ $this->trackid = bin2hex(openssl_random_pseudo_bytes(5));
$this->dirty = true;
@@ -408,7 +408,7 @@ class SimpleSAML_Session
$this->authData[$authority] = $data;
- $this->authToken = SimpleSAML_Utilities::generateID();
+ $this->authToken = SimpleSAML\Utils\Random::generateID();
$sessionHandler = SimpleSAML_SessionHandler::getSessionHandler();
if (!$this->transient && (!empty($data['RememberMe']) || $this->rememberMeExpire) &&
diff --git a/lib/SimpleSAML/SessionHandler.php b/lib/SimpleSAML/SessionHandler.php
index 8ad3a13..9586d56 100644
--- a/lib/SimpleSAML/SessionHandler.php
+++ b/lib/SimpleSAML/SessionHandler.php
@@ -155,7 +155,7 @@ abstract class SimpleSAML_SessionHandler {
$params = $this->getCookieParams();
}
- SimpleSAML_Utilities::setCookie($name, $value, $params);
+ \SimpleSAML\Utils\HTTP::setCookie($name, $value, $params);
}
}
diff --git a/lib/SimpleSAML/SessionHandlerCookie.php b/lib/SimpleSAML/SessionHandlerCookie.php
index 60b033a..9e47a8a 100644
--- a/lib/SimpleSAML/SessionHandlerCookie.php
+++ b/lib/SimpleSAML/SessionHandlerCookie.php
@@ -93,7 +93,7 @@ extends SimpleSAML_SessionHandler {
* A random session id.
*/
private static function createSessionID() {
- return SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
+ return bin2hex(openssl_random_pseudo_bytes(16));
}
diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php
index afb62a6..9857d84 100644
--- a/lib/SimpleSAML/SessionHandlerPHP.php
+++ b/lib/SimpleSAML/SessionHandlerPHP.php
@@ -68,7 +68,7 @@ class SimpleSAML_SessionHandlerPHP extends SimpleSAML_SessionHandler {
public function newSessionId() {
$session_cookie_params = session_get_cookie_params();
- if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
+ if ($session_cookie_params['secure'] && !\SimpleSAML\Utils\HTTP::isHTTPS()) {
throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
}
@@ -77,7 +77,7 @@ class SimpleSAML_SessionHandlerPHP extends SimpleSAML_SessionHandler {
}
/* Generate new (secure) session id. */
- $sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
+ $sessionId = bin2hex(openssl_random_pseudo_bytes(16));
SimpleSAML_Session::createSession($sessionId);
if (session_id() !== '') {
@@ -105,7 +105,7 @@ class SimpleSAML_SessionHandlerPHP extends SimpleSAML_SessionHandler {
$session_cookie_params = session_get_cookie_params();
- if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
+ if ($session_cookie_params['secure'] && !\SimpleSAML\Utils\HTTP::isHTTPS()) {
throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
}
diff --git a/lib/SimpleSAML/Stats.php b/lib/SimpleSAML/Stats.php
index ec76a3f..acaf1d8 100644
--- a/lib/SimpleSAML/Stats.php
+++ b/lib/SimpleSAML/Stats.php
@@ -80,7 +80,7 @@ class SimpleSAML_Stats {
/* The ID generation is designed to cluster IDs related in time close together. */
$int_t = (int)$data['time'];
- $hd = SimpleSAML_Utilities::generateRandomBytes(16);
+ $hd = openssl_random_pseudo_bytes(16);
$data['_id'] = sprintf('%016x%s', $int_t, bin2hex($hd));
foreach (self::$outputs as $out) {
diff --git a/lib/SimpleSAML/Store.php b/lib/SimpleSAML/Store.php
index e45d4a7..2ea922d 100644
--- a/lib/SimpleSAML/Store.php
+++ b/lib/SimpleSAML/Store.php
@@ -47,9 +47,6 @@ abstract class SimpleSAML_Store {
self::$instance = new SimpleSAML_Store_SQL();
break;
default:
- if (strpos($storeType, ':') === FALSE) {
- throw new SimpleSAML_Error_Exception('Unknown datastore type: ' . var_export($storeType, TRUE));
- }
/* Datastore from module. */
$className = SimpleSAML_Module::resolveClass($storeType, 'Store', 'SimpleSAML_Store');
self::$instance = new $className();
diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index 44a9fbf..5f0e7cf 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -29,341 +29,100 @@ class SimpleSAML_Utilities {
/**
- * Will return sp.example.org
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getSelfHost() instead.
*/
public static function getSelfHost() {
-
- $url = self::getBaseURL();
-
- $start = strpos($url,'://') + 3;
- $length = strcspn($url,'/:',$start);
-
- return substr($url, $start, $length);
-
- }
-
- /**
- * Retrieve Host value from $_SERVER environment variables
- */
- private static function getServerHost() {
-
- if (array_key_exists('HTTP_HOST', $_SERVER)) {
- $currenthost = $_SERVER['HTTP_HOST'];
- } elseif (array_key_exists('SERVER_NAME', $_SERVER)) {
- $currenthost = $_SERVER['SERVER_NAME'];
- } else {
- /* Almost certainly not what you want, but ... */
- $currenthost = 'localhost';
- }
-
- if(strstr($currenthost, ":")) {
- $currenthostdecomposed = explode(":", $currenthost);
- $port = array_pop($currenthostdecomposed);
- if (!is_numeric($port)) {
- array_push($currenthostdecomposed, $port);
- }
- $currenthost = implode($currenthostdecomposed, ":");
- }
- return $currenthost;
-
+ return \SimpleSAML\Utils\HTTP::getSelfHost();
}
/**
- * Will return https://sp.example.org[:PORT]
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getSelfURLHost() instead.
*/
public static function selfURLhost() {
-
- $url = self::getBaseURL();
-
- $start = strpos($url,'://') + 3;
- $length = strcspn($url,'/',$start) + $start;
-
- return substr($url, 0, $length);
+ return \SimpleSAML\Utils\HTTP::getSelfURLHost();
}
/**
- * This function checks if we should set a secure cookie.
- *
- * @return TRUE if the cookie should be secure, FALSE otherwise.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::isHTTPS() instead.
*/
public static function isHTTPS() {
-
- $url = self::getBaseURL();
-
- $end = strpos($url,'://');
- $protocol = substr($url, 0, $end);
-
- if ($protocol === 'https') {
- return TRUE;
- } else {
- return FALSE;
- }
-
- }
-
- /**
- * retrieve HTTPS status from $_SERVER environment variables
- */
- private static function getServerHTTPS() {
-
- if(!array_key_exists('HTTPS', $_SERVER)) {
- /* Not an https-request. */
- return FALSE;
- }
-
- if($_SERVER['HTTPS'] === 'off') {
- /* IIS with HTTPS off. */
- return FALSE;
- }
-
- /* Otherwise, HTTPS will be a non-empty string. */
- return $_SERVER['HTTPS'] !== '';
-
+ return \SimpleSAML\Utils\HTTP::isHTTPS();
}
/**
- * Retrieve port number from $_SERVER environment variables
- * return it as a string such as ":80" if different from
- * protocol default port, otherwise returns an empty string
- */
- private static function getServerPort() {
-
- if (isset($_SERVER["SERVER_PORT"])) {
- $portnumber = $_SERVER["SERVER_PORT"];
- } else {
- $portnumber = 80;
- }
- $port = ':' . $portnumber;
-
- if (self::getServerHTTPS()) {
- if ($portnumber == '443') $port = '';
- } else {
- if ($portnumber == '80') $port = '';
- }
-
- return $port;
-
- }
-
- /**
- * Will return https://sp.example.org/universities/ruc/baz/simplesaml/saml2/SSOService.php
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getSelfURLNoQuery() instead.
*/
public static function selfURLNoQuery() {
-
- $selfURLhost = self::selfURLhost();
- $selfURLhost .= $_SERVER['SCRIPT_NAME'];
- if (isset($_SERVER['PATH_INFO'])) {
- $selfURLhost .= $_SERVER['PATH_INFO'];
- }
- return $selfURLhost;
+ return \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
}
/**
- * Will return sp.example.org/ssp/sp1
- *
- * Please note this function will return the base URL for the current
- * SP, as defined in the global configuration.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getSelfHostWithPath() instead.
*/
public static function getSelfHostWithPath() {
-
- $baseurl = explode("/", self::getBaseURL());
- $elements = array_slice($baseurl, 3 - count($baseurl), count($baseurl) - 4);
- $path = implode("/", $elements);
- $selfhostwithpath = self::getSelfHost();
- return $selfhostwithpath . "/" . $path;
+ return \SimpleSAML\Utils\HTTP::getSelfHostWithPath();
}
-
+
+
/**
- * Will return foo
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getFirstPathElement() instead.
*/
public static function getFirstPathElement($trailingslash = true) {
-
- if (preg_match('|^/(.*?)/|', $_SERVER['SCRIPT_NAME'], $matches)) {
- return ($trailingslash ? '/' : '') . $matches[1];
- }
- return '';
+ return \SimpleSAML\Utils\HTTP::getFirstPathElement($trailingslash);
}
-
- public static function selfURL() {
-
- $selfURLhost = self::selfURLhost();
-
- $requestURI = $_SERVER['REQUEST_URI'];
- if ($requestURI[0] !== '/') {
- /* We probably have a URL of the form: http://server/. */
- if (preg_match('#^https?://[^/]*(/.*)#i', $requestURI, $matches)) {
- $requestURI = $matches[1];
- }
- }
-
- return $selfURLhost . $requestURI;
+ /**
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getSelfURL() instead.
+ */
+ public static function selfURL() {
+ return \SimpleSAML\Utils\HTTP::getSelfURL();
}
/**
- * Retrieve and return the absolute base URL for the simpleSAMLphp installation.
- *
- * For example: https://idp.example.org/simplesaml/
- *
- * The URL will always end with a '/'.
- *
- * @return string The absolute base URL for the simpleSAMLphp installation.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getBaseURL() instead.
*/
public static function getBaseURL() {
-
- $globalConfig = SimpleSAML_Configuration::getInstance();
- $baseURL = $globalConfig->getString('baseurlpath', 'simplesaml/');
-
- if (preg_match('#^https?://.*/$#D', $baseURL, $matches)) {
- /* full URL in baseurlpath, override local server values */
- return $baseURL;
- } elseif (
- (preg_match('#^/?([^/]?.*/)$#D', $baseURL, $matches)) ||
- (preg_match('#^\*(.*)/$#D', $baseURL, $matches)) ||
- ($baseURL === '')) {
- /* get server values */
-
- if (self::getServerHTTPS()) {
- $protocol = 'https://';
- } else {
- $protocol = 'http://';
- }
-
- $hostname = self::getServerHost();
- $port = self::getServerPort();
- $path = '/' . $globalConfig->getBaseURL();
-
- return $protocol.$hostname.$port.$path;
- } else {
- throw new SimpleSAML_Error_Exception('Invalid value of \'baseurl\' in '.
- 'config.php. Valid format is in the form: '.
- '[(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/]. '.
- 'It must end with a \'/\'.');
- }
-
+ return \SimpleSAML\Utils\HTTP::getBaseURL();
}
/**
- * Add one or more query parameters to the given URL.
- *
- * @param $url The URL the query parameters should be added to.
- * @param $parameter The query parameters which should be added to the url. This should be
- * an associative array. For backwards comaptibility, it can also be a
- * query string representing the new parameters. This will write a warning
- * to the log.
- * @return The URL with the new query parameters.
- */
- public static function addURLparameter($url, $parameter) {
-
- /* For backwards compatibility - allow $parameter to be a string. */
- if(is_string($parameter)) {
- /* Print warning to log. */
- $backtrace = debug_backtrace();
- $where = $backtrace[0]['file'] . ':' . $backtrace[0]['line'];
- SimpleSAML_Logger::warning(
- 'Deprecated use of SimpleSAML_Utilities::addURLparameter at ' . $where .
- '. The parameter "$parameter" should now be an array, but a string was passed.');
-
- $parameter = self::parseQueryString($parameter);
- }
- assert('is_array($parameter)');
-
- $queryStart = strpos($url, '?');
- if($queryStart === FALSE) {
- $oldQuery = array();
- $url .= '?';
- } else {
- $oldQuery = substr($url, $queryStart + 1);
- if($oldQuery === FALSE) {
- $oldQuery = array();
- } else {
- $oldQuery = self::parseQueryString($oldQuery);
- }
- $url = substr($url, 0, $queryStart + 1);
- }
-
- $query = array_merge($oldQuery, $parameter);
- $url .= http_build_query($query, '', '&');
-
- return $url;
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::addURLParameters() instead.
+ */
+ public static function addURLparameter($url, $parameters) {
+ return \SimpleSAML\Utils\HTTP::addURLParameters($url, $parameters);
}
/**
- * Check if a URL is valid and is in our list of allowed URLs.
- *
- * @param string $url The URL to check.
- * @param array $trustedSites An optional white list of domains. If none specified, the 'trusted.url.domains'
- * configuration directive will be used.
- * @return string The normalized URL itself if it is allowed. An empty string if the $url parameter is empty as
- * defined by the empty() function.
- * @throws SimpleSAML_Error_Exception if the URL is malformed or is not allowed by configuration.
+ * @deprecated This method will be removed in SSP 2.0. Please use \SimpleSAML\Utils\HTTP::checkURLAllowed() instead.
*/
public static function checkURLAllowed($url, array $trustedSites = NULL) {
- if (empty($url)) {
- return '';
- }
- $url = self::normalizeURL($url);
-
- // get the white list of domains
- if ($trustedSites === NULL) {
- $trustedSites = SimpleSAML_Configuration::getInstance()->getArray('trusted.url.domains', NULL);
- if ($trustedSites === NULL) {
- $trustedSites = SimpleSAML_Configuration::getInstance()->getArray('redirect.trustedsites', NULL);
- }
- }
-
- // validates the URL's host is among those allowed
- if ($trustedSites !== NULL) {
- assert(is_array($trustedSites));
- preg_match('@^https?://([^/]+)@i', $url, $matches);
- $hostname = $matches[1];
-
- // add self host to the white list
- $self_host = self::getSelfHost();
- $trustedSites[] = $self_host;
-
- /* Throw exception due to redirection to untrusted site */
- if (!in_array($hostname, $trustedSites)) {
- throw new SimpleSAML_Error_Exception('URL not allowed: '.$url);
- }
- }
- return $url;
+ return \SimpleSAML\Utils\HTTP::checkURLAllowed($url, $trustedSites);
}
/**
- * Get the ID and (optionally) a URL embedded in a StateID,
- * in the form 'id:url'.
- *
- * @param string $stateId The state ID to use.
- * @return array A hashed array with the ID and the URL (if any),
- * in the 'id' and 'url' keys, respectively. If there's no URL
- * in the input parameter, NULL will be returned as the value for
- * the 'url' key.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML_Auth_State::parseStateID() instead.
*/
public static function parseStateID($stateId) {
- $tmp = explode(':', $stateId, 2);
- $id = $tmp[0];
- $url = NULL;
- if (count($tmp) === 2) {
- $url = $tmp[1];
- }
- return array('id' => $id, 'url' => $url);
+ return SimpleSAML_Auth_State::parseStateID($stateId);
}
+ /**
+ * @deprecated This method will be removed in SSP 2.0.
+ */
public static function checkDateConditions($start=NULL, $end=NULL) {
$currentTime = time();
-
+
if (!empty($start)) {
$startTime = SAML2_Utils::xsDateTimeToTimestamp($start);
/* Allow for a 10 minute difference in Time */
@@ -381,185 +140,45 @@ class SimpleSAML_Utilities {
}
+ /**
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Random::generateID() instead.
+ */
public static function generateID() {
- return '_' . self::stringToHex(self::generateRandomBytes(21));
+ return SimpleSAML\Utils\Random::generateID();
}
-
+
/**
- * This function generates a timestamp on the form used by the SAML protocols.
- *
- * @param $instant The time the timestamp should represent.
- * @return The timestamp.
+ * @deprecated This method will be removed in SSP 2.0. Please use \SimpleSAML\Utils\Time::generateTimestamp() instead.
*/
public static function generateTimestamp($instant = NULL) {
- if($instant === NULL) {
- $instant = time();
- }
- return gmdate('Y-m-d\TH:i:s\Z', $instant);
+ return SimpleSAML\Utils\Time::generateTimestamp($instant);
}
/**
- * Interpret a ISO8601 duration value relative to a given timestamp.
- *
- * @param string $duration The duration, as a string.
- * @param int $timestamp The unix timestamp we should apply the duration to. Optional, default
- * to the current time.
- * @return int The new timestamp, after the duration is applied.
+ * @deprecated This method will be removed in SSP 2.0. Please use \SimpleSAML\Utils\Time::parseDuration() instead.
*/
public static function parseDuration($duration, $timestamp = NULL) {
- assert('is_string($duration)');
- assert('is_null($timestamp) || is_int($timestamp)');
-
- /* Parse the duration. We use a very strict pattern. */
- $durationRegEx = '#^(-?)P(?:(?:(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:[.,]\d+)?S)?)?)|(?:(\\d+)W))$#D';
- if (!preg_match($durationRegEx, $duration, $matches)) {
- throw new Exception('Invalid ISO 8601 duration: ' . $duration);
- }
-
- $durYears = (empty($matches[2]) ? 0 : (int)$matches[2]);
- $durMonths = (empty($matches[3]) ? 0 : (int)$matches[3]);
- $durDays = (empty($matches[4]) ? 0 : (int)$matches[4]);
- $durHours = (empty($matches[5]) ? 0 : (int)$matches[5]);
- $durMinutes = (empty($matches[6]) ? 0 : (int)$matches[6]);
- $durSeconds = (empty($matches[7]) ? 0 : (int)$matches[7]);
- $durWeeks = (empty($matches[8]) ? 0 : (int)$matches[8]);
-
- if (!empty($matches[1])) {
- /* Negative */
- $durYears = -$durYears;
- $durMonths = -$durMonths;
- $durDays = -$durDays;
- $durHours = -$durHours;
- $durMinutes = -$durMinutes;
- $durSeconds = -$durSeconds;
- $durWeeks = -$durWeeks;
- }
-
- if ($timestamp === NULL) {
- $timestamp = time();
- }
-
- if ($durYears !== 0 || $durMonths !== 0) {
- /* Special handling of months and years, since they aren't a specific interval, but
- * instead depend on the current time.
- */
-
- /* We need the year and month from the timestamp. Unfortunately, PHP doesn't have the
- * gmtime function. Instead we use the gmdate function, and split the result.
- */
- $yearmonth = explode(':', gmdate('Y:n', $timestamp));
- $year = (int)($yearmonth[0]);
- $month = (int)($yearmonth[1]);
-
- /* Remove the year and month from the timestamp. */
- $timestamp -= gmmktime(0, 0, 0, $month, 1, $year);
-
- /* Add years and months, and normalize the numbers afterwards. */
- $year += $durYears;
- $month += $durMonths;
- while ($month > 12) {
- $year += 1;
- $month -= 12;
- }
- while ($month < 1) {
- $year -= 1;
- $month += 12;
- }
-
- /* Add year and month back into timestamp. */
- $timestamp += gmmktime(0, 0, 0, $month, 1, $year);
- }
-
- /* Add the other elements. */
- $timestamp += $durWeeks * 7 * 24 * 60 * 60;
- $timestamp += $durDays * 24 * 60 * 60;
- $timestamp += $durHours * 60 * 60;
- $timestamp += $durMinutes * 60;
- $timestamp += $durSeconds;
-
- return $timestamp;
+ return SimpleSAML\Utils\Time::parseDuration($duration, $timestamp);
}
/**
- * Show and log fatal error message.
- *
- * This function logs a error message to the error log and shows the
- * message to the user. Script execution terminates afterwards.
- *
- * The error code comes from the errors-dictionary. It can optionally include parameters, which
- * will be substituted into the output string.
- *
- * @param string $trackId The trackid of the user, from $session->getTrackID().
- * @param mixed $errorCode Either a string with the error code, or an array with the error code and
- * additional parameters.
- * @param Exception $e The exception which caused the error.
- * @deprecated
+ * @deprecated This method will be removed in SSP 2.0. Please raise a SimpleSAML_Error_Error exception instead.
*/
public static function fatalError($trackId = 'na', $errorCode = null, Exception $e = null) {
-
throw new SimpleSAML_Error_Error($errorCode, $e);
}
/**
- * Check whether an IP address is part of an CIDR.
+ * @deprecated This method will be removed in version 2.0. Use SimpleSAML\Utils\Net::ipCIDRcheck() instead.
*/
static function ipCIDRcheck($cidr, $ip = null) {
- if ($ip == null) $ip = $_SERVER['REMOTE_ADDR'];
- list ($net, $mask) = explode('/', $cidr);
-
- if (strstr($ip, ':') || strstr($net, ':')) {
- // Validate IPv6 with inet_pton, convert to hex with bin2hex
- // then store as a long with hexdec
-
- $ip_pack = inet_pton($ip);
- $net_pack = inet_pton($net);
-
- if ($ip_pack === false || $net_pack === false) {
- // not valid IPv6 address (warning already issued)
- return false;
- }
-
- $ip_ip = str_split(bin2hex($ip_pack),8);
- foreach ($ip_ip as &$value) {
- $value = hexdec($value);
- }
-
- $ip_net = str_split(bin2hex($net_pack),8);
- foreach ($ip_net as &$value) {
- $value = hexdec($value);
- }
- } else {
- $ip_ip[0] = ip2long ($ip);
- $ip_net[0] = ip2long ($net);
- }
-
- for($i = 0; $mask > 0 && $i < sizeof($ip_ip); $i++) {
- if ($mask > 32) {
- $iteration_mask = 32;
- } else {
- $iteration_mask = $mask;
- }
- $mask -= 32;
-
- $ip_mask = ~((1 << (32 - $iteration_mask)) - 1);
-
- $ip_net_mask = $ip_net[$i] & $ip_mask;
- $ip_ip_mask = $ip_ip[$i] & $ip_mask;
-
- if ($ip_ip_mask != $ip_net_mask)
- return false;
- }
- return true;
+ return SimpleSAML\Utils\Net::ipCIDRcheck($cidr, $ip);
}
- /*
- * This is a temporary function, holding the redirect() functionality,
- * meanwhile we are deprecating the it.
- */
private static function _doRedirect($url, $parameters = array()) {
assert('is_string($url)');
assert('!empty($url)');
@@ -617,27 +236,8 @@ class SimpleSAML_Utilities {
/**
- * This function redirects the user to the specified address.
- *
- * This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the
- * HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.
- *
- * The function will also generate a simple web page with a clickable link to the target page.
- *
- * @param string $url The URL we should redirect to. This URL may include query parameters. If this URL is a
- * relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute
- * URL to the root of the website.
- * @param string[] $parameters An array with extra query string parameters which should be appended to the URL. The
- * name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the
- * name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the
- * name, without a value.
- * @param string[] $allowed_redirect_hosts An array with a whitelist of hosts for which redirects are allowed. If
- * NULL, redirections will be allowed to any host. Otherwise, the host of the $url provided must be present in this
- * parameter. If the host is not whitelisted, an exception will be thrown.
- *
- * @return void This function never returns.
- * @deprecated 1.12.0 This function will be removed from the API. Instead, use the redirectTrustedURL or
- * redirectUntrustedURL functions accordingly.
+ * @deprecated 1.12.0 This method will be removed from the API. Instead, use the redirectTrustedURL() or
+ * redirectUntrustedURL() functions accordingly.
*/
public static function redirect($url, $parameters = array(), $allowed_redirect_hosts = NULL) {
assert('is_string($url)');
@@ -653,395 +253,88 @@ class SimpleSAML_Utilities {
}
/**
- * This function redirects to the specified URL without performing any security checks. Please, do NOT use this
- * function with user supplied URLs.
- *
- * This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the
- * HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.
- *
- * The function will also generate a simple web page with a clickable link to the target URL.
- *
- * @param string $url The URL we should redirect to. This URL may include query parameters. If this URL is a
- * relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute
- * URL to the root of the website.
- * @param string[] $parameters An array with extra query string parameters which should be appended to the URL. The
- * name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the
- * name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the
- * name, without a value.
- *
- * @return void This function never returns.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::redirectTrustedURL() instead.
*/
public static function redirectTrustedURL($url, $parameters = array()) {
- assert('is_string($url)');
- assert('is_array($parameters)');
-
- $url = self::normalizeURL($url);
- self::_doRedirect($url, $parameters);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $parameters);
}
/**
- * This function redirects to the specified URL after performing the appropriate security checks on it.
- * Particularly, it will make sure that the provided URL is allowed by the 'redirect.trustedsites' directive in the
- * configuration.
- *
- * If the aforementioned option is not set or the URL does correspond to a trusted site, it performs a redirection
- * to it. If the site is not trusted, an exception will be thrown.
- *
- * See the redirectTrustedURL function for more details.
- *
- * @return void This function never returns.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::redirectUntrustedURL() instead.
*/
public static function redirectUntrustedURL($url, $parameters = array()) {
- assert('is_string($url)');
- assert('is_array($parameters)');
-
- $url = self::checkURLAllowed($url);
- self::_doRedirect($url, $parameters);
+ \SimpleSAML\Utils\HTTP::redirectUntrustedURL($url, $parameters);
}
/**
- * This function transposes a two-dimensional array, so that
- * $a['k1']['k2'] becomes $a['k2']['k1'].
- *
- * @param $in Input two-dimensional array.
- * @return The transposed array.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Arrays::transpose() instead.
*/
public static function transposeArray($in) {
- assert('is_array($in)');
-
- $ret = array();
-
- foreach($in as $k1 => $a2) {
- assert('is_array($a2)');
-
- foreach($a2 as $k2 => $v) {
- if(!array_key_exists($k2, $ret)) {
- $ret[$k2] = array();
- }
-
- $ret[$k2][$k1] = $v;
- }
- }
-
- return $ret;
+ return SimpleSAML\Utils\Arrays::transpose($in);
}
/**
- * This function checks if the DOMElement has the correct localName and namespaceURI.
- *
- * We also define the following shortcuts for namespaces:
- * - '@ds': 'http://www.w3.org/2000/09/xmldsig#'
- * - '@md': 'urn:oasis:names:tc:SAML:2.0:metadata'
- * - '@saml1': 'urn:oasis:names:tc:SAML:1.0:assertion'
- * - '@saml1md': 'urn:oasis:names:tc:SAML:profiles:v1metadata'
- * - '@saml1p': 'urn:oasis:names:tc:SAML:1.0:protocol'
- * - '@saml2': 'urn:oasis:names:tc:SAML:2.0:assertion'
- * - '@saml2p': 'urn:oasis:names:tc:SAML:2.0:protocol'
- *
- * @param $element The element we should check.
- * @param $name The localname the element should have.
- * @param $nsURI The namespaceURI the element should have.
- * @return TRUE if both namespace and localname matches, FALSE otherwise.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::isDOMElementOfType() instead.
*/
public static function isDOMElementOfType(DOMNode $element, $name, $nsURI) {
- assert('is_string($name)');
- assert('is_string($nsURI)');
- assert('strlen($nsURI) > 0');
-
- if (!($element instanceof DOMElement)) {
- /* Most likely a comment-node. */
- return FALSE;
- }
-
- /* Check if the namespace is a shortcut, and expand it if it is. */
- if($nsURI[0] == '@') {
-
- /* The defined shortcuts. */
- $shortcuts = array(
- '@ds' => 'http://www.w3.org/2000/09/xmldsig#',
- '@md' => 'urn:oasis:names:tc:SAML:2.0:metadata',
- '@saml1' => 'urn:oasis:names:tc:SAML:1.0:assertion',
- '@saml1md' => 'urn:oasis:names:tc:SAML:profiles:v1metadata',
- '@saml1p' => 'urn:oasis:names:tc:SAML:1.0:protocol',
- '@saml2' => 'urn:oasis:names:tc:SAML:2.0:assertion',
- '@saml2p' => 'urn:oasis:names:tc:SAML:2.0:protocol',
- '@shibmd' => 'urn:mace:shibboleth:metadata:1.0',
- );
-
- /* Check if it is a valid shortcut. */
- if(!array_key_exists($nsURI, $shortcuts)) {
- throw new Exception('Unknown namespace shortcut: ' . $nsURI);
- }
-
- /* Expand the shortcut. */
- $nsURI = $shortcuts[$nsURI];
- }
-
-
- if($element->localName !== $name) {
- return FALSE;
- }
-
- if($element->namespaceURI !== $nsURI) {
- return FALSE;
- }
-
- return TRUE;
+ return SimpleSAML\Utils\XML::isDOMElementOfType($element, $name, $nsURI);
}
/**
- * This function finds direct descendants of a DOM element with the specified
- * localName and namespace. They are returned in an array.
- *
- * This function accepts the same shortcuts for namespaces as the isDOMElementOfType function.
- *
- * @param DOMElement $element The element we should look in.
- * @param string $localName The name the element should have.
- * @param string $namespaceURI The namespace the element should have.
- * @return array Array with the matching elements in the order they are found. An empty array is
- * returned if no elements match.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::getDOMChildren() instead.
*/
public static function getDOMChildren(DOMElement $element, $localName, $namespaceURI) {
- assert('is_string($localName)');
- assert('is_string($namespaceURI)');
-
- $ret = array();
-
- for($i = 0; $i < $element->childNodes->length; $i++) {
- $child = $element->childNodes->item($i);
-
- /* Skip text nodes and comment elements. */
- if($child instanceof DOMText || $child instanceof DOMComment) {
- continue;
- }
-
- if(self::isDOMElementOfType($child, $localName, $namespaceURI) === TRUE) {
- $ret[] = $child;
- }
- }
-
- return $ret;
+ return SimpleSAML\Utils\XML::getDOMChildren($element, $localName, $namespaceURI);
}
/**
- * This function extracts the text from DOMElements which should contain
- * only text content.
- *
- * @param $element The element we should extract text from.
- * @return The text content of the element.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::getDOMText() instead.
*/
public static function getDOMText($element) {
- assert('$element instanceof DOMElement');
-
- $txt = '';
-
- for($i = 0; $i < $element->childNodes->length; $i++) {
- $child = $element->childNodes->item($i);
- if(!($child instanceof DOMText)) {
- throw new Exception($element->localName . ' contained a non-text child node.');
- }
-
- $txt .= $child->wholeText;
- }
-
- $txt = trim($txt);
- return $txt;
+ return SimpleSAML\Utils\XML::getDOMText($element);
}
/**
- * This function parses the Accept-Language http header and returns an associative array with each
- * language and the score for that language.
- *
- * If an language includes a region, then the result will include both the language with the region
- * and the language without the region.
- *
- * The returned array will be in the same order as the input.
- *
- * @return An associative array with each language and the score for that language.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getAcceptLanguage() instead.
*/
public static function getAcceptLanguage() {
-
- if(!array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
- /* No Accept-Language header - return empty set. */
- return array();
- }
-
- $languages = explode(',', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
-
- $ret = array();
-
- foreach($languages as $l) {
- $opts = explode(';', $l);
-
- $l = trim(array_shift($opts)); /* The language is the first element.*/
-
- $q = 1.0;
-
- /* Iterate over all options, and check for the quality option. */
- foreach($opts as $o) {
- $o = explode('=', $o);
- if(count($o) < 2) {
- /* Skip option with no value. */
- continue;
- }
-
- $name = trim($o[0]);
- $value = trim($o[1]);
-
- if($name === 'q') {
- $q = (float)$value;
- }
- }
-
- /* Remove the old key to ensure that the element is added to the end. */
- unset($ret[$l]);
-
- /* Set the quality in the result. */
- $ret[$l] = $q;
-
- if(strpos($l, '-')) {
- /* The language includes a region part. */
-
- /* Extract the language without the region. */
- $l = explode('-', $l);
- $l = $l[0];
-
- /* Add this language to the result (unless it is defined already). */
- if(!array_key_exists($l, $ret)) {
- $ret[$l] = $q;
- }
- }
- }
-
- return $ret;
+ return \SimpleSAML\Utils\HTTP::getAcceptLanguage();
}
/**
- * This function attempts to validate an XML string against the specified schema.
- *
- * It will parse the string into a DOM document and validate this document against the schema.
- *
- * @param $xml The XML string or document which should be validated.
- * @param $schema The schema which should be used.
- * @return Returns a string with the errors if validation fails. An empty string is
- * returned if validation passes.
- * @deprecated
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::isValid() instead.
*/
public static function validateXML($xml, $schema) {
- assert('is_string($xml) || $xml instanceof DOMDocument');
- assert('is_string($schema)');
-
- SimpleSAML_XML_Errors::begin();
-
- if($xml instanceof DOMDocument) {
- $dom = $xml;
- $res = TRUE;
- } else {
- $dom = new DOMDocument;
- $res = $dom->loadXML($xml);
- }
-
- if($res) {
-
- $config = SimpleSAML_Configuration::getInstance();
- $schemaPath = $config->resolvePath('schemas') . '/';
- $schemaFile = $schemaPath . $schema;
-
- $res = $dom->schemaValidate($schemaFile);
- if($res) {
- SimpleSAML_XML_Errors::end();
- return '';
- }
-
- $errorText = "Schema validation failed on XML string:\n";
- } else {
- $errorText = "Failed to parse XML string for schema validation:\n";
- }
-
- $errors = SimpleSAML_XML_Errors::end();
- $errorText .= SimpleSAML_XML_Errors::formatErrors($errors);
-
- return $errorText;
+ $result = \SimpleSAML\Utils\XML::isValid($xml, $schema);
+ return ($result === true) ? '' : $result;
}
/**
- * This function performs some sanity checks on XML documents, and optionally validates them
- * against their schema. A warning will be printed to the log if validation fails.
- *
- * @param $message The message which should be validated, as a string.
- * @param $type The type of document - can be either 'saml20', 'saml11' or 'saml-meta'.
- * @deprecated
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::checkSAMLMessage() instead.
*/
public static function validateXMLDocument($message, $type) {
- assert('is_string($message)');
- assert($type === 'saml11' || $type === 'saml20' || $type === 'saml-meta');
-
- /* A SAML message should not contain a doctype-declaration. */
- if(strpos($message, '<!DOCTYPE') !== FALSE) {
- throw new Exception('XML contained a doctype declaration.');
- }
-
- $enabled = SimpleSAML_Configuration::getInstance()->getBoolean('debug.validatexml', NULL);
- if($enabled === NULL) {
- /* Fall back to old configuration option. */
- $enabled = SimpleSAML_Configuration::getInstance()->getBoolean('debug.validatesamlmessages', NULL);
- if($enabled === NULL) {
- /* Fall back to even older configuration option. */
- $enabled = SimpleSAML_Configuration::getInstance()->getBoolean('debug.validatesaml2messages', FALSE);
- }
- }
-
- if(!$enabled) {
- return;
- }
-
- switch($type) {
- case 'saml11':
- $result = self::validateXML($message, 'oasis-sstc-saml-schema-protocol-1.1.xsd');
- break;
- case 'saml20':
- $result = self::validateXML($message, 'saml-schema-protocol-2.0.xsd');
- break;
- case 'saml-meta':
- $result = self::validateXML($message, 'saml-schema-metadata-2.0.xsd');
- break;
- default:
- throw new Exception('Invalid message type.');
- }
-
- if($result !== '') {
- SimpleSAML_Logger::warning($result);
- }
+ \SimpleSAML\Utils\XML::checkSAMLMessage($message, $type);
}
/**
- * This function generates a binary string containing random bytes.
- *
- * It is implemented as a wrapper of the openssl_random_pseudo_bytes function,
- * available since PHP 5.3.0.
- *
- * @param int $length The number of random bytes to return.
- * @return string A string of $length random bytes.
+ * @deprecated This method will be removed in SSP 2.0. Please use openssl_random_pseudo_bytes() instead.
*/
public static function generateRandomBytes($length) {
assert('is_int($length)');
- return openssl_random_pseudo_bytes($length);
+ return openssl_random_pseudo_bytes($length);
}
/**
- * This function converts a binary string to hexadecimal characters.
- *
- * @param $bytes Input string.
- * @return String with lowercase hexadecimal characters.
+ * @deprecated This method will be removed in SSP 2.0. Please use bin2hex() instead.
*/
public static function stringToHex($bytes) {
$ret = '';
@@ -1053,262 +346,56 @@ class SimpleSAML_Utilities {
/**
- * Resolve a (possibly) relative path from the given base path.
- *
- * A path which starts with a '/' is assumed to be absolute, all others are assumed to be
- * relative. The default base path is the root of the simpleSAMPphp installation.
- *
- * @param $path The path we should resolve.
- * @param $base The base path, where we should search for $path from. Default value is the root
- * of the simpleSAMLphp installation.
- * @return An absolute path referring to $path.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\System::resolvePath() instead.
*/
public static function resolvePath($path, $base = NULL) {
- if($base === NULL) {
- $config = SimpleSAML_Configuration::getInstance();
- $base = $config->getBaseDir();
- }
-
- /* Remove trailing slashes from $base. */
- while(substr($base, -1) === '/') {
- $base = substr($base, 0, -1);
- }
-
- /* Check for absolute path. */
- if(substr($path, 0, 1) === '/') {
- /* Absolute path. */
- $ret = '/';
- } else {
- /* Path relative to base. */
- $ret = $base;
- }
-
- $path = explode('/', $path);
- foreach($path as $d) {
- if($d === '.') {
- continue;
- } elseif($d === '..') {
- $ret = dirname($ret);
- } else {
- if(substr($ret, -1) !== '/') {
- $ret .= '/';
- }
- $ret .= $d;
- }
- }
-
- return $ret;
+ return \SimpleSAML\Utils\System::resolvePath($path, $base);
}
/**
- * Resolve a (possibly) relative URL relative to a given base URL.
- *
- * This function supports these forms of relative URLs:
- * ^\w+: Absolute URL
- * ^// Same protocol.
- * ^/ Same protocol and host.
- * ^? Same protocol, host and path, replace query string & fragment
- * ^# Same protocol, host, path and query, replace fragment
- * The rest: Relative to the base path.
- *
- * @param $url The relative URL.
- * @param $base The base URL. Defaults to the base URL of this installation of simpleSAMLphp.
- * @return An absolute URL for the given relative URL.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::resolveURL() instead.
*/
public static function resolveURL($url, $base = NULL) {
- if($base === NULL) {
- $base = self::getBaseURL();
- }
-
- if(!preg_match('/^((((\w+:)\/\/[^\/]+)(\/[^?#]*))(?:\?[^#]*)?)(?:#.*)?/', $base, $baseParsed)) {
- throw new Exception('Unable to parse base url: ' . $base);
- }
-
- $baseDir = dirname($baseParsed[5] . 'filename');
- $baseScheme = $baseParsed[4];
- $baseHost = $baseParsed[3];
- $basePath = $baseParsed[2];
- $baseQuery = $baseParsed[1];
-
- if(preg_match('$^\w+:$', $url)) {
- return $url;
- }
-
- if(substr($url, 0, 2) === '//') {
- return $baseScheme . $url;
- }
-
- $firstChar = substr($url, 0, 1);
-
- if($firstChar === '/') {
- return $baseHost . $url;
- }
-
- if($firstChar === '?') {
- return $basePath . $url;
- }
-
- if($firstChar === '#') {
- return $baseQuery . $url;
- }
-
-
- /* We have a relative path. Remove query string/fragment and save it as $tail. */
- $queryPos = strpos($url, '?');
- $fragmentPos = strpos($url, '#');
- if($queryPos !== FALSE || $fragmentPos !== FALSE) {
- if($queryPos === FALSE) {
- $tailPos = $fragmentPos;
- } elseif($fragmentPos === FALSE) {
- $tailPos = $queryPos;
- } elseif($queryPos < $fragmentPos) {
- $tailPos = $queryPos;
- } else {
- $tailPos = $fragmentPos;
- }
-
- $tail = substr($url, $tailPos);
- $dir = substr($url, 0, $tailPos);
- } else {
- $dir = $url;
- $tail = '';
- }
-
- $dir = self::resolvePath($dir, $baseDir);
-
- return $baseHost . $dir . $tail;
+ return \SimpleSAML\Utils\HTTP::resolveURL($url, $base);
}
/**
- * Normalizes a URL to an absolute URL and validate it.
- *
- * In addition to resolving the URL, this function makes sure that it is
- * a link to a http or https site.
- *
- * @param string $url The relative URL.
- * @return string An absolute URL for the given relative URL.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::normalizeURL() instead.
*/
public static function normalizeURL($url) {
- assert('is_string($url)');
-
- $url = SimpleSAML_Utilities::resolveURL($url, SimpleSAML_Utilities::selfURL());
-
- /* Verify that the URL is to a http or https site. */
- if (!preg_match('@^https?://@i', $url)) {
- throw new SimpleSAML_Error_Exception('Invalid URL: ' . $url);
- }
-
- return $url;
+ return \SimpleSAML\Utils\HTTP::normalizeURL($url);
}
/**
- * Parse a query string into an array.
- *
- * This function parses a query string into an array, similar to the way the builtin
- * 'parse_str' works, except it doesn't handle arrays, and it doesn't do "magic quotes".
- *
- * Query parameters without values will be set to an empty string.
- *
- * @param $query_string The query string which should be parsed.
- * @return The query string as an associative array.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::parseQueryString() instead.
*/
public static function parseQueryString($query_string) {
- assert('is_string($query_string)');
-
- $res = array();
- foreach(explode('&', $query_string) as $param) {
- $param = explode('=', $param);
- $name = urldecode($param[0]);
- if(count($param) === 1) {
- $value = '';
- } else {
- $value = urldecode($param[1]);
- }
-
- $res[$name] = $value;
- }
-
- return $res;
+ return \SimpleSAML\Utils\HTTP::parseQueryString($query_string);
}
/**
- * Parse and validate an array with attributes.
- *
- * This function takes in an associative array with attributes, and parses and validates
- * this array. On success, it will return a normalized array, where each attribute name
- * is an index to an array of one or more strings. On failure an exception will be thrown.
- * This exception will contain an message describing what is wrong.
- *
- * @param array $attributes The attributes we should parse and validate.
- * @return array The parsed attributes.
+ * @deprecated This method will be removed in SSP 2.0. Please use
+ * SimpleSAML\Utils\Arrays::normalizeAttributesArray() instead.
*/
public static function parseAttributes($attributes) {
-
- if (!is_array($attributes)) {
- throw new Exception('Attributes was not an array. Was: ' . var_export($attributes, TRUE));
- }
-
- $newAttrs = array();
- foreach ($attributes as $name => $values) {
- if (!is_string($name)) {
- throw new Exception('Invalid attribute name: ' . var_export($name, TRUE));
- }
-
- if (!is_array($values)) {
- $values = array($values);
- }
-
- foreach ($values as $value) {
- if (!is_string($value)) {
- throw new Exception('Invalid attribute value for attribute ' . $name .
- ': ' . var_export($value, TRUE));
- }
- }
-
- $newAttrs[$name] = $values;
- }
-
- return $newAttrs;
+ return SimpleSAML\Utils\Arrays::normalizeAttributesArray($attributes);
}
/**
- * Retrieve secret salt.
- *
- * This function retrieves the value which is configured as the secret salt. It will
- * check that the value exists and is set to a non-default value. If it isn't, an
- * exception will be thrown.
- *
- * The secret salt can be used as a component in hash functions, to make it difficult to
- * test all possible values in order to retrieve the original value. It can also be used
- * as a simple method for signing data, by hashing the data together with the salt.
- *
- * @return string The secret salt.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Config::getSecretSalt() instead.
*/
public static function getSecretSalt() {
-
- $secretSalt = SimpleSAML_Configuration::getInstance()->getString('secretsalt');
- if ($secretSalt === 'defaultsecretsalt') {
- throw new Exception('The "secretsalt" configuration option must be set to a secret' .
- ' value.');
- }
-
- return $secretSalt;
+ return SimpleSAML\Utils\Config::getSecretSalt();
}
/**
- * Retrieve last error message.
- *
- * This function retrieves the last error message. If no error has occurred,
- * '[No error message found]' will be returned. If the required function isn't available,
- * '[Cannot get error message]' will be returned.
- *
- * @return string Last error message.
+ * @deprecated This method will be removed in SSP 2.0. Please call error_get_last() directly.
*/
public static function getLastError() {
@@ -1326,396 +413,99 @@ class SimpleSAML_Utilities {
/**
- * Resolves a path that may be relative to the cert-directory.
- *
- * @param string $path The (possibly relative) path to the file.
- * @return string The file path.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Config::getCertPath() instead.
*/
public static function resolveCert($path) {
- assert('is_string($path)');
-
- $globalConfig = SimpleSAML_Configuration::getInstance();
- $base = $globalConfig->getPathValue('certdir', 'cert/');
- return SimpleSAML_Utilities::resolvePath($path, $base);
+ return \SimpleSAML\Utils\Config::getCertPath($path);
}
/**
- * Get public key or certificate from metadata.
- *
- * This function implements a function to retrieve the public key or certificate from
- * a metadata array.
- *
- * It will search for the following elements in the metadata:
- * 'certData' The certificate as a base64-encoded string.
- * 'certificate' A file with a certificate or public key in PEM-format.
- * 'certFingerprint' The fingerprint of the certificate. Can be a single fingerprint,
- * or an array of multiple valid fingerprints.
- *
- * This function will return an array with these elements:
- * 'PEM' The public key/certificate in PEM-encoding.
- * 'certData' The certificate data, base64 encoded, on a single line. (Only
- * present if this is a certificate.)
- * 'certFingerprint' Array of valid certificate fingerprints. (Only present
- * if this is a certificate.)
- *
- * @param SimpleSAML_Configuration $metadata The metadata.
- * @param bool $required Whether the private key is required. If this is TRUE, a
- * missing key will cause an exception. Default is FALSE.
- * @param string $prefix The prefix which should be used when reading from the metadata
- * array. Defaults to ''.
- * @return array|NULL Public key or certificate data, or NULL if no public key or
- * certificate was found.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Crypto::loadPublicKey() instead.
*/
public static function loadPublicKey(SimpleSAML_Configuration $metadata, $required = FALSE, $prefix = '') {
- assert('is_bool($required)');
- assert('is_string($prefix)');
-
- $keys = $metadata->getPublicKeys(NULL, FALSE, $prefix);
- if ($keys !== NULL) {
- foreach ($keys as $key) {
- if ($key['type'] !== 'X509Certificate') {
- continue;
- }
- if ($key['signing'] !== TRUE) {
- continue;
- }
- $certData = $key['X509Certificate'];
- $pem = "-----BEGIN CERTIFICATE-----\n" .
- chunk_split($certData, 64) .
- "-----END CERTIFICATE-----\n";
- $certFingerprint = strtolower(sha1(base64_decode($certData)));
-
- return array(
- 'certData' => $certData,
- 'PEM' => $pem,
- 'certFingerprint' => array($certFingerprint),
- );
- }
- /* No valid key found. */
- } elseif ($metadata->hasValue($prefix . 'certFingerprint')) {
- /* We only have a fingerprint available. */
- $fps = $metadata->getArrayizeString($prefix . 'certFingerprint');
-
- /* Normalize fingerprint(s) - lowercase and no colons. */
- foreach($fps as &$fp) {
- assert('is_string($fp)');
- $fp = strtolower(str_replace(':', '', $fp));
- }
-
- /* We can't build a full certificate from a fingerprint, and may as well
- * return an array with only the fingerprint(s) immediately.
- */
- return array('certFingerprint' => $fps);
- }
-
- /* No public key/certificate available. */
- if ($required) {
- throw new Exception('No public key / certificate found in metadata.');
- } else {
- return NULL;
- }
+ return SimpleSAML\Utils\Crypto::loadPublicKey($metadata, $required, $prefix);
}
/**
- * Load private key from metadata.
- *
- * This function loads a private key from a metadata array. It searches for the
- * following elements:
- * 'privatekey' Name of a private key file in the cert-directory.
- * 'privatekey_pass' Password for the private key.
- *
- * It returns and array with the following elements:
- * 'PEM' Data for the private key, in PEM-format
- * 'password' Password for the private key.
- *
- * @param SimpleSAML_Configuration $metadata The metadata array the private key should be loaded from.
- * @param bool $required Whether the private key is required. If this is TRUE, a
- * missing key will cause an exception. Default is FALSE.
- * @param string $prefix The prefix which should be used when reading from the metadata
- * array. Defaults to ''.
- * @return array|NULL Extracted private key, or NULL if no private key is present.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Crypto::loadPrivateKey() instead.
*/
public static function loadPrivateKey(SimpleSAML_Configuration $metadata, $required = FALSE, $prefix = '') {
- assert('is_bool($required)');
- assert('is_string($prefix)');
-
- $file = $metadata->getString($prefix . 'privatekey', NULL);
- if ($file === NULL) {
- /* No private key found. */
- if ($required) {
- throw new Exception('No private key found in metadata.');
- } else {
- return NULL;
- }
- }
-
- $file = SimpleSAML_Utilities::resolveCert($file);
- $data = @file_get_contents($file);
- if ($data === FALSE) {
- throw new Exception('Unable to load private key from file "' . $file . '"');
- }
-
- $ret = array(
- 'PEM' => $data,
- );
-
- if ($metadata->hasValue($prefix . 'privatekey_pass')) {
- $ret['password'] = $metadata->getString($prefix . 'privatekey_pass');
- }
-
- return $ret;
+ return SimpleSAML\Utils\Crypto::loadPrivateKey($metadata, $required, $prefix);
}
/**
- * Format a DOM element.
- *
- * This function takes in a DOM element, and inserts whitespace to make it more
- * readable. Note that whitespace added previously will be removed.
- *
- * @param DOMElement $root The root element which should be formatted.
- * @param string $indentBase The indentation this element should be assumed to
- * have. Default is an empty string.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::formatDOMElement() instead.
*/
public static function formatDOMElement(DOMElement $root, $indentBase = '') {
- assert(is_string($indentBase));
-
- /* Check what this element contains. */
- $fullText = ''; /* All text in this element. */
- $textNodes = array(); /* Text nodes which should be deleted. */
- $childNodes = array(); /* Other child nodes. */
- for ($i = 0; $i < $root->childNodes->length; $i++) {
- $child = $root->childNodes->item($i);
-
- if($child instanceof DOMText) {
- $textNodes[] = $child;
- $fullText .= $child->wholeText;
-
- } elseif ($child instanceof DOMComment || $child instanceof DOMElement) {
- $childNodes[] = $child;
-
- } else {
- /* Unknown node type. We don't know how to format this. */
- return;
- }
- }
-
- $fullText = trim($fullText);
- if (strlen($fullText) > 0) {
- /* We contain text. */
- $hasText = TRUE;
- } else {
- $hasText = FALSE;
- }
-
- $hasChildNode = (count($childNodes) > 0);
-
- if ($hasText && $hasChildNode) {
- /* Element contains both text and child nodes - we don't know how to format this one. */
- return;
- }
-
- /* Remove text nodes. */
- foreach ($textNodes as $node) {
- $root->removeChild($node);
- }
-
- if ($hasText) {
- /* Only text - add a single text node to the element with the full text. */
- $root->appendChild(new DOMText($fullText));
- return;
-
- }
-
- if (!$hasChildNode) {
- /* Empty node. Nothing to do. */
- return;
- }
-
- /* Element contains only child nodes - add indentation before each one, and
- * format child elements.
- */
- $childIndentation = $indentBase . ' ';
- foreach ($childNodes as $node) {
- /* Add indentation before node. */
- $root->insertBefore(new DOMText("\n" . $childIndentation), $node);
-
- /* Format child elements. */
- if ($node instanceof DOMElement) {
- self::formatDOMElement($node, $childIndentation);
- }
- }
-
- /* Add indentation before closing tag. */
- $root->appendChild(new DOMText("\n" . $indentBase));
+ SimpleSAML\Utils\XML::formatDOMElement($root, $indentBase);
}
/**
- * Format an XML string.
- *
- * This function formats an XML string using the formatDOMElement function.
- *
- * @param string $xml XML string which should be formatted.
- * @param string $indentBase Optional indentation which should be applied to all
- * the output. Optional, defaults to ''.
- * @return string Formatted string.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::formatXMLString() instead.
*/
public static function formatXMLString($xml, $indentBase = '') {
- assert('is_string($xml)');
- assert('is_string($indentBase)');
-
- $doc = new DOMDocument();
- if (!$doc->loadXML($xml)) {
- throw new Exception('Error parsing XML string.');
- }
-
- $root = $doc->firstChild;
- self::formatDOMElement($root);
-
- return $doc->saveXML($root);
+ return SimpleSAML\Utils\XML::formatXMLString($xml, $indentBase);
}
- /*
- * Input is single value or array, returns an array.
+ /**
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Arrays::arrayize() instead.
*/
public static function arrayize($data, $index = 0) {
- if (is_array($data)) {
- return $data;
- } else {
- return array($index => $data);
- }
+ return SimpleSAML\Utils\Arrays::arrayize($data, $index);
}
/**
- * Check whether the current user is a admin user.
- *
- * @return bool TRUE if the current user is a admin user, FALSE if not.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Auth::isAdmin() instead.
*/
public static function isAdmin() {
-
- $session = SimpleSAML_Session::getSessionFromRequest();
-
- return $session->isValid('admin') || $session->isValid('login-admin');
+ return SimpleSAML\Utils\Auth::isAdmin();
}
/**
- * Retrieve a admin login URL.
- *
- * @param string|NULL $returnTo The URL the user should arrive on after admin authentication.
- * @return string A URL which can be used for admin authentication.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Auth::getAdminLoginURL instead();
*/
public static function getAdminLoginURL($returnTo = NULL) {
- assert('is_string($returnTo) || is_null($returnTo)');
-
- if ($returnTo === NULL) {
- $returnTo = SimpleSAML_Utilities::selfURL();
- }
-
- return SimpleSAML_Module::getModuleURL('core/login-admin.php', array('ReturnTo' => $returnTo));
+ return SimpleSAML\Utils\Auth::getAdminLoginURL($returnTo);
}
/**
- * Require admin access for current page.
- *
- * This is a helper-function for limiting a page to admin access. It will redirect
- * the user to a login page if the current user doesn't have admin access.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Auth::requireAdmin() instead.
*/
public static function requireAdmin() {
-
- if (self::isAdmin()) {
- return;
- }
-
- /* Not authenticated as admin user. Start authentication. */
-
- if (SimpleSAML_Auth_Source::getById('admin') !== NULL) {
- $as = new SimpleSAML_Auth_Simple('admin');
- $as->login();
- } else {
- throw new Exception('Cannot find "admin" auth source, and admin privileges are required.');
- }
+ \SimpleSAML\Utils\Auth::requireAdmin();
}
/**
- * Do a POST redirect to a page.
- *
- * This function never returns.
- *
- * @param string $destination The destination URL.
- * @param array $post An array of name-value pairs which will be posted.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::submitPOSTData() instead.
*/
public static function postRedirect($destination, $post) {
- assert('is_string($destination)');
- assert('is_array($post)');
-
- $config = SimpleSAML_Configuration::getInstance();
- $httpRedirect = $config->getBoolean('enable.http_post', FALSE);
-
- if ($httpRedirect && preg_match("#^http:#", $destination) && self::isHTTPS()) {
- $url = self::createHttpPostRedirectLink($destination, $post);
- self::redirect($url);
- assert('FALSE');
- }
-
- $p = new SimpleSAML_XHTML_Template($config, 'post.php');
- $p->data['destination'] = $destination;
- $p->data['post'] = $post;
- $p->show();
- exit(0);
+ \SimpleSAML\Utils\HTTP::submitPOSTData($destination, $post);
}
/**
- * Create a link which will POST data.
- *
- * @param string $destination The destination URL.
- * @param array $post The name-value pairs which will be posted to the destination.
- * @return string A URL which can be accessed to post the data.
+ * @deprecated This method will be removed in SSP 2.0. PLease use SimpleSAML\Utils\HTTP::getPOSTRedirectURL() instead.
*/
public static function createPostRedirectLink($destination, $post) {
- assert('is_string($destination)');
- assert('is_array($post)');
-
- $config = SimpleSAML_Configuration::getInstance();
- $httpRedirect = $config->getBoolean('enable.http_post', FALSE);
-
- if ($httpRedirect && preg_match("#^http:#", $destination) && self::isHTTPS()) {
- $url = self::createHttpPostRedirectLink($destination, $post);
- } else {
- $postId = SimpleSAML_Utilities::generateID();
- $postData = array(
- 'post' => $post,
- 'url' => $destination,
- );
-
- $session = SimpleSAML_Session::getSessionFromRequest();
- $session->setData('core_postdatalink', $postId, $postData);
-
- $url = SimpleSAML_Module::getModuleURL('core/postredirect.php', array('RedirId' => $postId));
- }
-
- return $url;
+ return \SimpleSAML\Utils\HTTP::getPOSTRedirectURL($destination, $post);
}
/**
- * Create a link which will POST data to HTTP in a secure way.
- *
- * @param string $destination The destination URL.
- * @param array $post The name-value pairs which will be posted to the destination.
- * @return string A URL which can be accessed to post the data.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::getPOSTRedirectURL() instead.
*/
public static function createHttpPostRedirectLink($destination, $post) {
assert('is_string($destination)');
assert('is_array($post)');
- $postId = SimpleSAML_Utilities::generateID();
+ $postId = SimpleSAML\Utils\Random::generateID();
$postData = array(
'post' => $post,
'url' => $destination,
@@ -1724,7 +514,7 @@ class SimpleSAML_Utilities {
$session = SimpleSAML_Session::getSessionFromRequest();
$session->setData('core_postdatalink', $postId, $postData);
- $redirInfo = base64_encode(self::aesEncrypt($session->getSessionId() . ':' . $postId));
+ $redirInfo = base64_encode(SimpleSAML\Utils\Crypto::aesEncrypt($session->getSessionId() . ':' . $postId));
$url = SimpleSAML_Module::getModuleURL('core/postredirect.php', array('RedirInfo' => $redirInfo));
$url = preg_replace("#^https:#", "http:", $url);
@@ -1734,181 +524,22 @@ class SimpleSAML_Utilities {
/**
- * Validate a certificate against a CA file, by using the builtin
- * openssl_x509_checkpurpose function
- *
- * @param string $certificate The certificate, in PEM format.
- * @param string $caFile File with trusted certificates, in PEM-format.
- * @return boolean|string TRUE on success, or a string with error messages if it failed.
- * @deprecated
- */
- private static function validateCABuiltIn($certificate, $caFile) {
- assert('is_string($certificate)');
- assert('is_string($caFile)');
-
- /* Clear openssl errors. */
- while(openssl_error_string() !== FALSE);
-
- $res = openssl_x509_checkpurpose($certificate, X509_PURPOSE_ANY, array($caFile));
-
- $errors = '';
- /* Log errors. */
- while( ($error = openssl_error_string()) !== FALSE) {
- $errors .= ' [' . $error . ']';
- }
-
- if($res !== TRUE) {
- return $errors;
- }
-
- return TRUE;
- }
-
-
- /**
- * Validate the certificate used to sign the XML against a CA file, by using the "openssl verify" command.
- *
- * This function uses the openssl verify command to verify a certificate, to work around limitations
- * on the openssl_x509_checkpurpose function. That function will not work on certificates without a purpose
- * set.
- *
- * @param string $certificate The certificate, in PEM format.
- * @param string $caFile File with trusted certificates, in PEM-format.
- * @return boolean|string TRUE on success, a string with error messages on failure.
- * @deprecated
- */
- private static function validateCAExec($certificate, $caFile) {
- assert('is_string($certificate)');
- assert('is_string($caFile)');
-
- $command = array(
- 'openssl', 'verify',
- '-CAfile', $caFile,
- '-purpose', 'any',
- );
-
- $cmdline = '';
- foreach($command as $c) {
- $cmdline .= escapeshellarg($c) . ' ';
- }
-
- $cmdline .= '2>&1';
- $descSpec = array(
- 0 => array('pipe', 'r'),
- 1 => array('pipe', 'w'),
- );
- $process = proc_open($cmdline, $descSpec, $pipes);
- if (!is_resource($process)) {
- throw new Exception('Failed to execute verification command: ' . $cmdline);
- }
-
- if (fwrite($pipes[0], $certificate) === FALSE) {
- throw new Exception('Failed to write certificate for verification.');
- }
- fclose($pipes[0]);
-
- $out = '';
- while (!feof($pipes[1])) {
- $line = trim(fgets($pipes[1]));
- if(strlen($line) > 0) {
- $out .= ' [' . $line . ']';
- }
- }
- fclose($pipes[1]);
-
- $status = proc_close($process);
- if ($status !== 0 || $out !== ' [stdin: OK]') {
- return $out;
- }
-
- return TRUE;
- }
-
-
- /**
- * Validate the certificate used to sign the XML against a CA file.
- *
- * This function throws an exception if unable to validate against the given CA file.
- *
- * @param string $certificate The certificate, in PEM format.
- * @param string $caFile File with trusted certificates, in PEM-format.
- * @deprecated
+ * @deprecated This method will be removed in SSP 2.0.
*/
public static function validateCA($certificate, $caFile) {
- assert('is_string($certificate)');
- assert('is_string($caFile)');
-
- if (!file_exists($caFile)) {
- throw new Exception('Could not load CA file: ' . $caFile);
- }
-
- SimpleSAML_Logger::debug('Validating certificate against CA file: ' . var_export($caFile, TRUE));
-
- $resBuiltin = self::validateCABuiltIn($certificate, $caFile);
- if ($resBuiltin !== TRUE) {
- SimpleSAML_Logger::debug('Failed to validate with internal function: ' . var_export($resBuiltin, TRUE));
-
- $resExternal = self::validateCAExec($certificate, $caFile);
- if ($resExternal !== TRUE) {
- SimpleSAML_Logger::debug('Failed to validate with external function: ' . var_export($resExternal, TRUE));
- throw new Exception('Could not verify certificate against CA file "'
- . $caFile . '". Internal result:' . $resBuiltin .
- ' External result:' . $resExternal);
- }
- }
-
- SimpleSAML_Logger::debug('Successfully validated certificate.');
+ SimpleSAML_XML_Validator::validateCertificate($certificate, $caFile);
}
/**
- * Initialize the timezone.
- *
- * This function should be called before any calls to date().
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Time::initTimezone() instead.
*/
public static function initTimezone() {
- static $initialized = FALSE;
-
- if ($initialized) {
- return;
- }
-
- $initialized = TRUE;
-
- $globalConfig = SimpleSAML_Configuration::getInstance();
-
- $timezone = $globalConfig->getString('timezone', NULL);
- if ($timezone !== NULL) {
- if (!date_default_timezone_set($timezone)) {
- throw new SimpleSAML_Error_Exception('Invalid timezone set in the \'timezone\'-option in config.php.');
- }
- return;
- }
-
- /* We don't have a timezone configured. */
-
- /*
- * The date_default_timezone_get()-function is likely to cause a warning.
- * Since we have a custom error handler which logs the errors with a backtrace,
- * this error will be logged even if we prefix the function call with '@'.
- * Instead we temporarily replace the error handler.
- */
- function ignoreError() {
- /* Don't do anything with this error. */
- return TRUE;
- }
- set_error_handler('ignoreError');
- $serverTimezone = date_default_timezone_get();
- restore_error_handler();
-
- /* Set the timezone to the default. */
- date_default_timezone_set($serverTimezone);
+ \SimpleSAML\Utils\Time::initTimezone();
}
/**
- * Disable the loading of external entities in XML documents to prevent local and
- * remote file inclusion attacks. This is in most cases already disabled by default
- * in system libraries, but to be safe we explicitly disable it also.
+ * @deprecated This method will be removed in SSP 2.0. Please use libxml_disable_entity_loader() instead.
*/
public static function disableXMLEntityLoader() {
/* Function only present in PHP >= 5.2.11 while we support 5.2+ */
@@ -1918,90 +549,23 @@ class SimpleSAML_Utilities {
}
/**
- * Atomically write a file.
- *
- * This is a helper function for safely writing file data atomically.
- * It does this by writing the file data to a temporary file, and then
- * renaming this to the correct name.
- *
- * @param string $filename The name of the file.
- * @param string $data The data we should write to the file.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\System::writeFile() instead.
*/
public static function writeFile($filename, $data, $mode=0600) {
- assert('is_string($filename)');
- assert('is_string($data)');
- assert('is_numeric($mode)');
-
- $tmpFile = $filename . '.new.' . getmypid() . '.' . php_uname('n');
-
- $res = @file_put_contents($tmpFile, $data);
- if ($res === FALSE) {
- throw new SimpleSAML_Error_Exception('Error saving file ' . $tmpFile .
- ': ' . SimpleSAML_Utilities::getLastError());
- }
-
- if (!self::isWindowsOS()) {
- $res = chmod($tmpFile, $mode);
- if ($res === FALSE) {
- unlink($tmpFile);
- throw new SimpleSAML_Error_Exception('Error changing file mode ' . $tmpFile .
- ': ' . SimpleSAML_Utilities::getLastError());
- }
- }
-
- $res = rename($tmpFile, $filename);
- if ($res === FALSE) {
- unlink($tmpFile);
- throw new SimpleSAML_Error_Exception('Error renaming ' . $tmpFile . ' to ' .
- $filename . ': ' . SimpleSAML_Utilities::getLastError());
- }
+ \SimpleSAML\Utils\System::writeFile($filename, $data, $mode);
}
/**
- * Get temp directory path.
- *
- * This function retrieves the path to a directory where
- * temporary files can be saved.
- *
- * @return string Path to temp directory, without a trailing '/'.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\System::getTempDir instead.
*/
public static function getTempDir() {
-
- $globalConfig = SimpleSAML_Configuration::getInstance();
-
- $tempDir = $globalConfig->getString('tempdir', '/tmp/simplesaml');
-
- while (substr($tempDir, -1) === '/') {
- $tempDir = substr($tempDir, 0, -1);
- }
-
- if (!is_dir($tempDir)) {
- $ret = mkdir($tempDir, 0700, TRUE);
- if (!$ret) {
- throw new SimpleSAML_Error_Exception('Error creating temp dir ' .
- var_export($tempDir, TRUE) . ': ' . SimpleSAML_Utilities::getLastError());
- }
- } elseif (function_exists('posix_getuid')) {
-
- /* Check that the owner of the temp diretory is the current user. */
- $stat = lstat($tempDir);
- if ($stat['uid'] !== posix_getuid()) {
- throw new SimpleSAML_Error_Exception('Temp directory (' . var_export($tempDir, TRUE) .
- ') not owned by current user.');
- }
- }
-
- return $tempDir;
+ return SimpleSAML\Utils\System::getTempDir();
}
/**
- * Disable reporting of the given log levels.
- *
- * Every call to this function must be followed by a call to popErrorMask();
- *
- * @param int $mask The log levels that should be masked.
+ * @deprecated This method will be removed in SSP 2.0.
*/
public static function maskErrors($mask) {
assert('is_int($mask)');
@@ -2016,12 +580,9 @@ class SimpleSAML_Utilities {
/**
- * Pop an error mask.
- *
- * This function restores the previous error mask.
+ * @deprecated This method will be removed in SSP 2.0.
*/
public static function popErrorMask() {
-
$lastMask = array_pop(self::$logLevelStack);
error_reporting($lastMask[0]);
self::$logMask = $lastMask[1];
@@ -2029,344 +590,66 @@ class SimpleSAML_Utilities {
/**
- * Find the default endpoint in an endpoint array.
- *
- * @param array $endpoints Array with endpoints.
- * @param array $bindings Array with acceptable bindings. Can be NULL if any binding is allowed.
- * @return array|NULL The default endpoint, or NULL if no acceptable endpoints are used.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint() instead.
*/
public static function getDefaultEndpoint(array $endpoints, array $bindings = NULL) {
-
- $firstNotFalse = NULL;
- $firstAllowed = NULL;
-
- /* Look through the endpoint list for acceptable endpoints. */
- foreach ($endpoints as $i => $ep) {
- if ($bindings !== NULL && !in_array($ep['Binding'], $bindings, TRUE)) {
- /* Unsupported binding. Skip it. */
- continue;
- }
-
- if (array_key_exists('isDefault', $ep)) {
- if ($ep['isDefault'] === TRUE) {
- /* This is the first endpoitn with isDefault set to TRUE. */
- return $ep;
- }
- /* isDefault is set to FALSE, but the endpoint is still useable as a last resort. */
- if ($firstAllowed === NULL) {
- /* This is the first endpoint that we can use. */
- $firstAllowed = $ep;
- }
- } else {
- if ($firstNotFalse === NULL) {
- /* This is the first endpoint without isDefault set. */
- $firstNotFalse = $ep;
- }
- }
- }
-
- if ($firstNotFalse !== NULL) {
- /* We have an endpoint without isDefault set to FALSE. */
- return $firstNotFalse;
- }
-
- /*
- * $firstAllowed either contains the first endpoint we can use, or it
- * contains NULL if we cannot use any of the endpoints. Either way we
- * return the value of it.
- */
- return $firstAllowed;
+ return \SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint($endpoints, $bindings);
}
/**
- * Check for session cookie, and show missing-cookie page if it is missing.
- *
- * @param string|NULL $retryURL The URL the user should access to retry the operation.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::checkSessionCookie() instead.
*/
public static function checkCookie($retryURL = NULL) {
- assert('is_string($retryURL) || is_null($retryURL)');
-
- $session = SimpleSAML_Session::getSessionFromRequest();
- if ($session->hasSessionCookie()) {
- return;
- }
-
- /* We didn't have a session cookie. Redirect to the no-cookie page. */
-
- $url = SimpleSAML_Module::getModuleURL('core/no_cookie.php');
- if ($retryURL !== NULL) {
- $url = self::addURLParameter($url, array('retryURL' => $retryURL));
- }
- self::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::checkSessionCookie($retryURL);
}
/**
- * Helper function to log messages that we send or receive.
- *
- * @param string|DOMElement $message The message, as an XML string or an XML element.
- * @param string $type Whether this message is sent or received, encrypted or decrypted.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::debugSAMLMessage() instead.
*/
public static function debugMessage($message, $type) {
- assert('is_string($message) || $message instanceof DOMElement');
-
- $globalConfig = SimpleSAML_Configuration::getInstance();
- if (!$globalConfig->getBoolean('debug', FALSE)) {
- /* Message debug disabled. */
- return;
- }
-
- if ($message instanceof DOMElement) {
- $message = $message->ownerDocument->saveXML($message);
- }
-
- switch ($type) {
- case 'in':
- SimpleSAML_Logger::debug('Received message:');
- break;
- case 'out':
- SimpleSAML_Logger::debug('Sending message:');
- break;
- case 'decrypt':
- SimpleSAML_Logger::debug('Decrypted message:');
- break;
- case 'encrypt':
- SimpleSAML_Logger::debug('Encrypted message:');
- break;
- default:
- assert(FALSE);
- }
-
- $str = self::formatXMLString($message);
- foreach (explode("\n", $str) as $line) {
- SimpleSAML_Logger::debug($line);
- }
+ \SimpleSAML\Utils\XML::debugSAMLMessage($message, $type);
}
/**
- * Helper function to retrieve a file or URL with proxy support.
- *
- * An exception will be thrown if we are unable to retrieve the data.
- *
- * @param string $path The path or URL we should fetch.
- * @param array $context Extra context options. This parameter is optional.
- * @param boolean $getHeaders Whether to also return response headers. Optional.
- * @return mixed array if $getHeaders is set, string otherwise
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::fetch() instead.
*/
public static function fetch($path, $context = array(), $getHeaders = FALSE) {
- assert('is_string($path)');
-
- $config = SimpleSAML_Configuration::getInstance();
-
- $proxy = $config->getString('proxy', NULL);
- if ($proxy !== NULL) {
- if (!isset($context['http']['proxy'])) {
- $context['http']['proxy'] = $proxy;
- }
- if (!isset($context['http']['request_fulluri'])) {
- $context['http']['request_fulluri'] = TRUE;
- }
- // If the remote endpoint over HTTPS uses the SNI extension
- // (Server Name Indication RFC 4366), the proxy could
- // introduce a mismatch between the names in the
- // Host: HTTP header and the SNI_server_name in TLS
- // negotiation (thanks to Cristiano Valli @ GARR-IDEM
- // to have pointed this problem).
- // See: https://bugs.php.net/bug.php?id=63519
- // These controls will force the same value for both fields.
- // Marco Ferrante (marco@csita.unige.it), Nov 2012
- if (preg_match('#^https#i', $path)
- && defined('OPENSSL_TLSEXT_SERVER_NAME')
- && OPENSSL_TLSEXT_SERVER_NAME) {
- // Extract the hostname
- $hostname = parse_url($path, PHP_URL_HOST);
- if (!empty($hostname)) {
- $context['ssl'] = array(
- 'SNI_server_name' => $hostname,
- 'SNI_enabled' => TRUE,
- );
- }
- else {
- SimpleSAML_Logger::warning('Invalid URL format or local URL used through a proxy');
- }
- }
- }
-
- $context = stream_context_create($context);
-
- $data = file_get_contents($path, FALSE, $context);
- if ($data === FALSE) {
- throw new SimpleSAML_Error_Exception('Error fetching ' . var_export($path, TRUE) . ':' . self::getLastError());
- }
-
- // Data and headers.
- if ($getHeaders) {
-
- if (isset($http_response_header)) {
- $headers = array();
- foreach($http_response_header as $h) {
- if(preg_match('@^HTTP/1\.[01]\s+\d{3}\s+@', $h)) {
- $headers = array(); // reset
- $headers[0] = $h;
- continue;
- }
- $bits = explode(':', $h, 2);
- if(count($bits) === 2) {
- $headers[strtolower($bits[0])] = trim($bits[1]);
- }
- }
- } else {
- /* No HTTP headers - probably a different protocol, e.g. file. */
- $headers = NULL;
- }
-
- return array($data, $headers);
- }
-
- return $data;
+ return \SimpleSAML\Utils\HTTP::fetch($path, $context, $getHeaders);
}
/**
- * Function to AES encrypt data.
- *
- * @param string $clear Data to encrypt.
- * @return array The encrypted data and IV.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Crypto::aesEncrypt() instead.
*/
public static function aesEncrypt($clear) {
- assert('is_string($clear)');
-
- if (!function_exists("mcrypt_encrypt")) {
- throw new Exception("aesEncrypt needs mcrypt php module.");
- }
-
- $enc = MCRYPT_RIJNDAEL_256;
- $mode = MCRYPT_MODE_CBC;
-
- $blockSize = mcrypt_get_block_size($enc, $mode);
- $ivSize = mcrypt_get_iv_size($enc, $mode);
- $keySize = mcrypt_get_key_size($enc, $mode);
-
- $key = hash('sha256', self::getSecretSalt(), TRUE);
- $key = substr($key, 0, $keySize);
-
- $len = strlen($clear);
- $numpad = $blockSize - ($len % $blockSize);
- $clear = str_pad($clear, $len + $numpad, chr($numpad));
-
- $iv = self::generateRandomBytes($ivSize);
-
- $data = mcrypt_encrypt($enc, $key, $clear, $mode, $iv);
-
- return $iv . $data;
+ return SimpleSAML\Utils\Crypto::aesEncrypt($clear);
}
/**
- * Function to AES decrypt data.
- *
- * @param $data Encrypted data.
- * @param $iv IV of encrypted data.
- * @return string The decrypted data.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\Crypto::aesDecrypt() instead.
*/
public static function aesDecrypt($encData) {
- assert('is_string($encData)');
-
- if (!function_exists("mcrypt_encrypt")) {
- throw new Exception("aesDecrypt needs mcrypt php module.");
- }
-
- $enc = MCRYPT_RIJNDAEL_256;
- $mode = MCRYPT_MODE_CBC;
-
- $ivSize = mcrypt_get_iv_size($enc, $mode);
- $keySize = mcrypt_get_key_size($enc, $mode);
-
- $key = hash('sha256', self::getSecretSalt(), TRUE);
- $key = substr($key, 0, $keySize);
-
- $iv = substr($encData, 0, $ivSize);
- $data = substr($encData, $ivSize);
-
- $clear = mcrypt_decrypt($enc, $key, $data, $mode, $iv);
-
- $len = strlen($clear);
- $numpad = ord($clear[$len - 1]);
- $clear = substr($clear, 0, $len - $numpad);
-
- return $clear;
+ return SimpleSAML\Utils\Crypto::aesDecrypt($encData);
}
/**
- * This function checks if we are running on Windows OS.
- *
- * @return TRUE if we are on Windows OS, FALSE otherwise.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\System::getOS() instead.
*/
public static function isWindowsOS() {
- return substr(strtoupper(PHP_OS),0,3) == 'WIN';
+ return SimpleSAML\Utils\System::getOS() === SimpleSAML\Utils\System::WINDOWS;
}
/**
- * Set a cookie.
- *
- * @param string $name The name of the session cookie.
- * @param string|NULL $value The value of the cookie. Set to NULL to delete the cookie.
- * @param array|NULL $params Cookie parameters.
- * @param bool $throw Whether to throw exception if setcookie fails.
+ * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::setCookie() instead.
*/
public static function setCookie($name, $value, array $params = NULL, $throw = TRUE) {
- assert('is_string($name)');
- assert('is_string($value) || is_null($value)');
-
- $default_params = array(
- 'lifetime' => 0,
- 'expire' => NULL,
- 'path' => '/',
- 'domain' => NULL,
- 'secure' => FALSE,
- 'httponly' => TRUE,
- 'raw' => FALSE,
- );
-
- if ($params !== NULL) {
- $params = array_merge($default_params, $params);
- } else {
- $params = $default_params;
- }
-
- // Do not set secure cookie if not on HTTPS
- if ($params['secure'] && !self::isHTTPS()) {
- SimpleSAML_Logger::warning('Setting secure cookie on http not allowed.');
- return;
- }
-
- if ($value === NULL) {
- $expire = time() - 365*24*60*60;
- } elseif (isset($params['expire'])) {
- $expire = $params['expire'];
- } elseif ($params['lifetime'] === 0) {
- $expire = 0;
- } else {
- $expire = time() + $params['lifetime'];
- }
-
- if ($params['raw']) {
- $success = setrawcookie($name, $value, $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
- } else {
- $success = setcookie($name, $value, $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
- }
-
- if (!$success) {
- if ($throw) {
- throw new SimpleSAML_Error_Exception('Error setting cookie - headers already sent.');
- } else {
- SimpleSAML_Logger::warning('Error setting cookie - headers already sent.');
- }
- }
+ \SimpleSAML\Utils\HTTP::setCookie($name, $value, $params, $throw);
}
}
diff --git a/lib/SimpleSAML/Utils/Arrays.php b/lib/SimpleSAML/Utils/Arrays.php
new file mode 100644
index 0000000..a620a11
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Arrays.php
@@ -0,0 +1,104 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * Array-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+class Arrays
+{
+
+ /**
+ * Put a non-array variable into an array.
+ *
+ * @param array $data The data to place into an array.
+ * @param mixed $index The index or key of the array where to place the data. Defaults to 0.
+ *
+ * @return array An array with one element containing $data, with key $index, or $data itself if it's already an
+ * array.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function arrayize($data, $index = 0)
+ {
+ return (is_array($data)) ? $data : array($index => $data);
+ }
+
+ /**
+ * Validate and normalize an array with attributes.
+ *
+ * This function takes in an associative array with attributes, and parses and validates
+ * this array. On success, it will return a normalized array, where each attribute name
+ * is an index to an array of one or more strings. On failure an exception will be thrown.
+ * This exception will contain an message describing what is wrong.
+ *
+ * @param array $attributes The array containing attributes that we should validate and normalize.
+ *
+ * @return array The normalized attributes array.
+ * @throws \InvalidArgumentException If input is not an array, array keys are not strings or attribute values are
+ * not strings.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function normalizeAttributesArray($attributes)
+ {
+
+ if (!is_array($attributes)) {
+ throw new \InvalidArgumentException('Attributes was not an array. Was: '.print_r($attributes, true).'".');
+ }
+
+ $newAttrs = array();
+ foreach ($attributes as $name => $values) {
+ if (!is_string($name)) {
+ throw new \InvalidArgumentException('Invalid attribute name: "'.print_r($name, true).'".');
+ }
+
+ $values = self::arrayize($values);
+
+ foreach ($values as $value) {
+ if (!is_string($value)) {
+ throw new \InvalidArgumentException('Invalid attribute value for attribute '.$name.
+ ': "'.print_r($value, true).'".');
+ }
+ }
+
+ $newAttrs[$name] = $values;
+ }
+
+ return $newAttrs;
+ }
+
+ /**
+ * This function transposes a two-dimensional array, so that $a['k1']['k2'] becomes $a['k2']['k1'].
+ *
+ * @param array $array The two-dimensional array to transpose.
+ *
+ * @return mixed The transposed array, or false if $array is not a valid two-dimensional array.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ */
+ public static function transpose($array)
+ {
+ if (!is_array($array)) {
+ return false;
+ }
+
+ $ret = array();
+ foreach ($array as $k1 => $a2) {
+ if (!is_array($a2)) {
+ return false;
+ }
+
+ foreach ($a2 as $k2 => $v) {
+ if (!array_key_exists($k2, $ret)) {
+ $ret[$k2] = array();
+ }
+ $ret[$k2][$k1] = $v;
+ }
+ }
+ return $ret;
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/Auth.php b/lib/SimpleSAML/Utils/Auth.php
new file mode 100644
index 0000000..089f94e
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Auth.php
@@ -0,0 +1,72 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * Auth-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+class Auth
+{
+
+ /**
+ * Retrieve a admin login URL.
+ *
+ * @param string|NULL $returnTo The URL the user should arrive on after admin authentication. Defaults to null.
+ *
+ * @return string A URL which can be used for admin authentication.
+ * @throws \InvalidArgumentException If $returnTo is neither a string nor null.
+ */
+ public static function getAdminLoginURL($returnTo = null)
+ {
+ if (!(is_string($returnTo) || is_null($returnTo))) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ if ($returnTo === null) {
+ $returnTo = \SimpleSAML\Utils\HTTP::getSelfURL();
+ }
+
+ return \SimpleSAML_Module::getModuleURL('core/login-admin.php', array('ReturnTo' => $returnTo));
+ }
+
+ /**
+ * Check whether the current user is admin.
+ *
+ * @return boolean True if the current user is an admin user, false otherwise.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function isAdmin()
+ {
+ $session = \SimpleSAML_Session::getSessionFromRequest();
+ return $session->isValid('admin') || $session->isValid('login-admin');
+ }
+
+ /**
+ * Require admin access to the current page.
+ *
+ * This is a helper function for limiting a page to those with administrative access. It will redirect the user to
+ * a login page if the current user doesn't have admin access.
+ *
+ * @return void This function will only return if the user is admin.
+ * @throws \SimpleSAML_Error_Exception If no "admin" authentication source was configured.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function requireAdmin()
+ {
+ if (self::isAdmin()) {
+ return;
+ }
+
+ // not authenticated as admin user, start authentication
+ if (\SimpleSAML_Auth_Source::getById('admin') !== null) {
+ $as = new \SimpleSAML_Auth_Simple('admin');
+ $as->login();
+ } else {
+ throw new \SimpleSAML_Error_Exception('Cannot find "admin" auth source, and admin privileges are required.');
+ }
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/Config.php b/lib/SimpleSAML/Utils/Config.php
new file mode 100644
index 0000000..e0c3f57
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Config.php
@@ -0,0 +1,58 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * Utility class for SimpleSAMLphp configuration management and manipulation.
+ *
+ * @package SimpleSAMLphp
+ */
+class Config
+{
+
+ /**
+ * Resolves a path that may be relative to the cert-directory.
+ *
+ * @param string $path The (possibly relative) path to the file.
+ *
+ * @return string The file path.
+ * @throws \InvalidArgumentException If $path is not a string.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getCertPath($path)
+ {
+ if (!is_string($path)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $globalConfig = \SimpleSAML_Configuration::getInstance();
+ $base = $globalConfig->getPathValue('certdir', 'cert/');
+ return System::resolvePath($path, $base);
+ }
+
+
+ /**
+ * Retrieve the secret salt.
+ *
+ * This function retrieves the value which is configured as the secret salt. It will check that the value exists
+ * and is set to a non-default value. If it isn't, an exception will be thrown.
+ *
+ * The secret salt can be used as a component in hash functions, to make it difficult to test all possible values
+ * in order to retrieve the original value. It can also be used as a simple method for signing data, by hashing the
+ * data together with the salt.
+ *
+ * @return string The secret salt.
+ * @throws \InvalidArgumentException If the secret salt hasn't been configured.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getSecretSalt()
+ {
+ $secretSalt = \SimpleSAML_Configuration::getInstance()->getString('secretsalt');
+ if ($secretSalt === 'defaultsecretsalt') {
+ throw new \InvalidArgumentException('The "secretsalt" configuration option must be set to a secret value.');
+ }
+
+ return $secretSalt;
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/Config/Metadata.php b/lib/SimpleSAML/Utils/Config/Metadata.php
index d85abe4..82c47ba 100644
--- a/lib/SimpleSAML/Utils/Config/Metadata.php
+++ b/lib/SimpleSAML/Utils/Config/Metadata.php
@@ -1,11 +1,13 @@
<?php
+namespace SimpleSAML\Utils\Config;
+
/**
* Class with utilities to fetch different configuration objects from metadata configuration arrays.
*
* @package SimpleSAMLphp
* @author Jaime Pérez Crespo, UNINETT AS <jaime.perez@uninett.no>
*/
-class SimpleSAML_Utils_Config_Metadata
+class Metadata
{
/**
@@ -13,7 +15,12 @@ class SimpleSAML_Utils_Config_Metadata
* @see "Metadata for the OASIS Security Assertion Markup Language (SAML) V2.0", section 2.3.2.2.
*/
public static $VALID_CONTACT_OPTIONS = array(
- 'contactType', 'emailAddress', 'givenName', 'surName', 'telephoneNumber', 'company',
+ 'contactType',
+ 'emailAddress',
+ 'givenName',
+ 'surName',
+ 'telephoneNumber',
+ 'company',
);
@@ -22,7 +29,11 @@ class SimpleSAML_Utils_Config_Metadata
* @see "Metadata for the OASIS Security Assertion Markup Language (SAML) V2.0", section 2.3.2.2.
*/
public static $VALID_CONTACT_TYPES = array(
- 'technical', 'support', 'administrative', 'billing', 'other',
+ 'technical',
+ 'support',
+ 'administrative',
+ 'billing',
+ 'other',
);
@@ -57,24 +68,28 @@ class SimpleSAML_Utils_Config_Metadata
* otherwise it will just return the name as "givenName" in the resulting array.
*
* @param array $contact The contact to parse and sanitize.
+ *
* @return array An array holding valid contact configuration options. If a key 'name' was part of the input array,
* it will try to decompose the name into its parts, and place the parts into givenName and surName, if those are
* missing.
- * @throws InvalidArgumentException if the contact does not conform to valid configuration rules for contacts.
+ * @throws \InvalidArgumentException If $contact is neither a string nor null, or the contact does not conform to
+ * valid configuration rules for contacts.
*/
public static function getContact($contact)
{
- assert('is_array($contact) || is_null($contact)');
+ if (!(is_array($contact) || is_null($contact))) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
// check the type
if (!isset($contact['contactType']) || !in_array($contact['contactType'], self::$VALID_CONTACT_TYPES, true)) {
$types = join(', ', array_map(
- function($t) {
+ function ($t) {
return '"'.$t.'"';
},
self::$VALID_CONTACT_TYPES
));
- throw new InvalidArgumentException('"contactType" is mandatory and must be one of '. $types.".");
+ throw new \InvalidArgumentException('"contactType" is mandatory and must be one of '.$types.".");
}
// try to fill in givenName and surName from name
@@ -100,34 +115,38 @@ class SimpleSAML_Utils_Config_Metadata
// check givenName
if (isset($contact['givenName']) && (
empty($contact['givenName']) || !is_string($contact['givenName'])
- )) {
- throw new InvalidArgumentException('"givenName" must be a string and cannot be empty.');
+ )
+ ) {
+ throw new \InvalidArgumentException('"givenName" must be a string and cannot be empty.');
}
// check surName
if (isset($contact['surName']) && (
empty($contact['surName']) || !is_string($contact['surName'])
- )) {
- throw new InvalidArgumentException('"surName" must be a string and cannot be empty.');
+ )
+ ) {
+ throw new \InvalidArgumentException('"surName" must be a string and cannot be empty.');
}
// check company
if (isset($contact['company']) && (
empty($contact['company']) || !is_string($contact['company'])
- )) {
- throw new InvalidArgumentException('"company" must be a string and cannot be empty.');
+ )
+ ) {
+ throw new \InvalidArgumentException('"company" must be a string and cannot be empty.');
}
// check emailAddress
if (isset($contact['emailAddress'])) {
if (empty($contact['emailAddress']) ||
- !(is_string($contact['emailAddress']) || is_array($contact['emailAddress']))) {
- throw new InvalidArgumentException('"emailAddress" must be a string or an array and cannot be empty.');
+ !(is_string($contact['emailAddress']) || is_array($contact['emailAddress']))
+ ) {
+ throw new \InvalidArgumentException('"emailAddress" must be a string or an array and cannot be empty.');
}
if (is_array($contact['emailAddress'])) {
foreach ($contact['emailAddress'] as $address) {
if (!is_string($address) || empty($address)) {
- throw new InvalidArgumentException('Email addresses must be a string and cannot be empty.');
+ throw new \InvalidArgumentException('Email addresses must be a string and cannot be empty.');
}
}
}
@@ -136,13 +155,14 @@ class SimpleSAML_Utils_Config_Metadata
// check telephoneNumber
if (isset($contact['telephoneNumber'])) {
if (empty($contact['telephoneNumber']) ||
- !(is_string($contact['telephoneNumber']) || is_array($contact['telephoneNumber']))) {
- throw new InvalidArgumentException('"telephoneNumber" must be a string or an array and cannot be empty.');
+ !(is_string($contact['telephoneNumber']) || is_array($contact['telephoneNumber']))
+ ) {
+ throw new \InvalidArgumentException('"telephoneNumber" must be a string or an array and cannot be empty.');
}
if (is_array($contact['telephoneNumber'])) {
foreach ($contact['telephoneNumber'] as $address) {
if (!is_string($address) || empty($address)) {
- throw new InvalidArgumentException('Telephone numbers must be a string and cannot be empty.');
+ throw new \InvalidArgumentException('Telephone numbers must be a string and cannot be empty.');
}
}
}
@@ -152,4 +172,55 @@ class SimpleSAML_Utils_Config_Metadata
return array_intersect_key($contact, array_flip(self::$VALID_CONTACT_OPTIONS));
}
+
+ /**
+ * Find the default endpoint in an endpoint array.
+ *
+ * @param array $endpoints An array with endpoints.
+ * @param array $bindings An array with acceptable bindings. Can be null if any binding is allowed.
+ *
+ * @return array|NULL The default endpoint, or null if no acceptable endpoints are used.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getDefaultEndpoint(array $endpoints, array $bindings = null)
+ {
+ $firstNotFalse = null;
+ $firstAllowed = null;
+
+ // look through the endpoint list for acceptable endpoints
+ foreach ($endpoints as $i => $ep) {
+ if ($bindings !== null && !in_array($ep['Binding'], $bindings, true)) {
+ // unsupported binding, skip it
+ continue;
+ }
+
+ if (array_key_exists('isDefault', $ep)) {
+ if ($ep['isDefault'] === true) {
+ // this is the first endpoint with isDefault set to true
+ return $ep;
+ }
+ // isDefault is set to false, but the endpoint is still usable as a last resort
+ if ($firstAllowed === null) {
+ // this is the first endpoint that we can use
+ $firstAllowed = $ep;
+ }
+ } else {
+ if ($firstNotFalse === null) {
+ // this is the first endpoint without isDefault set
+ $firstNotFalse = $ep;
+ }
+ }
+ }
+
+ if ($firstNotFalse !== null) {
+ // we have an endpoint without isDefault set to false
+ return $firstNotFalse;
+ }
+
+ /* $firstAllowed either contains the first endpoint we can use, or it contains null if we cannot use any of the
+ * endpoints. Either way we return its value.
+ */
+ return $firstAllowed;
+ }
}
diff --git a/lib/SimpleSAML/Utils/Crypto.php b/lib/SimpleSAML/Utils/Crypto.php
index 1bf2dd2..e09bbfe 100644
--- a/lib/SimpleSAML/Utils/Crypto.php
+++ b/lib/SimpleSAML/Utils/Crypto.php
@@ -1,142 +1,334 @@
<?php
+namespace SimpleSAML\Utils;
+
/**
- * A class for crypto related functions
+ * A class for cryptography-related functions
*
- * @author Dyonisius Visser, TERENA. <visser@terena.org>
- * @package simpleSAMLphp
+ * @package SimpleSAMLphp
*/
-class SimpleSAML_Utils_Crypto {
-
- /**
- * This function generates a password hash
- * @param $password The unencrypted password
- * @param $algo The hashing algorithm, capitals, optionally prepended with 'S' (salted)
- * @param $salt Optional salt
- */
- public static function pwHash($password, $algo, $salt = NULL) {
- assert('is_string($algo)');
- assert('is_string($password)');
-
- if(in_array(strtolower($algo), hash_algos())) {
- $php_algo = strtolower($algo); // 'sha256' etc
- // LDAP compatibility
- return '{' . preg_replace('/^SHA1$/', 'SHA', $algo) . '}'
- .base64_encode(hash($php_algo, $password, TRUE));
- }
-
- // Salt
- if(!$salt) {
- // Default 8 byte salt, but 4 byte for LDAP SHA1 hashes
- $bytes = ($algo == 'SSHA1') ? 4 : 8;
- $salt = SimpleSAML_Utilities::generateRandomBytes($bytes);
- }
-
- if($algo[0] == 'S' && in_array(substr(strtolower($algo),1), hash_algos())) {
- $php_algo = substr(strtolower($algo),1); // 'sha256' etc
- // Salted hash, with LDAP compatibility
- return '{' . preg_replace('/^SSHA1$/', 'SSHA', $algo) . '}' .
- base64_encode(hash($php_algo, $password.$salt, TRUE) . $salt);
- }
-
- throw new Exception('Hashing algoritm \'' . strtolower($algo) . '\' not supported');
-
- }
-
-
- /**
- * This function checks if a password is valid
- * @param $crypted Password as appears in password file, optionally prepended with algorithm
- * @param $clear Password to check
- */
- public static function pwValid($crypted, $clear) {
- assert('is_string($crypted)');
- assert('is_string($clear)');
-
- // Match algorithm string ('{SSHA256}', '{MD5}')
- if(preg_match('/^{(.*?)}(.*)$/', $crypted, $matches)) {
-
- // LDAP compatibility
- $algo = preg_replace('/^(S?SHA)$/', '${1}1', $matches[1]);
-
- $cryptedpw = $matches[2];
-
- if(in_array(strtolower($algo), hash_algos())) {
- // Unsalted hash
- return ( $crypted == self::pwHash($clear, $algo) );
- }
-
- if($algo[0] == 'S' && in_array(substr(strtolower($algo),1), hash_algos())) {
- $php_algo = substr(strtolower($algo),1);
- // Salted hash
- $hash_length = strlen(hash($php_algo, 'whatever', TRUE));
- $salt = substr(base64_decode($cryptedpw), $hash_length);
- return ( $crypted == self::pwHash($clear, $algo, $salt) );
- }
-
- throw new Exception('Hashing algoritm \'' . strtolower($algo) . '\' not supported');
-
- } else {
- return $crypted === $clear;
- }
- }
-
- /**
- * This function generates an Apache 'apr1' password hash, which uses a modified
- * version of MD5: http://httpd.apache.org/docs/2.2/misc/password_encryptions.html
- * @param $password The unencrypted password
- * @param $salt Optional salt
- */
- public static function apr1Md5Hash($password, $salt = NULL) {
- assert('is_string($password)');
-
- $chars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
- if(!$salt) {
- $salt = substr(str_shuffle($allowed_chars), 0, 8);
- }
-
- $len = strlen($password);
- $text = $password.'$apr1$'.$salt;
- $bin = pack("H32", md5($password.$salt.$password));
- for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
- for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $password{0}; }
- $bin = pack("H32", md5($text));
- for($i = 0; $i < 1000; $i++) {
- $new = ($i & 1) ? $password : $bin;
- if ($i % 3) $new .= $salt;
- if ($i % 7) $new .= $password;
- $new .= ($i & 1) ? $bin : $password;
- $bin = pack("H32", md5($new));
- }
- $tmp= '';
- for ($i = 0; $i < 5; $i++) {
- $k = $i + 6;
- $j = $i + 12;
- if ($j == 16) $j = 5;
- $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
- }
- $tmp = chr(0).chr(0).$bin[11].$tmp;
- $tmp = strtr(
- strrev(substr(base64_encode($tmp), 2)),
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
- $chars
- );
- return "$"."apr1"."$".$salt."$".$tmp;
- }
-
-
- /**
- * This function verifies an Apache 'apr1' password hash
- */
- public static function apr1Md5Valid($crypted, $clear) {
- assert('is_string($crypted)');
- assert('is_string($clear)');
- $pattern = '/^\$apr1\$([A-Za-z0-9\.\/]{8})\$([A-Za-z0-9\.\/]{22})$/';
-
- if(preg_match($pattern, $crypted, $matches)) {
- $salt = $matches[1];
- return ( $crypted == self::apr1Md5Hash($clear, $salt) );
- }
- return FALSE;
- }
+class Crypto
+{
+
+ /**
+ * Decrypt data using AES and the system-wide secret salt as key.
+ *
+ * @param string $ciphertext The encrypted data to decrypt.
+ *
+ * @return string The decrypted data.
+ * @htorws \InvalidArgumentException If $ciphertext is not a string.
+ * @throws \SimpleSAML_Error_Exception If the mcrypt module is not loaded.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function aesDecrypt($ciphertext)
+ {
+ if (!is_string($ciphertext)) {
+ throw new \InvalidArgumentException('Input parameter "$ciphertext" must be a string.');
+ }
+ if (!function_exists("mcrypt_encrypt")) {
+ throw new \SimpleSAML_Error_Exception("The mcrypt PHP module is not loaded.");
+ }
+
+ $enc = MCRYPT_RIJNDAEL_256;
+ $mode = MCRYPT_MODE_CBC;
+
+ $ivSize = mcrypt_get_iv_size($enc, $mode);
+ $keySize = mcrypt_get_key_size($enc, $mode);
+
+ $key = hash('sha256', Config::getSecretSalt(), true);
+ $key = substr($key, 0, $keySize);
+
+ $iv = substr($ciphertext, 0, $ivSize);
+ $data = substr($ciphertext, $ivSize);
+
+ $clear = mcrypt_decrypt($enc, $key, $data, $mode, $iv);
+
+ $len = strlen($clear);
+ $numpad = ord($clear[$len - 1]);
+ $clear = substr($clear, 0, $len - $numpad);
+
+ return $clear;
+ }
+
+
+ /**
+ * Encrypt data using AES and the system-wide secret salt as key.
+ *
+ * @param string $data The data to encrypt.
+ *
+ * @return string The encrypted data and IV.
+ * @throws \InvalidArgumentException If $data is not a string.
+ * @throws \SimpleSAML_Error_Exception If the mcrypt module is not loaded.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function aesEncrypt($data)
+ {
+ if (!is_string($data)) {
+ throw new \InvalidArgumentException('Input parameter "$data" must be a string.');
+ }
+ if (!function_exists("mcrypt_encrypt")) {
+ throw new \SimpleSAML_Error_Exception('The mcrypt PHP module is not loaded.');
+ }
+
+ $enc = MCRYPT_RIJNDAEL_256;
+ $mode = MCRYPT_MODE_CBC;
+
+ $blockSize = mcrypt_get_block_size($enc, $mode);
+ $ivSize = mcrypt_get_iv_size($enc, $mode);
+ $keySize = mcrypt_get_key_size($enc, $mode);
+
+ $key = hash('sha256', Config::getSecretSalt(), true);
+ $key = substr($key, 0, $keySize);
+
+ $len = strlen($data);
+ $numpad = $blockSize - ($len % $blockSize);
+ $data = str_pad($data, $len + $numpad, chr($numpad));
+
+ $iv = openssl_random_pseudo_bytes($ivSize);
+
+ $data = mcrypt_encrypt($enc, $key, $data, $mode, $iv);
+
+ return $iv.$data;
+ }
+
+
+ /**
+ * Load a private key from metadata.
+ *
+ * This function loads a private key from a metadata array. It looks for the following elements:
+ * - 'privatekey': Name of a private key file in the cert-directory.
+ * - 'privatekey_pass': Password for the private key.
+ *
+ * It returns and array with the following elements:
+ * - 'PEM': Data for the private key, in PEM-format.
+ * - 'password': Password for the private key.
+ *
+ * @param \SimpleSAML_Configuration $metadata The metadata array the private key should be loaded from.
+ * @param bool $required Whether the private key is required. If this is true, a
+ * missing key will cause an exception. Defaults to false.
+ * @param string $prefix The prefix which should be used when reading from the metadata
+ * array. Defaults to ''.
+ *
+ * @return array|NULL Extracted private key, or NULL if no private key is present.
+ * @throws \InvalidArgumentException If $required is not boolean or $prefix is not a string.
+ * @throws \SimpleSAML_Error_Exception If no private key is found in the metadata, or it was not possible to load
+ * it.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function loadPrivateKey(\SimpleSAML_Configuration $metadata, $required = false, $prefix = '')
+ {
+ if (!is_bool($required) || !is_string($prefix)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $file = $metadata->getString($prefix.'privatekey', null);
+ if ($file === null) {
+ // no private key found
+ if ($required) {
+ throw new \SimpleSAML_Error_Exception('No private key found in metadata.');
+ } else {
+ return null;
+ }
+ }
+
+ $file = Config::getCertPath($file);
+ $data = @file_get_contents($file);
+ if ($data === false) {
+ throw new \SimpleSAML_Error_Exception('Unable to load private key from file "'.$file.'"');
+ }
+
+ $ret = array(
+ 'PEM' => $data,
+ );
+
+ if ($metadata->hasValue($prefix.'privatekey_pass')) {
+ $ret['password'] = $metadata->getString($prefix.'privatekey_pass');
+ }
+
+ return $ret;
+ }
+
+
+ /**
+ * Get public key or certificate from metadata.
+ *
+ * This function implements a function to retrieve the public key or certificate from a metadata array.
+ *
+ * It will search for the following elements in the metadata:
+ * - 'certData': The certificate as a base64-encoded string.
+ * - 'certificate': A file with a certificate or public key in PEM-format.
+ * - 'certFingerprint': The fingerprint of the certificate. Can be a single fingerprint, or an array of multiple
+ * valid fingerprints.
+ *
+ * This function will return an array with these elements:
+ * - 'PEM': The public key/certificate in PEM-encoding.
+ * - 'certData': The certificate data, base64 encoded, on a single line. (Only present if this is a certificate.)
+ * - 'certFingerprint': Array of valid certificate fingerprints. (Only present if this is a certificate.)
+ *
+ * @param \SimpleSAML_Configuration $metadata The metadata.
+ * @param bool $required Whether the private key is required. If this is TRUE, a missing key
+ * will cause an exception. Default is FALSE.
+ * @param string $prefix The prefix which should be used when reading from the metadata array.
+ * Defaults to ''.
+ *
+ * @return array|NULL Public key or certificate data, or NULL if no public key or certificate was found.
+ * @throws \InvalidArgumentException If $metadata is not an instance of \SimpleSAML_Configuration, $required is not
+ * boolean or $prefix is not a string.
+ * @throws \SimpleSAML_Error_Exception If no private key is found in the metadata, or it was not possible to load
+ * it.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Lasse Birnbaum Jensen
+ */
+ public static function loadPublicKey(\SimpleSAML_Configuration $metadata, $required = false, $prefix = '')
+ {
+ if (!is_bool($required) || !is_string($prefix)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $keys = $metadata->getPublicKeys(null, false, $prefix);
+ if ($keys !== null) {
+ foreach ($keys as $key) {
+ if ($key['type'] !== 'X509Certificate') {
+ continue;
+ }
+ if ($key['signing'] !== true) {
+ continue;
+ }
+ $certData = $key['X509Certificate'];
+ $pem = "-----BEGIN CERTIFICATE-----\n".
+ chunk_split($certData, 64).
+ "-----END CERTIFICATE-----\n";
+ $certFingerprint = strtolower(sha1(base64_decode($certData)));
+
+ return array(
+ 'certData' => $certData,
+ 'PEM' => $pem,
+ 'certFingerprint' => array($certFingerprint),
+ );
+ }
+ // no valid key found
+ } elseif ($metadata->hasValue($prefix.'certFingerprint')) {
+ // we only have a fingerprint available
+ $fps = $metadata->getArrayizeString($prefix.'certFingerprint');
+
+ // normalize fingerprint(s) - lowercase and no colons
+ foreach ($fps as &$fp) {
+ assert('is_string($fp)');
+ $fp = strtolower(str_replace(':', '', $fp));
+ }
+
+ // We can't build a full certificate from a fingerprint, and may as well return an array with only the
+ //fingerprint(s) immediately.
+ return array('certFingerprint' => $fps);
+ }
+
+ // no public key/certificate available
+ if ($required) {
+ throw new \SimpleSAML_Error_Exception('No public key / certificate found in metadata.');
+ } else {
+ return null;
+ }
+ }
+
+
+ /**
+ * This function hashes a password with a given algorithm.
+ *
+ * @param string $password The password to hash.
+ * @param string $algorithm The hashing algorithm, uppercase, optionally prepended with 'S' (salted). See
+ * hash_algos() for a complete list of hashing algorithms.
+ * @param string $salt An optional salt to use.
+ *
+ * @return string The hashed password.
+ * @throws \InvalidArgumentException If the input parameters are not strings.
+ * @throws \SimpleSAML_Error_Exception If the algorithm specified is not supported.
+ *
+ * @see hash_algos()
+ *
+ * @author Dyonisius Visser, TERENA <visser@terena.org>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function pwHash($password, $algorithm, $salt = null)
+ {
+ if (!is_string($algorithm) || !is_string($password)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ // hash w/o salt
+ if (in_array(strtolower($algorithm), hash_algos())) {
+ $alg_str = '{'.str_replace('SHA1', 'SHA', $algorithm).'}'; // LDAP compatibility
+ $hash = hash(strtolower($algorithm), $password, true);
+ return $alg_str.base64_encode($hash);
+ }
+
+ // hash w/ salt
+ if (!$salt) { // no salt provided, generate one
+ // default 8 byte salt, but 4 byte for LDAP SHA1 hashes
+ $bytes = ($algorithm == 'SSHA1') ? 4 : 8;
+ $salt = openssl_random_pseudo_bytes($bytes);
+ }
+
+ if ($algorithm[0] == 'S' && in_array(substr(strtolower($algorithm), 1), hash_algos())) {
+ $alg = substr(strtolower($algorithm), 1); // 'sha256' etc
+ $alg_str = '{'.str_replace('SSHA1', 'SSHA', $algorithm).'}'; // LDAP compatibility
+ $hash = hash($alg, $password.$salt, true);
+ return $alg_str.base64_encode($hash.$salt);
+ }
+
+ throw new \SimpleSAML_Error_Exception('Hashing algorithm \''.strtolower($algorithm).'\' is not supported');
+ }
+
+
+ /**
+ * This function checks if a password is valid
+ *
+ * @param string $hash The password as it appears in password file, optionally prepended with algorithm.
+ * @param string $password The password to check in clear.
+ *
+ * @return boolean True if the hash corresponds with the given password, false otherwise.
+ * @throws \InvalidArgumentException If the input parameters are not strings.
+ * @throws \SimpleSAML_Error_Exception If the algorithm specified is not supported.
+ *
+ * @author Dyonisius Visser, TERENA <visser@terena.org>
+ */
+ public static function pwValid($hash, $password)
+ {
+ if (!is_string($hash) || !is_string($password)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ // match algorithm string (e.g. '{SSHA256}', '{MD5}')
+ if (preg_match('/^{(.*?)}(.*)$/', $hash, $matches)) {
+
+ // LDAP compatibility
+ $alg = preg_replace('/^(S?SHA)$/', '${1}1', $matches[1]);
+
+ // hash w/o salt
+ if (in_array(strtolower($alg), hash_algos())) {
+ return $hash === self::pwHash($password, $alg);
+ }
+
+ // hash w/ salt
+ if ($alg[0] === 'S' && in_array(substr(strtolower($alg), 1), hash_algos())) {
+ $php_alg = substr(strtolower($alg), 1);
+
+ // get hash length of this algorithm to learn how long the salt is
+ $hash_length = strlen(hash($php_alg, '', true));
+ $salt = substr(base64_decode($matches[2]), $hash_length);
+ return ($hash === self::pwHash($password, $alg, $salt));
+ }
+ } else {
+ return $hash === $password;
+ }
+
+ throw new \SimpleSAML_Error_Exception('Hashing algorithm \''.strtolower($alg).'\' is not supported');
+ }
}
diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
new file mode 100644
index 0000000..7518bfa
--- /dev/null
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -0,0 +1,1027 @@
+<?php
+namespace SimpleSAML\Utils;
+
+
+/**
+ * HTTP-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+class HTTP
+{
+
+ /**
+ * Obtain a URL where we can redirect to securely post a form with the given data to a specific destination.
+ *
+ * @param string $destination The destination URL.
+ * @param array $data An associative array containing the data to be posted to $destination.
+ *
+ * @return string A URL which allows to securely post a form to $destination.
+ *
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ private static function getSecurePOSTRedirectURL($destination, $data)
+ {
+ $session = \SimpleSAML_Session::getSessionFromRequest();
+ $id = self::savePOSTData($session, $destination, $data);
+
+ // encrypt the session ID and the random ID
+ $info = base64_encode(Crypto::aesEncrypt($session->getSessionId().':'.$id));
+
+ $url = \SimpleSAML_Module::getModuleURL('core/postredirect.php', array('RedirInfo' => $info));
+ return preg_replace('#^https:#', 'http:', $url);
+ }
+
+
+ /**
+ * Retrieve Host value from $_SERVER environment variables.
+ *
+ * @return string The current host name, including the port if needed. It will use localhost when unable to
+ * determine the current host.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ private static function getServerHost()
+ {
+ if (array_key_exists('HTTP_HOST', $_SERVER)) {
+ $current = $_SERVER['HTTP_HOST'];
+ } elseif (array_key_exists('SERVER_NAME', $_SERVER)) {
+ $current = $_SERVER['SERVER_NAME'];
+ } else {
+ // almost certainly not what you want, but...
+ $current = 'localhost';
+ }
+
+ if (strstr($current, ":")) {
+ $decomposed = explode(":", $current);
+ $port = array_pop($decomposed);
+ if (!is_numeric($port)) {
+ array_push($decomposed, $port);
+ }
+ $current = implode($decomposed, ":");
+ }
+ return $current;
+ }
+
+
+ /**
+ * Retrieve HTTPS status from $_SERVER environment variables.
+ *
+ * @return boolean True if the request was performed through HTTPS, false otherwise.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ private static function getServerHTTPS()
+ {
+ if (!array_key_exists('HTTPS', $_SERVER)) {
+ // not an https-request
+ return false;
+ }
+
+ if ($_SERVER['HTTPS'] === 'off') {
+ // IIS with HTTPS off
+ return false;
+ }
+
+ // otherwise, HTTPS will be a non-empty string
+ return $_SERVER['HTTPS'] !== '';
+ }
+
+
+ /**
+ * Retrieve the port number from $_SERVER environment variables.
+ *
+ * @return string The port number prepended by a colon, if it is different than the default port for the protocol
+ * (80 for HTTP, 443 for HTTPS), or an empty string otherwise.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ private static function getServerPort()
+ {
+ $port = (isset($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : '80';
+ if (self::getServerHTTPS()) {
+ if ($port !== '443') {
+ return ':'.$port;
+ }
+ } else {
+ if ($port !== '80') {
+ return ':'.$port;
+ }
+ }
+ return '';
+ }
+
+
+ /**
+ * This function redirects the user to the specified address.
+ *
+ * This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the
+ * HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.
+ *
+ * The function will also generate a simple web page with a clickable link to the target page.
+ *
+ * @param string $url The URL we should redirect to. This URL may include query parameters. If this URL is a
+ * relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the
+ * absolute URL to the root of the website.
+ * @param string[] $parameters An array with extra query string parameters which should be appended to the URL. The
+ * name of the parameter is the array index. The value of the parameter is the value stored in the index. Both
+ * the name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just
+ * the name, without a value.
+ *
+ * @return void This function never returns.
+ * @throws \InvalidArgumentException If $url is not a string or is empty, or $parameters is not an array.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Mads Freek Petersen
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ private static function redirect($url, $parameters = array())
+ {
+ if (!is_string($url) || empty($url) || !is_array($parameters)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+ if (!empty($parameters)) {
+ $url = self::addURLParameters($url, $parameters);
+ }
+
+ /* Set the HTTP result code. This is either 303 See Other or
+ * 302 Found. HTTP 303 See Other is sent if the HTTP version
+ * is HTTP/1.1 and the request type was a POST request.
+ */
+ if ($_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1' &&
+ $_SERVER['REQUEST_METHOD'] === 'POST'
+ ) {
+ $code = 303;
+ } else {
+ $code = 302;
+ }
+
+ if (strlen($url) > 2048) {
+ \SimpleSAML_Logger::warning('Redirecting to a URL longer than 2048 bytes.');
+ }
+
+ // set the location header
+ header('Location: '.$url, true, $code);
+
+ // disable caching of this response
+ header('Pragma: no-cache');
+ header('Cache-Control: no-cache, must-revalidate');
+
+ // show a minimal web page with a clickable link to the URL
+ echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
+ echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"';
+ echo ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n";
+ echo '<html xmlns="http://www.w3.org/1999/xhtml">'."\n";
+ echo " <head>\n";
+ echo ' <meta http-equiv="content-type" content="text/html; charset=utf-8">'."\n";
+ echo " <title>Redirect</title>\n";
+ echo " </head>\n";
+ echo " <body>\n";
+ echo " <h1>Redirect</h1>\n";
+ echo ' <p>You were redirected to: <a id="redirlink" href="'.htmlspecialchars($url).'">';
+ echo htmlspecialchars($url)."</a>\n";
+ echo ' <script type="text/javascript">document.getElementById("redirlink").focus();</script>'."\n";
+ echo " </p>\n";
+ echo " </body>\n";
+ echo '</html>';
+
+ // end script execution
+ exit;
+ }
+
+
+ /**
+ * Save the given HTTP POST data and the destination where it should be posted to a given session.
+ *
+ * @param \SimpleSAML_Session $session The session where to temporarily store the data.
+ * @param string $destination The destination URL where the form should be posted.
+ * @param array $data An associative array with the data to be posted to $destination.
+ *
+ * @return string A random identifier that can be used to retrieve the data from the current session.
+ *
+ * @author Andjelko Horvat
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ private static function savePOSTData(\SimpleSAML_Session $session, $destination, $data)
+ {
+ // generate a random ID to avoid replay attacks
+ $id = Random::generateID();
+ $postData = array(
+ 'post' => $data,
+ 'url' => $destination,
+ );
+
+ // save the post data to the session, tied to the random ID
+ $session->setData('core_postdatalink', $id, $postData);
+
+ return $id;
+ }
+
+
+ /**
+ * Add one or more query parameters to the given URL.
+ *
+ * @param string $url The URL the query parameters should be added to.
+ * @param array $parameters The query parameters which should be added to the url. This should be an associative
+ * array.
+ *
+ * @return string The URL with the new query parameters.
+ * @throws \InvalidArgumentException If $url is not a string or $parameters is not an array.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function addURLParameters($url, $parameters)
+ {
+ if (!is_string($url) || !is_array($parameters)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $queryStart = strpos($url, '?');
+ if ($queryStart === false) {
+ $oldQuery = array();
+ $url .= '?';
+ } else {
+ $oldQuery = substr($url, $queryStart + 1);
+ if ($oldQuery === false) {
+ $oldQuery = array();
+ } else {
+ $oldQuery = self::parseQueryString($oldQuery);
+ }
+ $url = substr($url, 0, $queryStart + 1);
+ }
+
+ $query = array_merge($oldQuery, $parameters);
+ $url .= http_build_query($query, '', '&');
+
+ return $url;
+ }
+
+
+ /**
+ * Check for session cookie, and show missing-cookie page if it is missing.
+ *
+ * @param string|NULL $retryURL The URL the user should access to retry the operation. Defaults to null.
+ *
+ * @return void If there is a session cookie, nothing will be returned. Otherwise, the user will be redirected to a
+ * page telling about the missing cookie.
+ * @throws \InvalidArgumentException If $retryURL is neither a string nor null.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function checkSessionCookie($retryURL = null)
+ {
+ if (!is_string($retryURL) || !is_null($retryURL)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $session = \SimpleSAML_Session::getSessionFromRequest();
+ if ($session->hasSessionCookie()) {
+ return;
+ }
+
+ // we didn't have a session cookie. Redirect to the no-cookie page
+
+ $url = \SimpleSAML_Module::getModuleURL('core/no_cookie.php');
+ if ($retryURL !== null) {
+ $url = self::addURLParameters($url, array('retryURL' => $retryURL));
+ }
+ self::redirectTrustedURL($url);
+ }
+
+
+ /**
+ * Check if a URL is valid and is in our list of allowed URLs.
+ *
+ * @param string $url The URL to check.
+ * @param array $trustedSites An optional white list of domains. If none specified, the 'trusted.url.domains'
+ * configuration directive will be used.
+ *
+ * @return string The normalized URL itself if it is allowed. An empty string if the $url parameter is empty as
+ * defined by the empty() function.
+ * @throws \InvalidArgumentException If the URL is malformed.
+ * @throws \SimpleSAML_Error_Exception If the URL is not allowed by configuration.
+ *
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function checkURLAllowed($url, array $trustedSites = null)
+ {
+ if (empty($url)) {
+ return '';
+ }
+ $url = self::normalizeURL($url);
+
+ // get the white list of domains
+ if ($trustedSites === null) {
+ $trustedSites = \SimpleSAML_Configuration::getInstance()->getArray('trusted.url.domains', null);
+ // TODO: remove this before 2.0
+ if ($trustedSites === null) {
+ $trustedSites = \SimpleSAML_Configuration::getInstance()->getArray('redirect.trustedsites', null);
+ }
+ }
+
+ // validates the URL's host is among those allowed
+ if ($trustedSites !== null) {
+ assert(is_array($trustedSites));
+ preg_match('@^https?://([^/]+)@i', $url, $matches);
+ $hostname = $matches[1];
+
+ // add self host to the white list
+ $self_host = self::getSelfHost();
+ $trustedSites[] = $self_host;
+
+ // throw exception due to redirection to untrusted site
+ if (!in_array($hostname, $trustedSites)) {
+ throw new \SimpleSAML_Error_Exception('URL not allowed: '.$url);
+ }
+ }
+ return $url;
+ }
+
+
+ /**
+ * Helper function to retrieve a file or URL with proxy support.
+ *
+ * An exception will be thrown if we are unable to retrieve the data.
+ *
+ * @param string $url The path or URL we should fetch.
+ * @param array $context Extra context options. This parameter is optional.
+ * @param boolean $getHeaders Whether to also return response headers. Optional.
+ *
+ * @return mixed array if $getHeaders is set, string otherwise
+ * @throws \InvalidArgumentException If the input parameters are invalid.
+ * @throws \SimpleSAML_Error_Exception If the file or URL cannot be retrieved.
+ *
+ * @author Andjelko Horvat
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Marco Ferrante, University of Genova <marco@csita.unige.it>
+ */
+ public static function fetch($url, $context = array(), $getHeaders = false)
+ {
+ if (!is_string($url)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $config = \SimpleSAML_Configuration::getInstance();
+
+ $proxy = $config->getString('proxy', null);
+ if ($proxy !== null) {
+ if (!isset($context['http']['proxy'])) {
+ $context['http']['proxy'] = $proxy;
+ }
+ if (!isset($context['http']['request_fulluri'])) {
+ $context['http']['request_fulluri'] = true;
+ }
+ /*
+ * If the remote endpoint over HTTPS uses the SNI extension (Server Name Indication RFC 4366), the proxy
+ * could introduce a mismatch between the names in the Host: HTTP header and the SNI_server_name in TLS
+ * negotiation (thanks to Cristiano Valli @ GARR-IDEM to have pointed this problem).
+ * See: https://bugs.php.net/bug.php?id=63519
+ * These controls will force the same value for both fields.
+ * Marco Ferrante (marco@csita.unige.it), Nov 2012
+ */
+ if (preg_match('#^https#i', $url)
+ && defined('OPENSSL_TLSEXT_SERVER_NAME')
+ && OPENSSL_TLSEXT_SERVER_NAME
+ ) {
+ // extract the hostname
+ $hostname = parse_url($url, PHP_URL_HOST);
+ if (!empty($hostname)) {
+ $context['ssl'] = array(
+ 'SNI_server_name' => $hostname,
+ 'SNI_enabled' => true,
+ );
+ } else {
+ \SimpleSAML_Logger::warning('Invalid URL format or local URL used through a proxy');
+ }
+ }
+ }
+
+ $context = stream_context_create($context);
+ $data = file_get_contents($url, false, $context);
+ if ($data === false) {
+ $error = error_get_last();
+ throw new \SimpleSAML_Error_Exception('Error fetching '.var_export($url, true).':'.$error['message']);
+ }
+
+ // data and headers.
+ if ($getHeaders) {
+ if (isset($http_response_header)) {
+ $headers = array();
+ foreach ($http_response_header as $h) {
+ if (preg_match('@^HTTP/1\.[01]\s+\d{3}\s+@', $h)) {
+ $headers = array(); // reset
+ $headers[0] = $h;
+ continue;
+ }
+ $bits = explode(':', $h, 2);
+ if (count($bits) === 2) {
+ $headers[strtolower($bits[0])] = trim($bits[1]);
+ }
+ }
+ } else {
+ // no HTTP headers, probably a different protocol, e.g. file
+ $headers = null;
+ }
+ return array($data, $headers);
+ }
+
+ return $data;
+ }
+
+
+ /**
+ * This function parses the Accept-Language HTTP header and returns an associative array with each language and the
+ * score for that language. If a language includes a region, then the result will include both the language with
+ * the region and the language without the region.
+ *
+ * The returned array will be in the same order as the input.
+ *
+ * @return array An associative array with each language and the score for that language.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getAcceptLanguage()
+ {
+ if (!array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
+ // no Accept-Language header, return an empty set
+ return array();
+ }
+
+ $languages = explode(',', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
+
+ $ret = array();
+
+ foreach ($languages as $l) {
+ $opts = explode(';', $l);
+
+ $l = trim(array_shift($opts)); // the language is the first element
+
+ $q = 1.0;
+
+ // iterate over all options, and check for the quality option
+ foreach ($opts as $o) {
+ $o = explode('=', $o);
+ if (count($o) < 2) {
+ // skip option with no value
+ continue;
+ }
+
+ $name = trim($o[0]);
+ $value = trim($o[1]);
+
+ if ($name === 'q') {
+ $q = (float) $value;
+ }
+ }
+
+ // remove the old key to ensure that the element is added to the end
+ unset($ret[$l]);
+
+ // set the quality in the result
+ $ret[$l] = $q;
+
+ if (strpos($l, '-')) {
+ // the language includes a region part
+
+ // extract the language without the region
+ $l = explode('-', $l);
+ $l = $l[0];
+
+ // add this language to the result (unless it is defined already)
+ if (!array_key_exists($l, $ret)) {
+ $ret[$l] = $q;
+ }
+ }
+ }
+ return $ret;
+ }
+
+
+ /**
+ * Retrieve the base URL of the SimpleSAMLphp installation. The URL will always end with a '/'. For example:
+ * https://idp.example.org/simplesaml/
+ *
+ * @return string The absolute base URL for the simpleSAMLphp installation.
+ * @throws \SimpleSAML_Error_Exception If 'baseurlpath' has an invalid format.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getBaseURL()
+ {
+ $globalConfig = \SimpleSAML_Configuration::getInstance();
+ $baseURL = $globalConfig->getString('baseurlpath', 'simplesaml/');
+
+ if (preg_match('#^https?://.*/$#D', $baseURL, $matches)) {
+ // full URL in baseurlpath, override local server values
+ return $baseURL;
+ } elseif (
+ (preg_match('#^/?([^/]?.*/)$#D', $baseURL, $matches)) ||
+ (preg_match('#^\*(.*)/$#D', $baseURL, $matches)) ||
+ ($baseURL === '')
+ ) {
+ // get server values
+ $protocol = 'http';
+ $protocol .= (self::getServerHTTPS()) ? 's' : '';
+ $protocol .= '://';
+
+ $hostname = self::getServerHost();
+ $port = self::getServerPort();
+ $path = '/'.$globalConfig->getBaseURL();
+
+ return $protocol.$hostname.$port.$path;
+ } else {
+ throw new \SimpleSAML_Error_Exception('Invalid value for \'baseurlpath\' in '.
+ 'config.php. Valid format is in the form: '.
+ '[(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/]. '.
+ 'It must end with a \'/\'.');
+ }
+ }
+
+
+ /**
+ * Retrieve the first element of the URL path.
+ *
+ * @param boolean $trailingslash Whether to add a trailing slash to the element or not. Defaults to true.
+ *
+ * @return string The first element of the URL path, with an optional, trailing slash.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ */
+ public static function getFirstPathElement($trailingslash = true)
+ {
+ if (preg_match('|^/(.*?)/|', $_SERVER['SCRIPT_NAME'], $matches)) {
+ return ($trailingslash ? '/' : '').$matches[1];
+ }
+ return '';
+ }
+
+
+ /**
+ * Create a link which will POST data.
+ *
+ * @param string $destination The destination URL.
+ * @param array $data The name-value pairs which will be posted to the destination.
+ *
+ * @return string A URL which can be accessed to post the data.
+ * @throws \InvalidArgumentException If $destination is not a string or $data is not an array.
+ *
+ * @author Andjelko Horvat
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function getPOSTRedirectURL($destination, $data)
+ {
+ if (!is_string($destination) || !is_array($data)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $config = \SimpleSAML_Configuration::getInstance();
+ $allowed = $config->getBoolean('enable.http_post', false);
+
+ if ($allowed && preg_match("#^http:#", $destination) && self::isHTTPS()) {
+ // we need to post the data to HTTP
+ $url = self::getSecurePOSTRedirectURL($destination, $data);
+ } else { // post the data directly
+ $session = \SimpleSAML_Session::getSessionFromRequest();
+ $id = self::savePOSTData($session, $destination, $data);
+ $url = \SimpleSAML_Module::getModuleURL('core/postredirect.php', array('RedirId' => $id));
+ }
+
+ return $url;
+ }
+
+
+ /**
+ * Retrieve our own host.
+ *
+ * @return string The current host (with non-default ports included).
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getSelfHost()
+ {
+ $url = self::getBaseURL();
+
+ $start = strpos($url, '://') + 3;
+ $length = strcspn($url, '/:', $start);
+
+ return substr($url, $start, $length);
+ }
+
+
+ /**
+ * Retrieve our own host together with the URL path. Please note this function will return the base URL for the
+ * current SP, as defined in the global configuration.
+ *
+ * @return string The current host (with non-default ports included) plus the URL path.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getSelfHostWithPath()
+ {
+ $baseurl = explode("/", self::getBaseURL());
+ $elements = array_slice($baseurl, 3 - count($baseurl), count($baseurl) - 4);
+ $path = implode("/", $elements);
+ return self::getSelfHost()."/".$path;
+ }
+
+
+ /**
+ * Retrieve the current, complete URL.
+ *
+ * @return string The current URL, including query parameters.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getSelfURL()
+ {
+ $url = self::getSelfURLHost();
+ $requestURI = $_SERVER['REQUEST_URI'];
+ if ($requestURI[0] !== '/') {
+ // we probably have a URL of the form: http://server/
+ if (preg_match('#^https?://[^/]*(/.*)#i', $requestURI, $matches)) {
+ $requestURI = $matches[1];
+ }
+ }
+ return $url.$requestURI;
+ }
+
+
+ /**
+ * Retrieve a URL containing the protocol, the current host and optionally, the port number.
+ *
+ * @return string The current URL without a URL path or query parameters.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getSelfURLHost()
+ {
+ $url = self::getBaseURL();
+ $start = strpos($url, '://') + 3;
+ $length = strcspn($url, '/', $start) + $start;
+ return substr($url, 0, $length);
+ }
+
+
+ /**
+ * Retrieve the current URL without the query parameters.
+ *
+ * @return string The current URL, not including query parameters.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ */
+ public static function getSelfURLNoQuery()
+ {
+ $url = self::getSelfURLHost();
+ $url .= $_SERVER['SCRIPT_NAME'];
+ if (isset($_SERVER['PATH_INFO'])) {
+ $url .= $_SERVER['PATH_INFO'];
+ }
+ return $url;
+ }
+
+
+ /**
+ * This function checks if we are using HTTPS as protocol.
+ *
+ * @return boolean True if the HTTPS is used, false otherwise.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function isHTTPS()
+ {
+ return strpos(self::getBaseURL(), 'https://') === 0;
+ }
+
+
+ /**
+ * Normalizes a URL to an absolute URL and validate it. In addition to resolving the URL, this function makes sure
+ * that it is a link to an http or https site.
+ *
+ * @param string $url The relative URL.
+ *
+ * @return string An absolute URL for the given relative URL.
+ * @throws \InvalidArgumentException If $url is not a string or a valid URL.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function normalizeURL($url)
+ {
+ if (!is_string($url)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $url = self::resolveURL($url, self::getSelfURL());
+
+ // verify that the URL is to a http or https site
+ if (!preg_match('@^https?://@i', $url)) {
+ throw new \InvalidArgumentException('Invalid URL: '.$url);
+ }
+
+ return $url;
+ }
+
+
+ /**
+ * Parse a query string into an array.
+ *
+ * This function parses a query string into an array, similar to the way the builtin 'parse_str' works, except it
+ * doesn't handle arrays, and it doesn't do "magic quotes".
+ *
+ * Query parameters without values will be set to an empty string.
+ *
+ * @param string $query_string The query string which should be parsed.
+ *
+ * @return array The query string as an associative array.
+ * @throws \InvalidArgumentException If $query_string is not a string.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function parseQueryString($query_string)
+ {
+ if (!is_string($query_string)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $res = array();
+ foreach (explode('&', $query_string) as $param) {
+ $param = explode('=', $param);
+ $name = urldecode($param[0]);
+ if (count($param) === 1) {
+ $value = '';
+ } else {
+ $value = urldecode($param[1]);
+ }
+ $res[$name] = $value;
+ }
+ return $res;
+ }
+
+
+ /**
+ * This function redirects to the specified URL without performing any security checks. Please, do NOT use this
+ * function with user supplied URLs.
+ *
+ * This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the
+ * HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used.
+ *
+ * The function will also generate a simple web page with a clickable link to the target URL.
+ *
+ * @param string $url The URL we should redirect to. This URL may include query parameters. If this URL is a
+ * relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute
+ * URL to the root of the website.
+ * @param string[] $parameters An array with extra query string parameters which should be appended to the URL. The
+ * name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the
+ * name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the
+ * name, without a value.
+ *
+ * @return void This function never returns.
+ * @throws \InvalidArgumentException If $url is not a string or $parameters is not an array.
+ *
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function redirectTrustedURL($url, $parameters = array())
+ {
+ if (!is_string($url) || !is_array($parameters)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $url = self::normalizeURL($url);
+ self::redirect($url, $parameters);
+ }
+
+
+ /**
+ * This function redirects to the specified URL after performing the appropriate security checks on it.
+ * Particularly, it will make sure that the provided URL is allowed by the 'redirect.trustedsites' directive in the
+ * configuration.
+ *
+ * If the aforementioned option is not set or the URL does correspond to a trusted site, it performs a redirection
+ * to it. If the site is not trusted, an exception will be thrown.
+ *
+ * @param string $url The URL we should redirect to. This URL may include query parameters. If this URL is a
+ * relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute
+ * URL to the root of the website.
+ * @param string[] $parameters An array with extra query string parameters which should be appended to the URL. The
+ * name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the
+ * name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the
+ * name, without a value.
+ *
+ * @return void This function never returns.
+ * @throws \InvalidArgumentException If $url is not a string or $parameters is not an array.
+ *
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function redirectUntrustedURL($url, $parameters = array())
+ {
+ if (!is_string($url) || !is_array($parameters)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $url = self::checkURLAllowed($url);
+ self::redirect($url, $parameters);
+ }
+
+
+ /**
+ * Resolve a (possibly relative) URL relative to a given base URL.
+ *
+ * This function supports these forms of relative URLs:
+ * - ^\w+: Absolute URL. E.g. "http://www.example.com:port/path?query#fragment".
+ * - ^// Same protocol. E.g. "//www.example.com:port/path?query#fragment".
+ * - ^/ Same protocol and host. E.g. "/path?query#fragment".
+ * - ^? Same protocol, host and path, replace query string & fragment. E.g. "?query#fragment".
+ * - ^# Same protocol, host, path and query, replace fragment. E.g. "#fragment".
+ * - The rest: Relative to the base path.
+ *
+ * @param string $url The relative URL.
+ * @param string $base The base URL. Defaults to the base URL of this installation of SimpleSAMLphp.
+ *
+ * @return string An absolute URL for the given relative URL.
+ * @throws \InvalidArgumentException If the base URL cannot be parsed into a valid URL, or the given parameters
+ * are not strings.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function resolveURL($url, $base = null)
+ {
+ if ($base === null) {
+ $base = self::getBaseURL();
+ }
+
+ if (!is_string($url) || !is_string($base)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ if (!preg_match('/^((((\w+:)\/\/[^\/]+)(\/[^?#]*))(?:\?[^#]*)?)(?:#.*)?/', $base, $baseParsed)) {
+ throw new \InvalidArgumentException('Unable to parse base url: '.$base);
+ }
+
+ $baseDir = dirname($baseParsed[5].'filename');
+ $baseScheme = $baseParsed[4];
+ $baseHost = $baseParsed[3];
+ $basePath = $baseParsed[2];
+ $baseQuery = $baseParsed[1];
+
+ if (preg_match('$^\w+:$', $url)) {
+ return $url;
+ }
+
+ if (substr($url, 0, 2) === '//') {
+ return $baseScheme.$url;
+ }
+
+ $firstChar = substr($url, 0, 1);
+ if ($firstChar === '/') {
+ return $baseHost.$url;
+ }
+ if ($firstChar === '?') {
+ return $basePath.$url;
+ }
+ if ($firstChar === '#') {
+ return $baseQuery.$url;
+ }
+
+ // we have a relative path. Remove query string/fragment and save it as $tail
+ $queryPos = strpos($url, '?');
+ $fragmentPos = strpos($url, '#');
+ if ($queryPos !== false || $fragmentPos !== false) {
+ if ($queryPos === false) {
+ $tailPos = $fragmentPos;
+ } elseif ($fragmentPos === false) {
+ $tailPos = $queryPos;
+ } elseif ($queryPos < $fragmentPos) {
+ $tailPos = $queryPos;
+ } else {
+ $tailPos = $fragmentPos;
+ }
+
+ $tail = substr($url, $tailPos);
+ $dir = substr($url, 0, $tailPos);
+ } else {
+ $dir = $url;
+ $tail = '';
+ }
+
+ $dir = System::resolvePath($dir, $baseDir);
+
+ return $baseHost.$dir.$tail;
+ }
+
+
+ /**
+ * Set a cookie.
+ *
+ * @param string $name The name of the cookie.
+ * @param string|NULL $value The value of the cookie. Set to NULL to delete the cookie.
+ * @param array|NULL $params Cookie parameters.
+ * @param bool $throw Whether to throw exception if setcookie() fails.
+ *
+ * @throws \InvalidArgumentException If any parameter has an incorrect type.
+ * @throws \SimpleSAML_Error_Exception If the headers were already sent and the cookie cannot be set.
+ *
+ * @author Andjelko Horvat
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function setCookie($name, $value, $params = null, $throw = true)
+ {
+ if (!(is_string($name) && // $name must be a string
+ (is_string($value) || is_null($value)) && // $value can be a string or null
+ (is_array($params) || is_null($params)) && // $params can be an array or null
+ is_bool($throw)) // $throw must be boolean
+ ) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $default_params = array(
+ 'lifetime' => 0,
+ 'expire' => null,
+ 'path' => '/',
+ 'domain' => null,
+ 'secure' => false,
+ 'httponly' => true,
+ 'raw' => false,
+ );
+
+ if ($params !== null) {
+ $params = array_merge($default_params, $params);
+ } else {
+ $params = $default_params;
+ }
+
+ // Do not set secure cookie if not on HTTPS
+ if ($params['secure'] && !self::isHTTPS()) {
+ \SimpleSAML_Logger::warning('Setting secure cookie on plain HTTP is not allowed.');
+ return;
+ }
+
+ if ($value === null) {
+ $expire = time() - 365 * 24 * 60 * 60;
+ } elseif (isset($params['expire'])) {
+ $expire = $params['expire'];
+ } elseif ($params['lifetime'] === 0) {
+ $expire = 0;
+ } else {
+ $expire = time() + $params['lifetime'];
+ }
+
+ if ($params['raw']) {
+ $success = setrawcookie($name, $value, $expire, $params['path'], $params['domain'], $params['secure'],
+ $params['httponly']);
+ } else {
+ $success = setcookie($name, $value, $expire, $params['path'], $params['domain'], $params['secure'],
+ $params['httponly']);
+ }
+
+ if (!$success) {
+ if ($throw) {
+ throw new \SimpleSAML_Error_Exception('Error setting cookie: headers already sent.');
+ } else {
+ \SimpleSAML_Logger::warning('Error setting cookie: headers already sent.');
+ }
+ }
+ }
+
+
+ /**
+ * Submit a POST form to a specific destination.
+ *
+ * This function never returns.
+ *
+ * @param string $destination The destination URL.
+ * @param array $data An associative array with the data to be posted to $destination.
+ *
+ * @throws \InvalidArgumentException If $destination is not a string or $data is not an array.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Andjelko Horvat
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function submitPOSTData($destination, $data)
+ {
+ if (!is_string($destination) || !is_array($data)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $config = \SimpleSAML_Configuration::getInstance();
+ $allowed = $config->getBoolean('enable.http_post', false);
+
+ if ($allowed && preg_match("#^http:#", $destination) && self::isHTTPS()) {
+ // we need to post the data to HTTP
+ self::redirect(self::getSecurePOSTRedirectURL($destination, $data));
+ }
+
+ $p = new \SimpleSAML_XHTML_Template($config, 'post.php');
+ $p->data['destination'] = $destination;
+ $p->data['post'] = $data;
+ $p->show();
+ exit(0);
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/Net.php b/lib/SimpleSAML/Utils/Net.php
new file mode 100644
index 0000000..22082b7
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Net.php
@@ -0,0 +1,82 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * Net-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+class Net
+{
+
+ /**
+ * Check whether an IP address is part of a CIDR.
+ *
+ * @param string $cidr The network CIDR address.
+ * @param string $ip The IP address to check. Optional. Current remote address will be used if none specified. Do
+ * not rely on default parameter if running behind load balancers.
+ *
+ * @return boolean True if the IP address belongs to the specified CIDR, false otherwise.
+ *
+ * @author Andreas Ã…kre Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Brook Schofield, TERENA
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ static function ipCIDRcheck($cidr, $ip = null)
+ {
+ if ($ip === null) {
+ $ip = $_SERVER['REMOTE_ADDR'];
+ }
+ if (strpos($cidr, '/') === false) {
+ return false;
+ }
+
+ list ($net, $mask) = explode('/', $cidr);
+
+ if (strstr($ip, ':') || strstr($net, ':')) {
+ // Validate IPv6 with inet_pton, convert to hex with bin2hex
+ // then store as a long with hexdec
+
+ $ip_pack = inet_pton($ip);
+ $net_pack = inet_pton($net);
+
+ if ($ip_pack === false || $net_pack === false) {
+ // not valid IPv6 address (warning already issued)
+ return false;
+ }
+
+ $ip_ip = str_split(bin2hex($ip_pack), 8);
+ foreach ($ip_ip as &$value) {
+ $value = hexdec($value);
+ }
+
+ $ip_net = str_split(bin2hex($net_pack), 8);
+ foreach ($ip_net as &$value) {
+ $value = hexdec($value);
+ }
+ } else {
+ $ip_ip[0] = ip2long($ip);
+ $ip_net[0] = ip2long($net);
+ }
+
+ for ($i = 0; $mask > 0 && $i < sizeof($ip_ip); $i++) {
+ if ($mask > 32) {
+ $iteration_mask = 32;
+ } else {
+ $iteration_mask = $mask;
+ }
+ $mask -= 32;
+
+ $ip_mask = ~((1 << (32 - $iteration_mask)) - 1);
+
+ $ip_net_mask = $ip_net[$i] & $ip_mask;
+ $ip_ip_mask = $ip_ip[$i] & $ip_mask;
+
+ if ($ip_ip_mask != $ip_net_mask) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/lib/SimpleSAML/Utils/Random.php b/lib/SimpleSAML/Utils/Random.php
new file mode 100644
index 0000000..fc87dcf
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Random.php
@@ -0,0 +1,25 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * Utility class for random data generation and manipulation.
+ *
+ * @package SimpleSAMLphp
+ */
+class Random
+{
+
+ /**
+ * Generate a random identifier, 22 bytes long.
+ *
+ * @return string A 22-bytes long string with a random, hex string.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function generateID()
+ {
+ return '_'.bin2hex(openssl_random_pseudo_bytes(21));
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/System.php b/lib/SimpleSAML/Utils/System.php
new file mode 100644
index 0000000..8889251
--- /dev/null
+++ b/lib/SimpleSAML/Utils/System.php
@@ -0,0 +1,199 @@
+<?php
+namespace SimpleSAML\Utils;
+
+/**
+ * System-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+class System
+{
+
+ const WINDOWS = 1;
+ const LINUX = 2;
+ const OSX = 3;
+ const HPUX = 4;
+ const UNIX = 5;
+ const BSD = 6;
+ const IRIX = 7;
+ const SUNOS = 8;
+
+
+ /**
+ * This function returns the Operating System we are running on.
+ *
+ * @return mixed A predefined constant identifying the OS we are running on. False if we are unable to determine it.
+ *
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function getOS()
+ {
+ if (stristr(PHP_OS, 'LINUX')) {
+ return self::LINUX;
+ }
+ if (stristr(PHP_OS, 'WIN')) {
+ return self::WINDOWS;
+ }
+ if (stristr(PHP_OS, 'DARWIN')) {
+ return self::OSX;
+ }
+ if (stristr(PHP_OS, 'BSD')) {
+ return self::BSD;
+ }
+ if (stristr(PHP_OS, 'UNIX')) {
+ return self::UNIX;
+ }
+ if (stristr(PHP_OS, 'HP-UX')) {
+ return self::HPUX;
+ }
+ if (stristr(PHP_OS, 'IRIX')) {
+ return self::IRIX;
+ }
+ if (stristr(PHP_OS, 'SUNOS')) {
+ return self::SUNOS;
+ }
+ return false;
+ }
+
+
+ /**
+ * This function retrieves the path to a directory where temporary files can be saved.
+ *
+ * @return string Path to a temporary directory, without a trailing directory separator.
+ * @throws \SimpleSAML_Error_Exception If the temporary directory cannot be created or it exists and does not belong
+ * to the current user.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function getTempDir()
+ {
+ $globalConfig = \SimpleSAML_Configuration::getInstance();
+
+ $tempDir = rtrim($globalConfig->getString('tempdir', sys_get_temp_dir().DIRECTORY_SEPARATOR.'simplesaml'),
+ DIRECTORY_SEPARATOR);
+
+ if (!is_dir($tempDir)) {
+ if (!mkdir($tempDir, 0700, true)) {
+ $error = error_get_last();
+ throw new \SimpleSAML_Error_Exception('Error creating temporary directory "'.$tempDir.
+ '": '.$error['message']);
+ }
+ } elseif (function_exists('posix_getuid')) {
+ // check that the owner of the temp directory is the current user
+ $stat = lstat($tempDir);
+ if ($stat['uid'] !== posix_getuid()) {
+ throw new \SimpleSAML_Error_Exception('Temporary directory "'.$tempDir.
+ '" does not belong to the current user.');
+ }
+ }
+
+ return $tempDir;
+ }
+
+
+ /**
+ * Resolve a (possibly) relative path from the given base path.
+ *
+ * A path which starts with a '/' is assumed to be absolute, all others are assumed to be
+ * relative. The default base path is the root of the SimpleSAMLphp installation.
+ *
+ * @param string $path The path we should resolve.
+ * @param string|null $base The base path, where we should search for $path from. Default value is the root of the
+ * SimpleSAMLphp installation.
+ *
+ * @return string An absolute path referring to $path.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function resolvePath($path, $base = null)
+ {
+ if ($base === null) {
+ $config = \SimpleSAML_Configuration::getInstance();
+ $base = $config->getBaseDir();
+ }
+
+ // remove trailing slashes from $base
+ while (substr($base, -1) === '/') {
+ $base = substr($base, 0, -1);
+ }
+
+ // check for absolute path
+ if (substr($path, 0, 1) === '/') {
+ // absolute path. */
+ $ret = '/';
+ } else {
+ // path relative to base
+ $ret = $base;
+ }
+
+ $path = explode('/', $path);
+ foreach ($path as $d) {
+ if ($d === '.') {
+ continue;
+ } elseif ($d === '..') {
+ $ret = dirname($ret);
+ } else {
+ if (substr($ret, -1) !== '/') {
+ $ret .= '/';
+ }
+ $ret .= $d;
+ }
+ }
+
+ return $ret;
+ }
+
+
+ /**
+ * Atomically write a file.
+ *
+ * This is a helper function for writing data atomically to a file. It does this by writing the file data to a
+ * temporary file, then renaming it to the required file name.
+ *
+ * @param string $filename The path to the file we want to write to.
+ * @param string $data The data we should write to the file.
+ * @param int $mode The permissions to apply to the file. Defaults to 0600.
+ *
+ * @throws \InvalidArgumentException If any of the input parameters doesn't have the proper types.
+ * @throws \SimpleSAML_Error_Exception If the file cannot be saved, permissions cannot be changed or it is not
+ * possible to write to the target file.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Andjelko Horvat
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function writeFile($filename, $data, $mode = 0600)
+ {
+ if (!is_string($filename) || !is_string($data) || !is_numeric($mode)) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
+
+ $tmpFile = self::getTempDir().DIRECTORY_SEPARATOR.rand();
+
+ $res = @file_put_contents($tmpFile, $data);
+ if ($res === false) {
+ $error = error_get_last();
+ throw new \SimpleSAML_Error_Exception('Error saving file "'.$tmpFile.
+ '": '.$error['message']);
+ }
+
+ if (self::getOS() !== self::WINDOWS) {
+ if (!chmod($tmpFile, $mode)) {
+ unlink($tmpFile);
+ $error = error_get_last();
+ throw new \SimpleSAML_Error_Exception('Error changing file mode of "'.$tmpFile.
+ '": '.$error['message']);
+ }
+ }
+
+ if (!rename($tmpFile, $filename)) {
+ unlink($tmpFile);
+ $error = error_get_last();
+ throw new \SimpleSAML_Error_Exception('Error moving "'.$tmpFile.'" to "'.
+ $filename.'": '.$error['message']);
+ }
+ }
+}
diff --git a/lib/SimpleSAML/Utils/Time.php b/lib/SimpleSAML/Utils/Time.php
new file mode 100644
index 0000000..9898f8b
--- /dev/null
+++ b/lib/SimpleSAML/Utils/Time.php
@@ -0,0 +1,162 @@
+<?php
+/**
+ * Time-related utility methods.
+ *
+ * @package SimpleSAMLphp
+ */
+
+namespace SimpleSAML\Utils;
+
+
+class Time
+{
+
+ /**
+ * This function generates a timestamp on the form used by the SAML protocols.
+ *
+ * @param int $instant The time the timestamp should represent. Defaults to current time.
+ *
+ * @return string The timestamp.
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function generateTimestamp($instant = null)
+ {
+ if ($instant === null) {
+ $instant = time();
+ }
+ return gmdate('Y-m-d\TH:i:s\Z', $instant);
+ }
+
+
+ /**
+ * Initialize the timezone.
+ *
+ * This function should be called before any calls to date().
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function initTimezone()
+ {
+ static $initialized = false;
+
+ if ($initialized) {
+ return;
+ }
+
+ $initialized = true;
+
+ $globalConfig = \SimpleSAML_Configuration::getInstance();
+
+ $timezone = $globalConfig->getString('timezone', null);
+ if ($timezone !== null) {
+ if (!date_default_timezone_set($timezone)) {
+ throw new \SimpleSAML_Error_Exception('Invalid timezone set in the "timezone" option in config.php.');
+ }
+ return;
+ }
+ // we don't have a timezone configured
+
+ /*
+ * The date_default_timezone_get() function is likely to cause a warning.
+ * Since we have a custom error handler which logs the errors with a backtrace,
+ * this error will be logged even if we prefix the function call with '@'.
+ * Instead we temporarily replace the error handler.
+ */
+ set_error_handler(function () {
+ return true;
+ });
+ $serverTimezone = date_default_timezone_get();
+ restore_error_handler();
+
+ // set the timezone to the default
+ date_default_timezone_set($serverTimezone);
+ }
+
+
+ /**
+ * Interpret a ISO8601 duration value relative to a given timestamp.
+ *
+ * @param string $duration The duration, as a string.
+ * @param int $timestamp The unix timestamp we should apply the duration to. Optional, default to the current
+ * time.
+ *
+ * @return int The new timestamp, after the duration is applied.
+ * @throws \InvalidArgumentException If $duration is not a valid ISO 8601 duration or if the input parameters do
+ * not have the right data types.
+ */
+ public static function parseDuration($duration, $timestamp = null)
+ {
+ if (!(is_string($duration) && (is_int($timestamp) || is_null($timestamp)))) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
+
+ // parse the duration. We use a very strict pattern
+ $durationRegEx = '#^(-?)P(?:(?:(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:[.,]\d+)?S)?)?)|(?:(\\d+)W))$#D';
+ if (!preg_match($durationRegEx, $duration, $matches)) {
+ throw new \InvalidArgumentException('Invalid ISO 8601 duration: '.$duration);
+ }
+
+ $durYears = (empty($matches[2]) ? 0 : (int) $matches[2]);
+ $durMonths = (empty($matches[3]) ? 0 : (int) $matches[3]);
+ $durDays = (empty($matches[4]) ? 0 : (int) $matches[4]);
+ $durHours = (empty($matches[5]) ? 0 : (int) $matches[5]);
+ $durMinutes = (empty($matches[6]) ? 0 : (int) $matches[6]);
+ $durSeconds = (empty($matches[7]) ? 0 : (int) $matches[7]);
+ $durWeeks = (empty($matches[8]) ? 0 : (int) $matches[8]);
+
+ if (!empty($matches[1])) {
+ // negative
+ $durYears = -$durYears;
+ $durMonths = -$durMonths;
+ $durDays = -$durDays;
+ $durHours = -$durHours;
+ $durMinutes = -$durMinutes;
+ $durSeconds = -$durSeconds;
+ $durWeeks = -$durWeeks;
+ }
+
+ if ($timestamp === null) {
+ $timestamp = time();
+ }
+
+ if ($durYears !== 0 || $durMonths !== 0) {
+ /* Special handling of months and years, since they aren't a specific interval, but
+ * instead depend on the current time.
+ */
+
+ /* We need the year and month from the timestamp. Unfortunately, PHP doesn't have the
+ * gmtime function. Instead we use the gmdate function, and split the result.
+ */
+ $yearmonth = explode(':', gmdate('Y:n', $timestamp));
+ $year = (int) ($yearmonth[0]);
+ $month = (int) ($yearmonth[1]);
+
+ // remove the year and month from the timestamp
+ $timestamp -= gmmktime(0, 0, 0, $month, 1, $year);
+
+ // add years and months, and normalize the numbers afterwards
+ $year += $durYears;
+ $month += $durMonths;
+ while ($month > 12) {
+ $year += 1;
+ $month -= 12;
+ }
+ while ($month < 1) {
+ $year -= 1;
+ $month += 12;
+ }
+
+ // add year and month back into timestamp
+ $timestamp += gmmktime(0, 0, 0, $month, 1, $year);
+ }
+
+ // add the other elements
+ $timestamp += $durWeeks * 7 * 24 * 60 * 60;
+ $timestamp += $durDays * 24 * 60 * 60;
+ $timestamp += $durHours * 60 * 60;
+ $timestamp += $durMinutes * 60;
+ $timestamp += $durSeconds;
+
+ return $timestamp;
+ }
+} \ No newline at end of file
diff --git a/lib/SimpleSAML/Utils/XML.php b/lib/SimpleSAML/Utils/XML.php
new file mode 100644
index 0000000..bd09a31
--- /dev/null
+++ b/lib/SimpleSAML/Utils/XML.php
@@ -0,0 +1,428 @@
+<?php
+/**
+ * Utility class for XML and DOM manipulation.
+ *
+ * @package SimpleSAMLphp
+ */
+
+namespace SimpleSAML\Utils;
+
+
+class XML
+{
+
+ /**
+ * This function performs some sanity checks on XML documents, and optionally validates them against their schema
+ * if the 'debug.validatexml' option is enabled. A warning will be printed to the log if validation fails.
+ *
+ * @param string $message The SAML document we want to check.
+ * @param string $type The type of document. Can be one of:
+ * - 'saml20'
+ * - 'saml11'
+ * - 'saml-meta'
+ *
+ * @throws \InvalidArgumentException If $message is not a string or $type is not a string containing one of the
+ * values allowed.
+ * @throws \SimpleSAML_Error_Exception If $message contains a doctype declaration.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
+ */
+ public static function checkSAMLMessage($message, $type)
+ {
+ $allowed_types = array('saml20', 'saml11', 'saml-meta');
+ if (!(is_string($message) && in_array($type, $allowed_types))) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ // a SAML message should not contain a doctype-declaration
+ if (strpos($message, '<!DOCTYPE') !== false) {
+ throw new \SimpleSAML_Error_Exception('XML contained a doctype declaration.');
+ }
+
+ $enabled = \SimpleSAML_Configuration::getInstance()->getBoolean('debug.validatexml', null);
+ if (!$enabled) {
+ return;
+ }
+
+ $result = true;
+ switch ($type) {
+ case 'saml11':
+ $result = self::isValid($message, 'oasis-sstc-saml-schema-protocol-1.1.xsd');
+ break;
+ case 'saml20':
+ $result = self::isValid($message, 'saml-schema-protocol-2.0.xsd');
+ break;
+ case 'saml-meta':
+ $result = self::isValid($message, 'saml-schema-metadata-2.0.xsd');
+ }
+ if ($result !== true) {
+ \SimpleSAML_Logger::warning($result);
+ }
+ }
+
+
+ /**
+ * Helper function to log SAML messages that we send or receive.
+ *
+ * @param string|\DOMElement $message The message, as an string containing the XML or an XML element.
+ * @param string $type Whether this message is sent or received, encrypted or decrypted. The following
+ * values are supported:
+ * - 'in': for messages received.
+ * - 'out': for outgoing messages.
+ * - 'decrypt': for decrypted messages.
+ * - 'encrypt': for encrypted messages.
+ *
+ * @throws \InvalidArgumentException If $type is not a string or $message is neither a string nor a \DOMElement.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function debugSAMLMessage($message, $type)
+ {
+ if (!(is_string($type) && (is_string($message) || $message instanceof \DOMElement))) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $globalConfig = \SimpleSAML_Configuration::getInstance();
+ if (!$globalConfig->getBoolean('debug', false)) {
+ // message debug disabled
+ return;
+ }
+
+ if ($message instanceof \DOMElement) {
+ $message = $message->ownerDocument->saveXML($message);
+ }
+
+ switch ($type) {
+ case 'in':
+ \SimpleSAML_Logger::debug('Received message:');
+ break;
+ case 'out':
+ \SimpleSAML_Logger::debug('Sending message:');
+ break;
+ case 'decrypt':
+ \SimpleSAML_Logger::debug('Decrypted message:');
+ break;
+ case 'encrypt':
+ \SimpleSAML_Logger::debug('Encrypted message:');
+ break;
+ default:
+ assert(false);
+ }
+
+ $str = self::formatXMLString($message);
+ foreach (explode("\n", $str) as $line) {
+ \SimpleSAML_Logger::debug($line);
+ }
+ }
+
+
+ /**
+ * Format a DOM element.
+ *
+ * This function takes in a DOM element, and inserts whitespace to make it more readable. Note that whitespace
+ * added previously will be removed.
+ *
+ * @param \DOMElement $root The root element which should be formatted.
+ * @param string $indentBase The indentation this element should be assumed to have. Defaults to an empty
+ * string.
+ *
+ * @throws \InvalidArgumentException If $root is not a DOMElement or $indentBase is not a string.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function formatDOMElement(\DOMElement $root, $indentBase = '')
+ {
+ if (!is_string($indentBase)) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
+
+ // check what this element contains
+ $fullText = ''; // all text in this element
+ $textNodes = array(); // text nodes which should be deleted
+ $childNodes = array(); // other child nodes
+ for ($i = 0; $i < $root->childNodes->length; $i++) {
+ $child = $root->childNodes->item($i);
+
+ if ($child instanceof \DOMText) {
+ $textNodes[] = $child;
+ $fullText .= $child->wholeText;
+ } elseif ($child instanceof \DOMComment || $child instanceof \DOMElement) {
+ $childNodes[] = $child;
+ } else {
+ // unknown node type. We don't know how to format this
+ return;
+ }
+ }
+
+ $fullText = trim($fullText);
+ if (strlen($fullText) > 0) {
+ // we contain textelf
+ $hasText = true;
+ } else {
+ $hasText = false;
+ }
+
+ $hasChildNode = (count($childNodes) > 0);
+
+ if ($hasText && $hasChildNode) {
+ // element contains both text and child nodes - we don't know how to format this one
+ return;
+ }
+
+ // remove text nodes
+ foreach ($textNodes as $node) {
+ $root->removeChild($node);
+ }
+
+ if ($hasText) {
+ // only text - add a single text node to the element with the full text
+ $root->appendChild(new \DOMText($fullText));
+ return;
+ }
+
+ if (!$hasChildNode) {
+ // empty node. Nothing to do
+ return;
+ }
+
+ /* Element contains only child nodes - add indentation before each one, and
+ * format child elements.
+ */
+ $childIndentation = $indentBase.' ';
+ foreach ($childNodes as $node) {
+ // add indentation before node
+ $root->insertBefore(new \DOMText("\n".$childIndentation), $node);
+
+ // format child elements
+ if ($node instanceof \DOMElement) {
+ self::formatDOMElement($node, $childIndentation);
+ }
+ }
+
+ // add indentation before closing tag
+ $root->appendChild(new \DOMText("\n".$indentBase));
+ }
+
+
+ /**
+ * Format an XML string.
+ *
+ * This function formats an XML string using the formatDOMElement() function.
+ *
+ * @param string $xml An XML string which should be formatted.
+ * @param string $indentBase Optional indentation which should be applied to all the output. Optional, defaults
+ * to ''.
+ *
+ * @return string The formatted string.
+ * @throws \InvalidArgumentException If the parameters are not strings.
+ * @throws \DOMException If the input does not parse correctly as an XML string.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function formatXMLString($xml, $indentBase = '')
+ {
+ if (!is_string($xml) || !is_string($indentBase)) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
+
+ $doc = new \DOMDocument();
+ if (!$doc->loadXML($xml)) {
+ throw new \DOMException('Error parsing XML string.');
+ }
+
+ $root = $doc->firstChild;
+ self::formatDOMElement($root, $indentBase);
+
+ return $doc->saveXML($root);
+ }
+
+
+ /**
+ * This function finds direct descendants of a DOM element with the specified
+ * localName and namespace. They are returned in an array.
+ *
+ * This function accepts the same shortcuts for namespaces as the isDOMElementOfType function.
+ *
+ * @param \DOMElement $element The element we should look in.
+ * @param string $localName The name the element should have.
+ * @param string $namespaceURI The namespace the element should have.
+ *
+ * @return array Array with the matching elements in the order they are found. An empty array is
+ * returned if no elements match.
+ * @throws \InvalidArgumentException If $element is not an instance of DOMElement, $localName is not a string or
+ * $namespaceURI is not a string.
+ */
+ public static function getDOMChildren(\DOMElement $element, $localName, $namespaceURI)
+ {
+ if (!($element instanceof \DOMElement) || !is_string($localName) || !is_string($namespaceURI)) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ $ret = array();
+
+ for ($i = 0; $i < $element->childNodes->length; $i++) {
+ $child = $element->childNodes->item($i);
+
+ // skip text nodes and comment elements
+ if ($child instanceof \DOMText || $child instanceof \DOMComment) {
+ continue;
+ }
+
+ if (self::isDOMElementOfType($child, $localName, $namespaceURI) === true) {
+ $ret[] = $child;
+ }
+ }
+
+ return $ret;
+ }
+
+
+ /**
+ * This function extracts the text from DOMElements which should contain only text content.
+ *
+ * @param \DOMElement $element The element we should extract text from.
+ *
+ * @return string The text content of the element.
+ * @throws \InvalidArgumentException If $element is not an instance of DOMElement.
+ * @throws \SimpleSAML_Error_Exception If the element contains a non-text child node.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function getDOMText(\DOMElement $element)
+ {
+ if (!($element instanceof \DOMElement)) {
+ throw new \InvalidArgumentException('Invalid input parameters');
+ }
+
+ $txt = '';
+
+ for ($i = 0; $i < $element->childNodes->length; $i++) {
+ $child = $element->childNodes->item($i);
+ if (!($child instanceof \DOMText)) {
+ throw new \SimpleSAML_Error_Exception($element->localName.' contained a non-text child node.');
+ }
+
+ $txt .= $child->wholeText;
+ }
+
+ $txt = trim($txt);
+ return $txt;
+ }
+
+
+ /**
+ * This function checks if the DOMElement has the correct localName and namespaceURI.
+ *
+ * We also define the following shortcuts for namespaces:
+ * - '@ds': 'http://www.w3.org/2000/09/xmldsig#'
+ * - '@md': 'urn:oasis:names:tc:SAML:2.0:metadata'
+ * - '@saml1': 'urn:oasis:names:tc:SAML:1.0:assertion'
+ * - '@saml1md': 'urn:oasis:names:tc:SAML:profiles:v1metadata'
+ * - '@saml1p': 'urn:oasis:names:tc:SAML:1.0:protocol'
+ * - '@saml2': 'urn:oasis:names:tc:SAML:2.0:assertion'
+ * - '@saml2p': 'urn:oasis:names:tc:SAML:2.0:protocol'
+ *
+ * @param \DOMNode $element The element we should check.
+ * @param string $name The local name the element should have.
+ * @param string $nsURI The namespaceURI the element should have.
+ *
+ * @return boolean True if both namespace and local name matches, false otherwise.
+ * @throws \InvalidArgumentException If the namespace shortcut is unknown.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function isDOMElementOfType(\DOMNode $element, $name, $nsURI)
+ {
+ if (!($element instanceof \DOMElement) || !is_string($name) || !is_string($nsURI) || strlen($nsURI) === 0) {
+ // most likely a comment-node
+ return false;
+ }
+
+ // check if the namespace is a shortcut, and expand it if it is
+ if ($nsURI[0] === '@') {
+ // the defined shortcuts
+ $shortcuts = array(
+ '@ds' => 'http://www.w3.org/2000/09/xmldsig#',
+ '@md' => 'urn:oasis:names:tc:SAML:2.0:metadata',
+ '@saml1' => 'urn:oasis:names:tc:SAML:1.0:assertion',
+ '@saml1md' => 'urn:oasis:names:tc:SAML:profiles:v1metadata',
+ '@saml1p' => 'urn:oasis:names:tc:SAML:1.0:protocol',
+ '@saml2' => 'urn:oasis:names:tc:SAML:2.0:assertion',
+ '@saml2p' => 'urn:oasis:names:tc:SAML:2.0:protocol',
+ '@shibmd' => 'urn:mace:shibboleth:metadata:1.0',
+ );
+
+ // check if it is a valid shortcut
+ if (!array_key_exists($nsURI, $shortcuts)) {
+ throw new \InvalidArgumentException('Unknown namespace shortcut: '.$nsURI);
+ }
+
+ // expand the shortcut
+ $nsURI = $shortcuts[$nsURI];
+ }
+ if ($element->localName !== $name) {
+ return false;
+ }
+ if ($element->namespaceURI !== $nsURI) {
+ return false;
+ }
+ return true;
+ }
+
+
+ /**
+ * This function attempts to validate an XML string against the specified schema. It will parse the string into a
+ * DOM document and validate this document against the schema.
+ *
+ * Note that this function returns values that are evaluated as a logical true, both when validation works and when
+ * it doesn't. Please use strict comparisons to check the values returned.
+ *
+ * @param string|\DOMDocument $xml The XML string or document which should be validated.
+ * @param string $schema The filename of the schema that should be used to validate the document.
+ *
+ * @return boolean|string Returns a string with errors found if validation fails. True if validation passes ok.
+ * @throws \InvalidArgumentException If $schema is not a string, or $xml is neither a string nor a \DOMDocument.
+ *
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ public static function isValid($xml, $schema)
+ {
+ if (!(is_string($schema) && (is_string($xml) || $xml instanceof \DOMDocument))) {
+ throw new \InvalidArgumentException('Invalid input parameters.');
+ }
+
+ \SimpleSAML_XML_Errors::begin();
+
+ if ($xml instanceof \DOMDocument) {
+ $dom = $xml;
+ $res = true;
+ } else {
+ $dom = new \DOMDocument;
+ $res = $dom->loadXML($xml);
+ }
+
+ if ($res) {
+
+ $config = \SimpleSAML_Configuration::getInstance();
+ $schemaPath = $config->resolvePath('schemas').'/';
+ $schemaFile = $schemaPath.$schema;
+
+ $res = $dom->schemaValidate($schemaFile);
+ if ($res) {
+ \SimpleSAML_XML_Errors::end();
+ return true;
+ }
+
+ $errorText = "Schema validation failed on XML string:\n";
+ } else {
+ $errorText = "Failed to parse XML string for schema validation:\n";
+ }
+
+ $errors = \SimpleSAML_XML_Errors::end();
+ $errorText .= \SimpleSAML_XML_Errors::formatErrors($errors);
+
+ return $errorText;
+ }
+}
diff --git a/lib/SimpleSAML/XHTML/EMail.php b/lib/SimpleSAML/XHTML/EMail.php
index 67989b1..5b69962 100644
--- a/lib/SimpleSAML/XHTML/EMail.php
+++ b/lib/SimpleSAML/XHTML/EMail.php
@@ -65,7 +65,7 @@ pre {
if ($this->subject == NULL) throw new Exception('EMail field [subject] is required and not set.');
if ($this->body == NULL) throw new Exception('EMail field [body] is required and not set.');
- $random_hash = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
+ $random_hash = bin2hex(openssl_random_pseudo_bytes(16));
if (isset($this->from))
$this->headers[]= 'From: ' . $this->from;
diff --git a/lib/SimpleSAML/XHTML/IdPDisco.php b/lib/SimpleSAML/XHTML/IdPDisco.php
index 87e7db3..8b084f3 100644
--- a/lib/SimpleSAML/XHTML/IdPDisco.php
+++ b/lib/SimpleSAML/XHTML/IdPDisco.php
@@ -123,7 +123,7 @@ class SimpleSAML_XHTML_IdPDisco {
if(!array_key_exists('return', $_GET)) {
throw new Exception('Missing parameter: return');
} else {
- $this->returnURL = SimpleSAML_Utilities::checkURLAllowed($_GET['return']);
+ $this->returnURL = \SimpleSAML\Utils\HTTP::checkURLAllowed($_GET['return']);
}
$this->isPassive = FALSE;
@@ -197,7 +197,7 @@ class SimpleSAML_XHTML_IdPDisco {
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie($prefixedName, $value, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($prefixedName, $value, $params, FALSE);
}
@@ -462,8 +462,7 @@ class SimpleSAML_XHTML_IdPDisco {
$extDiscoveryStorage = $this->config->getString('idpdisco.extDiscoveryStorage', NULL);
if ($extDiscoveryStorage !== NULL) {
$this->log('Choice made [' . $idp . '] (Forwarding to external discovery storage)');
- SimpleSAML_Utilities::redirectTrustedURL($extDiscoveryStorage, array(
-// $this->returnIdParam => $idp,
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($extDiscoveryStorage, array(
'entityID' => $this->spEntityId,
'IdPentityID' => $idp,
'returnIDParam' => $this->returnIdParam,
@@ -473,7 +472,7 @@ class SimpleSAML_XHTML_IdPDisco {
} else {
$this->log('Choice made [' . $idp . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')');
- SimpleSAML_Utilities::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idp));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idp));
}
return;
@@ -481,7 +480,7 @@ class SimpleSAML_XHTML_IdPDisco {
if ($this->isPassive) {
$this->log('Choice not made. (Redirecting the user back without answer)');
- SimpleSAML_Utilities::redirectTrustedURL($this->returnURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL);
return;
}
@@ -495,12 +494,12 @@ class SimpleSAML_XHTML_IdPDisco {
$idpList = array_intersect_key($idpList, array_fill_keys($idpintersection, NULL));
}
- $idpintersection = array_values($idpintersection);
-
- if(sizeof($idpintersection) == 1) {
- $this->log('Choice made [' . $idpintersection[0] . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')');
- SimpleSAML_Utilities::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idpintersection[0]));
- }
+ $idpintersection = array_values($idpintersection);
+
+ if(sizeof($idpintersection) == 1) {
+ $this->log('Choice made [' . $idpintersection[0] . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')');
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idpintersection[0]));
+ }
/*
* Make use of an XHTML template to present the select IdP choice to the user.
@@ -523,7 +522,7 @@ class SimpleSAML_XHTML_IdPDisco {
$t->data['return'] = $this->returnURL;
$t->data['returnIDParam'] = $this->returnIdParam;
$t->data['entityID'] = $this->spEntityId;
- $t->data['urlpattern'] = htmlspecialchars(SimpleSAML_Utilities::selfURLNoQuery());
+ $t->data['urlpattern'] = htmlspecialchars(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery());
$t->data['rememberenabled'] = $this->config->getBoolean('idpdisco.enableremember', FALSE);
$t->show();
}
diff --git a/lib/SimpleSAML/XHTML/Template.php b/lib/SimpleSAML/XHTML/Template.php
index 4186eb9..68275de 100644
--- a/lib/SimpleSAML/XHTML/Template.php
+++ b/lib/SimpleSAML/XHTML/Template.php
@@ -141,7 +141,7 @@ class SimpleSAML_XHTML_Template {
* languages in the header were available.
*/
private function getHTTPLanguage() {
- $languageScore = SimpleSAML_Utilities::getAcceptLanguage();
+ $languageScore = \SimpleSAML\Utils\HTTP::getAcceptLanguage();
/* For now we only use the default language map. We may use a configurable language map
* in the future.
@@ -413,7 +413,6 @@ class SimpleSAML_XHTML_Template {
$translated = $this->getTranslation($tagData);
-# if (!empty($replacements)){ echo('<pre> [' . $tag . ']'); print_r($replacements); exit; }
foreach ($replacements as $k => $v) {
/* try to translate if no replacement is given */
if ($v == NULL) $v = $this->t($k);
@@ -712,7 +711,7 @@ class SimpleSAML_XHTML_Template {
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie($name, $language, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($name, $language, $params, FALSE);
}
}
diff --git a/lib/SimpleSAML/XML/Parser.php b/lib/SimpleSAML/XML/Parser.php
index b309666..d73472d 100644
--- a/lib/SimpleSAML/XML/Parser.php
+++ b/lib/SimpleSAML/XML/Parser.php
@@ -10,11 +10,8 @@ class SimpleSAML_XML_Parser {
var $simplexml = null;
-
- function __construct($xml) {
- #parent::construct($xml);
+ function __construct($xml) {;
$this->simplexml = new SimpleXMLElement($xml);
-
$this->simplexml->registerXPathNamespace('saml2', 'urn:oasis:names:tc:SAML:2.0:assertion');
$this->simplexml->registerXPathNamespace('saml2meta', 'urn:oasis:names:tc:SAML:2.0:metadata');
$this->simplexml->registerXPathNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#');
diff --git a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
index 0d91446..0424245 100644
--- a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
+++ b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
@@ -4,7 +4,7 @@
* The Shibboleth 1.3 Authentication Request. Not part of SAML 1.1,
* but an extension using query paramters no XML.
*
- * @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
+ * @author Andreas Ã…kre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @package simpleSAMLphp
*/
class SimpleSAML_XML_Shib13_AuthnRequest {
diff --git a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
index 12e6c6d..d228d81 100644
--- a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
+++ b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
@@ -3,7 +3,7 @@
/**
* A Shibboleth 1.3 authentication response.
*
- * @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
+ * @author Andreas Ã…kre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @package simpleSAMLphp
*/
class SimpleSAML_XML_Shib13_AuthnResponse {
@@ -106,7 +106,7 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
$this->validator->validateFingerprint($certFingerprints);
} elseif ($md->hasValue('caFile')) {
/* Validate against CA. */
- $this->validator->validateCA(SimpleSAML_Utilities::resolveCert($md->getString('caFile')));
+ $this->validator->validateCA(\SimpleSAML\Utils\Config::getCertPath($md->getString('caFile')));
} else {
throw new SimpleSAML_Error_Exception('Missing certificate in Shibboleth 1.3 IdP Remote metadata for identity provider [' . $issuer . '].');
}
@@ -115,7 +115,7 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
}
- /* Checks if the given node is validated by the signatore on this response.
+ /* Checks if the given node is validated by the signature on this response.
*
* Returns:
* TRUE if the node is validated or FALSE if not.
@@ -212,7 +212,7 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
$end = $condition->getAttribute('NotOnOrAfter');
if ($start && $end) {
- if (! SimpleSAML_Utilities::checkDateConditions($start, $end)) {
+ if (!self::checkDateConditions($start, $end)) {
error_log('Date check failed ... (from ' . $start . ' to ' . $end . ')');
continue;
}
@@ -304,16 +304,16 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
$scopedAttributes = array();
}
- $id = SimpleSAML_Utilities::generateID();
+ $id = SimpleSAML\Utils\Random::generateID();
- $issueInstant = SimpleSAML_Utilities::generateTimestamp();
+ $issueInstant = SimpleSAML\Utils\Time::generateTimestamp();
// 30 seconds timeskew back in time to allow differing clocks.
- $notBefore = SimpleSAML_Utilities::generateTimestamp(time() - 30);
+ $notBefore = SimpleSAML\Utils\Time::generateTimestamp(time() - 30);
- $assertionExpire = SimpleSAML_Utilities::generateTimestamp(time() + 60 * 5);# 5 minutes
- $assertionid = SimpleSAML_Utilities::generateID();
+ $assertionExpire = SimpleSAML\Utils\Time::generateTimestamp(time() + 60 * 5);# 5 minutes
+ $assertionid = SimpleSAML\Utils\Random::generateID();
$spEntityId = $sp->getString('entityid');
@@ -321,7 +321,7 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
$base64 = $sp->getBoolean('base64attributes', FALSE);
$namequalifier = $sp->getString('NameQualifier', $spEntityId);
- $nameid = SimpleSAML_Utilities::generateID();
+ $nameid = SimpleSAML\Utils\Random::generateID();
$subjectNode =
'<Subject>' .
'<NameIdentifier' .
@@ -427,5 +427,42 @@ class SimpleSAML_XML_Shib13_AuthnResponse {
return $attr;
}
+ /**
+ * Check if we are currently between the given date & time conditions.
+ *
+ * Note that this function allows a 10-minute leap from the initial time as marked by $start.
+ *
+ * @param string|null $start A SAML2 timestamp marking the start of the period to check. Defaults to null, in which
+ * case there's no limitations in the past.
+ * @param string|null $end A SAML2 timestamp marking the end of the period to check. Defaults to null, in which
+ * case there's no limitations in the future.
+ *
+ * @return bool True if the current time belongs to the period specified by $start and $end. False otherwise.
+ *
+ * @see \SAML2_Utils::xsDateTimeToTimestamp.
+ *
+ * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
+ * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
+ */
+ protected static function checkDateConditions($start = null, $end = null)
+ {
+ $currentTime = time();
+
+ if (!empty($start)) {
+ $startTime = \SAML2_Utils::xsDateTimeToTimestamp($start);
+ // allow for a 10 minute difference in time
+ if (($startTime < 0) || (($startTime - 600) > $currentTime)) {
+ return false;
+ }
+ }
+ if (!empty($end)) {
+ $endTime = \SAML2_Utils::xsDateTimeToTimestamp($end);
+ if (($endTime < 0) || ($endTime <= $currentTime)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
}
diff --git a/lib/SimpleSAML/XML/Signer.php b/lib/SimpleSAML/XML/Signer.php
index 15bf719..d855358 100644
--- a/lib/SimpleSAML/XML/Signer.php
+++ b/lib/SimpleSAML/XML/Signer.php
@@ -117,7 +117,7 @@ class SimpleSAML_XML_Signer {
assert('is_string($file)');
assert('is_string($pass) || is_null($pass)');
- $keyFile = SimpleSAML_Utilities::resolveCert($file);
+ $keyFile = \SimpleSAML\Utils\Config::getCertPath($file);
if (!file_exists($keyFile)) {
throw new Exception('Could not find private key file "' . $keyFile . '".');
}
@@ -167,7 +167,7 @@ class SimpleSAML_XML_Signer {
public function loadCertificate($file) {
assert('is_string($file)');
- $certFile = SimpleSAML_Utilities::resolveCert($file);
+ $certFile = \SimpleSAML\Utils\Config::getCertPath($file);
if (!file_exists($certFile)) {
throw new Exception('Could not find certificate file "' . $certFile . '".');
}
@@ -202,7 +202,7 @@ class SimpleSAML_XML_Signer {
public function addCertificate($file) {
assert('is_string($file)');
- $certFile = SimpleSAML_Utilities::resolveCert($file);
+ $certFile = \SimpleSAML\Utils\Config::getCertPath($file);
if (!file_exists($certFile)) {
throw new Exception('Could not find extra certificate file "' . $certFile . '".');
}
diff --git a/lib/SimpleSAML/XML/Validator.php b/lib/SimpleSAML/XML/Validator.php
index c973636..b9a9dfd 100644
--- a/lib/SimpleSAML/XML/Validator.php
+++ b/lib/SimpleSAML/XML/Validator.php
@@ -289,7 +289,134 @@ class SimpleSAML_XML_Validator {
throw new Exception('Key used to sign the message was not an X509 certificate.');
}
- SimpleSAML_Utilities::validateCA($this->x509Certificate, $caFile);
+ self::validateCertificate($this->x509Certificate, $caFile);
+ }
+
+ /**
+ * Validate a certificate against a CA file, by using the builtin
+ * openssl_x509_checkpurpose function
+ *
+ * @param string $certificate The certificate, in PEM format.
+ * @param string $caFile File with trusted certificates, in PEM-format.
+ * @return boolean|string TRUE on success, or a string with error messages if it failed.
+ * @deprecated
+ */
+ private static function validateCABuiltIn($certificate, $caFile) {
+ assert('is_string($certificate)');
+ assert('is_string($caFile)');
+
+ /* Clear openssl errors. */
+ while(openssl_error_string() !== FALSE);
+
+ $res = openssl_x509_checkpurpose($certificate, X509_PURPOSE_ANY, array($caFile));
+
+ $errors = '';
+ /* Log errors. */
+ while( ($error = openssl_error_string()) !== FALSE) {
+ $errors .= ' [' . $error . ']';
+ }
+
+ if($res !== TRUE) {
+ return $errors;
+ }
+
+ return TRUE;
+ }
+
+
+ /**
+ * Validate the certificate used to sign the XML against a CA file, by using the "openssl verify" command.
+ *
+ * This function uses the openssl verify command to verify a certificate, to work around limitations
+ * on the openssl_x509_checkpurpose function. That function will not work on certificates without a purpose
+ * set.
+ *
+ * @param string $certificate The certificate, in PEM format.
+ * @param string $caFile File with trusted certificates, in PEM-format.
+ * @return boolean|string TRUE on success, a string with error messages on failure.
+ * @deprecated
+ */
+ private static function validateCAExec($certificate, $caFile) {
+ assert('is_string($certificate)');
+ assert('is_string($caFile)');
+
+ $command = array(
+ 'openssl', 'verify',
+ '-CAfile', $caFile,
+ '-purpose', 'any',
+ );
+
+ $cmdline = '';
+ foreach($command as $c) {
+ $cmdline .= escapeshellarg($c) . ' ';
+ }
+
+ $cmdline .= '2>&1';
+ $descSpec = array(
+ 0 => array('pipe', 'r'),
+ 1 => array('pipe', 'w'),
+ );
+ $process = proc_open($cmdline, $descSpec, $pipes);
+ if (!is_resource($process)) {
+ throw new Exception('Failed to execute verification command: ' . $cmdline);
+ }
+
+ if (fwrite($pipes[0], $certificate) === FALSE) {
+ throw new Exception('Failed to write certificate for verification.');
+ }
+ fclose($pipes[0]);
+
+ $out = '';
+ while (!feof($pipes[1])) {
+ $line = trim(fgets($pipes[1]));
+ if(strlen($line) > 0) {
+ $out .= ' [' . $line . ']';
+ }
+ }
+ fclose($pipes[1]);
+
+ $status = proc_close($process);
+ if ($status !== 0 || $out !== ' [stdin: OK]') {
+ return $out;
+ }
+
+ return TRUE;
+ }
+
+
+ /**
+ * Validate the certificate used to sign the XML against a CA file.
+ *
+ * This function throws an exception if unable to validate against the given CA file.
+ *
+ * @param string $certificate The certificate, in PEM format.
+ * @param string $caFile File with trusted certificates, in PEM-format.
+ * @deprecated
+ */
+ public static function validateCertificate($certificate, $caFile) {
+ assert('is_string($certificate)');
+ assert('is_string($caFile)');
+
+ if (!file_exists($caFile)) {
+ throw new Exception('Could not load CA file: ' . $caFile);
+ }
+
+ SimpleSAML_Logger::debug('Validating certificate against CA file: ' . var_export($caFile, TRUE));
+
+ $resBuiltin = self::validateCABuiltIn($certificate, $caFile);
+ if ($resBuiltin !== TRUE) {
+ SimpleSAML_Logger::debug('Failed to validate with internal function: ' . var_export($resBuiltin, TRUE));
+
+ $resExternal = self::validateCAExec($certificate, $caFile);
+ if ($resExternal !== TRUE) {
+ SimpleSAML_Logger::debug('Failed to validate with external function: ' . var_export($resExternal, TRUE));
+ throw new Exception('Could not verify certificate against CA file "'
+ . $caFile . '". Internal result:' . $resBuiltin .
+ ' External result:' . $resExternal);
+ }
+ }
+
+ SimpleSAML_Logger::debug('Successfully validated certificate.');
}
}
diff --git a/modules/adfs/lib/IdP/ADFS.php b/modules/adfs/lib/IdP/ADFS.php
index d7fc51f..edb15c4 100644
--- a/modules/adfs/lib/IdP/ADFS.php
+++ b/modules/adfs/lib/IdP/ADFS.php
@@ -34,8 +34,6 @@ class sspmod_adfs_IdP_ADFS {
$state = array(
'Responder' => array('sspmod_adfs_IdP_ADFS', 'sendResponse'),
-// SimpleSAML_Auth_State::EXCEPTION_HANDLER_FUNC => array('sspmod_adfs_IdP', 'handleAuthError'),
-// SimpleSAML_Auth_State::RESTART => $sessionLostURL,
'SPMetadata' => $spMetadata->toArray(),
'ForceAuthn' => $forceAuthn,
'isPassive' => $isPassive,
@@ -46,11 +44,10 @@ class sspmod_adfs_IdP_ADFS {
}
public static function ADFS_GenerateResponse($issuer, $target, $nameid, $attributes) {
- #$nameid = 'hans@surfnet.nl';
- $issueInstant = SimpleSAML_Utilities::generateTimestamp();
- $notBefore = SimpleSAML_Utilities::generateTimestamp(time() - 30);
- $assertionExpire = SimpleSAML_Utilities::generateTimestamp(time() + 60 * 5);
- $assertionID = SimpleSAML_Utilities::generateID();
+ $issueInstant = SimpleSAML\Utils\Time::generateTimestamp();
+ $notBefore = SimpleSAML\Utils\Time::generateTimestamp(time() - 30);
+ $assertionExpire = SimpleSAML\Utils\Time::generateTimestamp(time() + 60 * 5);
+ $assertionID = SimpleSAML\Utils\Random::generateID();
$nameidFormat = 'http://schemas.xmlsoap.org/claims/UPN';
$result =
'<wst:RequestSecurityTokenResponse xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust">
@@ -75,7 +72,7 @@ class sspmod_adfs_IdP_ADFS {
$hasValue = FALSE;
$r = '<saml:Attribute AttributeNamespace="http://schemas.xmlsoap.org/claims" AttributeName="' . htmlspecialchars($name) .'">';
foreach ($values as $value) {
- if ( (!isset($value)) or ($value === '')) continue;
+ if ( (!isset($value)) || ($value === '')) continue;
$r .= '<saml:AttributeValue>' . htmlspecialchars($value) . '</saml:AttributeValue>';
$hasValue = TRUE;
}
@@ -141,7 +138,7 @@ class sspmod_adfs_IdP_ADFS {
}
$nameid = $attributes[$nameidattribute][0];
} else {
- $nameid = SimpleSAML_Utilities::generateID();
+ $nameid = SimpleSAML\Utils\Random::generateID();
}
$idp = SimpleSAML_IdP::getByState($state);
@@ -156,8 +153,8 @@ class sspmod_adfs_IdP_ADFS {
$response = sspmod_adfs_IdP_ADFS::ADFS_GenerateResponse($idpEntityId, $spEntityId, $nameid, $attributes);
- $privateKeyFile = SimpleSAML_Utilities::resolveCert($idpMetadata->getString('privatekey'));
- $certificateFile = SimpleSAML_Utilities::resolveCert($idpMetadata->getString('certificate'));
+ $privateKeyFile = \SimpleSAML\Utils\Config::getCertPath($idpMetadata->getString('privatekey'));
+ $certificateFile = \SimpleSAML\Utils\Config::getCertPath($idpMetadata->getString('certificate'));
$wresult = sspmod_adfs_IdP_ADFS::ADFS_SignResponse($response, $privateKeyFile, $certificateFile);
$wctx = $state['adfs:wctx'];
@@ -171,22 +168,20 @@ class sspmod_adfs_IdP_ADFS {
// NB:: we don't know from which SP the logout request came from
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpMetadata = $idp->getConfig();
- SimpleSAML_Utilities::redirectTrustedURL($idpMetadata->getValue('redirect-after-logout', SimpleSAML_Utilities::getBaseURL()));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($idpMetadata->getValue('redirect-after-logout', \SimpleSAML\Utils\HTTP::getBaseURL()));
}
public static function receiveLogoutMessage(SimpleSAML_IdP $idp) {
// if a redirect is to occur based on wreply, we will redirect to url as
// this implies an override to normal sp notification.
if(isset($_GET['wreply']) && !empty($_GET['wreply'])) {
- $idp->doLogoutRedirect(SimpleSAML_Utilities::checkURLAllowed($_GET['wreply']));
+ $idp->doLogoutRedirect(\SimpleSAML\Utils\HTTP::checkURLAllowed($_GET['wreply']));
assert(FALSE);
}
$state = array(
'Responder' => array('sspmod_adfs_IdP_ADFS', 'sendLogoutResponse'),
);
- //$spEntityId = NULL;
- //$assocId = 'adfs:' . $spEntityId;
$assocId = NULL;
// TODO: verify that this is really no problem for:
// a) SSP, because there's no caller SP...
@@ -199,7 +194,6 @@ class sspmod_adfs_IdP_ADFS {
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpMetadata = $idp->getConfig();
$spMetadata = $metadata->getMetaDataConfig($association['adfs:entityID'], 'adfs-sp-remote');
- // 'https://adfs-test.showcase.surfnet.nl/adfs/ls/?wa=wsignoutcleanup1.0&wreply=https%3A%2F%2Flocalhost%2Fsimplesaml');
$returnTo = SimpleSAML_Module::getModuleURL('adfs/idp/prp.php?assocId=' . urlencode($association["id"]) . '&relayState=' . urlencode($relayState));
return $spMetadata->getValue('prp') . '?' . 'wa=wsignoutcleanup1.0&wreply=' . urlencode($returnTo);
}
diff --git a/modules/adfs/www/idp/metadata.php b/modules/adfs/www/idp/metadata.php
index 8dcd6ba..a77a0a0 100644
--- a/modules/adfs/www/idp/metadata.php
+++ b/modules/adfs/www/idp/metadata.php
@@ -9,7 +9,7 @@ if (!$config->getBoolean('enable.adfs-idp', false))
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectmetadata', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
@@ -20,7 +20,7 @@ try {
$availableCerts = array();
$keys = array();
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_');
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, FALSE, 'new_');
if ($certInfo !== NULL) {
$availableCerts['new_idp.crt'] = $certInfo;
$keys[] = array(
@@ -34,7 +34,7 @@ try {
$hasNewCert = FALSE;
}
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE);
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE);
$availableCerts['idp.crt'] = $certInfo;
$keys[] = array(
'type' => 'X509Certificate',
@@ -44,7 +44,7 @@ try {
);
if ($idpmeta->hasValue('https.certificate')) {
- $httpsCert = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE, 'https.');
+ $httpsCert = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE, 'https.');
assert('isset($httpsCert["certData"])');
$availableCerts['https.crt'] = $httpsCert;
$keys[] = array(
@@ -112,7 +112,7 @@ try {
$metaBuilder->addOrganizationInfo($metaArray);
$technicalContactEmail = $config->getString('technicalcontact_email', NULL);
if ($technicalContactEmail && $technicalContactEmail !== 'na@example.org') {
- $metaBuilder->addContact('technical', SimpleSAML_Utils_Config_Metadata::getContact(array(
+ $metaBuilder->addContact('technical', \SimpleSAML\Utils\Config\Metadata::getContact(array(
'emailAddress' => $technicalContactEmail,
'name' => $config->getString('technicalcontact_name', NULL),
'contactType' => 'technical',
@@ -134,7 +134,7 @@ try {
$t->data['available_certs'] = $availableCerts;
$t->data['header'] = 'adfs-idp';
- $t->data['metaurl'] = SimpleSAML_Utilities::selfURLNoQuery();
+ $t->data['metaurl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
$t->data['metadata'] = htmlspecialchars($metaxml);
$t->data['metadataflat'] = htmlspecialchars($metaflat);
$t->data['defaultidp'] = $defaultidp;
diff --git a/modules/aselect/lib/Auth/Source/aselect.php b/modules/aselect/lib/Auth/Source/aselect.php
index 874b5ca..f4fd0f6 100644
--- a/modules/aselect/lib/Auth/Source/aselect.php
+++ b/modules/aselect/lib/Auth/Source/aselect.php
@@ -52,7 +52,7 @@ class sspmod_aselect_Auth_Source_aselect extends SimpleSAML_Auth_Source {
$app_url = SimpleSAML_Module::getModuleURL('aselect/credentials.php', array('ssp_state' => $id));
$as_url = $this->request_authentication($app_url);
- SimpleSAML_Utilities::redirectTrustedURL($as_url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($as_url);
} catch(Exception $e) {
// attach the exception to the state
SimpleSAML_Auth_State::throwException($state, $e);
@@ -125,7 +125,7 @@ class sspmod_aselect_Auth_Source_aselect extends SimpleSAML_Auth_Source {
$signable .= $parameters[$p];
$parameters['signature'] = $this->base64_signature($signable);
}
- return SimpleSAML_Utilities::addURLparameter($this->server_url, $parameters);
+ return \SimpleSAML\Utils\HTTP::addURLParameters($this->server_url, $parameters);
}
/**
@@ -177,7 +177,7 @@ class sspmod_aselect_Auth_Source_aselect extends SimpleSAML_Auth_Source {
$as_url = $res['as_url'];
unset($res['as_url']);
- return SimpleSAML_Utilities::addURLparameter($as_url, $res);
+ return \SimpleSAML\Utils\HTTP::addURLParameters($as_url, $res);
}
/**
diff --git a/modules/authX509/templates/X509error.php b/modules/authX509/templates/X509error.php
index 90e2dbd..c55ae65 100644
--- a/modules/authX509/templates/X509error.php
+++ b/modules/authX509/templates/X509error.php
@@ -21,7 +21,7 @@ if ($this->data['errorcode'] !== NULL) {
<p><?php echo $this->t('{authX509:X509error:certificate_text}'); ?></p>
- <a href="<?php echo htmlspecialchars(SimpleSAML_Utilities::selfURL()); ?>">
+ <a href="<?php echo htmlspecialchars(\SimpleSAML\Utils\HTTP::getSelfURL()); ?>">
<?php echo $this->t('{login:login_button}'); ?>
</a>
diff --git a/modules/authYubiKey/lib/Auth/Source/YubiKey.php b/modules/authYubiKey/lib/Auth/Source/YubiKey.php
index 48c3047..865ceef 100644
--- a/modules/authYubiKey/lib/Auth/Source/YubiKey.php
+++ b/modules/authYubiKey/lib/Auth/Source/YubiKey.php
@@ -103,7 +103,7 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends SimpleSAML_Auth_Source {
$id = SimpleSAML_Auth_State::saveState($state, self::STAGEID);
$url = SimpleSAML_Module::getModuleURL('authYubiKey/yubikeylogin.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('AuthState' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('AuthState' => $id));
}
diff --git a/modules/authYubiKey/libextinc/Yubico.php b/modules/authYubiKey/libextinc/Yubico.php
index 9cdd51c..15cd461 100644
--- a/modules/authYubiKey/libextinc/Yubico.php
+++ b/modules/authYubiKey/libextinc/Yubico.php
@@ -40,8 +40,6 @@
* @link http://yubico.com/
*/
-#require_once 'PEAR.php';
-
/**
* Class for verifying Yubico One-Time-Passcodes
*
diff --git a/modules/authcrypt/lib/Auth/Source/Hash.php b/modules/authcrypt/lib/Auth/Source/Hash.php
index cc23bdc..7c68417 100644
--- a/modules/authcrypt/lib/Auth/Source/Hash.php
+++ b/modules/authcrypt/lib/Auth/Source/Hash.php
@@ -50,7 +50,7 @@ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase {
$passwordhash = $userpass[1];
try {
- $attributes = SimpleSAML_Utilities::parseAttributes($attributes);
+ $attributes = SimpleSAML\Utils\Arrays::normalizeAttributesArray($attributes);
} catch(Exception $e) {
throw new Exception('Invalid attributes for user ' . $username .
' in authentication source ' . $this->authId . ': ' .
@@ -82,7 +82,7 @@ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase {
foreach($this->users as $userpass=>$attrs) {
$matches = explode(':', $userpass, 2);
if ($matches[0] === $username) {
- if(SimpleSAML_Utils_Crypto::pwValid($matches[1], $password)) {
+ if(SimpleSAML\Utils\Crypto::pwValid($matches[1], $password)) {
return $this->users[$userpass];
} else {
SimpleSAML_Logger::debug('Incorrect password "' . $password . '" for user '. $username);
diff --git a/modules/authcrypt/lib/Auth/Source/Htpasswd.php b/modules/authcrypt/lib/Auth/Source/Htpasswd.php
index 9acd461..bf9fd83 100644
--- a/modules/authcrypt/lib/Auth/Source/Htpasswd.php
+++ b/modules/authcrypt/lib/Auth/Source/Htpasswd.php
@@ -6,6 +6,9 @@
* @author Dyonisius (Dick) Visser, TERENA.
* @package simpleSAMLphp
*/
+
+use WhiteHat101\Crypt\APR1_MD5;
+
class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBase {
@@ -36,7 +39,7 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas
$this->users = explode("\n", trim($htpasswd));
try {
- $this->attributes = SimpleSAML_Utilities::parseAttributes($config['static_attributes']);
+ $this->attributes = SimpleSAML\Utils\Arrays::normalizeAttributesArray($config['static_attributes']);
} catch(Exception $e) {
throw new Exception('Invalid static_attributes in authentication source ' .
$this->authId . ': ' . $e->getMessage());
@@ -77,13 +80,13 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas
}
// Apache's custom MD5
- if(SimpleSAML_Utils_Crypto::apr1Md5Valid($crypted, $password)) {
+ if(APR1_MD5::check($crypted, $password)) {
SimpleSAML_Logger::debug('User '. $username . ' authenticated successfully');
return $attributes;
}
// SHA1 or plain-text
- if(SimpleSAML_Utils_Crypto::pwValid($crypted, $password)) {
+ if(SimpleSAML\Utils\Crypto::pwValid($crypted, $password)) {
SimpleSAML_Logger::debug('User '. $username . ' authenticated successfully');
return $attributes;
}
diff --git a/modules/authfacebook/extlibinc/base_facebook.php b/modules/authfacebook/extlibinc/base_facebook.php
index 44ac08e..36a1c6f 100644
--- a/modules/authfacebook/extlibinc/base_facebook.php
+++ b/modules/authfacebook/extlibinc/base_facebook.php
@@ -1282,8 +1282,6 @@ abstract class BaseFacebook
if (php_sapi_name() != 'cli') {
error_log($msg);
}
- // uncomment this if you want to see the errors on the page
- // print 'error_log: '.$msg."\n";
// @codeCoverageIgnoreEnd
}
diff --git a/modules/authfacebook/lib/Auth/Source/Facebook.php b/modules/authfacebook/lib/Auth/Source/Facebook.php
index 7e6b952..c211ebc 100644
--- a/modules/authfacebook/lib/Auth/Source/Facebook.php
+++ b/modules/authfacebook/lib/Auth/Source/Facebook.php
@@ -79,7 +79,7 @@ class sspmod_authfacebook_Auth_Source_Facebook extends SimpleSAML_Auth_Source {
$url = $facebook->getLoginUrl(array('redirect_uri' => $linkback, 'scope' => $this->req_perms));
SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
}
diff --git a/modules/authmyspace/lib/Auth/Source/MySpace.php b/modules/authmyspace/lib/Auth/Source/MySpace.php
index b651466..8f00b1c 100644
--- a/modules/authmyspace/lib/Auth/Source/MySpace.php
+++ b/modules/authmyspace/lib/Auth/Source/MySpace.php
@@ -93,9 +93,6 @@ class sspmod_authmyspace_Auth_Source_MySpace extends SimpleSAML_Auth_Source {
SimpleSAML_Logger::debug("Got an access token from the OAuth service provider [" .
$accessToken->key . "] with the secret [" . $accessToken->secret . "]");
- // API depricated on 20th September 2010
- //$userdata = $consumer->getUserInfo('http://api.myspace.com/v1/user.json', $accessToken);
-
// People API - http://developerwiki.myspace.com/index.php?title=People_API
$userdata = $consumer->getUserInfo('http://api.myspace.com/1.0/people/@me/@self?fields=@all', $accessToken);
diff --git a/modules/authorize/lib/Auth/Process/Authorize.php b/modules/authorize/lib/Auth/Process/Authorize.php
index 2fe6292..d57f21c 100644
--- a/modules/authorize/lib/Auth/Process/Authorize.php
+++ b/modules/authorize/lib/Auth/Process/Authorize.php
@@ -128,6 +128,6 @@ class sspmod_authorize_Auth_Process_Authorize extends SimpleSAML_Auth_Processing
'authorize:Authorize');
$url = SimpleSAML_Module::getModuleURL(
'authorize/authorize_403.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
}
diff --git a/modules/authtwitter/lib/Auth/Source/Twitter.php b/modules/authtwitter/lib/Auth/Source/Twitter.php
index c071066..58e7ba6 100644
--- a/modules/authtwitter/lib/Auth/Source/Twitter.php
+++ b/modules/authtwitter/lib/Auth/Source/Twitter.php
@@ -72,7 +72,7 @@ class sspmod_authtwitter_Auth_Source_Twitter extends SimpleSAML_Auth_Source {
// Authorize the request token
$url = 'https://api.twitter.com/oauth/authenticate';
if ($this->force_login) {
- $url = SimpleSAML_Utilities::addURLparameter($url, array('force_login' => 'true'));
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array('force_login' => 'true'));
}
$consumer->getAuthorizeRequest($url, $requestToken);
}
diff --git a/modules/authwindowslive/lib/Auth/Source/LiveID.php b/modules/authwindowslive/lib/Auth/Source/LiveID.php
index a54061e..2788694 100644
--- a/modules/authwindowslive/lib/Auth/Source/LiveID.php
+++ b/modules/authwindowslive/lib/Auth/Source/LiveID.php
@@ -71,7 +71,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source {
. '&wrap_scope=WL_Profiles.View,Messenger.SignIn'
;
- SimpleSAML_Utilities::redirectTrustedURL($authorizeURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL);
}
@@ -96,7 +96,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source {
),
);
- $result = SimpleSAML_Utilities::fetch('https://consent.live.com/AccessToken.aspx', $context);
+ $result = \SimpleSAML\Utils\HTTP::fetch('https://consent.live.com/AccessToken.aspx', $context);
parse_str($result, $response);
@@ -111,8 +111,8 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends SimpleSAML_Auth_Source {
// Documentation at: http://msdn.microsoft.com/en-us/library/ff751708.aspx
$opts = array('http' => array('header' => "Accept: application/json\r\nAuthorization: WRAP access_token=" .
$response['wrap_access_token'] . "\r\n"));
- $data = SimpleSAML_Utilities::fetch('https://apis.live.net/V4.1/cid-'. $response['uid'] . '/Profiles',$opts);
- $userdata = json_decode($data, TRUE);
+ $data = \SimpleSAML\Utils\HTTP::fetch('https://apis.live.net/V4.1/cid-'. $response['uid'] . '/Profiles',$opts);
+ $userdata = json_decode($data, TRUE);
$attributes = array();
$attributes['windowslive_uid'] = array($response['uid']);
diff --git a/modules/cas/lib/Auth/Source/CAS.php b/modules/cas/lib/Auth/Source/CAS.php
index 611fd85..301cb76 100644
--- a/modules/cas/lib/Auth/Source/CAS.php
+++ b/modules/cas/lib/Auth/Source/CAS.php
@@ -89,11 +89,11 @@ class sspmod_cas_Auth_Source_CAS extends SimpleSAML_Auth_Source {
* @return list username and attributes
*/
private function casValidate($ticket, $service){
- $url = SimpleSAML_Utilities::addURLparameter($this->_casConfig['validate'], array(
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($this->_casConfig['validate'], array(
'ticket' => $ticket,
'service' => $service,
));
- $result = SimpleSAML_Utilities::fetch($url);
+ $result = \SimpleSAML\Utils\HTTP::fetch($url);
$res = preg_split("/\r?\n/",$result);
if (strcmp($res[0], "yes") == 0) {
@@ -112,11 +112,11 @@ class sspmod_cas_Auth_Source_CAS extends SimpleSAML_Auth_Source {
* @return list username and attributes
*/
private function casServiceValidate($ticket, $service){
- $url = SimpleSAML_Utilities::addURLparameter($this->_casConfig['serviceValidate'], array(
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($this->_casConfig['serviceValidate'], array(
'ticket' => $ticket,
'service' => $service,
));
- $result = SimpleSAML_Utilities::fetch($url);
+ $result = \SimpleSAML\Utils\HTTP::fetch($url);
$dom = DOMDocument::loadXML($result);
$xPath = new DOMXpath($dom);
@@ -205,7 +205,7 @@ class sspmod_cas_Auth_Source_CAS extends SimpleSAML_Auth_Source {
$serviceUrl = SimpleSAML_Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID));
- SimpleSAML_Utilities::redirectTrustedURL($this->_loginMethod, array(
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->_loginMethod, array(
'service' => $serviceUrl));
}
@@ -229,7 +229,7 @@ class sspmod_cas_Auth_Source_CAS extends SimpleSAML_Auth_Source {
SimpleSAML_Auth_State::deleteState($state);
// we want cas to log us out
- SimpleSAML_Utilities::redirectTrustedURL($logoutUrl);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($logoutUrl);
}
}
diff --git a/modules/casserver/www/login.php b/modules/casserver/www/login.php
index ebbaec3..008018b 100644
--- a/modules/casserver/www/login.php
+++ b/modules/casserver/www/login.php
@@ -41,15 +41,15 @@ $attributes = $as->getAttributes();
$path = $casconfig->resolvePath($casconfig->getValue('ticketcache', '/tmp'));
-$ticket = str_replace( '_', 'ST-', SimpleSAML_Utilities::generateID() );
+$ticket = str_replace( '_', 'ST-', SimpleSAML\Utils\Random::generateID() );
storeTicket($ticket, $path, array('service' => $service,
'forceAuthn' => $forceAuthn,
'attributes' => $attributes,
'proxies' => array(),
'validbefore' => time() + 5));
-SimpleSAML_Utilities::redirectTrustedURL(
- SimpleSAML_Utilities::addURLparameter($service,
+\SimpleSAML\Utils\HTTP::redirectTrustedURL(
+ \SimpleSAML\Utils\HTTP::addURLParameters($service,
array('ticket' => $ticket)
)
); \ No newline at end of file
diff --git a/modules/casserver/www/proxy.php b/modules/casserver/www/proxy.php
index 7b88e41..6fc14e4 100644
--- a/modules/casserver/www/proxy.php
+++ b/modules/casserver/www/proxy.php
@@ -26,7 +26,7 @@ $path = $casconfig->resolvePath($casconfig->getValue('ticketcache', 'ticketcache
$ticket = retrieveTicket($pgt, $path, false);
if ($ticket['validbefore'] > time()) {
- $pt = str_replace( '_', 'PT-', SimpleSAML_Utilities::generateID() );
+ $pt = str_replace( '_', 'PT-', SimpleSAML\Utils\Random::generateID() );
storeTicket($pt, $path, array(
'service' => $targetService,
'forceAuthn' => false,
diff --git a/modules/casserver/www/serviceValidate.php b/modules/casserver/www/serviceValidate.php
index ffb20bb..ad5616d 100644
--- a/modules/casserver/www/serviceValidate.php
+++ b/modules/casserver/www/serviceValidate.php
@@ -41,14 +41,14 @@ try {
if (isset($_GET['pgtUrl'])) {
$pgtUrl = $_GET['pgtUrl'];
- $pgtiou = str_replace( '_', 'PGTIOU-', SimpleSAML_Utilities::generateID());
- $pgt = str_replace( '_', 'PGT-', SimpleSAML_Utilities::generateID());
+ $pgtiou = str_replace( '_', 'PGTIOU-', SimpleSAML\Utils\Random::generateID());
+ $pgt = str_replace( '_', 'PGT-', SimpleSAML\Utils\Random::generateID());
$content = array(
'attributes' => $attributes,
'forceAuthn' => false,
'proxies' => array_merge(array($service), $ticketcontent['proxies']),
'validbefore' => time() + 60);
- SimpleSAML_Utilities::fetch($pgtUrl . '?pgtIou=' . $pgtiou . '&pgtId=' . $pgt);
+ \SimpleSAML\Utils\HTTP::fetch($pgtUrl . '?pgtIou=' . $pgtiou . '&pgtId=' . $pgt);
storeTicket($pgt, $path, $content);
$pgtiouxml = "\n<cas:proxyGrantingTicket>$pgtiou</cas:proxyGrantingTicket>\n";
}
diff --git a/modules/cdc/lib/Server.php b/modules/cdc/lib/Server.php
index 2aa8850..b27f50e 100644
--- a/modules/cdc/lib/Server.php
+++ b/modules/cdc/lib/Server.php
@@ -211,7 +211,7 @@ class sspmod_cdc_Server {
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie('_saml_idp', NULL, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie('_saml_idp', NULL, $params, FALSE);
return 'ok';
}
@@ -324,11 +324,11 @@ class sspmod_cdc_Server {
'Signature' => $signature,
);
- $url = SimpleSAML_Utilities::addURLparameter($to, $params);
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($to, $params);
if (strlen($url) < 2048) {
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
} else {
- SimpleSAML_Utilities::postRedirect($to, $params);
+ \SimpleSAML\Utils\HTTP::submitPOSTData($to, $params);
}
}
@@ -407,7 +407,7 @@ class sspmod_cdc_Server {
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie('_saml_idp', $cookie, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie('_saml_idp', $cookie, $params, FALSE);
}
}
diff --git a/modules/consent/lib/Auth/Process/Consent.php b/modules/consent/lib/Auth/Process/Consent.php
index ac0a4bd..bbd585d 100644
--- a/modules/consent/lib/Auth/Process/Consent.php
+++ b/modules/consent/lib/Auth/Process/Consent.php
@@ -75,7 +75,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
if (!is_bool($config['includeValues'])) {
throw new SimpleSAML_Error_Exception(
'Consent: includeValues must be boolean. ' .
- var_export($config['includeValues']) . ' given.'
+ var_export($config['includeValues'], true) . ' given.'
);
}
$this->_includeValues = $config['includeValues'];
@@ -85,7 +85,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
if (!is_bool($config['checked'])) {
throw new SimpleSAML_Error_Exception(
'Consent: checked must be boolean. ' .
- var_export($config['checked']) . ' given.'
+ var_export($config['checked'], true) . ' given.'
);
}
$this->_checked = $config['checked'];
@@ -95,7 +95,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
if (!in_array($config['focus'], array('yes', 'no'), true)) {
throw new SimpleSAML_Error_Exception(
'Consent: focus must be a string with values `yes` or `no`. ' .
- var_export($config['focus']) . ' given.'
+ var_export($config['focus'], true) . ' given.'
);
}
$this->_focus = $config['focus'];
@@ -105,7 +105,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
if (!is_array($config['hiddenAttributes'])) {
throw new SimpleSAML_Error_Exception(
'Consent: hiddenAttributes must be an array. ' .
- var_export($config['hiddenAttributes']) . ' given.'
+ var_export($config['hiddenAttributes'], true) . ' given.'
);
}
$this->_hiddenAttributes = $config['hiddenAttributes'];
@@ -115,7 +115,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
if (!is_array($config['noconsentattributes'])) {
throw new SimpleSAML_Error_Exception(
'Consent: noconsentattributes must be an array. ' .
- var_export($config['noconsentattributes']) . ' given.'
+ var_export($config['noconsentattributes'], true) . ' given.'
);
}
$this->_noconsentattributes = $config['noconsentattributes'];
@@ -267,7 +267,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
$state['consent:showNoConsentAboutService'] = $this->_showNoConsentAboutService;
// User interaction nessesary. Throw exception on isPassive request
- if (isset($state['isPassive']) && $state['isPassive'] == true) {
+ if (isset($state['isPassive']) && $state['isPassive'] === true) {
SimpleSAML_Stats::log('consent:nopassive', $statsData);
throw new SimpleSAML_Error_NoPassive(
'Unable to give consent on passive request.'
@@ -277,7 +277,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
// Save state and redirect
$id = SimpleSAML_Auth_State::saveState($state, 'consent:request');
$url = SimpleSAML_Module::getModuleURL('consent/getconsent.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
/**
@@ -290,7 +290,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
*/
public static function getHashedUserID($userid, $source)
{
- return hash('sha1', $userid . '|' . SimpleSAML_Utilities::getSecretSalt() . '|' . $source);
+ return hash('sha1', $userid . '|' . SimpleSAML\Utils\Config::getSecretSalt() . '|' . $source);
}
/**
@@ -304,7 +304,7 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
*/
public static function getTargetedID($userid, $source, $destination)
{
- return hash('sha1', $userid . '|' . SimpleSAML_Utilities::getSecretSalt() . '|' . $source . '|' . $destination);
+ return hash('sha1', $userid . '|' . SimpleSAML\Utils\Config::getSecretSalt() . '|' . $source . '|' . $destination);
}
/**
diff --git a/modules/consent/lib/Consent/Store/Cookie.php b/modules/consent/lib/Consent/Store/Cookie.php
index 265d36c..7eb153e 100644
--- a/modules/consent/lib/Consent/Store/Cookie.php
+++ b/modules/consent/lib/Consent/Store/Cookie.php
@@ -199,7 +199,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
{
assert('is_string($data)');
- $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+ $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
return sha1($secretSalt . $data . $secretSalt) . ':' . $data;
}
@@ -272,14 +272,14 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
'httponly' => FALSE,
);
- if (SimpleSAML_Utilities::isHTTPS()) {
+ if (\SimpleSAML\Utils\HTTP::isHTTPS()) {
/* Enable secure cookie for https-requests. */
$params['secure'] = true;
} else {
$params['secure'] = false;
}
- SimpleSAML_Utilities::setCookie($name, $value, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($name, $value, $params, FALSE);
}
}
diff --git a/modules/consent/lib/Consent/Store/Database.php b/modules/consent/lib/Consent/Store/Database.php
index daae61c..9223cfd 100644
--- a/modules/consent/lib/Consent/Store/Database.php
+++ b/modules/consent/lib/Consent/Store/Database.php
@@ -482,14 +482,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
$driver_options[PDO::ATTR_TIMEOUT] = $this->_timeout;
}
- // @TODO Cleanup this section
- //try {
$this->_db = new PDO($this->_dsn, $this->_username, $this->_password, $driver_options);
- // } catch (PDOException $e) {
- // SimpleSAML_Logger::error('consent:Database - Failed to connect to \'' .
- // $this->_dsn . '\': '. $e->getMessage());
- // $this->db = false;
- // }
return $this->_db;
}
diff --git a/modules/consent/lib/Logout.php b/modules/consent/lib/Logout.php
index 89fc8d4..a927eac 100644
--- a/modules/consent/lib/Logout.php
+++ b/modules/consent/lib/Logout.php
@@ -9,7 +9,7 @@ class sspmod_consent_Logout {
public static function postLogout(SimpleSAML_IdP $idp, array $state) {
$url = SimpleSAML_Module::getModuleURL('consent/logout_completed.php');
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
}
}
diff --git a/modules/consent/templates/consentform.php b/modules/consent/templates/consentform.php
index 59608f0..e1ed91f 100644
--- a/modules/consent/templates/consentform.php
+++ b/modules/consent/templates/consentform.php
@@ -74,7 +74,7 @@ if (array_key_exists('descr_purpose', $this->data['dstMetadata'])) {
array(
'SPNAME' => $dstName,
'SPDESC' => $this->getTranslation(
- SimpleSAML_Utilities::arrayize(
+ SimpleSAML\Utils\Arrays::arrayize(
$this->data['dstMetadata']['descr_purpose'],
'en'
)
@@ -167,7 +167,7 @@ function present_attributes($t, $attributes, $nameParent)
$isHidden = in_array($nameraw, $t->data['hiddenAttributes'], true);
if ($isHidden) {
- $hiddenId = SimpleSAML_Utilities::generateID();
+ $hiddenId = SimpleSAML\Utils\Random::generateID();
$str .= '<div class="attrvalue" style="display: none;" id="hidden_' . $hiddenId . '">';
} else {
diff --git a/modules/consentAdmin/templates/consentadmin.php b/modules/consentAdmin/templates/consentadmin.php
index a07cd22..496d514 100644
--- a/modules/consentAdmin/templates/consentadmin.php
+++ b/modules/consentAdmin/templates/consentadmin.php
@@ -68,7 +68,6 @@ span.showhide {
<?php
$spList = $this->data['spList'];
$show_spid = 0;
- //$show_hide_attributes= $this->t('show_hide_attributes');
$show_text = $this->t('show');
$hide_text = $this->t('hide');
$attributes_text = $this->t('attributes_text');
@@ -132,6 +131,6 @@ TRSTART;
<h2>Logout</h2>
- <p><a href="<?php echo SimpleSAML_Utilities::selfURL() . '?logout'; ?>">Logout</a></p>
+ <p><a href="<?php echo \SimpleSAML\Utils\HTTP::getSelfURL() . '?logout'; ?>">Logout</a></p>
<?php $this->includeAtTemplateBase('includes/footer.php');
diff --git a/modules/consentAdmin/www/consentAdmin.php b/modules/consentAdmin/www/consentAdmin.php
index efc2c19..fd75bc1 100644
--- a/modules/consentAdmin/www/consentAdmin.php
+++ b/modules/consentAdmin/www/consentAdmin.php
@@ -1,265 +1,273 @@
-<?php
-/*
- * consentAdmin - Consent administration module
- *
- * This module enables the user to add and remove consents given for a given
- * Service Provider.
- *
- * The module relies on methods and functions from the Consent module and can
- * not be user without it.
- *
- * Author: Mads Freen <freek@ruc.dk>, Jacob Christiansen <jach@wayf.dk>
- */
-
-/*
- * Runs the processingchain and ignores all filter which have user
- * interaction.
- */
-function driveProcessingChain($idp_metadata, $source, $sp_metadata, $sp_entityid, $attributes, $userid, $hashAttributes = FALSE) {
-
- /*
- * Create a new processing chain
- */
- $pc = new SimpleSAML_Auth_ProcessingChain($idp_metadata, $sp_metadata, 'idp');
-
- /*
- * Construct the state.
- * REMEMBER: Do not set Return URL if you are calling processStatePassive
- */
- $authProcState = array(
- 'Attributes' => $attributes,
- 'Destination' => $sp_metadata,
- 'Source' => $idp_metadata,
- 'isPassive' => TRUE,
- );
-
- /*
- * Call processStatePAssive.
- * We are not interested in any user interaction, only modifications to the attributes
- */
- $pc->processStatePassive($authProcState);
-
- $attributes = $authProcState['Attributes'];
-
- /*
- * Generate identifiers and hashes
- */
- $destination = $sp_metadata['metadata-set'] . '|' . $sp_entityid;
-
- $targeted_id = sspmod_consent_Auth_Process_Consent::getTargetedID($userid, $source, $destination);
- $attribute_hash = sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes, $hashAttributes);
-
- SimpleSAML_Logger::info('consentAdmin: user: ' . $userid);
- SimpleSAML_Logger::info('consentAdmin: target: ' . $targeted_id);
- SimpleSAML_Logger::info('consentAdmin: attribute: ' . $attribute_hash);
-
- /* Return values */
- return array($targeted_id, $attribute_hash, $attributes);
-}
-
-// Get config object
-$config = SimpleSAML_Configuration::getInstance();
-$cA_config = SimpleSAML_Configuration::getConfig('module_consentAdmin.php');
-$authority = $cA_config->getValue('authority');
-
-$as = new SimpleSAML_Auth_Simple($authority);
-
-// If request is a logout request
-if(array_key_exists('logout', $_REQUEST)) {
- $returnURL = $cA_config->getValue('returnURL');
- $as->logout($returnURL);
-}
-
-$hashAttributes = $cA_config->getValue('attributes.hash');
-
-/* Check if valid local session exists */
-$as->requireAuth();
-
-// Get released attributes
-$attributes = $as->getAttributes();
-
-// Get metadata storage handler
-$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
-
-/*
- * Get IdP id and metadata
- */
-
-
-$local_idp_entityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
-$local_idp_metadata = $metadata->getMetaData($local_idp_entityid, 'saml20-idp-hosted');
-
-if($as->getAuthData('saml:sp:IdP') !== NULL) {
- /*
- * From a remote idp (as bridge)
- */
- $idp_entityid = $as->getAuthData('saml:sp:IdP');
- $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-remote');
-} else {
- /*
- * from the local idp
- */
- $idp_entityid = $local_idp_entityid;
- $idp_metadata = $local_idp_metadata;
-}
-
-// Get user ID
-$userid_attributename = (isset($local_idp_metadata['userid.attribute']) && is_string($local_idp_metadata['userid.attribute'])) ? $local_idp_metadata['userid.attribute'] : 'eduPersonPrincipalName';
-
-$userids = $attributes[$userid_attributename];
-
-if (empty($userids)) {
- throw new Exception('Could not generate useridentifier for storing consent. Attribute [' .
- $userid_attributename . '] was not available.');
-}
-
-$userid = $userids[0];
-
-// Get all SP metadata
-$all_sp_metadata = $metadata->getList('saml20-sp-remote');
-
-// Parse action, if any
-$action = null;
-$sp_entityid = null;
-if (!empty($_GET['cv'])) {
- $sp_entityid=$_GET['cv'];
-}
-if (!empty($_GET['action'])) {
- $action=$_GET["action"];
-}
-
-SimpleSAML_Logger::critical('consentAdmin: sp: ' .$sp_entityid.' action: '.$action);
-
-// Remove services, whitch have consent disabled
-if(isset($idp_metadata['consent.disable'])) {
- foreach($idp_metadata['consent.disable'] AS $disable) {
- if(array_key_exists($disable, $all_sp_metadata)) {
- unset($all_sp_metadata[$disable]);
- }
- }
-}
-
-SimpleSAML_Logger::info('consentAdmin: '.$idp_entityid);
-
-// Calc correct source
-$source = $idp_metadata['metadata-set'] . '|' . $idp_entityid;
-
-// Parse consent config
-$consent_storage = sspmod_consent_Store::parseStoreConfig($cA_config->getValue('consentadmin'));
-
-// Calc correct user ID hash
-$hashed_user_id = sspmod_consent_Auth_Process_Consent::getHashedUserID($userid, $source);
-
-// If a checkbox have been clicked
-if ($action != null && $sp_entityid != null) {
- // Get SP metadata
- $sp_metadata = $metadata->getMetaData($sp_entityid, 'saml20-sp-remote');
-
- // Run AuthProc filters
- list($targeted_id, $attribute_hash, $attributes_new) = driveProcessingChain($idp_metadata, $source, $sp_metadata, $sp_entityid, $attributes, $userid, $hashAttributes);
-
- // Add a consent (or update if attributes have changed and old consent for SP and IdP exists)
- if($action == 'true') {
- $isStored = $consent_storage->saveConsent($hashed_user_id, $targeted_id, $attribute_hash);
- if($isStored) {
- $res = "added";
- } else {
- $res = "updated";
- }
- // Remove consent
- } else if($action == 'false') {
- // Got consent, so this is a request to remove it
- $rowcount = $consent_storage->deleteConsent($hashed_user_id, $targeted_id, $attribute_hash);
- if($rowcount > 0) {
- $res = "removed";
- }
- // Unknown action (should not happen)
- } else {
- SimpleSAML_Logger::info('consentAdmin: unknown action');
- $res = "unknown";
- }
- /*
- * Init template to enable translation of status messages
- */
- $et = new SimpleSAML_XHTML_Template($config, 'consentAdmin:consentadminajax.php', 'consentAdmin:consentadmin');
- $et->data['res'] = $res;
- $et->show();
- exit;
-}
-
-// Get all consents for user
-$user_consent_list = $consent_storage->getConsents($hashed_user_id);
-
-// Parse list of consents
-$user_consent = array();
-foreach ($user_consent_list as $c) {
- $user_consent[$c[0]]=$c[1];
-}
-
-$template_sp_content = array();
-
-// Init template
-$et = new SimpleSAML_XHTML_Template($config, 'consentAdmin:consentadmin.php', 'consentAdmin:consentadmin');
-$sp_empty_name = $et->getTag('sp_empty_name');
-$sp_empty_description = $et->getTag('sp_empty_description');
-
-// Process consents for all SP
-foreach ($all_sp_metadata as $sp_entityid => $sp_values) {
- // Get metadata for SP
- $sp_metadata = $metadata->getMetaData($sp_entityid, 'saml20-sp-remote');
-
- // Run attribute filters
- list($targeted_id, $attribute_hash, $attributes_new) = driveProcessingChain($idp_metadata, $source, $sp_metadata, $sp_entityid, $attributes, $userid, $hashAttributes);
-
- // Check if consent exists
- if (array_key_exists($targeted_id, $user_consent)) {
- $sp_status = "changed";
- SimpleSAML_Logger::info('consentAdmin: changed');
- // Check if consent is valid. (Possible that attributes has changed)
- if ($user_consent[$targeted_id] == $attribute_hash) {
- SimpleSAML_Logger::info('consentAdmin: ok');
- $sp_status = "ok";
- }
- // Consent does not exists
- } else {
- SimpleSAML_Logger::info('consentAdmin: none');
- $sp_status = "none";
- }
-
- // Set name of SP
- if(isset($sp_values['name']) && is_array($sp_values['name'])) {
- $sp_name = $sp_metadata['name'];
- } else if(isset($sp_values['name']) && is_string($sp_values['name'])) {
- $sp_name = $sp_metadata['name'];
- } elseif(isset($sp_values['OrganizationDisplayName']) && is_array($sp_values['OrganizationDisplayName'])) {
- $sp_name = $sp_metadata['OrganizationDisplayName'];
- } else {
- $sp_name = $sp_empty_name;
- }
-
- // Set description of SP
- if(empty($sp_metadata['description']) || !is_array($sp_metadata['description'])) {
- $sp_description = $sp_empty_description;
- } else {
- $sp_description = $sp_metadata['description'];
- }
-
- // Add a URL to the service if present in metadata
- $sp_service_url = isset($sp_metadata['ServiceURL']) ? $sp_metadata['ServiceURL'] : null;
-
- // Fill out array for the template
- $sp_list[$sp_entityid] = array(
- 'spentityid' => $sp_entityid,
- 'name' => $sp_name,
- 'description' => $sp_description,
- 'consentStatus' => $sp_status,
- 'consentValue' => $sp_entityid,
- 'attributes_by_sp' => $attributes_new,
- 'serviceurl' => $sp_service_url,
- );
-}
-
-$et->data['header'] = 'Consent Administration';
-$et->data['spList'] = $sp_list;
-$et->data['showDescription'] = $cA_config->getValue('showDescription');
-$et->show();
+<?php
+/*
+ * consentAdmin - Consent administration module
+ *
+ * This module enables the user to add and remove consents given for a given
+ * Service Provider.
+ *
+ * The module relies on methods and functions from the Consent module and can
+ * not be user without it.
+ *
+ * Author: Mads Freek <freek@ruc.dk>, Jacob Christiansen <jach@wayf.dk>
+ */
+
+/*
+ * Runs the processing chain and ignores all filter which have user
+ * interaction.
+ */
+function driveProcessingChain(
+ $idp_metadata,
+ $source,
+ $sp_metadata,
+ $sp_entityid,
+ $attributes,
+ $userid,
+ $hashAttributes = false
+) {
+
+ /*
+ * Create a new processing chain
+ */
+ $pc = new SimpleSAML_Auth_ProcessingChain($idp_metadata, $sp_metadata, 'idp');
+
+ /*
+ * Construct the state.
+ * REMEMBER: Do not set Return URL if you are calling processStatePassive
+ */
+ $authProcState = array(
+ 'Attributes' => $attributes,
+ 'Destination' => $sp_metadata,
+ 'Source' => $idp_metadata,
+ 'isPassive' => true,
+ );
+
+ /*
+ * Call processStatePAssive.
+ * We are not interested in any user interaction, only modifications to the attributes
+ */
+ $pc->processStatePassive($authProcState);
+
+ $attributes = $authProcState['Attributes'];
+
+ /*
+ * Generate identifiers and hashes
+ */
+ $destination = $sp_metadata['metadata-set'].'|'.$sp_entityid;
+
+ $targeted_id = sspmod_consent_Auth_Process_Consent::getTargetedID($userid, $source, $destination);
+ $attribute_hash = sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes, $hashAttributes);
+
+ SimpleSAML_Logger::info('consentAdmin: user: '.$userid);
+ SimpleSAML_Logger::info('consentAdmin: target: '.$targeted_id);
+ SimpleSAML_Logger::info('consentAdmin: attribute: '.$attribute_hash);
+
+ /* Return values */
+ return array($targeted_id, $attribute_hash, $attributes);
+}
+
+// Get config object
+$config = SimpleSAML_Configuration::getInstance();
+$cA_config = SimpleSAML_Configuration::getConfig('module_consentAdmin.php');
+$authority = $cA_config->getValue('authority');
+
+$as = new SimpleSAML_Auth_Simple($authority);
+
+// If request is a logout request
+if (array_key_exists('logout', $_REQUEST)) {
+ $returnURL = $cA_config->getValue('returnURL');
+ $as->logout($returnURL);
+}
+
+$hashAttributes = $cA_config->getValue('attributes.hash');
+
+/* Check if valid local session exists */
+$as->requireAuth();
+
+// Get released attributes
+$attributes = $as->getAttributes();
+
+// Get metadata storage handler
+$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
+
+/*
+ * Get IdP id and metadata
+ */
+
+
+$local_idp_entityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
+$local_idp_metadata = $metadata->getMetaData($local_idp_entityid, 'saml20-idp-hosted');
+
+if ($as->getAuthData('saml:sp:IdP') !== null) {
+ // from a remote idp (as bridge)
+ $idp_entityid = $as->getAuthData('saml:sp:IdP');
+ $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-remote');
+} else {
+ // from the local idp
+ $idp_entityid = $local_idp_entityid;
+ $idp_metadata = $local_idp_metadata;
+}
+
+// Get user ID
+$userid_attributename = (isset($local_idp_metadata['userid.attribute']) && is_string($local_idp_metadata['userid.attribute'])) ? $local_idp_metadata['userid.attribute'] : 'eduPersonPrincipalName';
+
+$userids = $attributes[$userid_attributename];
+
+if (empty($userids)) {
+ throw new Exception('Could not generate useridentifier for storing consent. Attribute ['.
+ $userid_attributename.'] was not available.');
+}
+
+$userid = $userids[0];
+
+// Get all SP metadata
+$all_sp_metadata = $metadata->getList('saml20-sp-remote');
+
+// Parse action, if any
+$action = null;
+$sp_entityid = null;
+if (!empty($_GET['cv'])) {
+ $sp_entityid = $_GET['cv'];
+}
+if (!empty($_GET['action'])) {
+ $action = $_GET["action"];
+}
+
+SimpleSAML_Logger::critical('consentAdmin: sp: '.$sp_entityid.' action: '.$action);
+
+// Remove services, whitch have consent disabled
+if (isset($idp_metadata['consent.disable'])) {
+ foreach ($idp_metadata['consent.disable'] AS $disable) {
+ if (array_key_exists($disable, $all_sp_metadata)) {
+ unset($all_sp_metadata[$disable]);
+ }
+ }
+}
+
+SimpleSAML_Logger::info('consentAdmin: '.$idp_entityid);
+
+// Calc correct source
+$source = $idp_metadata['metadata-set'].'|'.$idp_entityid;
+
+// Parse consent config
+$consent_storage = sspmod_consent_Store::parseStoreConfig($cA_config->getValue('consentadmin'));
+
+// Calc correct user ID hash
+$hashed_user_id = sspmod_consent_Auth_Process_Consent::getHashedUserID($userid, $source);
+
+// If a checkbox have been clicked
+if ($action !== null && $sp_entityid !== null) {
+ // Get SP metadata
+ $sp_metadata = $metadata->getMetaData($sp_entityid, 'saml20-sp-remote');
+
+ // Run AuthProc filters
+ list($targeted_id, $attribute_hash, $attributes_new) = driveProcessingChain($idp_metadata, $source, $sp_metadata,
+ $sp_entityid, $attributes, $userid, $hashAttributes);
+
+ // Add a consent (or update if attributes have changed and old consent for SP and IdP exists)
+ if ($action == 'true') {
+ $isStored = $consent_storage->saveConsent($hashed_user_id, $targeted_id, $attribute_hash);
+ if ($isStored) {
+ $res = "added";
+ } else {
+ $res = "updated";
+ }
+ // Remove consent
+ } else {
+ if ($action == 'false') {
+ // Got consent, so this is a request to remove it
+ $rowcount = $consent_storage->deleteConsent($hashed_user_id, $targeted_id, $attribute_hash);
+ if ($rowcount > 0) {
+ $res = "removed";
+ }
+ // Unknown action (should not happen)
+ } else {
+ SimpleSAML_Logger::info('consentAdmin: unknown action');
+ $res = "unknown";
+ }
+ }
+ // init template to enable translation of status messages
+ $et = new SimpleSAML_XHTML_Template($config, 'consentAdmin:consentadminajax.php', 'consentAdmin:consentadmin');
+ $et->data['res'] = $res;
+ $et->show();
+ exit;
+}
+
+// Get all consents for user
+$user_consent_list = $consent_storage->getConsents($hashed_user_id);
+
+// Parse list of consents
+$user_consent = array();
+foreach ($user_consent_list as $c) {
+ $user_consent[$c[0]] = $c[1];
+}
+
+$template_sp_content = array();
+
+// Init template
+$et = new SimpleSAML_XHTML_Template($config, 'consentAdmin:consentadmin.php', 'consentAdmin:consentadmin');
+$sp_empty_name = $et->getTag('sp_empty_name');
+$sp_empty_description = $et->getTag('sp_empty_description');
+
+// Process consents for all SP
+foreach ($all_sp_metadata as $sp_entityid => $sp_values) {
+ // Get metadata for SP
+ $sp_metadata = $metadata->getMetaData($sp_entityid, 'saml20-sp-remote');
+
+ // Run attribute filters
+ list($targeted_id, $attribute_hash, $attributes_new) = driveProcessingChain($idp_metadata, $source, $sp_metadata,
+ $sp_entityid, $attributes, $userid, $hashAttributes);
+
+ // Check if consent exists
+ if (array_key_exists($targeted_id, $user_consent)) {
+ $sp_status = "changed";
+ SimpleSAML_Logger::info('consentAdmin: changed');
+ // Check if consent is valid. (Possible that attributes has changed)
+ if ($user_consent[$targeted_id] == $attribute_hash) {
+ SimpleSAML_Logger::info('consentAdmin: ok');
+ $sp_status = "ok";
+ }
+ // Consent does not exists
+ } else {
+ SimpleSAML_Logger::info('consentAdmin: none');
+ $sp_status = "none";
+ }
+
+ // Set name of SP
+ if (isset($sp_values['name']) && is_array($sp_values['name'])) {
+ $sp_name = $sp_metadata['name'];
+ } else {
+ if (isset($sp_values['name']) && is_string($sp_values['name'])) {
+ $sp_name = $sp_metadata['name'];
+ } elseif (isset($sp_values['OrganizationDisplayName']) && is_array($sp_values['OrganizationDisplayName'])) {
+ $sp_name = $sp_metadata['OrganizationDisplayName'];
+ } else {
+ $sp_name = $sp_empty_name;
+ }
+ }
+
+ // Set description of SP
+ if (empty($sp_metadata['description']) || !is_array($sp_metadata['description'])) {
+ $sp_description = $sp_empty_description;
+ } else {
+ $sp_description = $sp_metadata['description'];
+ }
+
+ // Add a URL to the service if present in metadata
+ $sp_service_url = isset($sp_metadata['ServiceURL']) ? $sp_metadata['ServiceURL'] : null;
+
+ // Fill out array for the template
+ $sp_list[$sp_entityid] = array(
+ 'spentityid' => $sp_entityid,
+ 'name' => $sp_name,
+ 'description' => $sp_description,
+ 'consentStatus' => $sp_status,
+ 'consentValue' => $sp_entityid,
+ 'attributes_by_sp' => $attributes_new,
+ 'serviceurl' => $sp_service_url,
+ );
+}
+
+$et->data['header'] = 'Consent Administration';
+$et->data['spList'] = $sp_list;
+$et->data['showDescription'] = $cA_config->getValue('showDescription');
+$et->show();
diff --git a/modules/consentSimpleAdmin/www/consentAdmin.php b/modules/consentSimpleAdmin/www/consentAdmin.php
index f1c1d08..1c576e9 100644
--- a/modules/consentSimpleAdmin/www/consentAdmin.php
+++ b/modules/consentSimpleAdmin/www/consentAdmin.php
@@ -1,91 +1,87 @@
-<?php
-/*
- * consentSimpleAdmin - Simple Consent administration module
- *
- * This module is a simplification of the danish consent administration module.
- *
- * @author Andreas Ã…kre Solberg <andreas.solberg@uninett.no>
- * @author Mads Freen - WAYF
- * @author Jacob Christiansen - WAYF
- * @package simpleSAMLphp
- */
-
-
-// Get config object
-$config = SimpleSAML_Configuration::getInstance();
-$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');
-
-$as = $consentconfig->getValue('auth');
-$as = new SimpleSAML_Auth_Simple($as);
-$as->requireAuth();
-
-// Get all attributes
-$attributes = $as->getAttributes();
-
-
-
-// Get user ID
-$userid_attributename = $consentconfig->getValue('userid', 'eduPersonPrincipalName');
-if (empty($attributes[$userid_attributename])) {
- throw new Exception('Could not generate useridentifier for storing consent. Attribute [' .
- $userid_attributename . '] was not available.');
-}
-
-$userid = $attributes[$userid_attributename][0];
-
-// Get metadata storage handler
-$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
-
-/*
- * Get IdP id and metadata
- */
-if($as->getAuthData('saml:sp:IdP') != null) {
- // From a remote idp (as bridge)
- $idp_entityid = $as->getAuthData('saml:sp:IdP');
- $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-remote');
-} else {
- // from the local idp
- $idp_entityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
- $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-hosted');
-}
-
-SimpleSAML_Logger::debug('consentAdmin: IdP is ['.$idp_entityid . ']');
-
-$source = $idp_metadata['metadata-set'] . '|' . $idp_entityid;
-
-
-// Parse consent config
-$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));
-
-// Calc correct user ID hash
-$hashed_user_id = sspmod_consent_Auth_Process_Consent::getHashedUserID($userid, $source);
-
-
-
-// Check if button with withdraw all consent was clicked.
-if (array_key_exists('withdraw', $_REQUEST)) {
-
- SimpleSAML_Logger::info('consentAdmin: UserID ['.$hashed_user_id . '] has requested to withdraw all consents given...');
-
- $consent_storage->deleteAllConsents($hashed_user_id);
-
-}
-
-
-
-// Get all consents for user
-$user_consent_list = $consent_storage->getConsents($hashed_user_id);
-
-$consentServices = array();
-foreach($user_consent_list AS $c) $consentServices[$c[1]] = 1;
-
-SimpleSAML_Logger::debug('consentAdmin: no of consents [' . count($user_consent_list) . '] no of services [' . count($consentServices) . ']');
-
-// Init template
-$t = new SimpleSAML_XHTML_Template($config, 'consentSimpleAdmin:consentadmin.php');
-
-$t->data['consentServices'] = count($consentServices);
-$t->data['consents'] = count($user_consent_list);
-
-
-$t->show();
+<?php
+/*
+ * consentSimpleAdmin - Simple Consent administration module
+ *
+ * This module is a simplification of the danish consent administration module.
+ *
+ * @author Andreas Ã…kre Solberg <andreas.solberg@uninett.no>
+ * @author Mads Freek - WAYF
+ * @author Jacob Christiansen - WAYF
+ * @package SimpleSAMLphp
+ */
+
+
+// Get config object
+$config = SimpleSAML_Configuration::getInstance();
+$consentconfig = SimpleSAML_Configuration::getConfig('module_consentSimpleAdmin.php');
+
+$as = $consentconfig->getValue('auth');
+$as = new SimpleSAML_Auth_Simple($as);
+$as->requireAuth();
+
+// Get all attributes
+$attributes = $as->getAttributes();
+
+
+// Get user ID
+$userid_attributename = $consentconfig->getValue('userid', 'eduPersonPrincipalName');
+if (empty($attributes[$userid_attributename])) {
+ throw new Exception('Could not generate useridentifier for storing consent. Attribute ['.
+ $userid_attributename.'] was not available.');
+}
+
+$userid = $attributes[$userid_attributename][0];
+
+// Get metadata storage handler
+$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
+
+// Get IdP id and metadata
+if ($as->getAuthData('saml:sp:IdP') !== null) {
+ // From a remote idp (as bridge)
+ $idp_entityid = $as->getAuthData('saml:sp:IdP');
+ $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-remote');
+} else {
+ // from the local idp
+ $idp_entityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
+ $idp_metadata = $metadata->getMetaData($idp_entityid, 'saml20-idp-hosted');
+}
+
+SimpleSAML_Logger::debug('consentAdmin: IdP is ['.$idp_entityid.']');
+
+$source = $idp_metadata['metadata-set'].'|'.$idp_entityid;
+
+
+// Parse consent config
+$consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getValue('store'));
+
+// Calc correct user ID hash
+$hashed_user_id = sspmod_consent_Auth_Process_Consent::getHashedUserID($userid, $source);
+
+
+// Check if button with withdraw all consent was clicked.
+if (array_key_exists('withdraw', $_REQUEST)) {
+
+ SimpleSAML_Logger::info('consentAdmin: UserID ['.$hashed_user_id.'] has requested to withdraw all consents given...');
+
+ $consent_storage->deleteAllConsents($hashed_user_id);
+}
+
+
+// Get all consents for user
+$user_consent_list = $consent_storage->getConsents($hashed_user_id);
+
+$consentServices = array();
+foreach ($user_consent_list AS $c) {
+ $consentServices[$c[1]] = 1;
+}
+
+SimpleSAML_Logger::debug('consentAdmin: no of consents ['.count($user_consent_list).'] no of services ['.count($consentServices).']');
+
+// Init template
+$t = new SimpleSAML_XHTML_Template($config, 'consentSimpleAdmin:consentadmin.php');
+
+$t->data['consentServices'] = count($consentServices);
+$t->data['consents'] = count($user_consent_list);
+
+
+$t->show();
diff --git a/modules/consentSimpleAdmin/www/consentStats.php b/modules/consentSimpleAdmin/www/consentStats.php
index 92240e1..a9339c0 100644
--- a/modules/consentSimpleAdmin/www/consentStats.php
+++ b/modules/consentSimpleAdmin/www/consentStats.php
@@ -20,8 +20,6 @@ $consent_storage = sspmod_consent_Store::parseStoreConfig($consentconfig->getVal
// Get all consents for user
$stats = $consent_storage->getStatistics();
-#print_r($stats); exit;
-
// Init template
$t = new SimpleSAML_XHTML_Template($config, 'consentSimpleAdmin:consentstats.php');
diff --git a/modules/core/hooks/hook_sanitycheck.php b/modules/core/hooks/hook_sanitycheck.php
index d81ef25..b0848d3 100644
--- a/modules/core/hooks/hook_sanitycheck.php
+++ b/modules/core/hooks/hook_sanitycheck.php
@@ -23,12 +23,12 @@ function core_hook_sanitycheck(&$hookinfo) {
$hookinfo['info'][] = '[core] In config.php technicalcontact_email is set properly';
}
- if (version_compare(phpversion(), '5.2', '>=')) {
+ if (version_compare(phpversion(), '5.3', '>=')) {
$hookinfo['info'][] = '[core] You are running PHP version ' . phpversion() . '. Great.';
} elseif( version_compare(phpversion(), '5.1.2', '>=')) {
$hookinfo['info'][] = '[core] You are running PHP version ' . phpversion() . '. It\'s recommended to upgrade to >= 5.2';
} else {
- $hookinfo['errors'][] = '[core] You are running PHP version ' . phpversion() . '. SimpleSAMLphp requires version >= 5.1.2, and reccomends version >= 5.2. Please upgrade!';
+ $hookinfo['errors'][] = '[core] You are running PHP version ' . phpversion() . '. SimpleSAMLphp requires version >= 5.3. Please upgrade!';
}
$info = array();
@@ -40,7 +40,6 @@ function core_hook_sanitycheck(&$hookinfo) {
foreach($info AS $mi => $i) {
if (isset($i['dependencies']) && is_array($i['dependencies'])) {
foreach ($i['dependencies'] AS $dep) {
- // $hookinfo['info'][] = '[core] Module ' . $mi . ' requires ' . $dep;
if (!in_array($dep, $availmodules)) {
$hookinfo['errors'][] = '[core] Module dependency not met: ' . $mi . ' requires ' . $dep;
}
diff --git a/modules/core/lib/ACL.php b/modules/core/lib/ACL.php
index 65860ad..724f184 100644
--- a/modules/core/lib/ACL.php
+++ b/modules/core/lib/ACL.php
@@ -119,7 +119,7 @@ class sspmod_core_ACL {
case 'or':
return self::opOr($attributes, $rule);
default:
- throw new SimpleSAML_Error_Exception('Invalid ACL operation: ' . var_export($op. TRUE));
+ throw new SimpleSAML_Error_Exception('Invalid ACL operation: ' . var_export($op, TRUE));
}
}
diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php
index aafdd23..1151a24 100644
--- a/modules/core/lib/Auth/Process/TargetedID.php
+++ b/modules/core/lib/Auth/Process/TargetedID.php
@@ -100,7 +100,7 @@ class sspmod_core_Auth_Process_TargetedID extends SimpleSAML_Auth_ProcessingFilt
}
- $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+ $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
if (array_key_exists('Source', $state)) {
$srcID = self::getEntityId($state['Source']);
diff --git a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
index 1a731e3..e28bfd4 100644
--- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
+++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
@@ -46,7 +46,7 @@ class sspmod_core_Auth_Process_WarnShortSSOInterval extends SimpleSAML_Auth_Proc
/* Save state and redirect. */
$id = SimpleSAML_Auth_State::saveState($state, 'core:short_sso_interval');
$url = SimpleSAML_Module::getModuleURL('core/short_sso_interval.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
}
diff --git a/modules/core/lib/Auth/Source/AdminPassword.php b/modules/core/lib/Auth/Source/AdminPassword.php
index adab5d6..12cf0dc 100644
--- a/modules/core/lib/Auth/Source/AdminPassword.php
+++ b/modules/core/lib/Auth/Source/AdminPassword.php
@@ -54,7 +54,7 @@ class sspmod_core_Auth_Source_AdminPassword extends sspmod_core_Auth_UserPassBas
throw new SimpleSAML_Error_Error('WRONGUSERPASS');
}
- if (!SimpleSAML_Utils_Crypto::pwValid($adminPassword, $password)) {
+ if (!SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) {
throw new SimpleSAML_Error_Error('WRONGUSERPASS');
}
diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php
index a97fba7..7c6b5dd 100644
--- a/modules/core/lib/Auth/UserPassBase.php
+++ b/modules/core/lib/Auth/UserPassBase.php
@@ -194,7 +194,7 @@ abstract class sspmod_core_Auth_UserPassBase extends SimpleSAML_Auth_Source {
*/
$url = SimpleSAML_Module::getModuleURL('core/loginuserpass.php');
$params = array('AuthState' => $id);
- SimpleSAML_Utilities::redirectTrustedURL($url, $params);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
/* The previous function never returns, so this code is never executed. */
assert('FALSE');
diff --git a/modules/core/lib/Auth/UserPassOrgBase.php b/modules/core/lib/Auth/UserPassOrgBase.php
index 7bbddf2..5058537 100644
--- a/modules/core/lib/Auth/UserPassOrgBase.php
+++ b/modules/core/lib/Auth/UserPassOrgBase.php
@@ -156,7 +156,7 @@ abstract class sspmod_core_Auth_UserPassOrgBase extends SimpleSAML_Auth_Source {
$url = SimpleSAML_Module::getModuleURL('core/loginuserpassorg.php');
$params = array('AuthState' => $id);
- SimpleSAML_Utilities::redirectTrustedURL($url, $params);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
}
diff --git a/modules/core/lib/ModuleDefinition.php b/modules/core/lib/ModuleDefinition.php
index 64106e6..f633096 100644
--- a/modules/core/lib/ModuleDefinition.php
+++ b/modules/core/lib/ModuleDefinition.php
@@ -110,9 +110,7 @@ class sspmod_core_ModuleDefinition {
$remoteDef = self::load($this->def['definition'], 'remote');
$remoteVersion = $remoteDef->getVersion($branch);
-
- #echo ' Comparing versions local [' . $thisVersion . '] and remote [' . $remoteVersion . ']' . "\n";
-
+
return version_compare($remoteVersion, $thisVersion, '>');
}
diff --git a/modules/core/lib/ModuleInstaller.php b/modules/core/lib/ModuleInstaller.php
index a35cc3d..5dde6fe 100644
--- a/modules/core/lib/ModuleInstaller.php
+++ b/modules/core/lib/ModuleInstaller.php
@@ -20,11 +20,6 @@ class sspmod_core_ModuleInstaller {
$access = $this->module->getAccess($branch);
switch($access['type']) {
- // case 'svn' :
- // $this->requireInstalled();
- // $this->remove($access);
- // break;
-
default:
$this->requireInstalled();
$this->removeModuleDir($access);
diff --git a/modules/core/lib/Storage/SQLPermanentStorage.php b/modules/core/lib/Storage/SQLPermanentStorage.php
index 1496657..0a1a925 100644
--- a/modules/core/lib/Storage/SQLPermanentStorage.php
+++ b/modules/core/lib/Storage/SQLPermanentStorage.php
@@ -99,8 +99,6 @@ class sspmod_core_Storage_SQLPermanentStorage {
"key2 = '" . sqlite_escape_string($key2) . "' AND " .
"type = '" . sqlite_escape_string($type) . "'";
$results = $this->db->queryExec($query);
- # echo $query;
- # echo $this->db>changes;
return $results;
}
@@ -109,9 +107,7 @@ class sspmod_core_Storage_SQLPermanentStorage {
$condition = self::getCondition($type, $key1, $key2);
$query = "SELECT * FROM data WHERE " . $condition;
$results = $this->db->arrayQuery($query, SQLITE_ASSOC);
-
-# echo '<pre>type: ' . $type . ' key1:' . $key1 . ' ' . $query; print_r($results); exit;
-
+
if (count($results) !== 1) return NULL;
$res = $results[0];
diff --git a/modules/core/templates/frontpage_federation.tpl.php b/modules/core/templates/frontpage_federation.tpl.php
index 4891885..2be7e07 100644
--- a/modules/core/templates/frontpage_federation.tpl.php
+++ b/modules/core/templates/frontpage_federation.tpl.php
@@ -61,9 +61,9 @@ foreach ($this->data['metaentries']['hosted'] AS $hm) {
if ($hm['entityid'] !== $hm['metadata-index'])
echo '<br />Index: ' . $hm['metadata-index'];
if (!empty($hm['name']))
- echo '<br /><strong>' . $this->getTranslation(SimpleSAML_Utilities::arrayize($hm['name'], 'en')) . '</strong>';
+ echo '<br /><strong>' . $this->getTranslation(SimpleSAML\Utils\Arrays::arrayize($hm['name'], 'en')) . '</strong>';
if (!empty($hm['descr']))
- echo '<br /><strong>' . $this->getTranslation(SimpleSAML_Utilities::arrayize($hm['descr'], 'en')) . '</strong>';
+ echo '<br /><strong>' . $this->getTranslation(SimpleSAML\Utils\Arrays::arrayize($hm['descr'], 'en')) . '</strong>';
echo '<br />[ <a href="' . $hm['metadata-url'] . '">' . $this->t('{core:frontpage:show_metadata}') . '</a> ]';
@@ -82,9 +82,9 @@ foreach($this->data['metaentries']['remote'] AS $setkey => $set) {
htmlspecialchars(SimpleSAML_Module::getModuleURL('core/show_metadata.php', array('entityid' => $entry['entityid'], 'set' => $setkey ))) .
'">');
if (!empty($entry['name'])) {
- echo htmlspecialchars($this->getTranslation(SimpleSAML_Utilities::arrayize($entry['name'], 'en')));
+ echo htmlspecialchars($this->getTranslation(SimpleSAML\Utils\Arrays::arrayize($entry['name'], 'en')));
} elseif (!empty($entry['OrganizationDisplayName'])) {
- echo htmlspecialchars($this->getTranslation(SimpleSAML_Utilities::arrayize($entry['OrganizationDisplayName'], 'en')));
+ echo htmlspecialchars($this->getTranslation(SimpleSAML\Utils\Arrays::arrayize($entry['OrganizationDisplayName'], 'en')));
} else {
echo htmlspecialchars($entry['entityid']);
}
diff --git a/modules/core/templates/show_metadata.tpl.php b/modules/core/templates/show_metadata.tpl.php
index 6f6782f..ff55e9c 100644
--- a/modules/core/templates/show_metadata.tpl.php
+++ b/modules/core/templates/show_metadata.tpl.php
@@ -7,7 +7,7 @@ $this->includeAtTemplateBase('includes/header.php');
echo('<pre style="font-size: 110%">');
-echo(htmlspecialchars(var_export($this->data['m'])));
+echo(htmlspecialchars(var_export($this->data['m'], true)));
echo('</pre>');
diff --git a/modules/core/www/as_login.php b/modules/core/www/as_login.php
index 27c16fa..dc1a61b 100644
--- a/modules/core/www/as_login.php
+++ b/modules/core/www/as_login.php
@@ -18,7 +18,7 @@ if (!is_string($_REQUEST['AuthId'])) {
* Setting up the options for the requireAuth() call later..
*/
$options = array(
- 'ReturnTo' => SimpleSAML_Utilities::checkURLAllowed($_REQUEST['ReturnTo']),
+ 'ReturnTo' => \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']),
);
/*
@@ -32,4 +32,4 @@ if (!empty($_REQUEST['saml:idp'])) {
$as = new SimpleSAML_Auth_Simple($_REQUEST['AuthId']);
$as->requireAuth($options);
-SimpleSAML_Utilities::redirectTrustedURL($options['ReturnTo']);
+\SimpleSAML\Utils\HTTP::redirectTrustedURL($options['ReturnTo']);
diff --git a/modules/core/www/as_logout.php b/modules/core/www/as_logout.php
index 101c8ed..aa9effe 100644
--- a/modules/core/www/as_logout.php
+++ b/modules/core/www/as_logout.php
@@ -15,4 +15,4 @@ if (!isset($_REQUEST['AuthId']) || !is_string($_REQUEST['AuthId'])) {
}
$as = new SimpleSAML_Auth_Simple($_REQUEST['AuthId']);
-$as->logout(SimpleSAML_Utilities::checkURLAllowed($_REQUEST['ReturnTo']));
+$as->logout(\SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']));
diff --git a/modules/core/www/authenticate.php b/modules/core/www/authenticate.php
index 0e23193..6060950 100644
--- a/modules/core/www/authenticate.php
+++ b/modules/core/www/authenticate.php
@@ -53,6 +53,6 @@ $t->data['header'] = '{status:header_saml20_sp}';
$t->data['attributes'] = $attributes;
// if saml:sp:IdP is set, this is SAML auth so we can pass a NameId
$t->data['nameid'] = !is_null( $as->getAuthData('saml:sp:IdP') ) ? $as->getAuthData('saml:sp:NameID') : FALSE;
-$t->data['logouturl'] = SimpleSAML_Utilities::selfURLNoQuery() . '?as=' . urlencode($asId) . '&logout';
+$t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery() . '?as=' . urlencode($asId) . '&logout';
$t->show();
diff --git a/modules/core/www/cleardiscochoices.php b/modules/core/www/cleardiscochoices.php
index afd7299..0e8dab5 100644
--- a/modules/core/www/cleardiscochoices.php
+++ b/modules/core/www/cleardiscochoices.php
@@ -20,18 +20,18 @@ foreach($_COOKIE as $cookieName => $value) {
/* Delete the cookie. We delete it once without the secure flag and once with the secure flag. This
* ensures that the cookie will be deleted in any case.
*/
- SimpleSAML_Utilities::setCookie($cookieName, NULL, array('path' => $cookiePath, 'httponly' => FALSE), FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($cookieName, NULL, array('path' => $cookiePath, 'httponly' => FALSE), FALSE);
}
/* Find where we should go now. */
if(array_key_exists('ReturnTo', $_REQUEST)) {
- $returnTo = SimpleSAML_Utilities::checkURLAllowed($_REQUEST['ReturnTo']);
+ $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']);
} else {
/* Return to the front page if no other destination is given. This is the same as the base cookie path. */
$returnTo = $cookiePath;
}
/* Redirect to destination. */
-SimpleSAML_Utilities::redirectTrustedURL($returnTo);
+\SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo);
diff --git a/modules/core/www/frontpage_auth.php b/modules/core/www/frontpage_auth.php
index ef4fcaf..2622b1d 100644
--- a/modules/core/www/frontpage_auth.php
+++ b/modules/core/www/frontpage_auth.php
@@ -7,10 +7,10 @@ $session = SimpleSAML_Session::getSessionFromRequest();
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectindexpage', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
-$loginurl = SimpleSAML_Utilities::getAdminLoginURL();
-$isadmin = SimpleSAML_Utilities::isAdmin();
+$loginurl = SimpleSAML\Utils\Auth::getAdminLoginURL();
+$isadmin = SimpleSAML\Utils\Auth::isAdmin();
diff --git a/modules/core/www/frontpage_config.php b/modules/core/www/frontpage_config.php
index 8fc6f37..74c8c61 100644
--- a/modules/core/www/frontpage_config.php
+++ b/modules/core/www/frontpage_config.php
@@ -8,15 +8,15 @@ $session = SimpleSAML_Session::getSessionFromRequest();
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectindexpage', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
-$loginurl = SimpleSAML_Utilities::getAdminLoginURL();
-$isadmin = SimpleSAML_Utilities::isAdmin();
+$loginurl = SimpleSAML\Utils\Auth::getAdminLoginURL();
+$isadmin = SimpleSAML\Utils\Auth::isAdmin();
$warnings = array();
-if (!SimpleSAML_Utilities::isHTTPS()) {
+if (!\SimpleSAML\Utils\HTTP::isHTTPS()) {
$warnings[] = '{core:frontpage:warnings_https}';
}
@@ -44,12 +44,12 @@ $links_federation = array();
$links_config[] = array(
- 'href' => SimpleSAML_Utilities::getBaseURL() . 'admin/hostnames.php',
+ 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/hostnames.php',
'text' => '{core:frontpage:link_diagnostics}'
);
$links_config[] = array(
- 'href' => SimpleSAML_Utilities::getBaseURL() . 'admin/phpinfo.php',
+ 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/phpinfo.php',
'text' => '{core:frontpage:link_phpinfo}'
);
diff --git a/modules/core/www/frontpage_federation.php b/modules/core/www/frontpage_federation.php
index 512061e..aab31a5 100644
--- a/modules/core/www/frontpage_federation.php
+++ b/modules/core/www/frontpage_federation.php
@@ -8,10 +8,10 @@ $session = SimpleSAML_Session::getSessionFromRequest();
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectindexpage', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
-$loginurl = SimpleSAML_Utilities::getAdminLoginURL();
-$isadmin = SimpleSAML_Utilities::isAdmin();
+$loginurl = SimpleSAML\Utils\Auth::getAdminLoginURL();
+$isadmin = SimpleSAML\Utils\Auth::isAdmin();
@@ -37,7 +37,7 @@ if($config->getBoolean('idpdisco.enableremember', FALSE)) {
$links_federation[] = array(
- 'href' => SimpleSAML_Utilities::getBaseURL() . 'admin/metadata-converter.php',
+ 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/metadata-converter.php',
'text' => '{core:frontpage:link_xmlconvert}',
);
diff --git a/modules/core/www/frontpage_welcome.php b/modules/core/www/frontpage_welcome.php
index 281237a..4fb5227 100644
--- a/modules/core/www/frontpage_welcome.php
+++ b/modules/core/www/frontpage_welcome.php
@@ -7,10 +7,10 @@ $session = SimpleSAML_Session::getSessionFromRequest();
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectindexpage', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
-$loginurl = SimpleSAML_Utilities::getAdminLoginURL();
-$isadmin = SimpleSAML_Utilities::isAdmin();
+$loginurl = SimpleSAML\Utils\Auth::getAdminLoginURL();
+$isadmin = SimpleSAML\Utils\Auth::isAdmin();
diff --git a/modules/core/www/login-admin.php b/modules/core/www/login-admin.php
index 3e6438f..22bc785 100644
--- a/modules/core/www/login-admin.php
+++ b/modules/core/www/login-admin.php
@@ -7,7 +7,7 @@ if (!array_key_exists('ReturnTo', $_REQUEST)) {
throw new SimpleSAML_Error_BadRequest('Missing ReturnTo parameter.');
}
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
-SimpleSAML_Utilities::redirectUntrustedURL($_REQUEST['ReturnTo']);
+\SimpleSAML\Utils\HTTP::redirectUntrustedURL($_REQUEST['ReturnTo']);
diff --git a/modules/core/www/loginuserpass.php b/modules/core/www/loginuserpass.php
index 4ce0f93..f253ac5 100644
--- a/modules/core/www/loginuserpass.php
+++ b/modules/core/www/loginuserpass.php
@@ -53,7 +53,7 @@ if (!empty($_REQUEST['username']) || !empty($password)) {
$params = $sessionHandler->getCookieParams();
$params['expire'] = time();
$params['expire'] += (isset($_REQUEST['remember_username']) && $_REQUEST['remember_username'] == 'Yes' ? 31536000 : -300);
- SimpleSAML_Utilities::setCookie($source->getAuthId() . '-username', $username, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId() . '-username', $username, $params, FALSE);
}
if ($source->isRememberMeEnabled()) {
diff --git a/modules/core/www/loginuserpassorg.php b/modules/core/www/loginuserpassorg.php
index ad4ba44..441f046 100644
--- a/modules/core/www/loginuserpassorg.php
+++ b/modules/core/www/loginuserpassorg.php
@@ -57,7 +57,7 @@ if ($organizations === NULL || !empty($organization)) {
$params = $sessionHandler->getCookieParams();
$params['expire'] = time();
$params['expire'] += (isset($_REQUEST['remember_username']) && $_REQUEST['remember_username'] == 'Yes' ? 31536000 : -300);
- SimpleSAML_Utilities::setCookie($source->getAuthId() . '-username', $username, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId() . '-username', $username, $params, FALSE);
}
try {
diff --git a/modules/core/www/no_cookie.php b/modules/core/www/no_cookie.php
index a81055a..36aad7a 100644
--- a/modules/core/www/no_cookie.php
+++ b/modules/core/www/no_cookie.php
@@ -2,7 +2,7 @@
if (isset($_REQUEST['retryURL'])) {
$retryURL = (string)$_REQUEST['retryURL'];
- $retryURL = SimpleSAML_Utilities::normalizeURL($retryURL);
+ $retryURL = \SimpleSAML\Utils\HTTP::normalizeURL($retryURL);
} else {
$retryURL = NULL;
}
diff --git a/modules/core/www/postredirect.php b/modules/core/www/postredirect.php
index 9180bdf..3daa0cd 100644
--- a/modules/core/www/postredirect.php
+++ b/modules/core/www/postredirect.php
@@ -16,7 +16,7 @@ if (array_key_exists('RedirId', $_REQUEST)) {
throw new SimpleSAML_Error_BadRequest('Invalid RedirInfo data.');
}
- list($sessionId, $postId) = explode(':', SimpleSAML_Utilities::aesDecrypt($encData));
+ list($sessionId, $postId) = explode(':', SimpleSAML\Utils\Crypto::aesDecrypt($encData));
if (empty($sessionId) || empty($postId)) {
throw new SimpleSAML_Error_BadRequest('Invalid session info data.');
diff --git a/modules/core/www/show_metadata.php b/modules/core/www/show_metadata.php
index b2e9d96..8c20104 100644
--- a/modules/core/www/show_metadata.php
+++ b/modules/core/www/show_metadata.php
@@ -6,7 +6,7 @@
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
if (!array_key_exists('entityid', $_REQUEST))
@@ -21,10 +21,6 @@ $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$m = $metadata->getMetadata($_REQUEST['entityid'], $_REQUEST['set']);
-// echo('<pre>'); print_r($m);
-// exit;
-
-
$t = new SimpleSAML_XHTML_Template($config, 'core:show_metadata.tpl.php');
$t->data['pageid'] = 'show_metadata';
$t->data['header'] = 'simpleSAMLphp Show Metadata';
diff --git a/modules/cron/www/cron.php b/modules/cron/www/cron.php
index 3180ca5..682c242 100644
--- a/modules/cron/www/cron.php
+++ b/modules/cron/www/cron.php
@@ -22,7 +22,7 @@ $croninfo = array(
'summary' => &$summary,
'tag' => $_REQUEST['tag'],
);
-$url = SimpleSAML_Utilities::selfURL();
+$url = \SimpleSAML\Utils\HTTP::getSelfURL();
$time = date(DATE_RFC822);
SimpleSAML_Module::callHooks('cron', $croninfo);
diff --git a/modules/cron/www/croninfo.php b/modules/cron/www/croninfo.php
index 6be04eb..204f607 100644
--- a/modules/cron/www/croninfo.php
+++ b/modules/cron/www/croninfo.php
@@ -11,7 +11,7 @@ require_once('_include.php');
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
$cronconfig = SimpleSAML_Configuration::getConfig('module_cron.php');
diff --git a/modules/discojuice/templates/central.tpl.php b/modules/discojuice/templates/central.tpl.php
index 8067e16..0695b67 100644
--- a/modules/discojuice/templates/central.tpl.php
+++ b/modules/discojuice/templates/central.tpl.php
@@ -42,9 +42,6 @@ header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT
json_encode($this->data['hostedConfig'][4]) .
');';
- // echo " djc.country = false;\n";
- // echo " djc.showLocationInfo = false;\n";
-
if (!$this->data['enableCentralStorage']) {
echo " delete djc.disco;\n";
}
diff --git a/modules/discojuice/www/central.php b/modules/discojuice/www/central.php
index 6f1a7ea..9404fd5 100644
--- a/modules/discojuice/www/central.php
+++ b/modules/discojuice/www/central.php
@@ -12,7 +12,7 @@ $entityid = $_REQUEST['entityID'];
// Return to...
$returnidparam = !empty($_REQUEST['returnIDParam']) ? $_REQUEST['returnIDParam'] : 'entityID';
-$href = SimpleSAML_Utilities::addURLparameter(
+$href = \SimpleSAML\Utils\HTTP::addURLParameters(
$_REQUEST['return'],
array($returnidparam => '')
);
diff --git a/modules/discopower/lib/PowerIdPDisco.php b/modules/discopower/lib/PowerIdPDisco.php
index 0702141..44f4813 100644
--- a/modules/discopower/lib/PowerIdPDisco.php
+++ b/modules/discopower/lib/PowerIdPDisco.php
@@ -99,7 +99,6 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
* This function will structure the idp list in a hierarchy based upon the tags.
*/
protected function idplistStructured($list) {
- # echo '<pre>'; print_r($list); exit;
$slist = array();
$order = $this->discoconfig->getValue('taborder');
@@ -192,7 +191,7 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
$extDiscoveryStorage = $this->config->getString('idpdisco.extDiscoveryStorage',NULL);
if ($extDiscoveryStorage !== NULL) {
$this->log('Choice made [' . $idp . '] (Forwarding to external discovery storage)');
- SimpleSAML_Utilities::redirectTrustedURL($extDiscoveryStorage, array(
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($extDiscoveryStorage, array(
'entityID' => $this->spEntityId,
'IdPentityID' => $idp,
'returnIDParam' => $this->returnIdParam,
@@ -202,7 +201,7 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
} else {
$this->log('Choice made [' . $idp . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')');
- SimpleSAML_Utilities::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idp));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idp));
}
return;
@@ -210,7 +209,7 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
if ($this->isPassive) {
$this->log('Choice not made. (Redirecting the user back without answer)');
- SimpleSAML_Utilities::redirectTrustedURL($this->returnURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL);
return;
}
@@ -225,7 +224,7 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
$t->data['return'] = $this->returnURL;
$t->data['returnIDParam'] = $this->returnIdParam;
$t->data['entityID'] = $this->spEntityId;
- $t->data['urlpattern'] = htmlspecialchars(SimpleSAML_Utilities::selfURLNoQuery());
+ $t->data['urlpattern'] = htmlspecialchars(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery());
$t->data['rememberenabled'] = $this->config->getBoolean('idpdisco.enableremember', FALSE);
$t->data['rememberchecked'] = $this->config->getBoolean('idpdisco.rememberchecked', FALSE);
$t->data['defaulttab'] = $this->discoconfig->getValue('defaulttab', 0);
@@ -307,7 +306,7 @@ class sspmod_discopower_PowerIdPDisco extends SimpleSAML_XHTML_IdPDisco {
'secure' => TRUE,
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie('_saml_idp', $newCookie, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie('_saml_idp', $newCookie, $params, FALSE);
}
diff --git a/modules/discopower/templates/disco-tpl.php b/modules/discopower/templates/disco-tpl.php
index f3c9814..ef1ec7d 100644
--- a/modules/discopower/templates/disco-tpl.php
+++ b/modules/discopower/templates/disco-tpl.php
@@ -50,17 +50,6 @@ if (!empty($faventry)) $this->data['autofocus'] = 'favouritesubmit';
$this->includeAtTemplateBase('includes/header.php');
-// foreach ($this->data['idplist'] AS $slist) {
-// foreach ($slist AS $idpentry) {
-// if (isset($idpentry['name']))
-// $this->includeInlineTranslation('idpname_' . $idpentry['entityid'], $idpentry['name']);
-// if (isset($idpentry['description']))
-// $this->includeInlineTranslation('idpdesc_' . $idpentry['entityid'], $idpentry['description']);
-// }
-// }
-//
-
-
function showEntry($t, $metadata, $favourite = FALSE) {
$basequerystring = '?' .
@@ -73,21 +62,11 @@ function showEntry($t, $metadata, $favourite = FALSE) {
$html .= '' . htmlspecialchars(getTranslatedName($t, $metadata)) . '';
- #print_r($metadata['scopes']);
-
- // if (!empty($idpentry['description'])) {
- // $html .= ' <p>' . htmlspecialchars($t->t('idpdesc_' . $metadata['entityid'])) . '<br />';
- // }
-
if(array_key_exists('icon', $metadata) && $metadata['icon'] !== NULL) {
- $iconUrl = SimpleSAML_Utilities::resolveURL($metadata['icon']);
+ $iconUrl = \SimpleSAML\Utils\HTTP::resolveURL($metadata['icon']);
$html .= '<img alt="Icon for identity provider" class="entryicon" src="' . htmlspecialchars($iconUrl) . '" />';
}
-
- // $html .= '<input id="preferredidp" type="submit" name="idp_' .
- // htmlspecialchars($metadata['entityid']) . '" value="' .
- // $t->t('select') . '" /></p>';
-
+
$html .= '</a>';
return $html;
@@ -101,7 +80,6 @@ function showEntry($t, $metadata, $favourite = FALSE) {
<?php
function getTranslatedName($t, $metadata) {
-# if (is_null($metadata)) throw new Exception();
if (isset($metadata['UIInfo']['DisplayName'])) {
$displayName = $metadata['UIInfo']['DisplayName'];
assert('is_array($displayName)'); // Should always be an array of language code -> translation.
@@ -176,10 +154,6 @@ foreach( $this->data['idplist'] AS $tab => $slist) {
echo '<div id="' . $tab . '">';
if (!empty($slist)) {
-
- // echo 'Favourite :: ' . $this->data['preferredidp'];
- // echo '<pre>';
- // print_r($slist); exit;
echo(' <div class="inlinesearch">');
echo(' <p>Incremental search...</p>');
diff --git a/modules/exampleauth/lib/Auth/Process/RedirectTest.php b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
index 79e5293..28751cd 100644
--- a/modules/exampleauth/lib/Auth/Process/RedirectTest.php
+++ b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
@@ -22,7 +22,7 @@ class sspmod_exampleauth_Auth_Process_RedirectTest extends SimpleSAML_Auth_Proce
/* Save state and redirect. */
$id = SimpleSAML_Auth_State::saveState($state, 'exampleauth:redirectfilter-test');
$url = SimpleSAML_Module::getModuleURL('exampleauth/redirecttest.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
}
diff --git a/modules/exampleauth/lib/Auth/Source/External.php b/modules/exampleauth/lib/Auth/Source/External.php
index 3703852..22cc4e2 100644
--- a/modules/exampleauth/lib/Auth/Source/External.php
+++ b/modules/exampleauth/lib/Auth/Source/External.php
@@ -155,7 +155,7 @@ class sspmod_exampleauth_Auth_Source_External extends SimpleSAML_Auth_Source {
* Note the 'ReturnTo' parameter. This must most likely be replaced with
* the real name of the parameter for the login page.
*/
- SimpleSAML_Utilities::redirectTrustedURL($authPage, array(
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($authPage, array(
'ReturnTo' => $returnTo,
));
diff --git a/modules/exampleauth/lib/Auth/Source/Static.php b/modules/exampleauth/lib/Auth/Source/Static.php
index 68ddf57..8355442 100644
--- a/modules/exampleauth/lib/Auth/Source/Static.php
+++ b/modules/exampleauth/lib/Auth/Source/Static.php
@@ -34,7 +34,7 @@ class sspmod_exampleauth_Auth_Source_Static extends SimpleSAML_Auth_Source {
/* Parse attributes. */
try {
- $this->attributes = SimpleSAML_Utilities::parseAttributes($config);
+ $this->attributes = SimpleSAML\Utils\Arrays::normalizeAttributesArray($config);
} catch(Exception $e) {
throw new Exception('Invalid attributes for authentication source ' .
$this->authId . ': ' . $e->getMessage());
diff --git a/modules/exampleauth/lib/Auth/Source/UserPass.php b/modules/exampleauth/lib/Auth/Source/UserPass.php
index f34bc33..1b380de 100644
--- a/modules/exampleauth/lib/Auth/Source/UserPass.php
+++ b/modules/exampleauth/lib/Auth/Source/UserPass.php
@@ -50,7 +50,7 @@ class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassB
$password = $userpass[1];
try {
- $attributes = SimpleSAML_Utilities::parseAttributes($attributes);
+ $attributes = SimpleSAML\Utils\Arrays::normalizeAttributesArray($attributes);
} catch(Exception $e) {
throw new Exception('Invalid attributes for user ' . $username .
' in authentication source ' . $this->authId . ': ' .
diff --git a/modules/exampleauth/www/authpage.php b/modules/exampleauth/www/authpage.php
index 7b3dca2..fa77c9f 100644
--- a/modules/exampleauth/www/authpage.php
+++ b/modules/exampleauth/www/authpage.php
@@ -13,7 +13,7 @@ if (!isset($_REQUEST['ReturnTo'])) {
die('Missing ReturnTo parameter.');
}
-$returnTo = SimpleSAML_Utilities::checkURLAllowed($_REQUEST['ReturnTo']);
+$returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']);
/*
@@ -85,7 +85,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['mail'] = $user['mail'];
$_SESSION['type'] = $user['type'];
- SimpleSAML_Utilities::redirectTrustedURL($returnTo);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo);
}
}
diff --git a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
index 45a3719..9d04d76 100644
--- a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
+++ b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
@@ -76,7 +76,6 @@ class sspmod_expirycheck_Auth_Process_ExpiryDate extends SimpleSAML_Auth_Process
*
*/
public function shWarning(&$state, $expireOnDate, $warndaysbefore) {
- #date_default_timezone_set('Europe/Ljubljana');
$now = time();
$end = $expireOnDate;
@@ -135,12 +134,12 @@ class sspmod_expirycheck_Auth_Process_ExpiryDate extends SimpleSAML_Auth_Process
$state['netId'] = $netId;
$id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:about2expire');
$url = SimpleSAML_Module::getModuleURL('expirycheck/about2expire.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
if (!self::checkDate($expireOnDate)) {
SimpleSAML_Logger::error('expirycheck: NetID ' . $netId .
- ' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!');
+ ' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!');
$globalConfig = SimpleSAML_Configuration::getInstance();
/* Save state and redirect. */
@@ -148,7 +147,7 @@ class sspmod_expirycheck_Auth_Process_ExpiryDate extends SimpleSAML_Auth_Process
$state['netId'] = $netId;
$id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:expired');
$url = SimpleSAML_Module::getModuleURL('expirycheck/expired.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
}
diff --git a/modules/expirycheck/templates/about2expire.php b/modules/expirycheck/templates/about2expire.php
index 6b7752d..f695cdb 100644
--- a/modules/expirycheck/templates/about2expire.php
+++ b/modules/expirycheck/templates/about2expire.php
@@ -16,9 +16,6 @@
* @package simpleSAMLphp
*/
-
-//$this->data['header'] = $this->t('{expirycheck:expwarning:warning_header}');
-
# netid will expire today
if ($this->data['daysleft'] == 0) {
$this->data['header'] = $this->t('{expirycheck:expwarning:warning_header_today}', array(
@@ -63,7 +60,6 @@ else {
}
-//$this->data['header'] = str_replace("%DAYSLEFT%", $this->data['daysleft'], str_replace("%NETID%", $this->data['netId'], $this->t('{expirycheck:expwarning:warning_header}')));
$this->data['autofocus'] = 'yesbutton';
$this->includeAtTemplateBase('includes/header.php');
diff --git a/modules/logpeek/lib/File/reverseRead.php b/modules/logpeek/lib/File/reverseRead.php
index 26a1ac1..501c0d2 100644
--- a/modules/logpeek/lib/File/reverseRead.php
+++ b/modules/logpeek/lib/File/reverseRead.php
@@ -83,9 +83,7 @@ class sspmod_logpeek_File_reverseRead{
fseek($this->fileHandle, $this->blockStart, SEEK_SET);
$buff = fread($this->fileHandle, $splits);
-
- // $buff = stream_get_contents($this->fileHandle, $splits, $this->blockStart);
-
+
return $buff;
}
@@ -153,7 +151,7 @@ class sspmod_logpeek_File_reverseRead{
$pos++;
$cnt++;
}
- return $pos == false? false: substr($haystack, $pos, strlen($haystack));
+ return ($pos === false) ? false : substr($haystack, $pos, strlen($haystack));
}
@@ -182,7 +180,6 @@ class sspmod_logpeek_File_reverseRead{
}
return $lastLines;
- // return str_replace("\r", '', implode('', array_reverse($buff1)));
}
diff --git a/modules/logpeek/www/index.php b/modules/logpeek/www/index.php
index 9c76357..a0d8152 100644
--- a/modules/logpeek/www/index.php
+++ b/modules/logpeek/www/index.php
@@ -21,7 +21,7 @@ function logFilter($objFile, $tag, $cut){
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
$logpeekconfig = SimpleSAML_Configuration::getConfig('module_logpeek.php');
$logfile = $logpeekconfig->getValue('logfile', '/var/simplesamlphp.log');
diff --git a/modules/memcacheMonitor/templates/memcachestat.tpl.php b/modules/memcacheMonitor/templates/memcachestat.tpl.php
index a3e2d10..e763fed 100644
--- a/modules/memcacheMonitor/templates/memcachestat.tpl.php
+++ b/modules/memcacheMonitor/templates/memcachestat.tpl.php
@@ -58,7 +58,6 @@ foreach($column_titles as $ct) {
foreach($table as $row_title => $row_data) {
echo '<tr>' . "\n";
echo '<th class="rowtitle" style="text-align: right">' . $this->t('{memcacheMonitor:memcachestat:' . $row_title . '}') . '</th>' . "\n";
-# echo '<th class="rowtitle" style="text-align: right">' . $row_title . '</th>' . "\n";
foreach($column_titles as $ct) {
echo '<td>';
@@ -77,10 +76,6 @@ foreach($table as $row_title => $row_data) {
</table>
<?php
-
-
-#echo('<pre>'); print_r($this->data['statsraw']); exit;
-
if (array_key_exists('bytes', $this->data['statsraw']) && array_key_exists('limit_maxbytes', $this->data['statsraw'])) {
foreach($this->data['statsraw']['bytes'] as $key => $row_data) {
echo ('<h3>Storage usage on [' . $key . ']</h3>');
@@ -93,9 +88,4 @@ if (array_key_exists('bytes', $this->data['statsraw']) && array_key_exists('limi
}
}
-?>
-
-
-
-<?php
$this->includeAtTemplateBase('includes/footer.php');
diff --git a/modules/memcacheMonitor/www/memcachestat.php b/modules/memcacheMonitor/www/memcachestat.php
index 40a2efa..d925e2c 100644
--- a/modules/memcacheMonitor/www/memcachestat.php
+++ b/modules/memcacheMonitor/www/memcachestat.php
@@ -75,7 +75,7 @@ function humanreadable($input) {
$config = SimpleSAML_Configuration::getInstance();
/* Make sure that the user has admin access rights. */
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
$formats = array(
diff --git a/modules/metaedit/config-template/module_metaedit.php b/modules/metaedit/config-template/module_metaedit.php
index f482280..696880e 100644
--- a/modules/metaedit/config-template/module_metaedit.php
+++ b/modules/metaedit/config-template/module_metaedit.php
@@ -4,7 +4,6 @@
*/
$config = array (
- 'admins' => array('andreas@rnd.feide.no'),
'metahandlerConfig' => array('directory' => 'metadata/metaedit'),
'auth' => 'saml2',
'useridattr' => 'eduPersonPrincipalName',
diff --git a/modules/metaedit/lib/MetaEditor.php b/modules/metaedit/lib/MetaEditor.php
index f922be8..e2d2d6e 100644
--- a/modules/metaedit/lib/MetaEditor.php
+++ b/modules/metaedit/lib/MetaEditor.php
@@ -38,7 +38,6 @@ class sspmod_metaedit_MetaEditor {
$this->getStandardField($request, $metadata, 'description');
$this->getEndpointField($request, $metadata, 'AssertionConsumerService', SAML2_Const::BINDING_HTTP_POST, TRUE);
$this->getEndpointField($request, $metadata, 'SingleLogoutService', SAML2_Const::BINDING_HTTP_REDIRECT, FALSE);
- // $this->getStandardField($request, $metadata, 'certFingerprint');
$metadata['updated'] = time();
if ($override) {
@@ -109,8 +108,6 @@ class sspmod_metaedit_MetaEditor {
if (array_key_exists($key, $metadata)) {
$value = htmlspecialchars($metadata[$key]);
}
- #echo '<tr><td><pre>'; print_r($metadata); echo '</pre></td></tr>';
-
if ($textarea) {
return '<tr><td class="name">' . $name . '</td><td class="data">
<textarea name="field_' . $key . '" rows="5" cols="50">' . $value . '</textarea></td></tr>';
@@ -156,10 +153,7 @@ class sspmod_metaedit_MetaEditor {
'<div id="tabdiv">' .
'<ul>' .
'<li><a href="#basic">Name and descrition</a></li>' .
- '<li><a href="#saml">SAML 2.0</a></li>' .
- // '<li><a href="#attributes">Attributes</a></li>' .
- // '<li><a href="#orgs">Organizations</a></li>' .
- // '<li><a href="#contacts">Contacts</a></li>' .
+ '<li><a href="#saml">SAML 2.0</a></li>' .
'</ul>' .
'<div id="basic"><table class="formtable">' .
$this->standardField($metadata, 'entityid', 'EntityID') .
@@ -172,8 +166,6 @@ class sspmod_metaedit_MetaEditor {
'</table></div><div id="saml"><table class="formtable">' .
$this->endpointField($metadata, 'AssertionConsumerService', 'AssertionConsumerService endpoint') .
$this->endpointField($metadata, 'SingleLogoutService', 'SingleLogoutService endpoint') .
- // $this->standardField($metadata, 'certFingerprint', 'Certificate Fingerprint') .
-
'</table></div>' .
'</div>' .
'<input type="submit" name="submit" value="Save" style="margin-top: 5px" />' .
diff --git a/modules/metaedit/templates/metalist.php b/modules/metaedit/templates/metalist.php
index 368fe78..04b39cd 100644
--- a/modules/metaedit/templates/metalist.php
+++ b/modules/metaedit/templates/metalist.php
@@ -2,12 +2,6 @@
$this->data['jquery'] = array('version' => '1.6', 'core' => TRUE, 'ui' => TRUE, 'css' => TRUE);
$this->data['head'] = '<link rel="stylesheet" type="text/css" href="/' . $this->data['baseurlpath'] . 'module.php/metaedit/resources/style.css" />' . "\n";
-// $this->data['head'] .= '<script type="text/javascript">
-// $(document).ready(function() {
-// $("#tabdiv").tabs();
-// });
-// </script>';
-
$this->includeAtTemplateBase('includes/header.php');
diff --git a/modules/metaedit/templates/xmlimport.tpl.php b/modules/metaedit/templates/xmlimport.tpl.php
index 59ca4b8..68f046c 100644
--- a/modules/metaedit/templates/xmlimport.tpl.php
+++ b/modules/metaedit/templates/xmlimport.tpl.php
@@ -1,16 +1,6 @@
<?php
-
-// $this->data['jquery'] = array('version' => '1.6', 'core' => TRUE, 'ui' => TRUE, 'css' => TRUE);
-// $this->data['head'] = '<link rel="stylesheet" type="text/css" href="/' . $this->data['baseurlpath'] . 'module.php/metaedit/resources/style.css" />' . "\n";
-// $this->data['head'] .= '<script type="text/javascript">
-// $(document).ready(function() {
-// $("#tabdiv").tabs();
-// });
-// </script>';
-
$this->includeAtTemplateBase('includes/header.php');
-
echo('<h1>Import SAML 2.0 XML Metadata</h1>');
echo('<form method="post" action="edit.php">');
diff --git a/modules/metaedit/www/edit.php b/modules/metaedit/www/edit.php
index ea110f5..8a89c2b 100644
--- a/modules/metaedit/www/edit.php
+++ b/modules/metaedit/www/edit.php
@@ -31,16 +31,14 @@ if (array_key_exists('entityid', $_REQUEST)) {
} elseif(array_key_exists('xmlmetadata', $_REQUEST)) {
$xmldata = $_REQUEST['xmlmetadata'];
- SimpleSAML_Utilities::validateXMLDocument($xmldata, 'saml-meta');
+ \SimpleSAML\Utils\XML::checkSAMLMessage($xmldata, 'saml-meta');
$entities = SimpleSAML_Metadata_SAMLParser::parseDescriptorsString($xmldata);
$entity = array_pop($entities);
$metadata = $entity->getMetadata20SP();
/* Trim metadata endpoint arrays. */
- $metadata['AssertionConsumerService'] = array(SimpleSAML_Utilities::getDefaultEndpoint($metadata['AssertionConsumerService'], array(SAML2_Const::BINDING_HTTP_POST)));
- $metadata['SingleLogoutService'] = array(SimpleSAML_Utilities::getDefaultEndpoint($metadata['SingleLogoutService'], array(SAML2_Const::BINDING_HTTP_REDIRECT)));
-
- #echo '<pre>'; print_r($metadata); exit;
+ $metadata['AssertionConsumerService'] = array(\SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint($metadata['AssertionConsumerService'], array(SAML2_Const::BINDING_HTTP_POST)));
+ $metadata['SingleLogoutService'] = array(\SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint($metadata['SingleLogoutService'], array(SAML2_Const::BINDING_HTTP_REDIRECT)));
} else {
$metadata = array(
diff --git a/modules/metarefresh/bin/metarefresh.php b/modules/metarefresh/bin/metarefresh.php
index fd51caa..2e351f3 100755
--- a/modules/metarefresh/bin/metarefresh.php
+++ b/modules/metarefresh/bin/metarefresh.php
@@ -144,8 +144,6 @@ if($toStdOut) {
$metaloader->writeMetadataFiles($outputDir);
}
-exit(0);
-
/**
* This function prints the help output.
*/
@@ -178,8 +176,3 @@ function printHelp() {
echo(' seperate files in the output directory.' . "\n");
echo("\n");
}
-
-
-
-
-
diff --git a/modules/metarefresh/lib/ARP.php b/modules/metarefresh/lib/ARP.php
index ddcfc85..b9a9d7d 100644
--- a/modules/metarefresh/lib/ARP.php
+++ b/modules/metarefresh/lib/ARP.php
@@ -29,8 +29,6 @@ class sspmod_metarefresh_ARP {
$config = SimpleSAML_Configuration::getInstance();
include($config->getPathValue('attributemap', 'attributemap/') . $attributemap . '.php');
$this->attributes = $attributemap;
-
- # print_r($attributemap); exit;
}
private function surround($name) {
@@ -64,7 +62,6 @@ class sspmod_metarefresh_ARP {
foreach($this->metadata AS $metadata) {
- #$print_r($metadata); exit;
$xml .= $this->getEntryXML($metadata['metadata']);
}
diff --git a/modules/metarefresh/lib/MetaLoader.php b/modules/metarefresh/lib/MetaLoader.php
index 24790fd..3f09817 100644
--- a/modules/metarefresh/lib/MetaLoader.php
+++ b/modules/metarefresh/lib/MetaLoader.php
@@ -50,7 +50,7 @@ class sspmod_metarefresh_MetaLoader {
// GET!
try {
- list($data, $responseHeaders) = SimpleSAML_Utilities::fetch($source['src'], $context, TRUE);
+ list($data, $responseHeaders) = \SimpleSAML\Utils\HTTP::fetch($source['src'], $context, TRUE);
} catch(Exception $e) {
SimpleSAML_Logger::warning('metarefresh: ' . $e->getMessage());
}
@@ -180,7 +180,6 @@ class sspmod_metarefresh_MetaLoader {
foreach($this->oldMetadataSrc->getMetadataSet($type) as $entity) {
if(array_key_exists('metarefresh:src', $entity)) {
if($entity['metarefresh:src'] == $source['src']) {
- //SimpleSAML_Logger::debug('Re-using cached metadata for ' . $entity['entityid']);
$this->addMetadata($source['src'], $entity, $type);
}
}
@@ -238,7 +237,7 @@ class sspmod_metarefresh_MetaLoader {
public function writeState() {
if($this->changed) {
SimpleSAML_Logger::debug('Writing: ' . $this->stateFile);
- SimpleSAML_Utilities::writeFile(
+ SimpleSAML\Utils\System::writeFile(
$this->stateFile,
"<?php\n/* This file was generated by the metarefresh module at ".$this->getTime() . ".\n".
" Do not update it manually as it will get overwritten. */\n".
@@ -291,10 +290,6 @@ class sspmod_metarefresh_MetaLoader {
}
if (isset($template)) {
-// foreach($metadata AS $mkey => $mentry) {
-// echo '<pre>'; print_r($metadata); exit;
-// $metadata[$mkey] = array_merge($mentry, $template);
-// }
$metadata = array_merge($metadata, $template);
}
@@ -341,7 +336,7 @@ class sspmod_metarefresh_MetaLoader {
$md = array_merge($md, $elements);
}
- #$metadata, $attributemap, $prefix, $suffix
+ // $metadata, $attributemap, $prefix, $suffix
$arp = new sspmod_metarefresh_ARP($md,
$config->getValue('attributemap', ''),
$config->getValue('prefix', ''),
@@ -393,7 +388,7 @@ class sspmod_metarefresh_MetaLoader {
$content .= "\n" . '?>';
- SimpleSAML_Utilities::writeFile($filename, $content, 0644);
+ SimpleSAML\Utils\System::writeFile($filename, $content, 0644);
} elseif(is_file($filename)) {
if(unlink($filename)) {
SimpleSAML_Logger::debug('Deleting stale metadata file: ' . $filename);
diff --git a/modules/metarefresh/www/fetch.php b/modules/metarefresh/www/fetch.php
index a2739b8..322c344 100644
--- a/modules/metarefresh/www/fetch.php
+++ b/modules/metarefresh/www/fetch.php
@@ -3,7 +3,7 @@
$config = SimpleSAML_Configuration::getInstance();
$mconfig = SimpleSAML_Configuration::getOptionalConfig('config-metarefresh.php');
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
SimpleSAML_Logger::setCaptureLog(TRUE);
diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php
index de7fcd4..0235cda 100644
--- a/modules/multiauth/lib/Auth/Source/MultiAuth.php
+++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php
@@ -120,7 +120,7 @@ class sspmod_multiauth_Auth_Source_MultiAuth extends SimpleSAML_Auth_Source {
$params['source'] = $_GET['source'];
}
- SimpleSAML_Utilities::redirectTrustedURL($url, $params);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
/* The previous function never returns, so this code is never
executed */
@@ -208,7 +208,7 @@ class sspmod_multiauth_Auth_Source_MultiAuth extends SimpleSAML_Auth_Source {
'httponly' => FALSE,
);
- SimpleSAML_Utilities::setCookie($cookieName, $source, $params, FALSE);
+ \SimpleSAML\Utils\HTTP::setCookie($cookieName, $source, $params, FALSE);
}
/**
diff --git a/modules/negotiate/lib/Auth/Source/Negotiate.php b/modules/negotiate/lib/Auth/Source/Negotiate.php
index a29a0c2..7a33027 100644
--- a/modules/negotiate/lib/Auth/Source/Negotiate.php
+++ b/modules/negotiate/lib/Auth/Source/Negotiate.php
@@ -75,15 +75,15 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source {
// Check for disabled SPs. The disable flag is store in the SP
// metadata.
- if (array_key_exists('SPMetadata', $state) and $this->spDisabledInMetadata($state['SPMetadata']))
+ if (array_key_exists('SPMetadata', $state) && $this->spDisabledInMetadata($state['SPMetadata']))
$this->fallBack($state);
// Go straight to fallback if Negotiate is disabled or if you are
// sent back to the IdP directly from the SP after having logged out
$session = SimpleSAML_Session::getSessionFromRequest();
$disabled = $session->getData('negotiate:disable', 'session');
- if ($disabled or
- (!empty($_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT']) and
+ if ($disabled ||
+ (!empty($_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT']) &&
$_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT'] == 'True')) {
SimpleSAML_Logger::debug('Negotiate - session disabled. falling back');
$this->fallBack($state);
@@ -160,9 +160,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source {
if (array_key_exists('negotiate:disable', $spMetadata)) {
if ($spMetadata['negotiate:disable'] == TRUE) {
SimpleSAML_Logger::debug('Negotiate - SP disabled. falling back');
- return True;
- // Never executed
- assert('FALSE');
+ return true;
} else {
SimpleSAML_Logger::debug('Negotiate - SP disable flag found but set to FALSE');
}
@@ -186,7 +184,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends SimpleSAML_Auth_Source {
return TRUE;
$ip = $_SERVER['REMOTE_ADDR'];
foreach ($this->subnet as $cidr) {
- $ret = SimpleSAML_Utilities::ipCIDRcheck($cidr);
+ $ret = SimpleSAML\Utils\Net::ipCIDRcheck($cidr);
if ($ret) {
SimpleSAML_Logger::debug('Negotiate: Client "'.$ip.'" matched subnet.');
return TRUE;
diff --git a/modules/negotiate/www/disable.php b/modules/negotiate/www/disable.php
index 1cda47e..5262004 100644
--- a/modules/negotiate/www/disable.php
+++ b/modules/negotiate/www/disable.php
@@ -13,7 +13,7 @@ $params = array(
'secure' => FALSE,
'httponly' => TRUE,
);
-SimpleSAML_Utilities::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', 'True', $params, FALSE);
+\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', 'True', $params, FALSE);
$globalConfig = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
diff --git a/modules/negotiate/www/enable.php b/modules/negotiate/www/enable.php
index 0eda573..56d66a8 100644
--- a/modules/negotiate/www/enable.php
+++ b/modules/negotiate/www/enable.php
@@ -12,7 +12,7 @@ $params = array(
'secure' => FALSE,
'httponly' => TRUE,
);
-SimpleSAML_Utilities::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', NULL, $params, FALSE);
+\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', NULL, $params, FALSE);
$globalConfig = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
diff --git a/modules/oauth/bin/demo.php b/modules/oauth/bin/demo.php
index b1dcf52..f224ac3 100755
--- a/modules/oauth/bin/demo.php
+++ b/modules/oauth/bin/demo.php
@@ -22,7 +22,6 @@ try {
// Needed in order to make session_start to be called before output is printed.
$session = SimpleSAML_Session::getSessionFromRequest();
- //$baseurl = (isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : 'https://foodle.feide.no/simplesaml');
$baseurl = (isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : 'http://mars.foodle.local/simplesaml');
$key = (isset($_SERVER['argv'][2]) ? $_SERVER['argv'][2] : 'key');
$secret = (isset($_SERVER['argv'][3]) ? $_SERVER['argv'][3] : 'secret');
diff --git a/modules/oauth/lib/Consumer.php b/modules/oauth/lib/Consumer.php
index 6a16841..f17640c 100644
--- a/modules/oauth/lib/Consumer.php
+++ b/modules/oauth/lib/Consumer.php
@@ -91,9 +91,9 @@ class sspmod_oauth_Consumer {
if ($callback) {
$params['oauth_callback'] = $callback;
}
- $authorizeURL = SimpleSAML_Utilities::addURLparameter($url, $params);
+ $authorizeURL = \SimpleSAML\Utils\HTTP::addURLParameters($url, $params);
if ($redirect) {
- SimpleSAML_Utilities::redirectTrustedURL($authorizeURL);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL);
exit;
}
return $authorizeURL;
@@ -130,8 +130,6 @@ class sspmod_oauth_Consumer {
$opts = array(
'ssl' => array(
'verify_peer' => FALSE,
- // 'cafile' => $file,
- // 'local_cert' => $spKeyCertFile,
'capture_peer_cert' => TRUE,
'capture_peer_chain' => TRUE,
),
@@ -158,7 +156,6 @@ class sspmod_oauth_Consumer {
$opts = stream_context_create($opts);
}
$data = file_get_contents($data_req->to_url(), FALSE, $opts);
- #print_r($data);
$dataDecoded = json_decode($data, TRUE);
return $dataDecoded;
diff --git a/modules/oauth/lib/OAuthStore.php b/modules/oauth/lib/OAuthStore.php
index cd8e0d6..974387a 100644
--- a/modules/oauth/lib/OAuthStore.php
+++ b/modules/oauth/lib/OAuthStore.php
@@ -62,8 +62,8 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore {
if ($oConsumer && ($oConsumer->callback_url)) $url = $oConsumer->callback_url;
- $verifier = SimpleSAML_Utilities::generateID();
- $url = SimpleSAML_Utilities::addURLparameter($url, array("oauth_verifier"=>$verifier));
+ $verifier = SimpleSAML\Utils\Random::generateID();
+ $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array("oauth_verifier"=>$verifier));
$this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 60*30) );
@@ -111,7 +111,6 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore {
$callback = NULL;
if ($consumer['value']['callback_url']) $callback = $consumer['value']['callback_url'];
- // SimpleSAML_Logger::info('OAuth consumer dump(' . var_export($consumer, TRUE) . ')');
if ($consumer['value']['RSAcertificate']) {
return new OAuthConsumer($consumer['value']['key'], $consumer['value']['RSAcertificate'], $callback);
} else {
@@ -138,7 +137,7 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore {
$lifetime = $this->config->getValue('requestTokenDuration', 60*30);
- $token = new OAuthToken(SimpleSAML_Utilities::generateID(), SimpleSAML_Utilities::generateID());
+ $token = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
$token->callback = $callback; // OAuth1.0-RevA
$this->store->set('request', $token->key, $consumer->key, $token, $lifetime);
@@ -158,8 +157,7 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore {
function new_access_token($requestToken, $consumer, $verifier = null) {
SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')');
- $accestoken = new OAuthToken(SimpleSAML_Utilities::generateID(), SimpleSAML_Utilities::generateID());
- // SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ',' . $accestoken . ')');
+ $accestoken = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
$this->store->set('access', $accestoken->key, $consumer->key, $accestoken, $this->config->getValue('accessTokenDuration', 60*60*24) );
return $accestoken;
}
diff --git a/modules/oauth/lib/Registry.php b/modules/oauth/lib/Registry.php
index 8ae9f93..b8eb7fa 100644
--- a/modules/oauth/lib/Registry.php
+++ b/modules/oauth/lib/Registry.php
@@ -107,17 +107,10 @@ class sspmod_oauth_Registry {
}
public function metaToForm($metadata) {
- // $this->flattenLanguageField($metadata, 'name');
- // $this->flattenLanguageField($metadata, 'description');
-
- return '<form action="registry.edit.php" method="post">' .
+ return '<form action="registry.edit.php" method="post">' .
'<div id="tabdiv">' .
'<ul>' .
- '<li><a href="#basic">Name and descrition</a></li>' .
- // '<li><a href="#saml">SAML 2.0</a></li>' .
- // '<li><a href="#attributes">Attributes</a></li>' .
- // '<li><a href="#orgs">Organizations</a></li>' .
- // '<li><a href="#contacts">Contacts</a></li>' .
+ '<li><a href="#basic">Name and descrition</a></li>' .
'</ul>' .
'<div id="basic"><table class="formtable">' .
$this->standardField($metadata, 'name', 'Name of client') .
@@ -127,17 +120,9 @@ class sspmod_oauth_Registry {
$this->readonlyField($metadata, 'secret', 'Consumer Secret<br/>(Used for HMAC_SHA1 signatures)') .
$this->standardField($metadata, 'RSAcertificate', 'RSA certificate (PEM)<br/>(Used for RSA_SHA1 signatures)', TRUE) .
$this->standardField($metadata, 'callback_url', 'Static/enforcing callback-url') .
-
-// $this->hiddenField('field_key', $metadata['key']) .
$this->hiddenField('field_secret', $metadata['secret']) .
- '</table></div>' .
- // '<div id="saml"><table class="formtable">' .
- // $this->standardField($metadata, 'AssertionConsumerService', 'AssertionConsumerService endpoint') .
- // $this->standardField($metadata, 'SingleLogoutService', 'SingleLogoutService endpoint') .
- // // $this->standardField($metadata, 'certFingerprint', 'Certificate Fingerprint') .
- //
- // '</table></div>' .
+ '</table></div>' .
'</div>' .
'<input type="submit" name="submit" value="Save" style="margin-top: 5px" />' .
'</form>';
diff --git a/modules/oauth/templates/registry.list.php b/modules/oauth/templates/registry.list.php
index 0d11fd6..b1cdbc9 100644
--- a/modules/oauth/templates/registry.list.php
+++ b/modules/oauth/templates/registry.list.php
@@ -2,12 +2,6 @@
$this->data['jquery'] = array('version' => '1.6', 'core' => TRUE, 'ui' => TRUE, 'css' => TRUE);
$this->data['head'] = '<link rel="stylesheet" type="text/css" href="/' . $this->data['baseurlpath'] . 'module.php/oauth/resources/style.css" />' . "\n";
-// $this->data['head'] .= '<script type="text/javascript">
-// $(document).ready(function() {
-// $("#tabdiv").tabs();
-// });
-// </script>';
-
$this->includeAtTemplateBase('includes/header.php');
diff --git a/modules/oauth/www/accessToken.php b/modules/oauth/www/accessToken.php
index 31c8132..82eed17 100644
--- a/modules/oauth/www/accessToken.php
+++ b/modules/oauth/www/accessToken.php
@@ -20,7 +20,7 @@ try {
$requestToken = $req->get_parameter('oauth_token');
- $verifier = $req->get_parameter("oauth_verifier"); if ($verifier == null) $verifier = '';
+ $verifier = $req->get_parameter("oauth_verifier"); if ($verifier === null) $verifier = '';
if (!$store->isAuthorized($requestToken, $verifier)) {
throw new Exception('Your request was not authorized. Request token [' . $requestToken . '] not found.');
@@ -35,7 +35,4 @@ try {
header('Content-type: text/plain; utf-8', TRUE, 500);
header('OAuth-Error: ' . $e->getMessage());
-
- print_r($e);
-
}
diff --git a/modules/oauth/www/authorize.php b/modules/oauth/www/authorize.php
index 25fe194..0816dec 100644
--- a/modules/oauth/www/authorize.php
+++ b/modules/oauth/www/authorize.php
@@ -30,7 +30,7 @@ try {
$as = $oauthconfig->getString('auth');
if (!$session->isValid($as)) {
- SimpleSAML_Auth_Default::initLogin($as, SimpleSAML_Utilities::selfURL());
+ SimpleSAML_Auth_Default::initLogin($as, \SimpleSAML\Utils\HTTP::getSelfURL());
}
@@ -40,8 +40,8 @@ try {
$t = new SimpleSAML_XHTML_Template($config, 'oauth:consent.php');
$t->data['header'] = '{status:header_saml20_sp}';
$t->data['consumer'] = $consumer; // array containint {name, description, key, secret, owner} keys
- $t->data['urlAgree'] = SimpleSAML_Utilities::addURLparameter( SimpleSAML_Utilities::selfURL(), array("consent" => "yes") );
- $t->data['logouturl'] = SimpleSAML_Utilities::selfURLNoQuery() . '?logout';
+ $t->data['urlAgree'] = \SimpleSAML\Utils\HTTP::addURLParameters(\SimpleSAML\Utils\HTTP::getSelfURL(), array("consent" => "yes"));
+ $t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery() . '?logout';
$t->show();
@@ -56,11 +56,11 @@ try {
if ($url) {
// If authorize() returns a URL, take user there (oauth1.0a)
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
}
else if (isset($_REQUEST['oauth_callback'])) {
// If callback was provided in the request (oauth1.0)
- SimpleSAML_Utilities::redirectUntrustedURL($_REQUEST['oauth_callback']);
+ \SimpleSAML\Utils\HTTP::redirectUntrustedURL($_REQUEST['oauth_callback']);
} else {
// No callback provided, display standard template
@@ -70,7 +70,7 @@ try {
$t->data['header'] = '{status:header_saml20_sp}';
$t->data['remaining'] = $session->getAuthData($as, "Expire") - time();
$t->data['attributes'] = $attributes;
- $t->data['logouturl'] = SimpleSAML_Utilities::selfURLNoQuery() . '?logout';
+ $t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery() . '?logout';
$t->data['oauth_verifier'] = $verifier;
$t->show();
}
@@ -79,13 +79,4 @@ try {
header('Content-type: text/plain; utf-8', TRUE, 500);
header('OAuth-Error: ' . $e->getMessage());
-
- print_r($e);
-
}
-
-
-//
-// $req = OAuthRequest::from_request();
-// $token = $server->fetch_request_token($req);
-// echo $token;
diff --git a/modules/oauth/www/registry.edit.php b/modules/oauth/www/registry.edit.php
index 1b752cd..555e77b 100644
--- a/modules/oauth/www/registry.edit.php
+++ b/modules/oauth/www/registry.edit.php
@@ -7,10 +7,8 @@ $oauthconfig = SimpleSAML_Configuration::getOptionalConfig('module_oauth.php');
$store = new sspmod_core_Storage_SQLPermanentStorage('oauth');
-//$authsource = $oauthconfig->getValue('auth', 'admin');
$authsource = "admin"; // force admin to authenticate as registry maintainer
$useridattr = $oauthconfig->getValue('useridattr', 'user');
-//$useridattr = $oauthconfig->getValue('useridattr', 'uid');
if ($session->isValid($authsource)) {
$attributes = $session->getAuthData($authsource, 'Attributes');
@@ -19,7 +17,7 @@ if ($session->isValid($authsource)) {
throw new Exception('User ID is missing');
$userid = $attributes[$useridattr][0];
} else {
- SimpleSAML_Auth_Default::initLogin($authsource, SimpleSAML_Utilities::selfURL());
+ SimpleSAML_Auth_Default::initLogin($authsource, \SimpleSAML\Utils\HTTP::getSelfURL());
}
function requireOwnership($entry, $userid) {
@@ -37,8 +35,8 @@ if (array_key_exists('editkey', $_REQUEST)) {
} else {
$entry = array(
'owner' => $userid,
- 'key' => SimpleSAML_Utilities::generateID(),
- 'secret' => SimpleSAML_Utilities::generateID(),
+ 'key' => SimpleSAML\Utils\Random::generateID(),
+ 'secret' => SimpleSAML\Utils\Random::generateID(),
);
}
@@ -52,9 +50,7 @@ if (isset($_POST['submit'])) {
$entry = $editor->formToMeta($_POST, array(), array('owner' => $userid));
requireOwnership($entry, $userid);
-
-# echo('<pre>Created: '); print_r($entry); exit;
-
+
$store->set('consumers', $entry['key'], '', $entry);
$template = new SimpleSAML_XHTML_Template($config, 'oauth:registry.saved.php');
diff --git a/modules/oauth/www/registry.php b/modules/oauth/www/registry.php
index 52b06f2..bd36ac4 100644
--- a/modules/oauth/www/registry.php
+++ b/modules/oauth/www/registry.php
@@ -7,10 +7,8 @@ $oauthconfig = SimpleSAML_Configuration::getOptionalConfig('module_oauth.php');
$store = new sspmod_core_Storage_SQLPermanentStorage('oauth');
-//$authsource = $oauthconfig->getValue('auth', 'admin');
$authsource = "admin"; // force admin to authenticate as registry maintainer
$useridattr = $oauthconfig->getValue('useridattr', 'user');
-//$useridattr = $oauthconfig->getValue('useridattr', 'uid');
if ($session->isValid($authsource)) {
$attributes = $session->getAuthData($authsource, 'Attributes');
@@ -19,7 +17,7 @@ if ($session->isValid($authsource)) {
throw new Exception('User ID is missing');
$userid = $attributes[$useridattr][0];
} else {
- SimpleSAML_Auth_Default::initLogin($authsource, SimpleSAML_Utilities::selfURL());
+ SimpleSAML_Auth_Default::initLogin($authsource, \SimpleSAML\Utils\HTTP::getSelfURL());
}
function requireOwnership($entry, $userid) {
@@ -52,8 +50,6 @@ foreach($list AS $listitem) {
$slist['others'][] = $listitem;
}
-// echo('<pre>'); print_r($slist); exit;
-
$template = new SimpleSAML_XHTML_Template($config, 'oauth:registry.list.php');
$template->data['entries'] = $slist;
$template->data['userid'] = $userid;
diff --git a/modules/oauth/www/requestToken.php b/modules/oauth/www/requestToken.php
index df86175..3e27070 100644
--- a/modules/oauth/www/requestToken.php
+++ b/modules/oauth/www/requestToken.php
@@ -26,7 +26,4 @@ try {
header('Content-type: text/plain; utf-8', TRUE, 500);
header('OAuth-Error: ' . $e->getMessage());
-
- print_r($e);
-
}
diff --git a/modules/portal/hooks/hook_htmlinject.php b/modules/portal/hooks/hook_htmlinject.php
index 83f0f25..fb68a3a 100644
--- a/modules/portal/hooks/hook_htmlinject.php
+++ b/modules/portal/hooks/hook_htmlinject.php
@@ -14,8 +14,6 @@ function portal_hook_htmlinject(&$hookinfo) {
$links = array('links' => array());
SimpleSAML_Module::callHooks('frontpage', $links);
-# echo('<pre>'); print_r($links); exit;
-
$portalConfig = SimpleSAML_Configuration::getOptionalConfig('module_portal.php');
$allLinks = array();
@@ -31,8 +29,6 @@ function portal_hook_htmlinject(&$hookinfo) {
if (!$portal->isPortalized($hookinfo['page'])) return;
- #print_r($portal->getMenu($hookinfo['page'])); exit;
-
// Include jquery UI CSS files in header.
$hookinfo['jquery']['css'] = TRUE;
$hookinfo['jquery']['version'] = '1.6';
diff --git a/modules/portal/lib/Portal.php b/modules/portal/lib/Portal.php
index 5177421..7478e0f 100644
--- a/modules/portal/lib/Portal.php
+++ b/modules/portal/lib/Portal.php
@@ -37,28 +37,15 @@ class sspmod_portal_Portal {
}
function getMenu($thispage) {
-
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php');
-
$tabset = $this->getTabset($thispage);
-
- #echo($thispage);
- #echo('<pre>'); print_r($this->pages); exit;
-
$logininfo = $this->getLoginInfo($t, $thispage);
- #echo $logininfo; exit;
-
$text = '';
-
-
$text .= '<ul class="tabset_tabs ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">';
foreach($this->pages AS $pageid => $page) {
if (isset($tabset) && !in_array($pageid, $tabset, TRUE)) continue;
-
- #echo('This page [' . $pageid . '] is part of [' . join(',', $tabset) . ']');
-
$name = 'uknown';
if (isset($page['text'])) $name = $page['text'];
if (isset($page['shorttext'])) $name = $page['shorttext'];
diff --git a/modules/preprodwarning/lib/Auth/Process/Warning.php b/modules/preprodwarning/lib/Auth/Process/Warning.php
index 1c73409..acb740c 100644
--- a/modules/preprodwarning/lib/Auth/Process/Warning.php
+++ b/modules/preprodwarning/lib/Auth/Process/Warning.php
@@ -28,7 +28,7 @@ class sspmod_preprodwarning_Auth_Process_Warning extends SimpleSAML_Auth_Process
/* Save state and redirect. */
$id = SimpleSAML_Auth_State::saveState($state, 'warning:request');
$url = SimpleSAML_Module::getModuleURL('preprodwarning/showwarning.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
diff --git a/modules/radius/lib/Auth/Source/Radius.php b/modules/radius/lib/Auth/Source/Radius.php
index 1bd8a50..3833692 100644
--- a/modules/radius/lib/Auth/Source/Radius.php
+++ b/modules/radius/lib/Auth/Source/Radius.php
@@ -161,7 +161,7 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase {
if ($this->vendor === NULL) {
/*
- * We aren't interrested in any vendor-specific attributes. We are
+ * We aren't interested in any vendor-specific attributes. We are
* therefore done now.
*/
return $attributes;
@@ -193,11 +193,6 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase {
$attrv = $resv['attr'];
$datav = $resv['data'];
- /*
- * Uncomment this to debug vendor attributes.
- */
- //printf("Got Vendor Attr:%d %d Bytes %s<br/>", $attrv, strlen($datav), bin2hex($datav));
-
if ($vendor != $this->vendor || $attrv != $this->vendorType) {
continue;
}
diff --git a/modules/saml/docs/sp.txt b/modules/saml/docs/sp.txt
index 45c1e60..063be47 100644
--- a/modules/saml/docs/sp.txt
+++ b/modules/saml/docs/sp.txt
@@ -270,11 +270,13 @@ Options
`redirect.sign`
: Whether authentication requests, logout requests and logout responses sent from this SP should be signed. The default is `FALSE`.
+ If set, the `AuthnRequestsSigned` attribute of the `SPSSODescriptor` element in SAML 2.0 metadata will contain its value. This
+ option takes precedence over the `sign.authnrequest` option in any metadata generated for this SP.
: *Note*: SAML 2 specific.
`redirect.validate`
-: Whether logout requests and logout responses received received by this SP should be validated. The default is `FALSE`.
+: Whether logout requests and logout responses received by this SP should be validated. The default is `FALSE`.
: *Note*: SAML 2 specific.
@@ -312,7 +314,8 @@ Options
See the documentation for the [Holder-of-Key profile](./simplesamlphp-hok-sp).
`sign.authnrequest`
-: Whether to sign authentication requests sent from this SP.
+: Whether to sign authentication requests sent from this SP. If set, the `AuthnRequestsSigned` attribute of the
+ `SPSSODescriptor` element in SAML 2.0 metadata will contain its value.
: Note that this option also exists in the IdP-remote metadata, and
any value in the IdP-remote metadata overrides the one configured
@@ -366,6 +369,11 @@ Options
: *Note*: SAML 2 specific.
+`WantAssertionsSigned`
+: Whether assertions received by this SP must be signed. The default value is `FALSE`.
+ The value set for this option will be used to set the `WantAssertionsSigned` attribute of the `SPSSODescriptor` element in
+ the exported SAML 2.0 metadata.
+
Examples
--------
diff --git a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
index 13daccd..c012a85 100644
--- a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
+++ b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
@@ -79,6 +79,6 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends SimpleSAML_A
$id = SimpleSAML_Auth_State::saveState($request, 'saml:ExpectedAuthnContextClassRef:unauthorized');
$url = SimpleSAML_Module::getModuleURL(
'saml/sp/wrong_authncontextclassref.php');
- SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id));
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
}
}
diff --git a/modules/saml/lib/Auth/Process/PersistentNameID.php b/modules/saml/lib/Auth/Process/PersistentNameID.php
index 5116755..255764f 100644
--- a/modules/saml/lib/Auth/Process/PersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/PersistentNameID.php
@@ -64,7 +64,7 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe
$uid = array_values($state['Attributes'][$this->attribute]); /* Just in case the first index is no longer 0. */
$uid = $uid[0];
- $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+ $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
$uidData = 'uidhashbase' . $secretSalt;
$uidData .= strlen($idpEntityId) . ':' . $idpEntityId;
diff --git a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
index 9a0ad36..767aec3 100644
--- a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
@@ -81,7 +81,7 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
throw new sspmod_saml_Error(SAML2_Const::STATUS_RESPONDER, 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy');
}
- $value = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(20));
+ $value = bin2hex(openssl_random_pseudo_bytes(20));
SimpleSAML_Logger::debug('SQLPersistentNameID: Created persistent NameID ' . var_export($value, TRUE) . ' for user ' . var_export($uid, TRUE) . '.');
sspmod_saml_IdP_SQLNameID::add($idpEntityId, $spEntityId, $uid, $value);
diff --git a/modules/saml/lib/Auth/Process/TransientNameID.php b/modules/saml/lib/Auth/Process/TransientNameID.php
index c51d8ca..b432ed3 100644
--- a/modules/saml/lib/Auth/Process/TransientNameID.php
+++ b/modules/saml/lib/Auth/Process/TransientNameID.php
@@ -28,7 +28,7 @@ class sspmod_saml_Auth_Process_TransientNameID extends sspmod_saml_BaseNameIDGen
*/
protected function getValue(array &$state) {
- return SimpleSAML_Utilities::generateID();
+ return SimpleSAML\Utils\Random::generateID();
}
}
diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php
index 565ad66..e514068 100644
--- a/modules/saml/lib/Auth/Source/SP.php
+++ b/modules/saml/lib/Auth/Source/SP.php
@@ -168,7 +168,7 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source {
SimpleSAML_Logger::debug('Starting SAML 1 SSO to ' . var_export($idpEntityId, TRUE) .
' from ' . var_export($this->entityId, TRUE) . '.');
- SimpleSAML_Utilities::redirectTrustedURL($url);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
}
@@ -193,7 +193,7 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source {
}
if (isset($state['saml:AuthnContextClassRef'])) {
- $accr = SimpleSAML_Utilities::arrayize($state['saml:AuthnContextClassRef']);
+ $accr = SimpleSAML\Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']);
$ar->setRequestedAuthnContext(array('AuthnContextClassRef' => $accr));
}
@@ -355,7 +355,7 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source {
$params['isPassive'] = 'true';
}
- SimpleSAML_Utilities::redirectTrustedURL($discoURL, $params);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($discoURL, $params);
}
diff --git a/modules/saml/lib/IdP/SAML1.php b/modules/saml/lib/IdP/SAML1.php
index 9ef95b7..be2e1de 100644
--- a/modules/saml/lib/IdP/SAML1.php
+++ b/modules/saml/lib/IdP/SAML1.php
@@ -69,7 +69,7 @@ class sspmod_saml_IdP_SAML1 {
* Less than five seconds has passed since we were
* here the last time. Cookies are probably disabled.
*/
- SimpleSAML_Utilities::checkCookie(SimpleSAML_Utilities::selfURL());
+ \SimpleSAML\Utils\HTTP::checkCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
}
}
@@ -115,14 +115,14 @@ class sspmod_saml_IdP_SAML1 {
'protocol' => 'saml1',
));
- $sessionLostURL = SimpleSAML_Utilities::addURLparameter(
- SimpleSAML_Utilities::selfURL(),
+ $sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(
+ \SimpleSAML\Utils\HTTP::getSelfURL(),
array('cookieTime' => time()));
$state = array(
'Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'),
'SPMetadata' => $spMetadata->toArray(),
-
+ SimpleSAML_Auth_State::RESTART => $sessionLostURL,
'saml:shire' => $shire,
'saml:target' => $target,
'saml:AuthnRequestReceivedAt' => microtime(TRUE),
diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php
index dbd6512..e22edad 100644
--- a/modules/saml/lib/IdP/SAML2.php
+++ b/modules/saml/lib/IdP/SAML2.php
@@ -247,7 +247,7 @@ class sspmod_saml_IdP_SAML2 {
* Less than five seconds has passed since we were
* here the last time. Cookies are probably disabled.
*/
- SimpleSAML_Utilities::checkCookie(SimpleSAML_Utilities::selfURL());
+ \SimpleSAML\Utils\HTTP::checkCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
}
}
@@ -347,7 +347,7 @@ class sspmod_saml_IdP_SAML2 {
$acsEndpoint = self::getAssertionConsumerService($supportedBindings, $spMetadata, $consumerURL, $protocolBinding, $consumerIndex);
$IDPList = array_unique(array_merge($IDPList, $spMetadata->getArrayizeString('IDPList', array())));
- if ($ProxyCount == null) $ProxyCount = $spMetadata->getInteger('ProxyCount', null);
+ if ($ProxyCount === null) $ProxyCount = $spMetadata->getInteger('ProxyCount', null);
if (!$forceAuthn) {
$forceAuthn = $spMetadata->getBoolean('ForceAuthn', FALSE);
@@ -361,8 +361,8 @@ class sspmod_saml_IdP_SAML2 {
$sessionLostParams['RelayState'] = $relayState;
}
- $sessionLostURL = SimpleSAML_Utilities::addURLparameter(
- SimpleSAML_Utilities::selfURLNoQuery(),
+ $sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(
+ \SimpleSAML\Utils\HTTP::getSelfURLNoQuery(),
$sessionLostParams);
$state = array(
@@ -628,7 +628,7 @@ class sspmod_saml_IdP_SAML2 {
$idpEntityId = $idpMetadata->getString('entityid');
$spEntityId = $spMetadata->getString('entityid');
- $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+ $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
$uidData = 'uidhashbase' . $secretSalt;
$uidData .= strlen($idpEntityId) . ':' . $idpEntityId;
@@ -809,7 +809,7 @@ class sspmod_saml_IdP_SAML2 {
$sessionLifetime = $config->getInteger('session.duration', 8*60*60);
$a->setSessionNotOnOrAfter(time() + $sessionLifetime);
- $a->setSessionIndex(SimpleSAML_Utilities::generateID());
+ $a->setSessionIndex(SimpleSAML\Utils\Random::generateID());
$sc = new SAML2_XML_saml_SubjectConfirmation();
$sc->SubjectConfirmationData = new SAML2_XML_saml_SubjectConfirmationData();
@@ -829,7 +829,7 @@ class sspmod_saml_IdP_SAML2 {
if ($hokAssertion) {
/* Holder-of-Key */
$sc->Method = SAML2_Const::CM_HOK;
- if (SimpleSAML_Utilities::isHTTPS()) {
+ if (\SimpleSAML\Utils\HTTP::isHTTPS()) {
if (isset($_SERVER['SSL_CLIENT_CERT']) && !empty($_SERVER['SSL_CLIENT_CERT'])) {
/* Extract certificate data (if this is a certificate). */
$clientCert = $_SERVER['SSL_CLIENT_CERT'];
@@ -892,7 +892,7 @@ class sspmod_saml_IdP_SAML2 {
if ($nameIdFormat === SAML2_Const::NAMEID_TRANSIENT) {
/* generate a random id */
- $nameIdValue = SimpleSAML_Utilities::generateID();
+ $nameIdValue = SimpleSAML\Utils\Random::generateID();
} else {
/* this code will end up generating either a fixed assigned id (via nameid.attribute)
or random id if not assigned/configured */
@@ -900,7 +900,7 @@ class sspmod_saml_IdP_SAML2 {
if ($nameIdValue === NULL) {
SimpleSAML_Logger::warning('Falling back to transient NameID.');
$nameIdFormat = SAML2_Const::NAMEID_TRANSIENT;
- $nameIdValue = SimpleSAML_Utilities::generateID();
+ $nameIdValue = SimpleSAML\Utils\Random::generateID();
}
}
diff --git a/modules/saml/lib/Message.php b/modules/saml/lib/Message.php
index 0d8efe1..da841b5 100644
--- a/modules/saml/lib/Message.php
+++ b/modules/saml/lib/Message.php
@@ -21,11 +21,11 @@ class sspmod_saml_Message {
$dstPrivateKey = $dstMetadata->getString('signature.privatekey', NULL);
if ($dstPrivateKey !== NULL) {
- $keyArray = SimpleSAML_Utilities::loadPrivateKey($dstMetadata, TRUE, 'signature.');
- $certArray = SimpleSAML_Utilities::loadPublicKey($dstMetadata, FALSE, 'signature.');
+ $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, TRUE, 'signature.');
+ $certArray = SimpleSAML\Utils\Crypto::loadPublicKey($dstMetadata, FALSE, 'signature.');
} else {
- $keyArray = SimpleSAML_Utilities::loadPrivateKey($srcMetadata, TRUE);
- $certArray = SimpleSAML_Utilities::loadPublicKey($srcMetadata, FALSE);
+ $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($srcMetadata, TRUE);
+ $certArray = SimpleSAML\Utils\Crypto::loadPublicKey($srcMetadata, FALSE);
}
$algo = $dstMetadata->getString('signature.algorithm', NULL);
@@ -281,7 +281,7 @@ class sspmod_saml_Message {
$keys = array();
/* Load the new private key if it exists. */
- $keyArray = SimpleSAML_Utilities::loadPrivateKey($dstMetadata, FALSE, 'new_');
+ $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, FALSE, 'new_');
if ($keyArray !== NULL) {
assert('isset($keyArray["PEM"])');
@@ -294,7 +294,7 @@ class sspmod_saml_Message {
}
/* Find the existing private key. */
- $keyArray = SimpleSAML_Utilities::loadPrivateKey($dstMetadata, TRUE);
+ $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, TRUE);
assert('isset($keyArray["PEM"])');
$key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type'=>'private'));
@@ -500,7 +500,7 @@ class sspmod_saml_Message {
}
/* Validate Response-element destination. */
- $currentURL = SimpleSAML_Utilities::selfURLNoQuery();
+ $currentURL = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
$msgDestination = $response->getDestination();
if ($msgDestination !== NULL && $msgDestination !== $currentURL) {
throw new Exception('Destination in response doesn\'t match the current URL. Destination is "' .
@@ -556,7 +556,7 @@ class sspmod_saml_Message {
}
/* At least one valid signature found. */
- $currentURL = SimpleSAML_Utilities::selfURLNoQuery();
+ $currentURL = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
/* Check various properties of the assertion. */
@@ -587,8 +587,9 @@ class sspmod_saml_Message {
$found = FALSE;
$lastError = 'No SubjectConfirmation element in Subject.';
+ $validSCMethods = array(SAML2_Const::CM_BEARER, SAML2_Const::CM_HOK, SAML2_Const::CM_VOUCHES);
foreach ($assertion->getSubjectConfirmation() as $sc) {
- if ($sc->Method !== SAML2_Const::CM_BEARER && $sc->Method !== SAML2_Const::CM_HOK) {
+ if (!in_array($sc->Method, $validSCMethods)) {
$lastError = 'Invalid Method on SubjectConfirmation: ' . var_export($sc->Method, TRUE);
continue;
}
@@ -610,7 +611,7 @@ class sspmod_saml_Message {
$scd = $sc->SubjectConfirmationData;
if ($sc->Method === SAML2_Const::CM_HOK) {
/* Check HoK Assertion */
- if (SimpleSAML_Utilities::isHTTPS() === FALSE) {
+ if (\SimpleSAML\Utils\HTTP::isHTTPS() === FALSE) {
$lastError = 'No HTTPS connection, but required for Holder-of-Key SSO';
continue;
}
diff --git a/modules/saml/lib/SP/LogoutStore.php b/modules/saml/lib/SP/LogoutStore.php
index 6f79f7b..fa78cdf 100644
--- a/modules/saml/lib/SP/LogoutStore.php
+++ b/modules/saml/lib/SP/LogoutStore.php
@@ -167,7 +167,7 @@ class sspmod_saml_SP_LogoutStore {
* it supports SLO, but we don't want an LogoutRequest with a specific
* SessionIndex to match this session. We therefore generate our own session index.
*/
- $sessionIndex = SimpleSAML_Utilities::generateID();
+ $sessionIndex = SimpleSAML\Utils\Random::generateID();
}
$store = SimpleSAML_Store::getInstance();
diff --git a/modules/saml/www/idp/certs.php b/modules/saml/www/idp/certs.php
index 328cda4..83f2f19 100644
--- a/modules/saml/www/idp/certs.php
+++ b/modules/saml/www/idp/certs.php
@@ -9,7 +9,7 @@ if (!$config->getBoolean('enable.saml20-idp', false))
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectmetadata', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
$idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
@@ -17,13 +17,13 @@ $idpmeta = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-hosted');
switch($_SERVER['PATH_INFO']) {
case '/new_idp.crt':
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_');
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, FALSE, 'new_');
break;
case '/idp.crt':
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE);
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE);
break;
case '/https.crt':
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE, 'https.');
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE, 'https.');
break;
default:
throw new SimpleSAML_Error_NotFound('Unknown certificate.');
diff --git a/modules/saml/www/sp/metadata.php b/modules/saml/www/sp/metadata.php
index 5a74709..1dde242 100644
--- a/modules/saml/www/sp/metadata.php
+++ b/modules/saml/www/sp/metadata.php
@@ -6,7 +6,7 @@ if (!array_key_exists('PATH_INFO', $_SERVER)) {
$config = SimpleSAML_Configuration::getInstance();
if ($config->getBoolean('admin.protectmetadata', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
$sourceId = substr($_SERVER['PATH_INFO'], 1);
$source = SimpleSAML_Auth_Source::getById($sourceId);
@@ -91,7 +91,7 @@ foreach ($assertionsconsumerservices as $services) {
$metaArray20['AssertionConsumerService'] = $eps;
$keys = array();
-$certInfo = SimpleSAML_Utilities::loadPublicKey($spconfig, FALSE, 'new_');
+$certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($spconfig, FALSE, 'new_');
if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) {
$hasNewCert = TRUE;
@@ -107,7 +107,7 @@ if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) {
$hasNewCert = FALSE;
}
-$certInfo = SimpleSAML_Utilities::loadPublicKey($spconfig);
+$certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($spconfig);
if ($certInfo !== NULL && array_key_exists('certData', $certInfo)) {
$certData = $certInfo['certData'];
@@ -164,7 +164,7 @@ if ($orgName !== NULL) {
if ($spconfig->hasValue('contacts')) {
$contacts = $spconfig->getArray('contacts');
foreach ($contacts as $contact) {
- $metaArray20['contacts'][] = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $metaArray20['contacts'][] = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
}
}
@@ -174,7 +174,7 @@ if ($email && $email !== 'na@example.org') {
$techcontact['emailAddress'] = $email;
$techcontact['name'] = $config->getString('technicalcontact_name', NULL);
$techcontact['contactType'] = 'technical';
- $metaArray20['contacts'][] = SimpleSAML_Utils_Config_Metadata::getContact($techcontact);
+ $metaArray20['contacts'][] = \SimpleSAML\Utils\Config\Metadata::getContact($techcontact);
}
// add certificate
@@ -194,6 +194,16 @@ if ($spconfig->hasValue('RegistrationInfo')) {
$metaArray20['RegistrationInfo'] = $spconfig->getArray('RegistrationInfo');
}
+// add signature options
+if ($spconfig->hasValue('WantAssertionsSigned')) {
+ $metaArray20['saml20.sign.assertion'] = $spconfig->getBoolean('WantAssertionsSigned');
+}
+if ($spconfig->hasValue('redirect.sign')) {
+ $metaArray20['redirect.validate'] = $spconfig->getBoolean('redirect.sign');
+} elseif ($spconfig->hasValue('sign.authnrequest')) {
+ $metaArray20['validate.authnrequest'] = $spconfig->getBoolean('sign.authnrequest');
+}
+
$supported_protocols = array('urn:oasis:names:tc:SAML:1.1:protocol', SAML2_Const::NS_SAMLP);
$metaArray20['metadata-set'] = 'saml20-sp-remote';
diff --git a/modules/saml/www/sp/saml1-acs.php b/modules/saml/www/sp/saml1-acs.php
index 45b317d..bd8d41b 100644
--- a/modules/saml/www/sp/saml1-acs.php
+++ b/modules/saml/www/sp/saml1-acs.php
@@ -30,7 +30,7 @@ if (preg_match('@^https?://@i', $target)) {
$state = array(
'saml:sp:isUnsolicited' => TRUE,
'saml:sp:AuthId' => $sourceId,
- 'saml:sp:RelayState' => SimpleSAML_Utilities::checkURLAllowed($target),
+ 'saml:sp:RelayState' => \SimpleSAML\Utils\HTTP::checkURLAllowed($target),
);
} else {
$state = SimpleSAML_Auth_State::loadState($_REQUEST['TARGET'], 'saml:sp:sso');
diff --git a/modules/saml/www/sp/saml2-acs.php b/modules/saml/www/sp/saml2-acs.php
index 21bdce2..68751e3 100644
--- a/modules/saml/www/sp/saml2-acs.php
+++ b/modules/saml/www/sp/saml2-acs.php
@@ -60,7 +60,7 @@ if ($prevAuth !== NULL && $prevAuth['id'] === $response->getId() && $prevAuth['i
* instead of displaying a confusing error message.
*/
SimpleSAML_Logger::info('Duplicate SAML 2 response detected - ignoring the response and redirecting the user to the correct page.');
- SimpleSAML_Utilities::redirectTrustedURL($prevAuth['redirect']);
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL($prevAuth['redirect']);
}
$idpMetadata = array();
@@ -90,7 +90,7 @@ if (!empty($stateId)) {
$state = array(
'saml:sp:isUnsolicited' => TRUE,
'saml:sp:AuthId' => $sourceId,
- 'saml:sp:RelayState' => SimpleSAML_Utilities::checkURLAllowed($response->getRelayState()),
+ 'saml:sp:RelayState' => \SimpleSAML\Utils\HTTP::checkURLAllowed($response->getRelayState()),
);
}
diff --git a/modules/saml/www/sp/saml2-logout.php b/modules/saml/www/sp/saml2-logout.php
index 1c5d875..637009a 100644
--- a/modules/saml/www/sp/saml2-logout.php
+++ b/modules/saml/www/sp/saml2-logout.php
@@ -48,7 +48,7 @@ $spMetadata = $source->getMetadata();
sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);
$destination = $message->getDestination();
-if ($destination !== NULL && $destination !== SimpleSAML_Utilities::selfURLNoQuery()) {
+if ($destination !== NULL && $destination !== \SimpleSAML\Utils\HTTP::getSelfURLNoQuery()) {
throw new SimpleSAML_Error_Exception('Destination in logout message is wrong.');
}
diff --git a/modules/saml2debug/www/debug.php b/modules/saml2debug/www/debug.php
index 644e600..4f83925 100644
--- a/modules/saml2debug/www/debug.php
+++ b/modules/saml2debug/www/debug.php
@@ -13,8 +13,6 @@ function getValue($raw) {
$arr = array();
$query = parse_str($val, $arr);
- #echo('<pre>');print_r($arr);
-
if (array_key_exists('SAMLResponse', $arr)) return $arr['SAMLResponse'];
if (array_key_exists('SAMLRequest', $arr)) return $arr['SAMLRequest'];
if (array_key_exists('LogoutRequest', $arr)) return $arr['LogoutRequest'];
@@ -25,8 +23,7 @@ function getValue($raw) {
function decode($raw) {
$message = getValue($raw);
- #echo 'using value: ' . $message; exit;
-
+
$base64decoded = base64_decode($message);
$gzinflated = gzinflate($base64decoded);
if ($gzinflated != FALSE) {
diff --git a/modules/statistics/bin/loganalyzer.php b/modules/statistics/bin/loganalyzer.php
index 7ea016e..7186890 100755
--- a/modules/statistics/bin/loganalyzer.php
+++ b/modules/statistics/bin/loganalyzer.php
@@ -11,7 +11,7 @@ require_once($baseDir . '/lib/_autoload.php');
/* Initialize the configuration. */
SimpleSAML_Configuration::setConfigDir($baseDir . '/config');
-SimpleSAML_Utilities::initTimezone();
+SimpleSAML\Utils\Time::initTimezone();
$progName = array_shift($argv);
$debug = FALSE;
diff --git a/modules/statistics/lib/AccessCheck.php b/modules/statistics/lib/AccessCheck.php
index 92d1f90..4d393b8 100644
--- a/modules/statistics/lib/AccessCheck.php
+++ b/modules/statistics/lib/AccessCheck.php
@@ -28,7 +28,7 @@ class sspmod_statistics_AccessCheck {
return;
}
- if (SimpleSAML_Utilities::isAdmin()) {
+ if (SimpleSAML\Utils\Auth::isAdmin()) {
// User logged in as admin. OK.
SimpleSAML_Logger::debug('Statistics auth - logged in as admin, access granted');
return;
@@ -36,7 +36,7 @@ class sspmod_statistics_AccessCheck {
if (!isset($authsource)) {
// If authsource is not defined, init admin login.
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
/* We are using an authsource for login. */
diff --git a/modules/statistics/lib/Aggregator.php b/modules/statistics/lib/Aggregator.php
index f588ca6..6806724 100644
--- a/modules/statistics/lib/Aggregator.php
+++ b/modules/statistics/lib/Aggregator.php
@@ -122,7 +122,7 @@ class sspmod_statistics_Aggregator {
echo("----------------------------------------\n");
echo('Log line: ' . $logline . "\n");
echo('Date parse [' . substr($logline, 0, $this->statconfig->getValue('datelength', 15)) . '] to [' . date(DATE_RFC822, $epoch) . ']' . "\n");
- print_r($content);
+ echo htmlentities(print_r($content, true));
if ($i >= 13) exit;
}
@@ -145,17 +145,15 @@ class sspmod_statistics_Aggregator {
if ($type !== 'aggregate') continue;
foreach($this->timeres AS $tres => $tresconfig ) {
-
- // echo 'Comparing action: [' . $rule['action'] . '] with [' . $action . ']' . "\n";
+
$dh = 'default';
if (isset($tresconfig['customDateHandler'])) $dh = $tresconfig['customDateHandler'];
$timeslot = $datehandler['default']->toSlot($epoch, $tresconfig['slot']);
- $fileslot = $datehandler[$dh]->toSlot($epoch, $tresconfig['fileslot']); //print_r($content);
+ $fileslot = $datehandler[$dh]->toSlot($epoch, $tresconfig['fileslot']);
if (isset($rule['action']) && ($action !== $rule['action'])) continue;
-
- #$difcol = trim($content[$rule['col']]); // echo '[...' . $difcol . '...]';
+
$difcol = self::getDifCol($content, $rule['col']);
if (!isset($results[$rulename][$tres][$fileslot][$timeslot]['_'])) $results[$rulename][$tres][$fileslot][$timeslot]['_'] = 0;
@@ -207,9 +205,7 @@ class sspmod_statistics_Aggregator {
public function store($results) {
-
- // print_r($results); // exit;
-
+
$datehandler = array(
'default' => new sspmod_statistics_DateHandler($this->offset),
'month' => new sspmod_statistics_DateHandlerMonth($this->offset),
@@ -217,11 +213,7 @@ class sspmod_statistics_Aggregator {
// Iterate the first level of results, which is per rule, as defined in the config.
foreach ($results AS $rulename => $timeresdata) {
-
- // $timeresl = array_keys($timeresdata);
- //
- // print_r($timeresl); exit;
-
+
// Iterate over time resolutions
foreach($timeresdata AS $tres => $resres) {
@@ -240,7 +232,6 @@ class sspmod_statistics_Aggregator {
// The last slot.
$maxslot = $slotlist[count($slotlist)-1];
- #print_r($slotlist);
// Get start and end slot number within the file, based on the fileslot.
$start = (int)$datehandler['default']->toSlot(
@@ -249,38 +240,28 @@ class sspmod_statistics_Aggregator {
$end = (int)$datehandler['default']->toSlot(
$datehandler[$dh]->fromSlot($fileno+1, $this->timeres[$tres]['fileslot']),
$this->timeres[$tres]['slot']);
-
- // echo('from slot ' . $start . ' to slot ' . $end . ' maxslot ' . $maxslot . "\n");
- // print_r($slotlist);
- // exit;
-
+
// Fill in missing entries and sort file results
$filledresult = array();
for ($slot = $start; $slot < $end; $slot++) {
if (array_key_exists($slot, $fileres)) {
$filledresult[$slot] = $fileres[$slot];
} else {
- #echo('SLot [' . $slot . '] of [' . $maxslot . ']' . "\n");
if ($lastfile == $fileno && $slot > $maxslot) {
$filledresult[$slot] = array('_' => NULL);
} else {
$filledresult[$slot] = array('_' => 0);
- }
+ }
}
- # print_r($filledresult[$slot]);
- # = (isset($fileres[$slot])) ? $fileres[$slot] : array('_' => NULL);
}
- // print_r($filledresult); exit;
$filename = $this->statdir . '/' . $rulename . '-' . $tres . '-' . $fileno . '.stat';
if (file_exists($filename)) {
- // echo('Reading existing file: ' . $filename . "\n");
$previousData = unserialize(file_get_contents($filename));
$filledresult = $this->cummulateData($previousData, $filledresult);
}
// store file
- # echo('Writing to file: ' . $filename . "\n");
file_put_contents($filename, serialize($filledresult), LOCK_EX);
}
diff --git a/modules/statistics/lib/DateHandler.php b/modules/statistics/lib/DateHandler.php
index 63ecacb..271d5a7 100644
--- a/modules/statistics/lib/DateHandler.php
+++ b/modules/statistics/lib/DateHandler.php
@@ -5,7 +5,7 @@
*/
class sspmod_statistics_DateHandler {
- private $offset;
+ protected $offset;
/**
* Constructor
@@ -27,8 +27,6 @@ class sspmod_statistics_DateHandler {
}
public function fromSlot($slot, $slotsize) {
- // echo("slot $slot slotsize $slotsize offset " . $this->offset);
- // throw new Exception();
$temp = $slot*$slotsize - $this->offset;
$dst = $this->getDST($temp);
return $slot*$slotsize - $this->offset - $dst;
@@ -49,16 +47,4 @@ class sspmod_statistics_DateHandler {
$text .= $this->prettyDateSlot($to, $slotsize, $dateformat);
return $text;
}
-
}
-
-// $datestr = substr($logline,0,$datenumbers);
-// #$datestr = substr($logline,0,23);
-// $timestamp = parse15($datestr) + $offset;
-// $restofline = substr($logline,$datenumbers+1);
-// $restcols = split(' ', $restofline);
-// $action = $restcols[5];
-
-// print_r($timestamp);
-// print_r($restcols); if ($i++ > 5) exit;
-
diff --git a/modules/statistics/lib/DateHandlerMonth.php b/modules/statistics/lib/DateHandlerMonth.php
index 5520a6a..c7f0fae 100644
--- a/modules/statistics/lib/DateHandlerMonth.php
+++ b/modules/statistics/lib/DateHandlerMonth.php
@@ -5,8 +5,6 @@
*/
class sspmod_statistics_DateHandlerMonth extends sspmod_statistics_DateHandler {
-
-
/**
* Constructor
*
@@ -19,10 +17,8 @@ class sspmod_statistics_DateHandlerMonth extends sspmod_statistics_DateHandler {
public function toSlot($epoch, $slotsize) {
$dsttime = $this->getDST($epoch) + $epoch;
- $parsed = getdate($dsttime);
- // print_r($parsed);
+ $parsed = getdate($dsttime);
$slot = (($parsed['year'] - 2000) * 12) + $parsed['mon'] - 1;
- // echo('converting ' . $epoch . ' to ' . $slot ); exit;
return $slot;
}
@@ -32,7 +28,6 @@ class sspmod_statistics_DateHandlerMonth extends sspmod_statistics_DateHandler {
$year = 2000 + floor($slot / 12);
$epoch = mktime(0, 0, 0, $month + 1, 1, $year, FALSE);
- // echo('epoch ' . $epoch . ' from slot '. $slot . " year " . $year . " month " . $month . "\n");
return $epoch;
}
@@ -43,17 +38,4 @@ class sspmod_statistics_DateHandlerMonth extends sspmod_statistics_DateHandler {
return $year . '-' . $month;
}
-
-
}
-
-// $datestr = substr($logline,0,$datenumbers);
-// #$datestr = substr($logline,0,23);
-// $timestamp = parse15($datestr) + $offset;
-// $restofline = substr($logline,$datenumbers+1);
-// $restcols = split(' ', $restofline);
-// $action = $restcols[5];
-
-// print_r($timestamp);
-// print_r($restcols); if ($i++ > 5) exit;
-
diff --git a/modules/statistics/lib/Graph/GoogleCharts.php b/modules/statistics/lib/Graph/GoogleCharts.php
index 385068e..cf1564c 100644
--- a/modules/statistics/lib/Graph/GoogleCharts.php
+++ b/modules/statistics/lib/Graph/GoogleCharts.php
@@ -46,13 +46,11 @@ class sspmod_statistics_Graph_GoogleCharts {
if($v >= 0 && $v <= 100){
$first = substr($extended_table, intval( ($delta*$v/100) / $size),1);
$second = substr($extended_table, intval( ($delta*$v/100) % $size), 1);
- $chardata .= "$first$second";
- #echo '<p>encoding ' . $v . ' to ' . $first . ' ' . $second . '';
+ $chardata .= "$first$second";
} else {
$chardata .= '__'; // Value out of max range;
}
- }
- #echo ' encoding ' . join(' ', $values) . ' to ' . $chardata; exit;
+ }
return($chardata);
}
@@ -105,7 +103,6 @@ class sspmod_statistics_Graph_GoogleCharts {
'&chd=' . $this->encodedata($datasets) .
// Fill area...
-# $this->getFillArea($datasets) .
'&chco=ff5c00,cca600' .
'&chls=1,1,0|1,6,3' .
@@ -113,9 +110,7 @@ class sspmod_statistics_Graph_GoogleCharts {
'&cht=lc' .
$labeld .
'&chxl=0:|' . $this->encodeaxis($axis) . # . $'|1:||top' .
- '&chxp=0,' . join(',', $axispos) .
-# '&chxp=0,0.3,0.4' .
-# '&chm=R,CCCCCC,0,0.25,0.5' .
+ '&chxp=0,' . join(',', $axispos) .
'&chg=' . (2400/(count($datasets[0])-1)) . ',-1,3,3'; // lines
return $url;
}
diff --git a/modules/statistics/lib/LogCleaner.php b/modules/statistics/lib/LogCleaner.php
index 55c7493..652dc67 100644
--- a/modules/statistics/lib/LogCleaner.php
+++ b/modules/statistics/lib/LogCleaner.php
@@ -46,9 +46,7 @@ class sspmod_statistics_LogCleaner {
$file = fopen($this->inputfile, 'r');
- #$logfile = file($this->inputfile, FILE_IGNORE_NEW_LINES );
-
-
+
$logparser = new sspmod_statistics_LogParser(
$this->statconfig->getValue('datestart', 0), $this->statconfig->getValue('datelength', 15), $this->statconfig->getValue('offsetspan', 44)
);
@@ -78,7 +76,6 @@ class sspmod_statistics_LogCleaner {
}
$trackid = $content[4];
- #echo "trackid: " . $content[4] . "\n";
if(!isset($sessioncounter[$trackid])) $sessioncounter[$trackid] = 0;
$sessioncounter[$trackid]++;
@@ -88,7 +85,7 @@ class sspmod_statistics_LogCleaner {
echo("----------------------------------------\n");
echo('Log line: ' . $logline . "\n");
echo('Date parse [' . substr($logline, 0, $this->statconfig->getValue('datelength', 15)) . '] to [' . date(DATE_RFC822, $epoch) . ']' . "\n");
- print_r($content);
+ echo htmlentities(print_r($content, true));
if ($i >= 13) exit;
}
@@ -105,8 +102,7 @@ class sspmod_statistics_LogCleaner {
foreach($sessioncounter AS $trackid => $sc) {
if($sc > 200) $todelete[] = $trackid;
}
-
- #print_r($histogram);
+
return $todelete;
}
@@ -122,8 +118,7 @@ class sspmod_statistics_LogCleaner {
throw new Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
$file = fopen($this->inputfile, 'r');
- #$logfile = file($this->inputfile, FILE_IGNORE_NEW_LINES );
-
+
/* Open the output file in a way that guarantees that we will not overwrite a random file. */
if (file_exists($outputfile)) {
/* Delete existing output file. */
@@ -157,10 +152,7 @@ class sspmod_statistics_LogCleaner {
$trackid = $content[4];
if (in_array($trackid, $todelete)) {
- #echo "Deleting entry with trackid: $trackid \n";
continue;
- } else {
- #echo "NOT Deleting entry with trackid: $trackid \n";
}
fputs($outfile, $logline);
diff --git a/modules/statistics/lib/LogParser.php b/modules/statistics/lib/LogParser.php
index d0d54ca..bde18db 100644
--- a/modules/statistics/lib/LogParser.php
+++ b/modules/statistics/lib/LogParser.php
@@ -38,9 +38,6 @@ class sspmod_statistics_LogParser {
$year = gmdate('Y', $epoch) - 1;
$epoch = gmmktime($hour, $minute, $second, $month, $day, $year);
}
-
-// echo 'debug ' . $line . "\n";
-// echo 'debug [' . substr($line, 0, $this->datelength) . '] => [' . $epoch . ']' . "\n";
return $epoch;
}
diff --git a/modules/statistics/lib/RatioDataset.php b/modules/statistics/lib/RatioDataset.php
index 9c1314c..653fc88 100644
--- a/modules/statistics/lib/RatioDataset.php
+++ b/modules/statistics/lib/RatioDataset.php
@@ -34,7 +34,6 @@ class sspmod_statistics_RatioDataset extends sspmod_statistics_StatDataset {
asort($this->summary);
$this->summary = array_reverse($this->summary, TRUE);
- // echo '<pre>'; print_r($summaryDataset); exit;
}
private function ag($k, $a) {
@@ -49,7 +48,6 @@ class sspmod_statistics_RatioDataset extends sspmod_statistics_StatDataset {
public function combine($result1, $result2) {
-
$combined = array();
foreach($result2 AS $tick => $val) {
@@ -62,17 +60,6 @@ class sspmod_statistics_RatioDataset extends sspmod_statistics_StatDataset {
}
}
-
- // echo('<pre>');
- // echo('combine 1 ');
- // print_r($result1);
- // echo('combine 2 ');
- // print_r($result2);
- // echo('combineed ');
- // print_r($combined);
- //
- // exit;
-
return $combined;
}
diff --git a/modules/statistics/lib/Ruleset.php b/modules/statistics/lib/Ruleset.php
index f237249..0af00dd 100644
--- a/modules/statistics/lib/Ruleset.php
+++ b/modules/statistics/lib/Ruleset.php
@@ -51,7 +51,6 @@ class sspmod_statistics_Ruleset {
foreach ($this->availrules AS $key) {
$available_rules[$key] = array('name' => $statrules[$key]['name'], 'descr' => $statrules[$key]['descr']);
}
- // echo('<pre>'); print_r($available_rules); exit;
$this->availrulenames = $available_rules;
}
diff --git a/modules/statistics/lib/StatDataset.php b/modules/statistics/lib/StatDataset.php
index 1ea4f1a..fab589d 100644
--- a/modules/statistics/lib/StatDataset.php
+++ b/modules/statistics/lib/StatDataset.php
@@ -65,7 +65,6 @@ class sspmod_statistics_StatDataset {
public function setDelimiter($delimiter = '_') {
if (empty($delimiter)) $delimiter = '_';
$this->delimiter = $delimiter;
- // echo 'delimiter set to ' . $delimiter; exit;
}
public function getDelimiter() {
if ($this->delimiter === '_') return NULL;
@@ -79,8 +78,7 @@ class sspmod_statistics_StatDataset {
*/
$slotsize = $this->ruleconfig->getValue('slot');
$dateformat_period = $this->timeresconfig->getValue('dateformat-period');
- $dateformat_intra = $this->timeresconfig->getValue('dateformat-intra');
- // $axislabelint = $this->ruleconfig->getValue('axislabelint');
+ $dateformat_intra = $this->timeresconfig->getValue('dateformat-intra');
$maxvalue = 0; $maxvaluetime = NULL;
@@ -96,12 +94,11 @@ class sspmod_statistics_StatDataset {
public function getDebugData() {
$debugdata = array();
-
+
$slotsize = $this->timeresconfig->getValue('slot');
$dateformat_period = $this->timeresconfig->getValue('dateformat-period');
- $dateformat_intra = $this->timeresconfig->getValue('dateformat-intra');
- // $axislabelint = $this->ruleconfig->getValue('axislabelint');
-
+ $dateformat_intra = $this->timeresconfig->getValue('dateformat-intra');
+
foreach($this->results AS $slot => &$res) {
$debugdata[$slot] = array($this->datehandlerTick->prettyDateSlot($slot, $slotsize, $dateformat_intra), $res[$this->delimiter] );
}
@@ -125,7 +122,6 @@ class sspmod_statistics_StatDataset {
}
asort($this->summary);
$this->summary = array_reverse($this->summary, TRUE);
- // echo '<pre>'; print_r($summaryDataset); exit;
}
public function getTopDelimiters() {
@@ -195,8 +191,7 @@ class sspmod_statistics_StatDataset {
// check if there should be an axis here...
if ( $slot % $axislabelint == 0) {
$axis[] = $this->datehandlerTick->prettyDateSlot($slot, $slotsize, $dateformat_intra);
- $axispos[] = (($i)/($xentries-1));
- // echo 'set axis on [' . $slot . '] = [' . $datehandler->prettyDateSlot($slot, $slotsize, $dateformat_intra) . ']';
+ $axispos[] = (($i)/($xentries-1));
}
$lastslot = $slot;
$i++;
@@ -218,18 +213,13 @@ class sspmod_statistics_StatDataset {
$dateformat_period = $this->timeresconfig->getValue('dateformat-period');
$dateformat_intra = $this->timeresconfig->getValue('dateformat-intra');
$axislabelint = $this->timeresconfig->getValue('axislabelint');
-
- #$max = 25;
+
$xentries = count($this->results);
$lastslot = 0; $i = 0;
$dataset = array();
foreach($this->results AS $slot => $res) {
- #echo ('<p>new value: ' . number_format(100*$res[$delimiter] / $max, 2));
- // echo('<hr><p>delimiter [<tt>' .$delimiter . '</tt>].');
- // echo('<p>Res <pre>'); print_r($res); echo( '</pre>');
- // echo('<p>return <pre>'); print_r(isset($res[$delimiter]) ? $res[$delimiter] : 'NO'); echo('</pre>');
if (array_key_exists($this->delimiter, $res)) {
if ($res[$this->delimiter] === NULL) {
$dataset[] = -1;
@@ -239,8 +229,6 @@ class sspmod_statistics_StatDataset {
} else {
$dataset[] = '0';
}
- // foreach(array_keys($res) AS $nd) $availdelimiters[$nd] = 1;
-
$lastslot = $slot;
$i++;
}
@@ -294,7 +282,7 @@ class sspmod_statistics_StatDataset {
$statdir = $this->statconfig->getValue('statdir');
$resarray = array();
- $rules = SimpleSAML_Utilities::arrayize($this->ruleid);
+ $rules = SimpleSAML\Utils\Arrays::arrayize($this->ruleid);
foreach($rules AS $rule) {
// Get file and extract results.
$resultFileName = $statdir . '/' . $rule . '-' . $this->timeres . '-'. $this->fileslot . '.stat';
diff --git a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
index 6c2068f..65099c8 100644
--- a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
+++ b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
@@ -39,7 +39,6 @@ class sspmod_statistics_Statistics_Rulesets_BaseRule {
if (array_key_exists($tres, $this->available))
$available_times[$tres] = $tresconfig['name'];
}
- // echo('<pre>'); print_r($available_times); exit;
return $available_times;
}
diff --git a/modules/statistics/templates/statistics-tpl.php b/modules/statistics/templates/statistics-tpl.php
index 6fe94a4..73f5e5f 100644
--- a/modules/statistics/templates/statistics-tpl.php
+++ b/modules/statistics/templates/statistics-tpl.php
@@ -3,8 +3,6 @@ $this->data['header'] = 'SimpleSAMLphp Statistics';
$this->data['jquery'] = array('version' => '1.6', 'core' => TRUE, 'ui' => TRUE, 'css' => TRUE);
-// $this->data['hideLanguageBar'] = TRUE;
-
$this->data['head'] ='';
$this->data['head'] .= '<script type="text/javascript">
$(document).ready(function() {
@@ -92,11 +90,6 @@ td.datacontent {
echo('<h1>'. $this->data['available.rules'][$this->data['selected.rule']]['name'] . '</h1>');
echo('<p>' . $this->data['available.rules'][$this->data['selected.rule']]['descr'] . '</p>');
-// echo('<pre>');
-// print_r($this->data);
-// exit;
-
-
// Report settings
echo '<table class="selecttime" style="width: 100%; border: 1px solid #ccc; background: #eee; margin: 1px 0px; padding: 0px">';
echo('<tr><td style="width: 50px; padding: 0px"><img style="margin: 0px" src="../../resources/icons/crystal_project/kchart.32x32.png" alt="Report settings" /></td>');
@@ -119,9 +112,6 @@ echo '</td>';
// Select delimiter
echo '<td style="text-align: right">';
-
-#echo('<pre>here'); print_r($this->data['delimiterPresentation']); echo('</pre>');
-
echo '<form style="display: inline">';
echo getBaseURL($this, 'post', 'd');
echo '<select onChange="submit();" name="d">';
@@ -168,7 +158,6 @@ if (isset($this->data['available.times.prev'])) {
echo '<td style="text-align: right">';
echo '<form style="display: inline">';
echo getBaseURL($this, 'post', 'res');
-// echo '<input type="hidden" name="rule" value="' . $this->data['selected.rule'] . '" />';
echo '<select onChange="submit();" name="res">';
foreach ($this->data['available.timeres'] AS $key => $timeresname) {
if ($key == $this->data['selected.timeres']) {
@@ -184,7 +173,6 @@ echo '</td>';
echo '<td style="text-align: left">';
echo '<form style="display: inline">';
echo getBaseURL($this, 'post', 'time');
-// echo '<input type="hidden" name="rule" value="' . $this->data['selected.rule'] . '" />';
echo '<select onChange="submit();" name="time">';
foreach ($this->data['available.times'] AS $key => $timedescr) {
if ($key == $this->data['selected.time']) {
@@ -272,18 +260,7 @@ foreach ( $this->data['summaryDataset'] as $key => $value ) {
echo '</table></div>';
// - - - - - - - End table view - - - - - - -
-
-//
-// echo('<pre>');
-// print_r($this->data['results']);
-// exit;
-
-
echo '<div id="debug" >';
-
-#echo $this->data['selected.time'];
-#echo '<input style="width: 80%" value="' . htmlspecialchars($this->data['imgurl']) . '" />';
-
echo '<table class="timeseries" style="">';
echo('<tr><th>Time</th><th>Total</th>');
foreach($this->data['topdelimiters'] AS $key) {
diff --git a/modules/statistics/www/showstats.php b/modules/statistics/www/showstats.php
index 0af0e9d..ed4c443 100644
--- a/modules/statistics/www/showstats.php
+++ b/modules/statistics/www/showstats.php
@@ -62,7 +62,6 @@ $maxes[] = $dataset->getMax();
if (isset($preferRule2)) {
$statrule = $ruleset->getRule($preferRule2);
-# $rule2 = $statrule->getRuleID();
$dataset2 = $statrule->getDataset($preferTimeRes, $preferTime);
$dataset2->aggregateSummary();
$dataset2->calculateMax();
diff --git a/templates/includes/header.php b/templates/includes/header.php
index cb59059..03f1953 100644
--- a/templates/includes/header.php
+++ b/templates/includes/header.php
@@ -186,7 +186,7 @@ if($onLoad !== '') {
if ($current) {
$textarray[] = $langnames[$lang];
} else {
- $textarray[] = '<a href="' . htmlspecialchars(SimpleSAML_Utilities::addURLparameter(SimpleSAML_Utilities::selfURL(), array($this->languageParameterName => $lang))) . '">' .
+ $textarray[] = '<a href="' . htmlspecialchars(\SimpleSAML\Utils\HTTP::addURLParameters(\SimpleSAML\Utils\HTTP::getSelfURL(), array($this->languageParameterName => $lang))) . '">' .
$langnames[$lang] . '</a>';
}
}
diff --git a/templates/selectidp-links.php b/templates/selectidp-links.php
index c513838..54d6696 100644
--- a/templates/selectidp-links.php
+++ b/templates/selectidp-links.php
@@ -46,7 +46,7 @@ foreach ($this->data['idplist'] AS $idpentry) {
echo ' <img src="/' . $this->data['baseurlpath'] .'resources/icons/experience/gtk-about.64x64.png" class="float-r" alt="'.$this->t('icon_prefered_idp').'" />';
if(array_key_exists('icon', $idpentry) && $idpentry['icon'] !== NULL) {
- $iconUrl = SimpleSAML_Utilities::resolveURL($idpentry['icon']);
+ $iconUrl = \SimpleSAML\Utils\HTTP::resolveURL($idpentry['icon']);
echo '<img class="float-l" style="margin: 1em; padding: 3px; border: 1px solid #999" src="' . htmlspecialchars($iconUrl) . '" />';
}
echo "\n" . ' <h3 style="margin-top: 8px">' . htmlspecialchars($this->t('idpname_' . $idpentry['entityid'])) . '</h3>';
@@ -65,7 +65,7 @@ foreach ($this->data['idplist'] AS $idpentry) {
if ($idpentry['entityid'] != $this->data['preferredidp']) {
if(array_key_exists('icon', $idpentry) && $idpentry['icon'] !== NULL) {
- $iconUrl = SimpleSAML_Utilities::resolveURL($idpentry['icon']);
+ $iconUrl = \SimpleSAML\Utils\HTTP::resolveURL($idpentry['icon']);
echo '<img class="float-l" style="clear: both; margin: 1em; padding: 3px; border: 1px solid #999" src="' . htmlspecialchars($iconUrl) . '" />';
}
echo "\n" . ' <h3 style="margin-top: 8px">' . htmlspecialchars($this->t('idpname_' . $idpentry['entityid'])) . '</h3>';
diff --git a/tests/Utils/MetadataTest.php b/tests/Metadata/MetadataTest.php
index 12eafa8..26ca926 100644
--- a/tests/Utils/MetadataTest.php
+++ b/tests/Metadata/MetadataTest.php
@@ -1,8 +1,9 @@
<?php
+
+
/**
- * Class Utils_MetadataTest
+ * Tests related to SAML metadata.
*/
-
class Utils_MetadataTest extends PHPUnit_Framework_TestCase
{
@@ -16,7 +17,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
'name' => 'John Doe'
);
try {
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertStringStartsWith('"contactType" is mandatory and must be one of ', $e->getMessage());
}
@@ -26,17 +27,17 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
'contactType' => 'invalid'
);
try {
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertStringStartsWith('"contactType" is mandatory and must be one of ', $e->getMessage());
}
// test all valid contact types
- foreach (SimpleSAML_Utils_Config_Metadata::$VALID_CONTACT_TYPES as $type) {
+ foreach (\SimpleSAML\Utils\Config\Metadata::$VALID_CONTACT_TYPES as $type) {
$contact = array(
'contactType' => $type
);
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
$this->assertArrayHasKey('contactType', $parsed);
$this->assertArrayNotHasKey('givenName', $parsed);
$this->assertArrayNotHasKey('surName', $parsed);
@@ -45,9 +46,9 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
// test basic name parsing
$contact = array(
'contactType' => 'technical',
- 'name' => 'John Doe'
+ 'name' => 'John Doe'
);
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
$this->assertArrayNotHasKey('name', $parsed);
$this->assertArrayHasKey('givenName', $parsed);
$this->assertArrayHasKey('surName', $parsed);
@@ -57,9 +58,9 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
// test comma-separated names
$contact = array(
'contactType' => 'technical',
- 'name' => 'Doe, John'
+ 'name' => 'Doe, John'
);
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
$this->assertArrayHasKey('givenName', $parsed);
$this->assertArrayHasKey('surName', $parsed);
$this->assertEquals('John', $parsed['givenName']);
@@ -68,9 +69,9 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
// test long names
$contact = array(
'contactType' => 'technical',
- 'name' => 'John Fitzgerald Doe Smith'
+ 'name' => 'John Fitzgerald Doe Smith'
);
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
$this->assertArrayNotHasKey('name', $parsed);
$this->assertArrayHasKey('givenName', $parsed);
$this->assertArrayNotHasKey('surName', $parsed);
@@ -79,9 +80,9 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
// test comma-separated long names
$contact = array(
'contactType' => 'technical',
- 'name' => 'Doe Smith, John Fitzgerald'
+ 'name' => 'Doe Smith, John Fitzgerald'
);
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
$this->assertArrayNotHasKey('name', $parsed);
$this->assertArrayHasKey('givenName', $parsed);
$this->assertArrayHasKey('surName', $parsed);
@@ -96,7 +97,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['givenName'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals('"givenName" must be a string and cannot be empty.', $e->getMessage());
}
@@ -110,7 +111,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['surName'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals('"surName" must be a string and cannot be empty.', $e->getMessage());
}
@@ -124,7 +125,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['company'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals('"company" must be a string and cannot be empty.', $e->getMessage());
}
@@ -138,7 +139,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['emailAddress'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals(
'"emailAddress" must be a string or an array and cannot be empty.',
@@ -150,7 +151,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['emailAddress'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals(
'Email addresses must be a string and cannot be empty.',
@@ -167,7 +168,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['telephoneNumber'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals(
'"telephoneNumber" must be a string or an array and cannot be empty.',
@@ -179,7 +180,7 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
foreach ($invalid_types as $type) {
$contact['telephoneNumber'] = $type;
try {
- SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ \SimpleSAML\Utils\Config\Metadata::getContact($contact);
} catch (InvalidArgumentException $e) {
$this->assertEquals('Telephone numbers must be a string and cannot be empty.', $e->getMessage());
}
@@ -187,12 +188,12 @@ class Utils_MetadataTest extends PHPUnit_Framework_TestCase
// test completeness
$contact = array();
- foreach (SimpleSAML_Utils_Config_Metadata::$VALID_CONTACT_OPTIONS as $option) {
+ foreach (\SimpleSAML\Utils\Config\Metadata::$VALID_CONTACT_OPTIONS as $option) {
$contact[$option] = 'string';
}
$contact['contactType'] = 'technical';
$contact['name'] = 'to_be_removed';
- $parsed = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $parsed = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
foreach (array_keys($parsed) as $key) {
$this->assertEquals($parsed[$key], $contact[$key]);
}
diff --git a/tests/Metadata/SAMLBuilderTest.php b/tests/Metadata/SAMLBuilderTest.php
new file mode 100644
index 0000000..48caa5e
--- /dev/null
+++ b/tests/Metadata/SAMLBuilderTest.php
@@ -0,0 +1,137 @@
+<?php
+
+
+/**
+ * Class SimpleSAML_Metadata_SAMLBuilderTest
+ */
+class SimpleSAML_Metadata_SAMLBuilderTest extends PHPUnit_Framework_TestCase
+{
+
+ /**
+ * Test the requeste attributes are valued correctly.
+ */
+ public function testAttributes()
+ {
+ $entityId = 'https://entity.example.com/id';
+
+ // test SP20 array parsing, no friendly name
+ $set = 'saml20-sp-remote';
+ $metadata = array(
+ 'entityid' => $entityId,
+ 'name' => array('en' => 'Test SP'),
+ 'metadata-set' => $set,
+ 'attributes' => array(
+ 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
+ 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
+ 'urn:oid:0.9.2342.19200300.100.1.3',
+ 'urn:oid:2.5.4.3',
+ ),
+ );
+
+ $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
+ $samlBuilder->addMetadata($set, $metadata);
+
+ $spDesc = $samlBuilder->getEntityDescriptor();
+ $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
+ $this->assertEquals(1, $acs->length);
+ $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
+ $this->assertEquals(4, $attributes->length);
+ for ($c = 0; $c < $attributes->length; $c++) {
+ $curAttribute = $attributes->item($c);
+ $this->assertTrue($curAttribute->hasAttribute("Name"));
+ $this->assertFalse($curAttribute->hasAttribute("FriendlyName"));
+ $this->assertEquals($metadata['attributes'][$c], $curAttribute->getAttribute("Name"));
+ }
+
+ // test SP20 array parsing, no friendly name
+ $set = 'saml20-sp-remote';
+ $metadata = array(
+ 'entityid' => $entityId,
+ 'name' => array('en' => 'Test SP'),
+ 'metadata-set' => $set,
+ 'attributes' => array(
+ 'eduPersonTargetedID' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
+ 'eduPersonPrincipalName' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
+ 'eduPersonOrgDN' => 'urn:oid:0.9.2342.19200300.100.1.3',
+ 'cn' => 'urn:oid:2.5.4.3',
+ ),
+ );
+
+ $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
+ $samlBuilder->addMetadata($set, $metadata);
+
+ $spDesc = $samlBuilder->getEntityDescriptor();
+ $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
+ $this->assertEquals(1, $acs->length);
+ $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
+ $this->assertEquals(4, $attributes->length);
+ $keys = array_keys($metadata['attributes']);
+ for ($c = 0; $c < $attributes->length; $c++) {
+ $curAttribute = $attributes->item($c);
+ $this->assertTrue($curAttribute->hasAttribute("Name"));
+ $this->assertTrue($curAttribute->hasAttribute("FriendlyName"));
+ $this->assertEquals($metadata['attributes'][$keys[$c]], $curAttribute->getAttribute("Name"));
+ $this->assertEquals($keys[$c], $curAttribute->getAttribute("FriendlyName"));
+ }
+
+ // test SP13 array parsing, no friendly name
+ $set = 'shib13-sp-remote';
+ $metadata = array(
+ 'entityid' => $entityId,
+ 'name' => array('en' => 'Test SP'),
+ 'metadata-set' => $set,
+ 'attributes' => array(
+ 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
+ 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
+ 'urn:oid:0.9.2342.19200300.100.1.3',
+ 'urn:oid:2.5.4.3',
+ ),
+ );
+
+ $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
+ $samlBuilder->addMetadata($set, $metadata);
+
+ $spDesc = $samlBuilder->getEntityDescriptor();
+ $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
+ $this->assertEquals(1, $acs->length);
+ $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
+ $this->assertEquals(4, $attributes->length);
+ for ($c = 0; $c < $attributes->length; $c++) {
+ $curAttribute = $attributes->item($c);
+ $this->assertTrue($curAttribute->hasAttribute("Name"));
+ $this->assertFalse($curAttribute->hasAttribute("FriendlyName"));
+ $this->assertEquals($metadata['attributes'][$c], $curAttribute->getAttribute("Name"));
+ }
+
+ // test SP20 array parsing, no friendly name
+ $set = 'shib13-sp-remote';
+ $metadata = array(
+ 'entityid' => $entityId,
+ 'name' => array('en' => 'Test SP'),
+ 'metadata-set' => $set,
+ 'attributes' => array(
+ 'eduPersonTargetedID' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
+ 'eduPersonPrincipalName' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
+ 'eduPersonOrgDN' => 'urn:oid:0.9.2342.19200300.100.1.3',
+ 'cn' => 'urn:oid:2.5.4.3',
+ ),
+ );
+
+ $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
+ $samlBuilder->addMetadata($set, $metadata);
+
+ $spDesc = $samlBuilder->getEntityDescriptor();
+ $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
+ $this->assertEquals(1, $acs->length);
+ $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
+ $this->assertEquals(4, $attributes->length);
+ $keys = array_keys($metadata['attributes']);
+ for ($c = 0; $c < $attributes->length; $c++) {
+ $curAttribute = $attributes->item($c);
+ $this->assertTrue($curAttribute->hasAttribute("Name"));
+ $this->assertTrue($curAttribute->hasAttribute("FriendlyName"));
+ $this->assertEquals($metadata['attributes'][$keys[$c]], $curAttribute->getAttribute("Name"));
+ $this->assertEquals($keys[$c], $curAttribute->getAttribute("FriendlyName"));
+ }
+ }
+}
diff --git a/tests/SimpleSAML/Metadata/SAMLBuilderTest.php b/tests/SimpleSAML/Metadata/SAMLBuilderTest.php
deleted file mode 100644
index 277a3b6..0000000
--- a/tests/SimpleSAML/Metadata/SAMLBuilderTest.php
+++ /dev/null
@@ -1,137 +0,0 @@
-<?php
-/**
- * Class SimpleSAML_Metadata_SAMLBuilderTest
- */
-
-class SimpleSAML_Metadata_SAMLBuilderTest extends PHPUnit_Framework_TestCase
-{
-
- /**
- * Test the requeste attributes are valued correctly.
- */
- public function testAttributes()
- {
- $entityId = 'https://entity.examle.com/id';
-
- // test SP20 array parsing, no friendly name
- $set = 'saml20-sp-remote';
- $metadata = array(
- 'entityid' => $entityId,
- 'name' => array('en' => 'Test SP'),
- 'metadata-set' => $set,
- 'attributes' => array(
- 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
- 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
- 'urn:oid:0.9.2342.19200300.100.1.3',
- 'urn:oid:2.5.4.3',
- ),
- );
-
- $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
- $samlBuilder->addMetadata($set, $metadata);
-
- $spDesc = $samlBuilder->getEntityDescriptor();
- $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
- $this->assertEquals(1, $acs->length);
- $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
- $this->assertEquals(4, $attributes->length);
- for ($c = 0; $c < $attributes->length; $c++) {
- $curAttribute = $attributes->item($c);
- $this->assertTrue($curAttribute->hasAttribute("Name"));
- $this->assertFalse($curAttribute->hasAttribute("FriendlyName"));
- $this->assertEquals($metadata['attributes'][$c], $curAttribute->getAttribute("Name"));
- }
-
- // test SP20 array parsing, no friendly name
- $set = 'saml20-sp-remote';
- $metadata = array(
- 'entityid' => $entityId,
- 'name' => array('en' => 'Test SP'),
- 'metadata-set' => $set,
- 'attributes' => array(
- 'eduPersonTargetedID' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
- 'eduPersonPrincipalName' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
- 'eduPersonOrgDN' => 'urn:oid:0.9.2342.19200300.100.1.3',
- 'cn' => 'urn:oid:2.5.4.3',
- ),
- );
-
- $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
- $samlBuilder->addMetadata($set, $metadata);
-
- $spDesc = $samlBuilder->getEntityDescriptor();
- $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
- $this->assertEquals(1, $acs->length);
- $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
- $this->assertEquals(4, $attributes->length);
- $keys = array_keys($metadata['attributes']);
- for ($c = 0; $c < $attributes->length; $c++) {
- $curAttribute = $attributes->item($c);
- $this->assertTrue($curAttribute->hasAttribute("Name"));
- $this->assertTrue($curAttribute->hasAttribute("FriendlyName"));
- $this->assertEquals($metadata['attributes'][$keys[$c]], $curAttribute->getAttribute("Name"));
- $this->assertEquals($keys[$c], $curAttribute->getAttribute("FriendlyName"));
- }
-
- // test SP13 array parsing, no friendly name
- $set = 'shib13-sp-remote';
- $metadata = array(
- 'entityid' => $entityId,
- 'name' => array('en' => 'Test SP'),
- 'metadata-set' => $set,
- 'attributes' => array(
- 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
- 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
- 'urn:oid:0.9.2342.19200300.100.1.3',
- 'urn:oid:2.5.4.3',
- ),
- );
-
- $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
- $samlBuilder->addMetadata($set, $metadata);
-
- $spDesc = $samlBuilder->getEntityDescriptor();
- $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
- $this->assertEquals(1, $acs->length);
- $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
- $this->assertEquals(4, $attributes->length);
- for ($c = 0; $c < $attributes->length; $c++) {
- $curAttribute = $attributes->item($c);
- $this->assertTrue($curAttribute->hasAttribute("Name"));
- $this->assertFalse($curAttribute->hasAttribute("FriendlyName"));
- $this->assertEquals($metadata['attributes'][$c], $curAttribute->getAttribute("Name"));
- }
-
- // test SP20 array parsing, no friendly name
- $set = 'shib13-sp-remote';
- $metadata = array(
- 'entityid' => $entityId,
- 'name' => array('en' => 'Test SP'),
- 'metadata-set' => $set,
- 'attributes' => array(
- 'eduPersonTargetedID' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
- 'eduPersonPrincipalName' => 'urn:oid:1.3.6.1.4.1.5923.1.1.1.6',
- 'eduPersonOrgDN' => 'urn:oid:0.9.2342.19200300.100.1.3',
- 'cn' => 'urn:oid:2.5.4.3',
- ),
- );
-
- $samlBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityId);
- $samlBuilder->addMetadata($set, $metadata);
-
- $spDesc = $samlBuilder->getEntityDescriptor();
- $acs = $spDesc->getElementsByTagName("AttributeConsumingService");
- $this->assertEquals(1, $acs->length);
- $attributes = $acs->item(0)->getElementsByTagName("RequestedAttribute");
- $this->assertEquals(4, $attributes->length);
- $keys = array_keys($metadata['attributes']);
- for ($c = 0; $c < $attributes->length; $c++) {
- $curAttribute = $attributes->item($c);
- $this->assertTrue($curAttribute->hasAttribute("Name"));
- $this->assertTrue($curAttribute->hasAttribute("FriendlyName"));
- $this->assertEquals($metadata['attributes'][$keys[$c]], $curAttribute->getAttribute("Name"));
- $this->assertEquals($keys[$c], $curAttribute->getAttribute("FriendlyName"));
- }
- }
-
-}
diff --git a/tests/Utils/ArraysTest.php b/tests/Utils/ArraysTest.php
new file mode 100644
index 0000000..5cc00de
--- /dev/null
+++ b/tests/Utils/ArraysTest.php
@@ -0,0 +1,165 @@
+<?php
+
+
+/**
+ * Tests for SimpleSAML\Utils\Arrays.
+ */
+class Utils_ArraysTest extends PHPUnit_Framework_TestCase
+{
+
+ /**
+ * Test the arrayize() function.
+ */
+ public function testArrayize()
+ {
+ // check with empty array as input
+ $array = array();
+ $this->assertEquals($array, SimpleSAML\Utils\Arrays::arrayize($array));
+
+ // check non-empty array as input
+ $array = array('key' => 'value');
+ $this->assertEquals($array, SimpleSAML\Utils\Arrays::arrayize($array));
+
+ // check indexes are ignored when input is an array
+ $this->assertArrayNotHasKey('invalid', SimpleSAML\Utils\Arrays::arrayize($array, 'invalid'));
+
+ // check default index
+ $expected = array('string');
+ $this->assertEquals($expected, SimpleSAML\Utils\Arrays::arrayize($expected[0]));
+
+ // check string index
+ $index = 'key';
+ $expected = array($index => 'string');
+ $this->assertEquals($expected, SimpleSAML\Utils\Arrays::arrayize($expected[$index], $index));
+ }
+
+ /**
+ * Test the normalizeAttributesArray() function with input not being an array
+ *
+ * @expectedException InvalidArgumentException
+ */
+ public function testNormalizeAttributesArrayBadInput()
+ {
+ SimpleSAML\Utils\Arrays::normalizeAttributesArray('string');
+ }
+
+ /**
+ * Test the normalizeAttributesArray() function with an array with non-string attribute names.
+ *
+ * @expectedException InvalidArgumentException
+ */
+ public function testNormalizeAttributesArrayBadKeys()
+ {
+ SimpleSAML\Utils\Arrays::normalizeAttributesArray(array('attr1' => 'value1', 1 => 'value2'));
+ }
+
+ /**
+ * Test the normalizeAttributesArray() function with an array with non-string attribute values.
+ *
+ * @expectedException InvalidArgumentException
+ */
+ public function testNormalizeAttributesArrayBadValues()
+ {
+ SimpleSAML\Utils\Arrays::normalizeAttributesArray(array('attr1' => 'value1', 'attr2' => 0));
+ }
+
+ /**
+ * Test the normalizeAttributesArray() function.
+ */
+ public function testNormalizeAttributesArray()
+ {
+ $attributes = array(
+ 'key1' => 'value1',
+ 'key2' => array('value2', 'value3'),
+ 'key3' => 'value1'
+ );
+ $expected = array(
+ 'key1' => array('value1'),
+ 'key2' => array('value2', 'value3'),
+ 'key3' => array('value1')
+ );
+ $this->assertEquals($expected, SimpleSAML\Utils\Arrays::normalizeAttributesArray($attributes),
+ 'Attribute array normalization failed');
+ }
+
+
+ /**
+ * Test the transpose() function.
+ */
+ public function testTranspose()
+ {
+ // check bad arrays
+ $this->assertFalse(SimpleSAML\Utils\Arrays::transpose(array('1', '2', '3')),
+ 'Invalid two-dimensional array was accepted');
+ $this->assertFalse(SimpleSAML\Utils\Arrays::transpose(array('1' => 0, '2' => '0', '3' => array(0))),
+ 'Invalid elements on a two-dimensional array were accepted');
+
+ // check array with numerical keys
+ $array = array(
+ 'key1' => array(
+ 'value1'
+ ),
+ 'key2' => array(
+ 'value1',
+ 'value2'
+ )
+ );
+ $transposed = array(
+ array(
+ 'key1' => 'value1',
+ 'key2' => 'value1'
+ ),
+ array(
+ 'key2' => 'value2'
+ )
+ );
+ $this->assertEquals($transposed, SimpleSAML\Utils\Arrays::transpose($array),
+ 'Unexpected result of transpose()');
+
+ // check array with string keys
+ $array = array(
+ 'key1' => array(
+ 'subkey1' => 'value1'
+ ),
+ 'key2' => array(
+ 'subkey1' => 'value1',
+ 'subkey2' => 'value2'
+ )
+ );
+ $transposed = array(
+ 'subkey1' => array(
+ 'key1' => 'value1',
+ 'key2' => 'value1'
+ ),
+ 'subkey2' => array(
+ 'key2' => 'value2'
+ )
+ );
+ $this->assertEquals($transposed, SimpleSAML\Utils\Arrays::transpose($array),
+ 'Unexpected result of transpose()');
+
+ // check array with no keys in common between sub arrays
+ $array = array(
+ 'key1' => array(
+ 'subkey1' => 'value1'
+ ),
+ 'key2' => array(
+ 'subkey2' => 'value1',
+ 'subkey3' => 'value2'
+ )
+ );
+ $transposed = array(
+ 'subkey1' => array(
+ 'key1' => 'value1',
+ ),
+ 'subkey2' => array(
+ 'key2' => 'value1'
+ ),
+ 'subkey3' => array(
+ 'key2' => 'value2'
+ )
+ );
+ $this->assertEquals($transposed, SimpleSAML\Utils\Arrays::transpose($array),
+ 'Unexpected result of transpose()');
+ }
+} \ No newline at end of file
diff --git a/tests/Utils/NetTest.php b/tests/Utils/NetTest.php
new file mode 100644
index 0000000..7632802
--- /dev/null
+++ b/tests/Utils/NetTest.php
@@ -0,0 +1,42 @@
+<?php
+
+
+/**
+ * Tests for SimpleSAML_Utils_Test.
+ */
+class Utils_Net_Test extends PHPUnit_Framework_TestCase
+{
+
+
+ /**
+ * Test the function that checks for IPs belonging to a CIDR.
+ */
+ public function testIpCIDRcheck()
+ {
+ // check CIDR w/o mask
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0', '127.0.0.1'));
+
+ // check wrong CIDR w/ mask
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.256/24', '127.0.0.1'));
+
+ // check wrong IP
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/24', '127.0.0'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/24', '127.0.0.*'));
+
+ // check limits for standard classes
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/24', '127.0.0.0'));
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/24', '127.0.0.255'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/24', '127.0.0.256'));
+
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/16', '127.0.0.0'));
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/16', '127.0.255.255'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/16', '127.0.255.256'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/16', '127.0.256.255'));
+
+ // check limits for non-standard classes
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/23', '127.0.0.0'));
+ $this->assertTrue(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/23', '127.0.1.255'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/23', '127.0.1.256'));
+ $this->assertFalse(SimpleSAML\Utils\Net::ipCIDRcheck('127.0.0.0/23', '127.0.2.0'));
+ }
+} \ No newline at end of file
diff --git a/tools/phpunit/phpunit.xml b/tools/phpunit/phpunit.xml
index edabe12..d0d82a9 100644
--- a/tools/phpunit/phpunit.xml
+++ b/tools/phpunit/phpunit.xml
@@ -1,5 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
-
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
@@ -11,8 +10,11 @@
syntaxCheck="false"
bootstrap="./../../vendor/autoload.php">
<testsuites>
- <testsuite name="Test Suite">
- <directory>./../../tests</directory>
+ <testsuite name="Utils">
+ <directory>./../../tests/Utils/</directory>
+ </testsuite>
+ <testsuite name="Metadata">
+ <directory>./../../tests/Metadata/</directory>
</testsuite>
</testsuites>
<filter>
diff --git a/www/_include.php b/www/_include.php
index 4e9b355..37f0c88 100644
--- a/www/_include.php
+++ b/www/_include.php
@@ -106,6 +106,6 @@ if (!file_exists($configdir . '/config.php')) {
}
/* Set the timezone. */
-SimpleSAML_Utilities::initTimezone();
+SimpleSAML\Utils\Time::initTimezone();
/* Disable XML external entity loading explicitly. */
-SimpleSAML_Utilities::disableXMLEntityLoader();
+libxml_disable_entity_loader();
diff --git a/www/admin/hostnames.php b/www/admin/hostnames.php
index f2a6592..51c2a80 100644
--- a/www/admin/hostnames.php
+++ b/www/admin/hostnames.php
@@ -7,7 +7,7 @@ $config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getSessionFromRequest();
/* Check if valid local session exists.. */
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
$attributes = array();
@@ -16,13 +16,13 @@ $attributes['HTTPS'] = array($_SERVER['HTTPS']);
$attributes['SERVER_PROTOCOL'] = array($_SERVER['SERVER_PROTOCOL']);
$attributes['SERVER_PORT'] = array($_SERVER['SERVER_PORT']);
-$attributes['Utilities_getBaseURL()'] = array(SimpleSAML_Utilities::getBaseURL());
-$attributes['Utilities_getSelfHost()'] = array(SimpleSAML_Utilities::getSelfHost());
-$attributes['Utilities_selfURLhost()'] = array(SimpleSAML_Utilities::selfURLhost());
-$attributes['Utilities_selfURLNoQuery()'] = array(SimpleSAML_Utilities::selfURLNoQuery());
-$attributes['Utilities_getSelfHostWithPath()'] = array(SimpleSAML_Utilities::getSelfHostWithPath());
-$attributes['Utilities_getFirstPathElement()'] = array(SimpleSAML_Utilities::getFirstPathElement());
-$attributes['Utilities_selfURL()'] = array(SimpleSAML_Utilities::selfURL());
+$attributes['Utilities_getBaseURL()'] = array(\SimpleSAML\Utils\HTTP::getBaseURL());
+$attributes['Utilities_getSelfHost()'] = array(\SimpleSAML\Utils\HTTP::getSelfHost());
+$attributes['Utilities_selfURLhost()'] = array(\SimpleSAML\Utils\HTTP::getSelfURLHost());
+$attributes['Utilities_selfURLNoQuery()'] = array(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery());
+$attributes['Utilities_getSelfHostWithPath()'] = array(\SimpleSAML\Utils\HTTP::getSelfHostWithPath());
+$attributes['Utilities_getFirstPathElement()'] = array(\SimpleSAML\Utils\HTTP::getFirstPathElement());
+$attributes['Utilities_selfURL()'] = array(\SimpleSAML\Utils\HTTP::getSelfURL());
$et = new SimpleSAML_XHTML_Template($config, 'hostnames.php');
diff --git a/www/admin/metadata-converter.php b/www/admin/metadata-converter.php
index f91fed0..828d2ce 100644
--- a/www/admin/metadata-converter.php
+++ b/www/admin/metadata-converter.php
@@ -3,14 +3,14 @@
require_once('../_include.php');
/* Make sure that the user has admin access rights. */
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
$config = SimpleSAML_Configuration::getInstance();
if(array_key_exists('xmldata', $_POST)) {
$xmldata = $_POST['xmldata'];
- SimpleSAML_Utilities::validateXMLDocument($xmldata, 'saml-meta');
+ \SimpleSAML\Utils\XML::checkSAMLMessage($xmldata, 'saml-meta');
$entities = SimpleSAML_Metadata_SAMLParser::parseDescriptorsString($xmldata);
/* Get all metadata for the entities. */
@@ -25,7 +25,7 @@ if(array_key_exists('xmldata', $_POST)) {
}
/* Transpose from $entities[entityid][type] to $output[type][entityid]. */
- $output = SimpleSAML_Utilities::transposeArray($entities);
+ $output = SimpleSAML\Utils\Arrays::transpose($entities);
/* Merge all metadata of each type to a single string which should be
* added to the corresponding file.
diff --git a/www/admin/phpinfo.php b/www/admin/phpinfo.php
index 64d2dbf..9451728 100644
--- a/www/admin/phpinfo.php
+++ b/www/admin/phpinfo.php
@@ -3,6 +3,6 @@
require_once('../_include.php');
/* Make sure that the user has admin access rights. */
-SimpleSAML_Utilities::requireAdmin();
+SimpleSAML\Utils\Auth::requireAdmin();
phpinfo();
diff --git a/www/authmemcookie.php b/www/authmemcookie.php
index 8acd307..b6a1f92 100644
--- a/www/authmemcookie.php
+++ b/www/authmemcookie.php
@@ -31,7 +31,7 @@ try {
$s->requireAuth();
/* Generate session id and save it in a cookie. */
- $sessionID = SimpleSAML_Utilities::generateID();
+ $sessionID = SimpleSAML\Utils\Random::generateID();
$cookieName = $amc->getCookieName();
@@ -93,7 +93,7 @@ try {
$session->registerLogoutHandler($sourceId, 'SimpleSAML_AuthMemCookie', 'logoutHandler');
/* Redirect the user back to this page to signal that the login is completed. */
- SimpleSAML_Utilities::redirectTrustedURL(SimpleSAML_Utilities::selfURL());
+ \SimpleSAML\Utils\HTTP::redirectTrustedURL(\SimpleSAML\Utils\HTTP::getSelfURL());
} catch(Exception $e) {
throw new SimpleSAML_Error_Error('CONFIG', $e);
}
diff --git a/www/errorreport.php b/www/errorreport.php
index a0f31e1..042f9a6 100644
--- a/www/errorreport.php
+++ b/www/errorreport.php
@@ -99,4 +99,4 @@ if ($config->getBoolean('errorreporting', TRUE) && $toAddress !== 'na@example.or
}
/* Redirect the user back to this page to clear the POST request. */
-SimpleSAML_Utilities::redirectTrustedURL(SimpleSAML_Utilities::selfURLNoQuery());
+\SimpleSAML\Utils\HTTP::redirectTrustedURL(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery());
diff --git a/www/index.php b/www/index.php
index 4ca3a3b..5d31340 100644
--- a/www/index.php
+++ b/www/index.php
@@ -2,5 +2,4 @@
require_once('_include.php');
-
-SimpleSAML_Utilities::redirectTrustedURL(SimpleSAML_Module::getModuleURL('core/frontpage_welcome.php'));
+\SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('core/frontpage_welcome.php'));
diff --git a/www/logout.php b/www/logout.php
index 5394253..c361b29 100644
--- a/www/logout.php
+++ b/www/logout.php
@@ -6,7 +6,7 @@ $config = SimpleSAML_Configuration::getInstance();
if(array_key_exists('link_href', $_REQUEST)) {
$link = (string)$_REQUEST['link_href'];
- $link = SimpleSAML_Utilities::normalizeURL($link);
+ $link = \SimpleSAML\Utils\HTTP::normalizeURL($link);
} else {
$link = 'index.php';
}
diff --git a/www/saml2/idp/SingleLogoutService.php b/www/saml2/idp/SingleLogoutService.php
index 032027a..1ecaf01 100644
--- a/www/saml2/idp/SingleLogoutService.php
+++ b/www/saml2/idp/SingleLogoutService.php
@@ -17,7 +17,7 @@ $idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
$idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
if (isset($_REQUEST['ReturnTo'])) {
- $idp->doLogoutRedirect(SimpleSAML_Utilities::checkURLAllowed((string)$_REQUEST['ReturnTo']));
+ $idp->doLogoutRedirect(\SimpleSAML\Utils\HTTP::checkURLAllowed((string)$_REQUEST['ReturnTo']));
} else {
try {
sspmod_saml_IdP_SAML2::receiveLogoutMessage($idp);
diff --git a/www/saml2/idp/initSLO.php b/www/saml2/idp/initSLO.php
index 87191b7..52c73b7 100644
--- a/www/saml2/idp/initSLO.php
+++ b/www/saml2/idp/initSLO.php
@@ -11,5 +11,5 @@ if (!isset($_GET['RelayState'])) {
throw new SimpleSAML_Error_Error('NORELAYSTATE');
}
-$idp->doLogoutRedirect(SimpleSAML_Utilities::checkURLAllowed((string)$_GET['RelayState']));
+$idp->doLogoutRedirect(\SimpleSAML\Utils\HTTP::checkURLAllowed((string)$_GET['RelayState']));
assert('FALSE'); \ No newline at end of file
diff --git a/www/saml2/idp/metadata.php b/www/saml2/idp/metadata.php
index de515e8..631865a 100644
--- a/www/saml2/idp/metadata.php
+++ b/www/saml2/idp/metadata.php
@@ -11,7 +11,7 @@ if (!$config->getBoolean('enable.saml20-idp', false))
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectmetadata', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
@@ -22,7 +22,7 @@ try {
$availableCerts = array();
$keys = array();
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_');
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, FALSE, 'new_');
if ($certInfo !== NULL) {
$availableCerts['new_idp.crt'] = $certInfo;
$keys[] = array(
@@ -36,7 +36,7 @@ try {
$hasNewCert = FALSE;
}
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE);
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE);
$availableCerts['idp.crt'] = $certInfo;
$keys[] = array(
'type' => 'X509Certificate',
@@ -46,7 +46,7 @@ try {
);
if ($idpmeta->hasValue('https.certificate')) {
- $httpsCert = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE, 'https.');
+ $httpsCert = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE, 'https.');
assert('isset($httpsCert["certData"])');
$availableCerts['https.crt'] = $httpsCert;
$keys[] = array(
@@ -105,7 +105,7 @@ try {
/* Artifact sending enabled. */
$metaArray['ArtifactResolutionService'][] = array(
'index' => 0,
- 'Location' => SimpleSAML_Utilities::getBaseURL() . 'saml2/idp/ArtifactResolutionService.php',
+ 'Location' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'saml2/idp/ArtifactResolutionService.php',
'Binding' => SAML2_Const::BINDING_SOAP,
);
}
@@ -115,7 +115,7 @@ try {
array_unshift($metaArray['SingleSignOnService'], array(
'hoksso:ProtocolBinding' => SAML2_Const::BINDING_HTTP_REDIRECT,
'Binding' => SAML2_Const::BINDING_HOK_SSO,
- 'Location' => SimpleSAML_Utilities::getBaseURL() . 'saml2/idp/SSOService.php'));
+ 'Location' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'saml2/idp/SSOService.php'));
}
$metaArray['NameIDFormat'] = $idpmeta->getString('NameIDFormat', 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
@@ -161,7 +161,7 @@ try {
if ($idpmeta->hasValue('contacts')) {
$contacts = $idpmeta->getArray('contacts');
foreach ($contacts as $contact) {
- $metaArray['contacts'][] = SimpleSAML_Utils_Config_Metadata::getContact($contact);
+ $metaArray['contacts'][] = \SimpleSAML\Utils\Config\Metadata::getContact($contact);
}
}
@@ -170,7 +170,7 @@ try {
$techcontact['emailAddress'] = $technicalContactEmail;
$techcontact['name'] = $config->getString('technicalcontact_name', NULL);
$techcontact['contactType'] = 'technical';
- $metaArray['contacts'][] = SimpleSAML_Utils_Config_Metadata::getContact($techcontact);
+ $metaArray['contacts'][] = \SimpleSAML\Utils\Config\Metadata::getContact($techcontact);
}
$metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($idpentityid);
@@ -191,7 +191,7 @@ try {
$t->data['available_certs'] = $availableCerts;
$t->data['header'] = 'saml20-idp';
- $t->data['metaurl'] = SimpleSAML_Utilities::selfURLNoQuery();
+ $t->data['metaurl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
$t->data['metadata'] = htmlspecialchars($metaxml);
$t->data['metadataflat'] = htmlspecialchars($metaflat);
$t->data['defaultidp'] = $defaultidp;
diff --git a/www/shib13/idp/SSOService.php b/www/shib13/idp/SSOService.php
index 74262ec..3052f22 100644
--- a/www/shib13/idp/SSOService.php
+++ b/www/shib13/idp/SSOService.php
@@ -4,7 +4,7 @@
* from a Shibboleth 1.3 SP, parses, and process it, and then authenticates the user and sends the user back
* to the SP with an Authentication Response.
*
- * @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
+ * @author Andreas Ã…kre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @package simpleSAMLphp
*/
diff --git a/www/shib13/idp/metadata.php b/www/shib13/idp/metadata.php
index e04345e..f47c591 100644
--- a/www/shib13/idp/metadata.php
+++ b/www/shib13/idp/metadata.php
@@ -11,7 +11,7 @@ if (!$config->getBoolean('enable.shib13-idp', false))
/* Check if valid local session exists.. */
if ($config->getBoolean('admin.protectmetadata', false)) {
- SimpleSAML_Utilities::requireAdmin();
+ SimpleSAML\Utils\Auth::requireAdmin();
}
@@ -21,7 +21,7 @@ try {
$idpmeta = $metadata->getMetaDataConfig($idpentityid, 'shib13-idp-hosted');
$keys = array();
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, FALSE, 'new_');
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, FALSE, 'new_');
if ($certInfo !== NULL) {
$keys[] = array(
'type' => 'X509Certificate',
@@ -31,7 +31,7 @@ try {
);
}
- $certInfo = SimpleSAML_Utilities::loadPublicKey($idpmeta, TRUE);
+ $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, TRUE);
$keys[] = array(
'type' => 'X509Certificate',
'signing' => TRUE,
@@ -69,7 +69,7 @@ try {
$metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($idpentityid);
$metaBuilder->addMetadataIdP11($metaArray);
$metaBuilder->addOrganizationInfo($metaArray);
- $metaBuilder->addContact('technical', SimpleSAML_Utils_Config_Metadata::getContact(array(
+ $metaBuilder->addContact('technical', \SimpleSAML\Utils\Config\Metadata::getContact(array(
'emailAddress' => $config->getString('technicalcontact_email', NULL),
'name' => $config->getString('technicalcontact_name', NULL),
'contactType' => 'technical',
@@ -87,7 +87,7 @@ try {
$t->data['header'] = 'shib13-idp';
- $t->data['metaurl'] = SimpleSAML_Utilities::addURLparameter(SimpleSAML_Utilities::selfURLNoQuery(), array('output' => 'xml'));
+ $t->data['metaurl'] = \SimpleSAML\Utils\HTTP::addURLParameters(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery(), array('output' => 'xml'));
$t->data['metadata'] = htmlspecialchars($metaxml);
$t->data['metadataflat'] = htmlspecialchars($metaflat);