diff --git a/composer.json b/composer.json index 07e7aa2d911da942d28ecb20a5746a7c6156eb1c..25fda8859f1dc27c7a263f385b7153024bf277c8 100644 --- a/composer.json +++ b/composer.json @@ -87,7 +87,8 @@ "require-dev": { "ext-curl": "*", "mikey179/vfsstream": "~1.6", - "phpunit/phpunit": "~5.7" + "phpunit/phpunit": "~5.7", + "squizlabs/php_codesniffer": "^3.5" }, "suggest": { "predis/predis": "Needed if a Redis server is used to store session information", diff --git a/composer.lock b/composer.lock index 4923b76a60084b406d9fa0efe77fea812e624652..4ed2040391e5ef6f0f5c0ace4c60067f66a317ea 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4d188ebe69a1f4f1eee30bf48b36d32c", + "content-hash": "be38a5bcca88dff2425610b5354c0029", "packages": [ { "name": "gettext/gettext", @@ -51,9 +51,9 @@ "authors": [ { "name": "Oscar Otero", - "role": "Developer", "email": "oom@oscarotero.com", - "homepage": "http://oscarotero.com" + "homepage": "http://oscarotero.com", + "role": "Developer" } ], "description": "PHP gettext manager", @@ -105,8 +105,8 @@ "authors": [ { "name": "Michele Locati", - "role": "Developer", - "email": "mlocati@gmail.com" + "email": "mlocati@gmail.com", + "role": "Developer" } ], "description": "gettext languages with plural rules", @@ -217,21 +217,21 @@ "authors": [ { "name": "Georges.L", - "role": "Maintainer", "email": "contact@geolim4.com", - "homepage": "https://github.com/Geolim4" + "homepage": "https://github.com/Geolim4", + "role": "Maintainer" }, { "name": "Christopher Mancini", - "role": "Former Lead Developer", "email": "cmancini@basho.com", - "homepage": "https://github.com/christophermancini" + "homepage": "https://github.com/christophermancini", + "role": "Former Lead Developer" }, { "name": "Alex Moore", - "role": "Former Developer", "email": "amoore@basho.com", - "homepage": "https://github.com/alexmoore" + "homepage": "https://github.com/alexmoore", + "role": "Former Developer" } ], "description": "Riak client for PHP (Fork of the official basho/riak due to maintainer significant inactivity)", @@ -252,16 +252,16 @@ }, { "name": "phpmailer/phpmailer", - "version": "v6.0.7", + "version": "v6.1.1", "source": { "type": "git", "url": "https://github.com/PHPMailer/PHPMailer.git", - "reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59" + "reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/0c41a36d4508d470e376498c1c0c527aa36a2d59", - "reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8", + "reference": "26bd96350b0b2fcbf0ef4e6f0f9cf3528302a9d8", "shasum": "" }, "require": { @@ -294,17 +294,17 @@ }, "notification-url": "https://packagist.org/downloads/", "license": [ - "LGPL-2.1" + "LGPL-2.1-only" ], "authors": [ - { - "name": "Jim Jagielski", - "email": "jimjag@gmail.com" - }, { "name": "Marcus Bointon", "email": "phpmailer@synchromedia.co.uk" }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, { "name": "Andy Prevost", "email": "codeworxtech@users.sourceforge.net" @@ -314,7 +314,7 @@ } ], "description": "PHPMailer is a full-featured email creation and transfer class for PHP", - "time": "2019-02-01T15:04:28+00:00" + "time": "2019-09-27T21:33:43+00:00" }, { "name": "psr/container", @@ -541,25 +541,26 @@ }, { "name": "simplesamlphp/simplesamlphp-module-adfs", - "version": "v0.9.3", + "version": "v0.9.4", "source": { "type": "git", "url": "https://github.com/simplesamlphp/simplesamlphp-module-adfs.git", - "reference": "516e16951af459a52eb6d393e87fe44af95278bb" + "reference": "edb1bbc59734875e33990c976917594b55fa412d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/simplesamlphp/simplesamlphp-module-adfs/zipball/516e16951af459a52eb6d393e87fe44af95278bb", - "reference": "516e16951af459a52eb6d393e87fe44af95278bb", + "url": "https://api.github.com/repos/simplesamlphp/simplesamlphp-module-adfs/zipball/edb1bbc59734875e33990c976917594b55fa412d", + "reference": "edb1bbc59734875e33990c976917594b55fa412d", "shasum": "" }, "require": { "php": ">=5.6", - "simplesamlphp/composer-module-installer": "~1.1" + "simplesamlphp/composer-module-installer": "~1.1", + "webmozart/assert": "~1.4" }, "require-dev": { - "phpunit/phpunit": "~5.7", - "simplesamlphp/simplesamlphp": "^1.17" + "simplesamlphp/simplesamlphp": "^1.17", + "simplesamlphp/simplesamlphp-test-framework": "^0.0.10" }, "type": "simplesamlphp-module", "autoload": { @@ -582,7 +583,7 @@ "adfs", "simplesamlphp" ], - "time": "2019-08-29T20:40:06+00:00" + "time": "2019-09-24T12:58:53+00:00" }, { "name": "simplesamlphp/simplesamlphp-module-authcrypt", @@ -1814,25 +1815,27 @@ }, { "name": "simplesamlphp/simplesamlphp-module-statistics", - "version": "v0.9.1", + "version": "v0.9.2", "source": { "type": "git", "url": "https://github.com/simplesamlphp/simplesamlphp-module-statistics.git", - "reference": "9043be4dfa66c572272638ab8306ab48c166d4d2" + "reference": "03d4d2fd0a2fd68b3aba312421841662ec63c4db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/simplesamlphp/simplesamlphp-module-statistics/zipball/9043be4dfa66c572272638ab8306ab48c166d4d2", - "reference": "9043be4dfa66c572272638ab8306ab48c166d4d2", + "url": "https://api.github.com/repos/simplesamlphp/simplesamlphp-module-statistics/zipball/03d4d2fd0a2fd68b3aba312421841662ec63c4db", + "reference": "03d4d2fd0a2fd68b3aba312421841662ec63c4db", "shasum": "" }, "require": { "php": ">=5.6", - "simplesamlphp/composer-module-installer": "~1.1" + "simplesamlphp/composer-module-installer": "~1.1", + "webmozart/assert": "^1.4" }, "require-dev": { "phpunit/phpunit": "~5.7", - "simplesamlphp/simplesamlphp": "^1.17" + "simplesamlphp/simplesamlphp": "^1.17", + "simplesamlphp/simplesamlphp-test-framework": "^0.0.10" }, "type": "simplesamlphp-module", "autoload": { @@ -1855,7 +1858,7 @@ "simplesamlphp", "statistics" ], - "time": "2019-08-26T14:58:20+00:00" + "time": "2019-08-26T14:57:57+00:00" }, { "name": "simplesamlphp/twig-configurable-i18n", @@ -2762,19 +2765,19 @@ "authors": [ { "name": "Fabien Potencier", - "role": "Lead Developer", "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org" + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" }, { "name": "Twig Team", - "role": "Contributors", - "homepage": "https://twig.symfony.com/contributors" + "homepage": "https://twig.symfony.com/contributors", + "role": "Contributors" }, { "name": "Armin Ronacher", - "role": "Project Founder", - "email": "armin.ronacher@active-4.com" + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" } ], "description": "Twig, the flexible, fast, and secure template language for PHP", @@ -2972,8 +2975,8 @@ "authors": [ { "name": "Frank Kleine", - "role": "Developer", - "homepage": "http://frankkleine.de/" + "homepage": "http://frankkleine.de/", + "role": "Developer" } ], "description": "Virtual file system to mock the real file system in unit tests.", @@ -3284,8 +3287,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sb@sebastian-bergmann.de" + "email": "sb@sebastian-bergmann.de", + "role": "lead" } ], "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", @@ -3332,8 +3335,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sb@sebastian-bergmann.de" + "email": "sb@sebastian-bergmann.de", + "role": "lead" } ], "description": "FilterIterator implementation that filters files based on a list of suffixes.", @@ -3374,8 +3377,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sebastian@phpunit.de" + "email": "sebastian@phpunit.de", + "role": "lead" } ], "description": "Simple template engine.", @@ -3423,8 +3426,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sb@sebastian-bergmann.de" + "email": "sb@sebastian-bergmann.de", + "role": "lead" } ], "description": "Utility class for timing", @@ -3552,8 +3555,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sebastian@phpunit.de" + "email": "sebastian@phpunit.de", + "role": "lead" } ], "description": "The PHP Unit Testing framework.", @@ -4130,13 +4133,64 @@ "authors": [ { "name": "Sebastian Bergmann", - "role": "lead", - "email": "sebastian@phpunit.de" + "email": "sebastian@phpunit.de", + "role": "lead" } ], "description": "Library that helps with managing the version number of Git-hosted PHP projects", "homepage": "https://github.com/sebastianbergmann/version", "time": "2016-10-03T07:35:21+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.5.0", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "0afebf16a2e7f1e434920fa976253576151effe9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/0afebf16a2e7f1e434920fa976253576151effe9", + "reference": "0afebf16a2e7f1e434920fa976253576151effe9", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2019-09-26T23:12:26+00:00" } ], "aliases": [], diff --git a/lib/SimpleSAML/Auth/DefaultAuth.php b/lib/SimpleSAML/Auth/DefaultAuth.php index 7379c3d99312eca58403828cb2629ebbba2207f3..4a2a5da54915ac3a7bf70b006ac1eaca17cece4e 100644 --- a/lib/SimpleSAML/Auth/DefaultAuth.php +++ b/lib/SimpleSAML/Auth/DefaultAuth.php @@ -159,7 +159,7 @@ class DefaultAuth { $as = Source::getById($id); if ($as === null) { - throw new \Exception('Invalid authentication source: '.$id); + throw new \Exception('Invalid authentication source: ' . $id); } return $as; } diff --git a/lib/SimpleSAML/Auth/LDAP.php b/lib/SimpleSAML/Auth/LDAP.php index 4124f2e467940c68d0133ebc3361d47566cf512f..413776c271b61f4bfccb180ae8fb1fefb13e31fe 100644 --- a/lib/SimpleSAML/Auth/LDAP.php +++ b/lib/SimpleSAML/Auth/LDAP.php @@ -2,7 +2,10 @@ namespace SimpleSAML\Auth; -@trigger_error(sprintf('Using the "SimpleSAML\Auth\LDAP" class is deprecated, use "SimpleSAML\Module\ldap\Auth\Ldap" instead.'), E_USER_DEPRECATED); +@trigger_error( + sprintf('Using the "SimpleSAML\Auth\LDAP" class is deprecated, use "SimpleSAML\Module\ldap\Auth\Ldap" instead.'), + E_USER_DEPRECATED +); /** * @deprecated To be removed in 2.0 diff --git a/lib/SimpleSAML/Auth/ProcessingChain.php b/lib/SimpleSAML/Auth/ProcessingChain.php index 3ff70888ceafcf6e5b9a8fe8b11f6e6d4099bf67..d160928a8fbbdb440c49b15316d277c12f8444d8 100644 --- a/lib/SimpleSAML/Auth/ProcessingChain.php +++ b/lib/SimpleSAML/Auth/ProcessingChain.php @@ -62,7 +62,7 @@ class ProcessingChain $this->filters = []; $config = Configuration::getInstance(); - $configauthproc = $config->getArray('authproc.'.$mode, null); + $configauthproc = $config->getArray('authproc.' . $mode, null); if (!empty($configauthproc)) { $configfilters = self::parseFilterList($configauthproc); @@ -79,8 +79,8 @@ class ProcessingChain self::addFilters($this->filters, $spFilters); } - Logger::debug('Filter config for '.$idpMetadata['entityid'].'->'. - $spMetadata['entityid'].': '.str_replace("\n", '', var_export($this->filters, true))); + Logger::debug('Filter config for ' . $idpMetadata['entityid'] . '->' . + $spMetadata['entityid'] . ': ' . str_replace("\n", '', var_export($this->filters, true))); } @@ -132,7 +132,7 @@ class ProcessingChain } if (!is_array($filter)) { - throw new \Exception('Invalid authentication processing filter configuration: '. + throw new \Exception('Invalid authentication processing filter configuration: ' . 'One of the filters wasn\'t a string or an array.'); } @@ -368,12 +368,12 @@ class ProcessingChain $uid = $state['Attributes'][$attributeName]; if (count($uid) === 0) { - Logger::warning('Empty user id attribute ['.$attributeName.'].'); + Logger::warning('Empty user id attribute [' . $attributeName . '].'); return; } if (count($uid) > 1) { - Logger::warning('Multiple attribute values for user id attribute ['.$attributeName.'].'); + Logger::warning('Multiple attribute values for user id attribute [' . $attributeName . '].'); return; } @@ -381,7 +381,7 @@ class ProcessingChain $uid = $uid[0]; if (empty($uid)) { - Logger::warning('Empty value in attribute '.$attributeName.". on user. Cannot set UserID."); + Logger::warning('Empty value in attribute ' . $attributeName . ". on user. Cannot set UserID."); return; } $state['UserID'] = $uid; diff --git a/lib/SimpleSAML/Auth/ProcessingFilter.php b/lib/SimpleSAML/Auth/ProcessingFilter.php index 8c01b1d7b8dcf4e9d5db1494b65bd7facd7c93e0..baeb5834b68dc81dd8c2f3e1f35cbde829a40663 100644 --- a/lib/SimpleSAML/Auth/ProcessingFilter.php +++ b/lib/SimpleSAML/Auth/ProcessingFilter.php @@ -50,7 +50,7 @@ abstract class ProcessingFilter if (array_key_exists('%priority', $config)) { $this->priority = $config['%priority']; if (!is_int($this->priority)) { - throw new \Exception('Invalid priority: '.var_export($this->priority, true)); + throw new \Exception('Invalid priority: ' . var_export($this->priority, true)); } unset($config['%priority']); } diff --git a/lib/SimpleSAML/Auth/Simple.php b/lib/SimpleSAML/Auth/Simple.php index efd77a70dce4e2ddfaf01d29c0c9f9d701a6de7b..3c5a4f1175bf16ef945506ab1b4b7a805308bc9d 100644 --- a/lib/SimpleSAML/Auth/Simple.php +++ b/lib/SimpleSAML/Auth/Simple.php @@ -2,11 +2,11 @@ namespace SimpleSAML\Auth; -use \SimpleSAML\Configuration; -use \SimpleSAML\Error; -use \SimpleSAML\Module; -use \SimpleSAML\Session; -use \SimpleSAML\Utils; +use SimpleSAML\Configuration; +use SimpleSAML\Error; +use SimpleSAML\Module; +use SimpleSAML\Session; +use SimpleSAML\Utils; /** * Helper class for simple authentication applications. @@ -384,15 +384,15 @@ class Simple $query = parse_url($url, PHP_URL_QUERY) ? : ''; $fragment = parse_url($url, PHP_URL_FRAGMENT) ? : ''; - $port = !empty($port) ? ':'.$port : ''; + $port = !empty($port) ? ':' . $port : ''; if (($scheme === 'http' && $port === ':80') || ($scheme === 'https' && $port === ':443')) { $port = ''; } $base = trim($this->app_config->getString( 'baseURL', - $scheme.'://'.$host.$port + $scheme . '://' . $host . $port ), '/'); - return $base.$path.($query ? '?'.$query : '').($fragment ? '#'.$fragment : ''); + return $base . $path . ($query ? '?' . $query : '') . ($fragment ? '#' . $fragment : ''); } } diff --git a/lib/SimpleSAML/Auth/Source.php b/lib/SimpleSAML/Auth/Source.php index 71469744c956be3a510ba28f645893a440725e6c..1e00aba0d4d0467758d4af2d1ebb318959a14d32 100644 --- a/lib/SimpleSAML/Auth/Source.php +++ b/lib/SimpleSAML/Auth/Source.php @@ -329,7 +329,7 @@ abstract class Source ); /** @var SourceFactory $factory */ - $factory = new $factoryClass; + $factory = new $factoryClass(); $authSource = $factory->create($info, $config); } catch (\Exception $e) { // If not, instantiate the Auth Source here @@ -372,8 +372,8 @@ abstract class Source if ($authConfig === null) { if ($type !== null) { throw new Error\Exception( - 'No authentication source with id '. - var_export($authId, true).' found.' + 'No authentication source with id ' . + var_export($authId, true) . ' found.' ); } return null; @@ -387,9 +387,9 @@ abstract class Source // the authentication source doesn't have the correct type throw new Error\Exception( - 'Invalid type of authentication source '. - var_export($authId, true).'. Was '.var_export(get_class($ret), true). - ', should be '.var_export($type, true).'.' + 'Invalid type of authentication source ' . + var_export($authId, true) . '. Was ' . var_export(get_class($ret), true) . + ', should be ' . var_export($type, true) . '.' ); } @@ -410,7 +410,7 @@ abstract class Source $session = Session::getSessionFromRequest(); if (!$session->isValid($source)) { Logger::warning( - 'Received logout from an invalid authentication source '. + 'Received logout from an invalid authentication source ' . var_export($source, true) ); @@ -450,7 +450,7 @@ abstract class Source $callbackState = []; } - $id = strlen($this->authId).':'.$this->authId.$assoc; + $id = strlen($this->authId) . ':' . $this->authId . $assoc; $data = [ 'callback' => $callback, @@ -482,7 +482,7 @@ abstract class Source { assert(is_string($assoc)); - $id = strlen($this->authId).':'.$this->authId.$assoc; + $id = strlen($this->authId) . ':' . $this->authId . $assoc; $session = Session::getSessionFromRequest(); @@ -532,7 +532,7 @@ abstract class Source { if (!array_key_exists(0, $source) || !is_string($source[0])) { throw new \Exception( - 'Invalid authentication source \''.$id. + 'Invalid authentication source \'' . $id . '\': First element must be a string which identifies the authentication source.' ); } diff --git a/lib/SimpleSAML/Auth/State.php b/lib/SimpleSAML/Auth/State.php index 22310d180bda124b45a2025ad13b7af221275295..ac915cbd3161194b72a70e8067e7c843703a2897 100644 --- a/lib/SimpleSAML/Auth/State.php +++ b/lib/SimpleSAML/Auth/State.php @@ -168,7 +168,7 @@ class State } // We have a restart URL. Return the ID with that URL. - return $id.':'.$state[self::RESTART]; + return $id . ':' . $state[self::RESTART]; } @@ -217,7 +217,7 @@ class State $session = Session::getSessionFromRequest(); $session->setData('\SimpleSAML\Auth\State', $id, $serializedState, self::getStateTimeout()); - Logger::debug('Saved state: '.var_export($return, true)); + Logger::debug('Saved state: ' . var_export($return, true)); return $return; } @@ -240,7 +240,7 @@ class State $clonedState[self::CLONE_ORIGINAL_ID] = $state[self::ID]; unset($clonedState[self::ID]); - Logger::debug('Cloned state: '.var_export($state[self::ID], true)); + Logger::debug('Cloned state: ' . var_export($state[self::ID], true)); } else { Logger::debug('Cloned state with undefined id.'); } @@ -270,7 +270,7 @@ class State assert(is_string($id)); assert(is_string($stage)); assert(is_bool($allowMissing)); - Logger::debug('Loading state: '.var_export($id, true)); + Logger::debug('Loading state: ' . var_export($id, true)); $sid = self::parseStateID($id); @@ -302,8 +302,8 @@ class State * request if that is possible. If not, show an error. */ - $msg = 'Wrong stage in state. Was \''.$state[self::STAGE]. - '\', should be \''.$stage.'\'.'; + $msg = 'Wrong stage in state. Was \'' . $state[self::STAGE] . + '\', should be \'' . $stage . '\'.'; Logger::warning($msg); @@ -335,7 +335,7 @@ class State return; } - Logger::debug('Deleting state: '.var_export($state[self::ID], true)); + Logger::debug('Deleting state: ' . var_export($state[self::ID], true)); $session = Session::getSessionFromRequest(); $session->deleteData('\SimpleSAML\Auth\State', $state[self::ID]); diff --git a/lib/SimpleSAML/Auth/TimeLimitedToken.php b/lib/SimpleSAML/Auth/TimeLimitedToken.php index 2f35984053687880ed176110736d7494c7655adb..ac5846dec9eb9c308086cd8d5406db8dc4312c6a 100644 --- a/lib/SimpleSAML/Auth/TimeLimitedToken.php +++ b/lib/SimpleSAML/Auth/TimeLimitedToken.php @@ -50,7 +50,7 @@ class TimeLimitedToken } if (!in_array($algo, hash_algos(), true)) { - throw new \InvalidArgumentException('Invalid hash algorithm "'.$algo.'"'); + throw new \InvalidArgumentException('Invalid hash algorithm "' . $algo . '"'); } $this->secretSalt = $secretSalt; @@ -72,7 +72,7 @@ class TimeLimitedToken */ public function addVerificationData($data) { - $this->secretSalt .= '|'.$data; + $this->secretSalt .= '|' . $data; } @@ -92,7 +92,7 @@ class TimeLimitedToken // a secret salt that should be randomly generated for each installation return hash( $this->algo, - $offset.':'.floor(($time - $offset) / ($this->lifetime + $this->skew)).':'.$this->secretSalt + $offset . ':' . floor(($time - $offset) / ($this->lifetime + $this->skew)) . ':' . $this->secretSalt ); } @@ -106,7 +106,7 @@ class TimeLimitedToken { $time = time(); $current_offset = ($time - $this->skew) % ($this->lifetime + $this->skew); - return dechex($current_offset).'-'.$this->calculateTokenValue($current_offset, $time); + return dechex($current_offset) . '-' . $this->calculateTokenValue($current_offset, $time); } diff --git a/lib/SimpleSAML/Configuration.php b/lib/SimpleSAML/Configuration.php index 2350b0665233db4d2603cc28531a4c3c40ba576f..145eb17ea4259f753d84a4a1826d72eccb23a9a3 100644 --- a/lib/SimpleSAML/Configuration.php +++ b/lib/SimpleSAML/Configuration.php @@ -222,14 +222,14 @@ class Configuration implements Utils\ClearableState if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { - throw new \Exception('Configuration set \''.$configSet.'\' not initialized.'); + throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); } else { - self::$configDirs['simplesaml'] = dirname(dirname(dirname(__FILE__))).'/config'; + self::$configDirs['simplesaml'] = dirname(dirname(dirname(__FILE__))) . '/config'; } } $dir = self::$configDirs[$configSet]; - $filePath = $dir.'/'.$filename; + $filePath = $dir . '/' . $filename; self::$loadedConfigs[$filePath] = $config; } @@ -251,14 +251,14 @@ class Configuration implements Utils\ClearableState if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { - throw new \Exception('Configuration set \''.$configSet.'\' not initialized.'); + throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); } else { self::$configDirs['simplesaml'] = Utils\Config::getConfigDir(); } } $dir = self::$configDirs[$configSet]; - $filePath = $dir.'/'.$filename; + $filePath = $dir . '/' . $filename; return self::loadFromFile($filePath, true); } @@ -281,14 +281,14 @@ class Configuration implements Utils\ClearableState if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { - throw new \Exception('Configuration set \''.$configSet.'\' not initialized.'); + throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); } else { self::$configDirs['simplesaml'] = Utils\Config::getConfigDir(); } } $dir = self::$configDirs[$configSet]; - $filePath = $dir.'/'.$filename; + $filePath = $dir . '/' . $filename; return self::loadFromFile($filePath, false); } @@ -350,7 +350,7 @@ class Configuration implements Utils\ClearableState } throw new Error\CriticalConfigurationError( - 'Configuration with name '.$instancename.' is not initialized.' + 'Configuration with name ' . $instancename . ' is not initialized.' ); } @@ -384,7 +384,7 @@ class Configuration implements Utils\ClearableState return self::$instance[$instancename]; } - self::$instance[$instancename] = self::loadFromFile($path.'/'.$configfilename, true); + self::$instance[$instancename] = self::loadFromFile($path . '/' . $configfilename, true); return self::$instance[$instancename]; } @@ -414,7 +414,7 @@ class Configuration implements Utils\ClearableState $dir = dirname($this->filename); - self::$instance[$instancename] = self::loadFromFile($dir.'/'.$filename, true); + self::$instance[$instancename] = self::loadFromFile($dir . '/' . $filename, true); return self::$instance[$instancename]; } @@ -448,7 +448,7 @@ class Configuration implements Utils\ClearableState if (!array_key_exists($name, $this->configuration)) { if ($default === self::REQUIRED_OPTION) { throw new \Exception( - $this->location.': Could not retrieve the required option '. + $this->location . ': Could not retrieve the required option ' . var_export($name, true) ); } @@ -513,7 +513,7 @@ class Configuration implements Utils\ClearableState } if (preg_match('/^\*(.*)$/D', $this->getString('baseurlpath', 'simplesaml/'), $matches)) { // deprecated behaviour, will be removed in the future - return Utils\HTTP::getFirstPathElement(false).$matches[1]; + return Utils\HTTP::getFirstPathElement(false) . $matches[1]; } return ltrim($this->getBasePath(), '/'); } @@ -538,13 +538,13 @@ class Configuration implements Utils\ClearableState // absolute URL without path return '/'; } - return '/'.rtrim($matches[1], '/')."/"; + return '/' . rtrim($matches[1], '/') . '/'; } elseif ($baseURL === '' || $baseURL === '/') { // root directory of site return '/'; } elseif (preg_match('#^/?((?:[^/\s]+/?)+)#', $baseURL, $matches)) { // local path only - return '/'.rtrim($matches[1], '/').'/'; + return '/' . rtrim($matches[1], '/') . '/'; } else { /* * Invalid 'baseurlpath'. We cannot recover from this, so throw a critical exception and try to be graceful @@ -553,8 +553,8 @@ class Configuration implements Utils\ClearableState $c = $this->toArray(); $c['baseurlpath'] = Utils\HTTP::guessBasePath(); throw new Error\CriticalConfigurationError( - 'Incorrect format for option \'baseurlpath\'. Value is: "'. - $this->getString('baseurlpath', 'simplesaml/').'". Valid format is in the form'. + 'Incorrect format for option \'baseurlpath\'. Value is: "' . + $this->getString('baseurlpath', 'simplesaml/') . '". Valid format is in the form' . ' [(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/].', $this->filename, $c @@ -613,7 +613,7 @@ class Configuration implements Utils\ClearableState return null; } - return $path.'/'; + return $path . '/'; } @@ -687,7 +687,7 @@ class Configuration implements Utils\ClearableState if (!is_bool($ret)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' is not a valid boolean value.' ); } @@ -725,7 +725,7 @@ class Configuration implements Utils\ClearableState if (!is_string($ret)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' is not a valid string value.' ); } @@ -763,7 +763,7 @@ class Configuration implements Utils\ClearableState if (!is_int($ret)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' is not a valid integer value.' ); } @@ -807,9 +807,9 @@ class Configuration implements Utils\ClearableState if ($ret < $minimum || $ret > $maximum) { throw new \Exception( - $this->location.': Value of option '.var_export($name, true). - ' is out of range. Value is '.$ret.', allowed range is [' - .$minimum.' - '.$maximum.']' + $this->location . ': Value of option ' . var_export($name, true) . + ' is out of range. Value is ' . $ret . ', allowed range is [' + . $minimum . ' - ' . $maximum . ']' ); } @@ -857,9 +857,9 @@ class Configuration implements Utils\ClearableState $strValues = implode(', ', $strValues); throw new \Exception( - $this->location.': Invalid value given for the option '. - var_export($name, true).'. It should have one of the following values: '. - $strValues.'; but it had the following value: '.var_export($ret, true) + $this->location . ': Invalid value given for the option ' . + var_export($name, true) . '. It should have one of the following values: ' . + $strValues . '; but it had the following value: ' . var_export($ret, true) ); } @@ -895,7 +895,7 @@ class Configuration implements Utils\ClearableState } if (!is_array($ret)) { - throw new \Exception($this->location.': The option '.var_export($name, true).' is not an array.'); + throw new \Exception($this->location . ': The option ' . var_export($name, true) . ' is not an array.'); } return $ret; @@ -961,7 +961,7 @@ class Configuration implements Utils\ClearableState foreach ($ret as $value) { if (!is_string($value)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' must be a string or an array of strings.' ); } @@ -1004,12 +1004,12 @@ class Configuration implements Utils\ClearableState if (!is_array($ret)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' is not an array.' ); } - return self::loadFromArray($ret, $this->location.'['.var_export($name, true).']'); + return self::loadFromArray($ret, $this->location . '[' . var_export($name, true) . ']'); } @@ -1039,17 +1039,17 @@ class Configuration implements Utils\ClearableState if (!is_array($ret)) { throw new \Exception( - $this->location.': The option '.var_export($name, true). + $this->location . ': The option ' . var_export($name, true) . ' is not an array.' ); } $out = []; foreach ($ret as $index => $config) { - $newLoc = $this->location.'['.var_export($name, true).']['. - var_export($index, true).']'; + $newLoc = $this->location . '[' . var_export($name, true) . '][' . + var_export($index, true) . ']'; if (!is_array($config)) { - throw new \Exception($newLoc.': The value of this element was expected to be an array.'); + throw new \Exception($newLoc . ': The value of this element was expected to be an array.'); } $out[$index] = self::loadFromArray($config, $newLoc); } @@ -1100,7 +1100,7 @@ class Configuration implements Utils\ClearableState assert(is_string($endpointType)); $set = $this->getString('metadata-set'); - switch ($set.':'.$endpointType) { + switch ($set . ':' . $endpointType) { case 'saml20-idp-remote:SingleSignOnService': case 'saml20-idp-remote:SingleLogoutService': case 'saml20-sp-remote:SingleLogoutService': @@ -1114,7 +1114,7 @@ class Configuration implements Utils\ClearableState case 'shib13-sp-remote:AssertionConsumerService': return 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post'; default: - throw new \Exception('Missing default binding for '.$endpointType.' in '.$set); + throw new \Exception('Missing default binding for ' . $endpointType . ' in ' . $set); } } @@ -1132,7 +1132,7 @@ class Configuration implements Utils\ClearableState { assert(is_string($endpointType)); - $loc = $this->location.'['.var_export($endpointType, true).']:'; + $loc = $this->location . '[' . var_export($endpointType, true) . ']:'; if (!array_key_exists($endpointType, $this->configuration)) { // no endpoints of the given type @@ -1145,12 +1145,12 @@ class Configuration implements Utils\ClearableState // for backwards-compatibility $eps = [$eps]; } elseif (!is_array($eps)) { - throw new \Exception($loc.': Expected array or string.'); + throw new \Exception($loc . ': Expected array or string.'); } foreach ($eps as $i => &$ep) { - $iloc = $loc.'['.var_export($i, true).']'; + $iloc = $loc . '[' . var_export($i, true) . ']'; if (is_string($ep)) { // for backwards-compatibility @@ -1158,37 +1158,37 @@ class Configuration implements Utils\ClearableState 'Location' => $ep, 'Binding' => $this->getDefaultBinding($endpointType), ]; - $responseLocation = $this->getString($endpointType.'Response', null); + $responseLocation = $this->getString($endpointType . 'Response', null); if ($responseLocation !== null) { $ep['ResponseLocation'] = $responseLocation; } } elseif (!is_array($ep)) { - throw new \Exception($iloc.': Expected a string or an array.'); + throw new \Exception($iloc . ': Expected a string or an array.'); } if (!array_key_exists('Location', $ep)) { - throw new \Exception($iloc.': Missing Location.'); + throw new \Exception($iloc . ': Missing Location.'); } if (!is_string($ep['Location'])) { - throw new \Exception($iloc.': Location must be a string.'); + throw new \Exception($iloc . ': Location must be a string.'); } if (!array_key_exists('Binding', $ep)) { - throw new \Exception($iloc.': Missing Binding.'); + throw new \Exception($iloc . ': Missing Binding.'); } if (!is_string($ep['Binding'])) { - throw new \Exception($iloc.': Binding must be a string.'); + throw new \Exception($iloc . ': Binding must be a string.'); } if (array_key_exists('ResponseLocation', $ep)) { if (!is_string($ep['ResponseLocation'])) { - throw new \Exception($iloc.': ResponseLocation must be a string.'); + throw new \Exception($iloc . ': ResponseLocation must be a string.'); } } if (array_key_exists('index', $ep)) { if (!is_int($ep['index'])) { - throw new \Exception($iloc.': index must be an integer.'); + throw new \Exception($iloc . ': index must be an integer.'); } } } @@ -1224,8 +1224,8 @@ class Configuration implements Utils\ClearableState } if ($default === self::REQUIRED_OPTION) { - $loc = $this->location.'['.var_export($endpointType, true).']:'; - throw new \Exception($loc.'Could not find a supported '.$endpointType.' endpoint.'); + $loc = $this->location . '[' . var_export($endpointType, true) . ']:'; + throw new \Exception($loc . 'Could not find a supported ' . $endpointType . ' endpoint.'); } return $default; @@ -1256,8 +1256,8 @@ class Configuration implements Utils\ClearableState } if ($default === self::REQUIRED_OPTION) { - $loc = $this->location.'['.var_export($endpointType, true).']:'; - throw new \Exception($loc.'Could not find a supported '.$endpointType.' endpoint.'); + $loc = $this->location . '[' . var_export($endpointType, true) . ']:'; + throw new \Exception($loc . 'Could not find a supported ' . $endpointType . ' endpoint.'); } return $default; @@ -1287,22 +1287,22 @@ class Configuration implements Utils\ClearableState return $ret; } - $loc = $this->location.'['.var_export($name, true).']'; + $loc = $this->location . '[' . var_export($name, true) . ']'; if (is_string($ret)) { $ret = ['en' => $ret]; } if (!is_array($ret)) { - throw new \Exception($loc.': Must be an array or a string.'); + throw new \Exception($loc . ': Must be an array or a string.'); } foreach ($ret as $k => $v) { if (!is_string($k)) { - throw new \Exception($loc.': Invalid language code: '.var_export($k, true)); + throw new \Exception($loc . ': Invalid language code: ' . var_export($k, true)); } if (!is_string($v)) { - throw new \Exception($loc.'['.var_export($v, true).']: Must be a string.'); + throw new \Exception($loc . '[' . var_export($v, true) . ']: Must be a string.'); } } @@ -1330,9 +1330,9 @@ class Configuration implements Utils\ClearableState assert(is_bool($required)); assert(is_string($prefix)); - if ($this->hasValue($prefix.'keys')) { + if ($this->hasValue($prefix . 'keys')) { $ret = []; - foreach ($this->getArray($prefix.'keys') as $key) { + foreach ($this->getArray($prefix . 'keys') as $key) { if ($use !== null && isset($key[$use]) && !$key[$use]) { continue; } @@ -1343,8 +1343,8 @@ class Configuration implements Utils\ClearableState $ret[] = $key; } return $ret; - } elseif ($this->hasValue($prefix.'certData')) { - $certData = $this->getString($prefix.'certData'); + } elseif ($this->hasValue($prefix . 'certData')) { + $certData = $this->getString($prefix . 'certData'); $certData = preg_replace('/\s+/', '', $certData); return [ [ @@ -1354,20 +1354,22 @@ class Configuration implements Utils\ClearableState 'X509Certificate' => $certData, ], ]; - } elseif ($this->hasValue($prefix.'certificate')) { - $file = $this->getString($prefix.'certificate'); + } elseif ($this->hasValue($prefix . 'certificate')) { + $file = $this->getString($prefix . 'certificate'); $file = Utils\Config::getCertPath($file); $data = @file_get_contents($file); if ($data === false) { - throw new \Exception($this->location.': Unable to load certificate/public key from file "'.$file.'".'); + throw new \Exception( + $this->location . ': Unable to load certificate/public key from file "' . $file . '".' + ); } // extract certificate data (if this is a certificate) $pattern = '/^-----BEGIN CERTIFICATE-----([^-]*)^-----END CERTIFICATE-----/m'; if (!preg_match($pattern, $data, $matches)) { throw new \SimpleSAML\Error\Exception( - $this->location.': Could not find PEM encoded certificate in "'.$file.'".' + $this->location . ': Could not find PEM encoded certificate in "' . $file . '".' ); } $certData = preg_replace('/\s+/', '', $matches[1]); @@ -1381,7 +1383,7 @@ class Configuration implements Utils\ClearableState ], ]; } elseif ($required === true) { - throw new \SimpleSAML\Error\Exception($this->location.': Missing certificate in metadata.'); + throw new \SimpleSAML\Error\Exception($this->location . ': Missing certificate in metadata.'); } else { return []; } diff --git a/lib/SimpleSAML/Database.php b/lib/SimpleSAML/Database.php index 8a1b67fe2b8e389266cd83e54628156b6b43313c..76ae112168c884f13d11acff1f4858b9ad1219f6 100644 --- a/lib/SimpleSAML/Database.php +++ b/lib/SimpleSAML/Database.php @@ -152,7 +152,7 @@ class Database return $db; } catch (PDOException $e) { - throw new \Exception("Database error: ".$e->getMessage()); + throw new \Exception("Database error: " . $e->getMessage()); } } @@ -183,7 +183,7 @@ class Database */ public function applyPrefix($table) { - return $this->tablePrefix.$table; + return $this->tablePrefix . $table; } @@ -219,7 +219,7 @@ class Database return $query; } catch (PDOException $e) { $this->lastError = $db->errorInfo(); - throw new \Exception("Database error: ".$e->getMessage()); + throw new \Exception("Database error: " . $e->getMessage()); } } @@ -242,7 +242,7 @@ class Database return $db->exec($stmt); } catch (PDOException $e) { $this->lastError = $db->errorInfo(); - throw new \Exception("Database error: ".$e->getMessage()); + throw new \Exception("Database error: " . $e->getMessage()); } } diff --git a/lib/SimpleSAML/Error/Assertion.php b/lib/SimpleSAML/Error/Assertion.php index 7e3581955d41a5bd2ee60ca017b642848f204579..4a26240afa30d47ef0d012893210b3aba2056ee7 100644 --- a/lib/SimpleSAML/Error/Assertion.php +++ b/lib/SimpleSAML/Error/Assertion.php @@ -30,7 +30,7 @@ class Assertion extends Exception { assert($assertion === null || is_string($assertion)); - $msg = 'Assertion failed: '.var_export($assertion, true); + $msg = 'Assertion failed: ' . var_export($assertion, true); parent::__construct($msg); $this->assertion = $assertion; diff --git a/lib/SimpleSAML/Error/ConfigurationError.php b/lib/SimpleSAML/Error/ConfigurationError.php index 128093dad543d0991272cae7d353fc9156bfe442..044771574a2e50502f2c98860ac6d7d1beb08de4 100644 --- a/lib/SimpleSAML/Error/ConfigurationError.php +++ b/lib/SimpleSAML/Error/ConfigurationError.php @@ -40,17 +40,17 @@ class ConfigurationError extends Error $params = ['CONFIG']; if ($file !== null) { $params['%FILE%'] = $file; - $basepath = dirname(dirname(dirname(dirname(__FILE__)))).'/'; - $file_str = '('.str_replace($basepath, '', $file).') '; + $basepath = dirname(dirname(dirname(dirname(__FILE__)))) . '/'; + $file_str = '(' . str_replace($basepath, '', $file) . ') '; } if ($reason !== null) { $params['%REASON%'] = $reason; - $reason_str = ': '.$reason; + $reason_str = ': ' . $reason; } $this->reason = $reason; $this->config_file = $file; parent::__construct($params); - $this->message = 'The configuration '.$file_str.'is invalid'.$reason_str; + $this->message = 'The configuration ' . $file_str . 'is invalid' . $reason_str; } diff --git a/lib/SimpleSAML/Error/Error.php b/lib/SimpleSAML/Error/Error.php index 8fa391cd7182b8329e92069565bf6a3218c880e4..1a83f9580657c76b14b3e5a988a526cb8960d42d 100644 --- a/lib/SimpleSAML/Error/Error.php +++ b/lib/SimpleSAML/Error/Error.php @@ -97,15 +97,15 @@ class Error extends Exception $this->dictDescr = ErrorCodes::getErrorCodeDescription($this->errorCode); if (!empty($this->parameters)) { - $msg = $this->errorCode.'('; + $msg = $this->errorCode . '('; foreach ($this->parameters as $k => $v) { if ($k === 0) { continue; } - $msg .= var_export($k, true).' => '.var_export($v, true).', '; + $msg .= var_export($k, true) . ' => ' . var_export($v, true) . ', '; } - $msg = substr($msg, 0, -2).')'; + $msg = substr($msg, 0, -2) . ')'; } else { $msg = $this->errorCode; } @@ -181,7 +181,7 @@ class Error extends Exception $etrace = implode("\n", $data); $reportId = bin2hex(openssl_random_pseudo_bytes(4)); - Logger::error('Error report with id '.$reportId.' generated.'); + Logger::error('Error report with id ' . $reportId . ' generated.'); $config = Configuration::getInstance(); $session = Session::getSessionFromRequest(); @@ -239,12 +239,13 @@ class Error extends Exception $data['clipboard.js'] = true; // check if there is a valid technical contact email address - if ($config->getBoolean('errorreporting', true) && - $config->getString('technicalcontact_email', 'na@example.org') !== 'na@example.org' + if ( + $config->getBoolean('errorreporting', true) + && $config->getString('technicalcontact_email', 'na@example.org') !== 'na@example.org' ) { // enable error reporting $baseurl = Utils\HTTP::getBaseURL(); - $data['errorReportAddress'] = $baseurl.'errorreport.php'; + $data['errorReportAddress'] = $baseurl . 'errorreport.php'; } $data['email'] = ''; diff --git a/lib/SimpleSAML/Error/Exception.php b/lib/SimpleSAML/Error/Exception.php index 18aabf398edfd659297df534aac8f1f8e0799d90..abfc6633ba8d33c37daff814ec6bd0acd15d1af7 100644 --- a/lib/SimpleSAML/Error/Exception.php +++ b/lib/SimpleSAML/Error/Exception.php @@ -87,24 +87,24 @@ class Exception extends \Exception $this->backtrace = []; // position in the top function on the stack - $pos = $exception->getFile().':'.$exception->getLine(); + $pos = $exception->getFile() . ':' . $exception->getLine(); foreach ($exception->getTrace() as $t) { $function = $t['function']; if (array_key_exists('class', $t)) { - $function = $t['class'].'::'.$function; + $function = $t['class'] . '::' . $function; } - $this->backtrace[] = $pos.' ('.$function.')'; + $this->backtrace[] = $pos . ' (' . $function . ')'; if (array_key_exists('file', $t)) { - $pos = $t['file'].':'.$t['line']; + $pos = $t['file'] . ':' . $t['line']; } else { $pos = '[builtin]'; } } - $this->backtrace[] = $pos.' (N/A)'; + $this->backtrace[] = $pos . ' (N/A)'; } @@ -153,7 +153,7 @@ class Exception extends \Exception public function format($anonymize = false) { $ret = [ - $this->getClass().': '.$this->getMessage(), + $this->getClass() . ': ' . $this->getMessage(), ]; return array_merge($ret, $this->formatBacktrace($anonymize)); } @@ -176,7 +176,7 @@ class Exception extends \Exception $e = $this; do { if ($e !== $this) { - $ret[] = 'Caused by: '.$e->getClass().': '.$e->getMessage(); + $ret[] = 'Caused by: ' . $e->getClass() . ': ' . $e->getMessage(); } $ret[] = 'Backtrace:'; @@ -186,7 +186,7 @@ class Exception extends \Exception $trace = str_replace($basedir, '', $trace); } - $ret[] = ($depth - $i - 1).' '.$trace; + $ret[] = ($depth - $i - 1) . ' ' . $trace; } $e = $e->cause; } while ($e !== null); @@ -205,12 +205,15 @@ class Exception extends \Exception // see if debugging is enabled for backtraces $debug = Configuration::getInstance()->getArrayize('debug', ['backtraces' => false]); - if (!(in_array('backtraces', $debug, true) // implicitly enabled - || (array_key_exists('backtraces', $debug) && $debug['backtraces'] === true) + if ( + !(in_array('backtraces', $debug, true) // implicitly enabled + || (array_key_exists('backtraces', $debug) + && $debug['backtraces'] === true) // explicitly set // TODO: deprecate the old style and remove it in 2.0 - || (array_key_exists(0, $debug) && $debug[0] === true) // old style 'debug' configuration option - )) { + || (array_key_exists(0, $debug) + && $debug[0] === true)) // old style 'debug' configuration option + ) { return; } @@ -259,7 +262,7 @@ class Exception extends \Exception */ public function logError() { - Logger::error($this->getClass().': '.$this->getMessage()); + Logger::error($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(Logger::ERR); } @@ -272,7 +275,7 @@ class Exception extends \Exception */ public function logWarning() { - Logger::warning($this->getClass().': '.$this->getMessage()); + Logger::warning($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(Logger::WARNING); } @@ -285,7 +288,7 @@ class Exception extends \Exception */ public function logInfo() { - Logger::info($this->getClass().': '.$this->getMessage()); + Logger::info($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(Logger::INFO); } @@ -298,7 +301,7 @@ class Exception extends \Exception */ public function logDebug() { - Logger::debug($this->getClass().': '.$this->getMessage()); + Logger::debug($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(Logger::DEBUG); } diff --git a/lib/SimpleSAML/Error/NotFound.php b/lib/SimpleSAML/Error/NotFound.php index 187b658d09ab559869556e4f4ba59536f27c4a99..ed556a38cf985333612a614384c72d70cc961554 100644 --- a/lib/SimpleSAML/Error/NotFound.php +++ b/lib/SimpleSAML/Error/NotFound.php @@ -38,7 +38,7 @@ class NotFound extends Error $this->message = "The requested page '$url' could not be found."; } else { parent::__construct(['NOTFOUNDREASON', '%URL%' => $url, '%REASON%' => $reason]); - $this->message = "The requested page '$url' could not be found. ".$reason; + $this->message = "The requested page '$url' could not be found. " . $reason; } $this->reason = $reason; @@ -68,7 +68,7 @@ class NotFound extends Error public function format($anonymize = false) { return [ - $this->getClass().': '.$this->getMessage(), + $this->getClass() . ': ' . $this->getMessage(), ]; } } diff --git a/lib/SimpleSAML/HTTP/Router.php b/lib/SimpleSAML/HTTP/Router.php index 7adb8ed80d75c31c19c1e5b66dafc195f708746c..48d0155e0d485510550361e3f10da8696d37e341 100644 --- a/lib/SimpleSAML/HTTP/Router.php +++ b/lib/SimpleSAML/HTTP/Router.php @@ -5,7 +5,6 @@ namespace SimpleSAML\HTTP; use SimpleSAML\Configuration; use SimpleSAML\Module\ControllerResolver; use SimpleSAML\Session; - use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; diff --git a/lib/SimpleSAML/IdP.php b/lib/SimpleSAML/IdP.php index d9c895ad8acf9d0cc793e28086225e8d6ba13377..ec6a622c7e3d8a6ca728dc0854d64754d0f5f939 100644 --- a/lib/SimpleSAML/IdP.php +++ b/lib/SimpleSAML/IdP.php @@ -3,7 +3,6 @@ namespace SimpleSAML; use SAML2\Constants as SAML2; - use SimpleSAML\Auth; use SimpleSAML\Error; use SimpleSAML\Metadata\MetaDataStorageHandler; @@ -94,7 +93,7 @@ class IdP try { // this makes the ADFS IdP use the same SP associations as the SAML 2.0 IdP $saml2EntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); - $this->associationGroup = 'saml2:'.$saml2EntityId; + $this->associationGroup = 'saml2:' . $saml2EntityId; } catch (\Exception $e) { // probably no SAML 2 IdP configured for this host. Ignore the error } @@ -106,7 +105,7 @@ class IdP if (Auth\Source::getById($auth) !== null) { $this->authSource = new Auth\Simple($auth); } else { - throw new Error\Exception('No such "'.$auth.'" auth source found.'); + throw new Error\Exception('No such "' . $auth . '" auth source found.'); } } @@ -282,7 +281,7 @@ class IdP $session = Session::getSessionFromRequest(); $session->setData( 'core:idp-ssotime', - $state['core:IdP'].';'.$state['core:SP'], + $state['core:IdP'] . ';' . $state['core:SP'], time(), Session::DATA_TIMEOUT_SESSION_END ); @@ -319,7 +318,7 @@ class IdP if (isset($state['core:SP'])) { $session = Session::getSessionFromRequest(); - $previousSSOTime = $session->getData('core:idp-ssotime', $state['core:IdP'].';'.$state['core:SP']); + $previousSSOTime = $session->getData('core:idp-ssotime', $state['core:IdP'] . ';' . $state['core:SP']); if ($previousSSOTime !== null) { $state['PreviousSSOTimestamp'] = $previousSSOTime; } @@ -446,7 +445,7 @@ class IdP $handler = '\SimpleSAML\IdP\IFrameLogoutHandler'; break; default: - throw new Error\Exception('Unknown logout handler: '.var_export($logouttype, true)); + throw new Error\Exception('Unknown logout handler: ' . var_export($logouttype, true)); } /** @var IdP\LogoutHandlerInterface */ @@ -493,7 +492,7 @@ class IdP if ($assocId !== null) { $this->terminateAssociation($assocId); $session = Session::getSessionFromRequest(); - $session->deleteData('core:idp-ssotime', $this->id.';'.$state['saml:SPEntityId']); + $session->deleteData('core:idp-ssotime', $this->id . ';' . $state['saml:SPEntityId']); } // terminate the local session @@ -529,7 +528,7 @@ class IdP assert(is_int($index)); $session = Session::getSessionFromRequest(); - $session->deleteData('core:idp-ssotime', $this->id.';'.substr($assocId, $index + 1)); + $session->deleteData('core:idp-ssotime', $this->id . ';' . substr($assocId, $index + 1)); $handler = $this->getLogoutHandler(); $handler->onResponse($assocId, $relayState, $error); diff --git a/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php b/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php index 7649ef75309f2f80d73d356bd6338d5080445627..9c18499364c707af8c95ad31a0e99e84e3327495 100644 --- a/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php +++ b/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php @@ -53,14 +53,14 @@ class TraditionalLogoutHandler implements LogoutHandlerInterface $relayState = Auth\State::saveState($state, 'core:LogoutTraditional', true); $id = $association['id']; - Logger::info('Logging out of '.var_export($id, true).'.'); + Logger::info('Logging out of ' . var_export($id, true) . '.'); try { $idp = IdP::getByState($association); $url = call_user_func([$association['Handler'], 'getLogoutURL'], $idp, $association, $relayState); Utils\HTTP::redirectTrustedURL($url); } catch (\Exception $e) { - Logger::warning('Unable to initialize logout to '.var_export($id, true).'.'); + Logger::warning('Unable to initialize logout to ' . var_export($id, true) . '.'); $this->idp->terminateAssociation($id); $state['core:Failed'] = true; @@ -112,10 +112,10 @@ class TraditionalLogoutHandler implements LogoutHandlerInterface $state = Auth\State::loadState($relayState, 'core:LogoutTraditional'); if ($error === null) { - Logger::info('Logged out of '.var_export($assocId, true).'.'); + Logger::info('Logged out of ' . var_export($assocId, true) . '.'); $this->idp->terminateAssociation($assocId); } else { - Logger::warning('Error received from '.var_export($assocId, true).' during logout:'); + Logger::warning('Error received from ' . var_export($assocId, true) . ' during logout:'); $error->logWarning(); $state['core:Failed'] = true; } diff --git a/lib/SimpleSAML/Locale/Localization.php b/lib/SimpleSAML/Locale/Localization.php index 3731b1e4ddd3572f05323ec5236f319223661026..e334bfc3761f58fb7252f179629b4d6d7119dec9 100644 --- a/lib/SimpleSAML/Locale/Localization.php +++ b/lib/SimpleSAML/Locale/Localization.php @@ -100,7 +100,11 @@ class Localization $this->localeDir = $locales; $this->language = new Language($configuration); $this->langcode = $this->language->getPosixLanguage($this->language->getLanguage()); - $this->i18nBackend = ($this->configuration->getBoolean('usenewui', false) ? self::GETTEXT_I18N_BACKEND : self::SSP_I18N_BACKEND); + $this->i18nBackend = ( + $this->configuration->getBoolean('usenewui', false) + ? self::GETTEXT_I18N_BACKEND + : self::SSP_I18N_BACKEND + ); $this->setupL10N(); } @@ -127,7 +131,7 @@ class Localization { /** @var string $base */ $base = $this->configuration->resolvePath('modules'); - $localeDir = $base.'/'.$domain.'/locales'; + $localeDir = $base . '/' . $domain . '/locales'; return $localeDir; } @@ -177,7 +181,7 @@ class Localization $langcode = explode('_', $this->langcode); $langcode = $langcode[0]; $localeDir = $this->localeDomainMap[$domain]; - $langPath = $localeDir.'/'.$langcode.'/LC_MESSAGES/'; + $langPath = $localeDir . '/' . $langcode . '/LC_MESSAGES/'; Logger::debug("Trying langpath for '$langcode' as '$langPath'"); if (is_dir($langPath) && is_readable($langPath)) { return $langPath; @@ -186,7 +190,7 @@ class Localization // Some langcodes have aliases.. $alias = $this->language->getLanguageCodeAlias($langcode); if (isset($alias)) { - $langPath = $localeDir.'/'.$alias.'/LC_MESSAGES/'; + $langPath = $localeDir . '/' . $alias . '/LC_MESSAGES/'; Logger::debug("Trying langpath for alternative '$alias' as '$langPath'"); if (is_dir($langPath) && is_readable($langPath)) { return $langPath; @@ -195,18 +199,18 @@ class Localization // Language not found, fall back to default $defLangcode = $this->language->getDefaultLanguage(); - $langPath = $localeDir.'/'.$defLangcode.'/LC_MESSAGES/'; + $langPath = $localeDir . '/' . $defLangcode . '/LC_MESSAGES/'; if (is_dir($langPath) && is_readable($langPath)) { // Report that the localization for the preferred language is missing - $error = "Localization not found for langcode '$langcode' at '$langPath', falling back to langcode '". - $defLangcode."'"; - Logger::error($_SERVER['PHP_SELF'].' - '.$error); + $error = "Localization not found for langcode '$langcode' at '$langPath', falling back to langcode '" . + $defLangcode . "'"; + Logger::error($_SERVER['PHP_SELF'] . ' - ' . $error); return $langPath; } // Locale for default language missing even, error out $error = "Localization directory missing/broken for langcode '$langcode' and domain '$domain'"; - Logger::critical($_SERVER['PHP_SELF'].' - '.$error); + Logger::critical($_SERVER['PHP_SELF'] . ' - ' . $error); throw new \Exception($error); } @@ -240,7 +244,7 @@ class Localization $langPath = $this->getLangPath($domain); } catch (\Exception $e) { $error = "Something went wrong when trying to get path to language file, cannot load domain '$domain'."; - Logger::debug($_SERVER['PHP_SELF'].' - '.$error); + Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error); if ($catchException) { // bail out! return; @@ -248,14 +252,14 @@ class Localization throw $e; } } - $poFile = $domain.'.po'; - $poPath = $langPath.$poFile; + $poFile = $domain . '.po'; + $poPath = $langPath . $poFile; if (file_exists($poPath) && is_readable($poPath)) { $translations = Translations::fromPoFile($poPath); $this->translator->loadTranslations($translations); } else { $error = "Localization file '$poFile' not found in '$langPath', falling back to default"; - Logger::debug($_SERVER['PHP_SELF'].' - '.$error); + Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error); } } diff --git a/lib/SimpleSAML/Locale/Translate.php b/lib/SimpleSAML/Locale/Translate.php index 77c00f0e67e9685b968c23edec74f709dd76fb35..0d0475edfe74bdb1ed9fb61eefffc86b64bd0698 100644 --- a/lib/SimpleSAML/Locale/Translate.php +++ b/lib/SimpleSAML/Locale/Translate.php @@ -67,9 +67,9 @@ class Translate // TODO: drop this entire if clause for 2.0 // for backwards compatibility - print warning $backtrace = debug_backtrace(); - $where = $backtrace[0]['file'].':'.$backtrace[0]['line']; + $where = $backtrace[0]['file'] . ':' . $backtrace[0]['line']; Logger::warning( - 'Deprecated use of new SimpleSAML\Locale\Translate(...) at '.$where. + 'Deprecated use of new SimpleSAML\Locale\Translate(...) at ' . $where . '. The last parameter is now a dictionary name, which should not end in ".php".' ); @@ -106,13 +106,13 @@ class Translate if ($sepPos !== false) { $module = substr($name, 0, $sepPos); $fileName = substr($name, $sepPos + 1); - $dictDir = Module::getModuleDir($module).'/dictionaries/'; + $dictDir = Module::getModuleDir($module) . '/dictionaries/'; } else { $dictDir = $this->configuration->getPathValue('dictionarydir', 'dictionaries/') ?: 'dictionaries/'; $fileName = $name; } - $this->dictionaries[$name] = $this->readDictionaryFile($dictDir.$fileName); + $this->dictionaries[$name] = $this->readDictionaryFile($dictDir . $fileName); } return $this->dictionaries[$name]; @@ -219,8 +219,8 @@ class Translate // search the default attribute dictionary $dict = $this->getDictionary('attributes'); - if (array_key_exists('attribute_'.$normName, $dict)) { - return $this->getPreferredTranslation($dict['attribute_'.$normName]); + if (array_key_exists('attribute_' . $normName, $dict)) { + return $this->getPreferredTranslation($dict['attribute_' . $normName]); } // no translations found @@ -274,11 +274,11 @@ class Translate $striptags = false ) { $backtrace = debug_backtrace(); - $where = $backtrace[0]['file'].':'.$backtrace[0]['line']; + $where = $backtrace[0]['file'] . ':' . $backtrace[0]['line']; if (!$fallbackdefault) { Logger::warning( - 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at '.$where. - '. This parameter will go away, the fallback will become'. + 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at ' . $where . + '. This parameter will go away, the fallback will become' . ' identical to the $tag in 2.0.' ); } @@ -287,7 +287,7 @@ class Translate // old style call to t(...). Print warning to log Logger::warning( - 'Deprecated use of SimpleSAML\Locale\Translate::t(...) at '.$where. + 'Deprecated use of SimpleSAML\Locale\Translate::t(...) at ' . $where . '. Please update the code to use the new style of parameters.' ); @@ -306,14 +306,14 @@ class Translate if (is_array($tag)) { $tagData = $tag; Logger::warning( - 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at '.$where. + 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at ' . $where . '. The $tag-parameter can only be a string in 2.0.' ); } else { $tagData = $this->getTag($tag); if ($tagData === null) { // tag not found - Logger::info('Translate: Looking up ['.$tag.']: not translated at all.'); + Logger::info('Translate: Looking up [' . $tag . ']: not translated at all.'); return $this->getStringNotTranslated($tag, $fallbackdefault); } } @@ -342,7 +342,7 @@ class Translate private function getStringNotTranslated($tag, $fallbacktag) { if ($fallbacktag) { - return 'not translated ('.$tag.')'; + return 'not translated (' . $tag . ')'; } else { return $tag; } @@ -364,10 +364,12 @@ class Translate if (is_string($translation)) { $translation = ['en' => $translation]; } elseif (!is_array($translation)) { - throw new \Exception("Inline translation should be string or array. Is ".gettype($translation)." now!"); + throw new \Exception( + "Inline translation should be string or array. Is " . gettype($translation) . " now!" + ); } - Logger::debug('Translate: Adding inline language translation for tag ['.$tag.']'); + Logger::debug('Translate: Adding inline language translation for tag [' . $tag . ']'); $this->langtext[$tag] = $translation; } @@ -390,8 +392,8 @@ class Translate } $filebase = $filebase ?: 'dictionaries/'; - $lang = $this->readDictionaryFile($filebase.$file); - Logger::debug('Translate: Merging language array. Loading ['.$file.']'); + $lang = $this->readDictionaryFile($filebase . $file); + Logger::debug('Translate: Merging language array. Loading [' . $file . ']'); $this->langtext = array_merge($this->langtext, $lang); } @@ -404,18 +406,18 @@ class Translate */ private function readDictionaryJSON($filename) { - $definitionFile = $filename.'.definition.json'; + $definitionFile = $filename . '.definition.json'; assert(file_exists($definitionFile)); $fileContent = file_get_contents($definitionFile); $lang = json_decode($fileContent, true); if (empty($lang)) { - Logger::error('Invalid dictionary definition file ['.$definitionFile.']'); + Logger::error('Invalid dictionary definition file [' . $definitionFile . ']'); return []; } - $translationFile = $filename.'.translation.json'; + $translationFile = $filename . '.translation.json'; if (file_exists($translationFile)) { $fileContent = file_get_contents($translationFile); $moreTrans = json_decode($fileContent, true); @@ -436,7 +438,7 @@ class Translate */ private function readDictionaryPHP($filename) { - $phpFile = $filename.'.php'; + $phpFile = $filename . '.php'; assert(file_exists($phpFile)); $lang = null; @@ -459,20 +461,20 @@ class Translate { assert(is_string($filename)); - Logger::debug('Translate: Reading dictionary ['.$filename.']'); + Logger::debug('Translate: Reading dictionary [' . $filename . ']'); - $jsonFile = $filename.'.definition.json'; + $jsonFile = $filename . '.definition.json'; if (file_exists($jsonFile)) { return $this->readDictionaryJSON($filename); } - $phpFile = $filename.'.php'; + $phpFile = $filename . '.php'; if (file_exists($phpFile)) { return $this->readDictionaryPHP($filename); } Logger::error( - $_SERVER['PHP_SELF'].' - Translate: Could not find dictionary file at ['.$filename.']' + $_SERVER['PHP_SELF'] . ' - Translate: Could not find dictionary file at [' . $filename . ']' ); return []; } @@ -522,10 +524,10 @@ class Translate /** * Pick a translation from a given array of translations for the current language. * - * @param array|null $context An array of options. The current language must be specified as an ISO 639 code accessible - * with the key "currentLanguage" in the array. - * @param array|null $translations An array of translations. Each translation has an ISO 639 code as its key, identifying - * the language it corresponds to. + * @param array|null $context An array of options. The current language must be specified + * as an ISO 639 code accessible with the key "currentLanguage" in the array. + * @param array|null $translations An array of translations. Each translation has an + * ISO 639 code as its key, identifying the language it corresponds to. * * @return null|string The translation appropriate for the current language, or null if none found. If the * $context or $translations arrays are null, or $context['currentLanguage'] is not defined, null is also returned. diff --git a/lib/SimpleSAML/Logger.php b/lib/SimpleSAML/Logger.php index 8c88e2a9cf71b59c82218e144f59512f47f37888..69d38ca699cf22a10964c26a980c604102a005e9 100644 --- a/lib/SimpleSAML/Logger.php +++ b/lib/SimpleSAML/Logger.php @@ -439,7 +439,7 @@ class Logger $handler = strtolower($handler); if (!array_key_exists($handler, $known_handlers)) { throw new \Exception( - "Invalid value for the 'logging.handler' configuration option. Unknown handler '".$handler."''." + "Invalid value for the 'logging.handler' configuration option. Unknown handler '" . $handler . "'." ); } $handler = $known_handlers[$handler]; @@ -479,7 +479,7 @@ class Logger } $_SERVER['REMOTE_ADDR'] = "CLI"; if (self::$trackid === self::NO_TRACKID) { - self::$trackid = 'CL'.bin2hex(openssl_random_pseudo_bytes(4)); + self::$trackid = 'CL' . bin2hex(openssl_random_pseudo_bytes(4)); } } elseif (!isset(self::$loggingHandler)) { // Initialize logging @@ -489,8 +489,8 @@ class Logger if (self::$captureLog) { $ts = microtime(true); $msecs = (int) (($ts - (int) $ts) * 1000); - $ts = gmdate('H:i:s', $ts).sprintf('.%03d', $msecs).'Z'; - self::$capturedLog[] = $ts.' '.$string; + $ts = gmdate('H:i:s', $ts) . sprintf('.%03d', $msecs) . 'Z'; + self::$capturedLog[] = $ts . ' ' . $string; } if (self::$logLevel >= $level || $statsLog) { diff --git a/lib/SimpleSAML/Logger/FileLoggingHandler.php b/lib/SimpleSAML/Logger/FileLoggingHandler.php index a85307f6b7f15e2357f52eb742c6654f6d1c1d0d..b7d041a03d016fb452dde193bfb28e0fbebe89f0 100644 --- a/lib/SimpleSAML/Logger/FileLoggingHandler.php +++ b/lib/SimpleSAML/Logger/FileLoggingHandler.php @@ -53,18 +53,18 @@ class FileLoggingHandler implements LoggingHandlerInterface public function __construct(Configuration $config) { // get the metadata handler option from the configuration - $this->logFile = $config->getPathValue('loggingdir', 'log/'). + $this->logFile = $config->getPathValue('loggingdir', 'log/') . $config->getString('logging.logfile', 'simplesamlphp.log'); $this->processname = $config->getString('logging.processname', 'SimpleSAMLphp'); if (@file_exists($this->logFile)) { if (!@is_writeable($this->logFile)) { - throw new \Exception("Could not write to logfile: ".$this->logFile); + throw new \Exception("Could not write to logfile: " . $this->logFile); } } else { if (!@touch($this->logFile)) { throw new \Exception( - "Could not create logfile: ".$this->logFile. + "Could not create logfile: " . $this->logFile . " The logging directory is not writable for the web server user." ); } @@ -117,7 +117,7 @@ class FileLoggingHandler implements LoggingHandlerInterface } $string = str_replace($formats, $replacements, $string); - file_put_contents($this->logFile, $string.\PHP_EOL, FILE_APPEND); + file_put_contents($this->logFile, $string . \PHP_EOL, FILE_APPEND); } } } diff --git a/lib/SimpleSAML/Memcache.php b/lib/SimpleSAML/Memcache.php index 5f6577ef578b1ef22f218898be023e8eb5e85f2a..bc5fea839b7ad625a2e857eab33e0e3398b63c23 100644 --- a/lib/SimpleSAML/Memcache.php +++ b/lib/SimpleSAML/Memcache.php @@ -232,7 +232,7 @@ class Memcache // the hostname must be a valid string if (!is_string($hostname)) { throw new \Exception( - "Invalid hostname for server in the 'memcache_store.servers' configuration option. The hostname is". + "Invalid hostname for server in the 'memcache_store.servers' configuration option. The hostname is" . ' supposed to be a string.' ); } @@ -246,7 +246,7 @@ class Memcache $port = (int) $server['port']; if (($port <= 0) || ($port > 65535)) { throw new \Exception( - "Invalid port for server in the 'memcache_store.servers' configuration option. The port number". + "Invalid port for server in the 'memcache_store.servers' configuration option. The port number" . ' is supposed to be an integer between 0 and 65535.' ); } @@ -265,7 +265,7 @@ class Memcache $weight = (int) $server['weight']; if ($weight <= 0) { throw new \Exception( - "Invalid weight for server in the 'memcache_store.servers' configuration option. The weight is". + "Invalid weight for server in the 'memcache_store.servers' configuration option. The weight is" . ' supposed to be a positive integer.' ); } @@ -280,7 +280,7 @@ class Memcache $timeout = (int) $server['timeout']; if ($timeout <= 0) { throw new \Exception( - "Invalid timeout for server in the 'memcache_store.servers' configuration option. The timeout is". + "Invalid timeout for server in the 'memcache_store.servers' configuration option. The timeout is" . ' supposed to be a positive integer.' ); } @@ -323,7 +323,9 @@ class Memcache } if (self::$extension === '\memcache') { - Logger::warning("The use of PHP-extension memcache is deprecated. Please migrate to the memcached extension."); + Logger::warning( + "The use of PHP-extension memcache is deprecated. Please migrate to the memcached extension." + ); } // iterate over all the servers in the group and add them to the Memcache object @@ -331,8 +333,8 @@ class Memcache // make sure that we don't have an index. An index would be a sign of invalid configuration if (!is_int($index)) { throw new \Exception( - "Invalid index on element in the 'memcache_store.servers' configuration option. Perhaps you". - ' have forgotten to add an array(...) around one of the server groups? The invalid index was: '. + "Invalid index on element in the 'memcache_store.servers' configuration option. Perhaps you" . + ' have forgotten to add an array(...) around one of the server groups? The invalid index was: ' . $index ); } @@ -340,8 +342,8 @@ class Memcache // make sure that the server object is an array. Each server is an array with name-value pairs if (!is_array($server)) { throw new \Exception( - 'Invalid value for the server with index '.$index. - '. Remeber that the \'memcache_store.servers\' configuration option'. + 'Invalid value for the server with index ' . $index . + '. Remeber that the \'memcache_store.servers\' configuration option' . ' contains an array of arrays of arrays.' ); } @@ -383,9 +385,9 @@ class Memcache // make sure that the group doesn't have an index. An index would be a sign of invalid configuration if (!is_int($index)) { throw new \Exception( - "Invalid index on element in the 'memcache_store.servers'". - ' configuration option. Perhaps you have forgotten to add an array(...)'. - ' around one of the server groups? The invalid index was: '.$index + "Invalid index on element in the 'memcache_store.servers'" . + ' configuration option. Perhaps you have forgotten to add an array(...)' . + ' around one of the server groups? The invalid index was: ' . $index ); } @@ -395,8 +397,8 @@ class Memcache */ if (!is_array($group)) { throw new \Exception( - "Invalid value for the server with index ".$index. - ". Remeber that the 'memcache_store.servers' configuration option". + "Invalid value for the server with index " . $index . + ". Remeber that the 'memcache_store.servers' configuration option" . ' contains an array of arrays of arrays.' ); } diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php index cbd5dbddb70f0444a8450c7682b6514459117228..5e77a43bbbfcf2e1a63244314040b91b5d90f1b5 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php @@ -76,7 +76,7 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState $this->sources = MetaDataStorageSource::parseSources($sourcesConfig); } catch (\Exception $e) { throw new \Exception( - "Invalid configuration of the 'metadata.sources' configuration option: ".$e->getMessage() + "Invalid configuration of the 'metadata.sources' configuration option: " . $e->getMessage() ); } } @@ -107,7 +107,7 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState $config = Configuration::getInstance(); assert($config instanceof Configuration); - $baseurl = Utils\HTTP::getSelfURLHost().$config->getBasePath(); + $baseurl = Utils\HTTP::getSelfURLHost() . $config->getBasePath(); if ($set == 'saml20-sp-hosted') { if ($property === 'SingleLogoutServiceBinding') { @@ -116,24 +116,24 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState } elseif ($set == 'saml20-idp-hosted') { switch ($property) { case 'SingleSignOnService': - return $baseurl.'saml2/idp/SSOService.php'; + return $baseurl . 'saml2/idp/SSOService.php'; case 'SingleSignOnServiceBinding': return Constants::BINDING_HTTP_REDIRECT; case 'SingleLogoutService': - return $baseurl.'saml2/idp/SingleLogoutService.php'; + return $baseurl . 'saml2/idp/SingleLogoutService.php'; case 'SingleLogoutServiceBinding': return Constants::BINDING_HTTP_REDIRECT; } } elseif ($set == 'shib13-idp-hosted') { if ($property === 'SingleSignOnService') { - return $baseurl.'shib13/idp/SSOService.php'; + return $baseurl . 'shib13/idp/SSOService.php'; } } - throw new \Exception('Could not generate metadata property '.$property.' for set '.$set.'.'); + throw new \Exception('Could not generate metadata property ' . $property . ' for set ' . $set . '.'); } @@ -160,8 +160,8 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState if (array_key_exists('expire', $le) && ($le['expire'] < time())) { unset($srcList[$key]); Logger::warning( - "Dropping metadata entity ".var_export($key, true).", expired ". - Utils\Time::generateTimestamp($le['expire'])."." + "Dropping metadata entity " . var_export($key, true) . ", expired " . + Utils\Time::generateTimestamp($le['expire']) . "." ); } } @@ -235,8 +235,8 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState // we were unable to find the hostname/path in any metadata source throw new \Exception( - 'Could not find any default metadata entities in set ['.$set.'] for host ['.$currenthost.' : '. - $currenthostwithpath.']' + 'Could not find any default metadata entities in set [' . $set . '] for host [' . $currenthost . ' : ' . + $currenthostwithpath . ']' ); } @@ -280,8 +280,8 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState if ($le['expire'] < time()) { unset($srcList[$key]); \SimpleSAML\Logger::warning( - "Dropping metadata entity ".var_export($key, true).", expired ". - \SimpleSAML\Utils\Time::generateTimestamp($le['expire'])."." + "Dropping metadata entity " . var_export($key, true) . ", expired " . + \SimpleSAML\Utils\Time::generateTimestamp($le['expire']) . "." ); continue; } @@ -324,8 +324,8 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState if (array_key_exists('expire', $metadata)) { if ($metadata['expire'] < time()) { throw new \Exception( - 'Metadata for the entity ['.$index.'] expired '. - (time() - $metadata['expire']).' seconds ago.' + 'Metadata for the entity [' . $index . '] expired ' . + (time() - $metadata['expire']) . ' seconds ago.' ); } } @@ -358,7 +358,7 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState assert(is_string($set)); $metadata = $this->getMetaData($entityId, $set); - return Configuration::loadFromArray($metadata, $set.'/'.var_export($entityId, true)); + return Configuration::loadFromArray($metadata, $set . '/' . var_export($entityId, true)); } @@ -392,7 +392,7 @@ class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState return Configuration::loadFromArray( $remote_provider, - $set.'/'.var_export($remote_provider['entityid'], true) + $set . '/' . var_export($remote_provider['entityid'], true) ); } } diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php index 03c7c1fc9ba80879c628f8e441c4c7f78e58921f..9f15a11f3ac27eab5a61242fc5a377096337ee36 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php @@ -61,7 +61,7 @@ class MetaDataStorageHandlerFlatFile extends MetaDataStorageSource /** @var string $base */ $base = $globalConfig->resolvePath($this->directory); - $this->directory = $base.'/'; + $this->directory = $base . '/'; } @@ -71,13 +71,13 @@ class MetaDataStorageHandlerFlatFile extends MetaDataStorageSource * * @param string $set The set of metadata we are loading. * - * @return array|null An associative array with the metadata, or null if we are unable to load metadata from the given - * file. + * @return array|null An associative array with the metadata, + * or null if we are unable to load metadata from the given file. * @throws \Exception If the metadata set cannot be loaded. */ private function load($set) { - $metadatasetfile = $this->directory.$set.'.php'; + $metadatasetfile = $this->directory . $set . '.php'; if (!file_exists($metadatasetfile)) { return null; @@ -88,7 +88,7 @@ class MetaDataStorageHandlerFlatFile extends MetaDataStorageSource include($metadatasetfile); if (!is_array($metadata)) { - throw new \Exception('Could not load metadata set ['.$set.'] from file: '.$metadatasetfile); + throw new \Exception('Could not load metadata set [' . $set . '] from file: ' . $metadatasetfile); } return $metadata; diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php index 233e6f6a47471c149236d0190f03a005606be424..c6f6c3aed44185f3d7d75ea1906af669f7883abf 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php @@ -106,7 +106,9 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource return $metadata; } else { - throw new \Exception('PDO metadata handler: Database error: '.var_export($this->db->getLastError(), true)); + throw new \Exception( + 'PDO metadata handler: Database error: ' . var_export($this->db->getLastError(), true) + ); } } @@ -172,12 +174,12 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource // any dynamic entries to see if the dynamic hosted entity id matches if (substr($set, -10) == 'idp-hosted') { $stmt = $this->db->read( - "SELECT entity_id, entity_data FROM {$tableName} WHERE (entity_id LIKE :dynamicId OR entity_id = :entityId)", + "SELECT entity_id, entity_data FROM {$tableName} " + . "WHERE (entity_id LIKE :dynamicId OR entity_id = :entityId)", ['dynamicId' => '__DYNAMIC%', 'entityId' => $entityId] ); - } - // other metadata types should be able to match on entity id - else { + } else { + // other metadata types should be able to match on entity id $stmt = $this->db->read( "SELECT entity_id, entity_data FROM {$tableName} WHERE entity_id = :entityId", ['entityId' => $entityId] @@ -186,7 +188,9 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource // throw pdo exception upon execution failure if (!$stmt->execute()) { - throw new \Exception('PDO metadata handler: Database error: '.var_export($this->db->getLastError(), true)); + throw new \Exception( + 'PDO metadata handler: Database error: ' . var_export($this->db->getLastError(), true) + ); } // load the metadata into an array @@ -194,7 +198,9 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource while ($d = $stmt->fetch()) { $data = json_decode($d['entity_data'], true); if (json_last_error() != JSON_ERROR_NONE) { - throw new \SimpleSAML\Error\Exception("Cannot decode metadata for entity '${d['entity_id']}'"); + throw new \SimpleSAML\Error\Exception( + "Cannot decode metadata for entity '${d['entity_id']}'" + ); } // update the entity id to either the key (if not dynamic or generate the dynamic hosted url) @@ -273,7 +279,7 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource { assert(is_string($table)); - return $this->db->applyPrefix(str_replace("-", "_", $this->tablePrefix.$table)); + return $this->db->applyPrefix(str_replace("-", "_", $this->tablePrefix . $table)); } @@ -289,7 +295,7 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource foreach ($this->supportedSets as $set) { $tableName = $this->getTableName($set); $rows = $this->db->write( - "CREATE TABLE IF NOT EXISTS $tableName (entity_id VARCHAR(255) PRIMARY KEY NOT NULL, entity_data ". + "CREATE TABLE IF NOT EXISTS $tableName (entity_id VARCHAR(255) PRIMARY KEY NOT NULL, entity_data " . "TEXT NOT NULL)" ); if ($rows === false) { diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php index db1b086bed9cc1cc341787593843cd861bed45ba..85c2440d152e4014c1b892c2e8f14c33783f841f 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php @@ -67,7 +67,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource assert(is_string($entityId)); assert(is_string($set)); - return $this->directory.'/'.rawurlencode($set).'/'.rawurlencode($entityId).self::EXTENSION; + return $this->directory . '/' . rawurlencode($set) . '/' . rawurlencode($entityId) . self::EXTENSION; } @@ -83,7 +83,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource $dh = @opendir($this->directory); if ($dh === false) { Logger::warning( - 'Serialize metadata handler: Unable to open directory: '.var_export($this->directory, true) + 'Serialize metadata handler: Unable to open directory: ' . var_export($this->directory, true) ); return $ret; } @@ -94,12 +94,12 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource continue; } - $path = $this->directory.'/'.$entry; + $path = $this->directory . '/' . $entry; if (!is_dir($path)) { Logger::warning( - 'Serialize metadata handler: Metadata directory contained a file where only directories should '. - 'exist: '.var_export($path, true) + 'Serialize metadata handler: Metadata directory contained a file where only directories should ' . + 'exist: ' . var_export($path, true) ); continue; } @@ -126,7 +126,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource $ret = []; - $dir = $this->directory.'/'.rawurlencode($set); + $dir = $this->directory . '/' . rawurlencode($set); if (!is_dir($dir)) { // probably some code asked for a metadata set which wasn't available return $ret; @@ -135,7 +135,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource $dh = @opendir($dir); if ($dh === false) { Logger::warning( - 'Serialize metadata handler: Unable to open directory: '.var_export($dir, true) + 'Serialize metadata handler: Unable to open directory: ' . var_export($dir, true) ); return $ret; } @@ -191,14 +191,14 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource /** @var array $error */ $error = error_get_last(); Logger::warning( - 'Error reading file '.$filePath.': '.$error['message'] + 'Error reading file ' . $filePath . ': ' . $error['message'] ); return null; } $data = @unserialize($data); if ($data === false) { - Logger::warning('Error unserializing file: '.$filePath); + Logger::warning('Error unserializing file: ' . $filePath); return null; } @@ -226,29 +226,29 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource assert(is_array($metadata)); $filePath = $this->getMetadataPath($entityId, $set); - $newPath = $filePath.'.new'; + $newPath = $filePath . '.new'; $dir = dirname($filePath); if (!is_dir($dir)) { - Logger::info('Creating directory: '.$dir); + Logger::info('Creating directory: ' . $dir); $res = @mkdir($dir, 0777, true); if ($res === false) { /** @var array $error */ $error = error_get_last(); - Logger::error('Failed to create directory '.$dir.': '.$error['message']); + Logger::error('Failed to create directory ' . $dir . ': ' . $error['message']); return false; } } $data = serialize($metadata); - Logger::debug('Writing: '.$newPath); + Logger::debug('Writing: ' . $newPath); $res = file_put_contents($newPath, $data); if ($res === false) { /** @var array $error */ $error = error_get_last(); - Logger::error('Error saving file '.$newPath.': '.$error['message']); + Logger::error('Error saving file ' . $newPath . ': ' . $error['message']); return false; } @@ -256,7 +256,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource if ($res === false) { /** @var array $error */ $error = error_get_last(); - Logger::error('Error renaming '.$newPath.' to '.$filePath.': '.$error['message']); + Logger::error('Error renaming ' . $newPath . ' to ' . $filePath . ': ' . $error['message']); return false; } @@ -280,8 +280,8 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource if (!file_exists($filePath)) { Logger::warning( - 'Attempted to erase nonexistent metadata entry '. - var_export($entityId, true).' in set '.var_export($set, true).'.' + 'Attempted to erase nonexistent metadata entry ' . + var_export($entityId, true) . ' in set ' . var_export($set, true) . '.' ); return; } @@ -291,8 +291,8 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource /** @var array $error */ $error = error_get_last(); Logger::error( - 'Failed to delete file '.$filePath. - ': '.$error['message'] + 'Failed to delete file ' . $filePath . + ': ' . $error['message'] ); } } diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php index 507306b026e5b21f15869717e4476bd493fa4686..5ba3fd19ffba28a9a71c49f8c5d9c2ffba7254c6 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php @@ -190,9 +190,11 @@ abstract class MetaDataStorageSource } // support discohints in idp metadata for idp discovery - if (array_key_exists('DiscoHints', $entry) + if ( + array_key_exists('DiscoHints', $entry) && array_key_exists('IPHint', $entry['DiscoHints']) - && is_array($entry['DiscoHints']['IPHint'])) { + && is_array($entry['DiscoHints']['IPHint']) + ) { // merge with hints derived from discohints, but prioritize hint.cidr in case it is used $cidrHints = array_merge($entry['DiscoHints']['IPHint'], $cidrHints); } @@ -330,22 +332,17 @@ abstract class MetaDataStorageSource $baseUrl = Utils\HTTP::getBaseURL(); if ($set === 'saml20-idp-hosted') { - return $baseUrl.'saml2/idp/metadata.php'; - } - else if ($set === 'saml20-sp-hosted') { - return $baseUrl.'saml2/sp/metadata.php'; - } - else if ($set === 'shib13-idp-hosted') { - return $baseUrl.'shib13/idp/metadata.php'; - } - else if ($set === 'shib13-sp-hosted') { - return $baseUrl.'shib13/sp/metadata.php'; - } - else if ($set === 'adfs-idp-hosted') { - return 'urn:federation:'.Utils\HTTP::getSelfHost().':idp'; - } - else { - throw new \Exception('Can not generate dynamic EntityID for metadata of this type: ['.$set.']'); + return $baseUrl . 'saml2/idp/metadata.php'; + } elseif ($set === 'saml20-sp-hosted') { + return $baseUrl . 'saml2/sp/metadata.php'; + } elseif ($set === 'shib13-idp-hosted') { + return $baseUrl . 'shib13/idp/metadata.php'; + } elseif ($set === 'shib13-sp-hosted') { + return $baseUrl . 'shib13/sp/metadata.php'; + } elseif ($set === 'adfs-idp-hosted') { + return 'urn:federation:' . Utils\HTTP::getSelfHost() . ':idp'; + } else { + throw new \Exception('Can not generate dynamic EntityID for metadata of this type: [' . $set . ']'); } } @@ -372,9 +369,8 @@ abstract class MetaDataStorageSource // generate a dynamic hosted url if (preg_match('/__DYNAMIC(:[0-9]+)?__/', $entityId)) { $modifiedMetadataEntry['entityid'] = $this->getDynamicHostedUrl($metadataSet); - } - // set the entityid metadata array key to the provided entity id - else { + } else { + // set the entityid metadata array key to the provided entity id $modifiedMetadataEntry['entityid'] = $entityId; } diff --git a/lib/SimpleSAML/Metadata/SAMLBuilder.php b/lib/SimpleSAML/Metadata/SAMLBuilder.php index c8eb4af3978a727f5eb4b87708a03b834f945015..0752591bebfa117a5f34a071082e58966696e0e7 100644 --- a/lib/SimpleSAML/Metadata/SAMLBuilder.php +++ b/lib/SimpleSAML/Metadata/SAMLBuilder.php @@ -95,7 +95,7 @@ class SAMLBuilder } if ($this->maxCache !== null) { - $this->entityDescriptor->setCacheDuration('PT'.$this->maxCache.'S'); + $this->entityDescriptor->setCacheDuration('PT' . $this->maxCache . 'S'); } if ($this->maxDuration !== null) { $this->entityDescriptor->setValidUntil(time() + $this->maxDuration); @@ -337,7 +337,8 @@ class SAMLBuilder */ public function addOrganizationInfo(array $metadata) { - if (empty($metadata['OrganizationName']) || + if ( + empty($metadata['OrganizationName']) || empty($metadata['OrganizationDisplayName']) || empty($metadata['OrganizationURL']) ) { @@ -499,7 +500,7 @@ class SAMLBuilder $this->addAttributeAuthority($metadata); break; default: - Logger::warning('Unable to generate metadata for unknown type \''.$set.'\'.'); + Logger::warning('Unable to generate metadata for unknown type \'' . $set . '\'.'); } } diff --git a/lib/SimpleSAML/Metadata/SAMLParser.php b/lib/SimpleSAML/Metadata/SAMLParser.php index 53cc9ffa9acf8d8f157d2e4a0d4a0d4629c958b8..eb72cedddedd94de207b715e7e22189c75944f50 100644 --- a/lib/SimpleSAML/Metadata/SAMLParser.php +++ b/lib/SimpleSAML/Metadata/SAMLParser.php @@ -249,7 +249,7 @@ class SAMLParser try { $doc = DOMDocumentFactory::fromString($data); } catch (\Exception $e) { - throw new \Exception('Failed to read XML from file: '.$file); + throw new \Exception('Failed to read XML from file: ' . $file); } return self::parseDocument($doc); @@ -331,7 +331,7 @@ class SAMLParser try { $doc = DOMDocumentFactory::fromString($data); } catch (\Exception $e) { - throw new \Exception('Failed to read XML from file: '.$file); + throw new \Exception('Failed to read XML from file: ' . $file); } return self::parseDescriptorsElement($doc->documentElement); @@ -383,7 +383,7 @@ class SAMLParser } elseif (Utils\XML::isDOMNodeOfType($element, 'EntitiesDescriptor', '@md') === true) { return self::processDescriptorsElement(new EntitiesDescriptor($element)); } else { - throw new \Exception('Unexpected root node: ['.$element->namespaceURI.']:'.$element->localName); + throw new \Exception('Unexpected root node: [' . $element->namespaceURI . ']:' . $element->localName); } } @@ -391,12 +391,9 @@ class SAMLParser /** * * @param \SAML2\XML\md\EntityDescriptor|\SAML2\XML\md\EntitiesDescriptor $element The element we should process. - * @param int|NULL $maxExpireTime The maximum expiration time - * of the entities. - * @param array $validators The parent-elements that may be - * signed. - * @param array $parentExtensions An optional array of - * extensions from the parent element. + * @param int|NULL $maxExpireTime The maximum expiration time of the entities. + * @param array $validators The parent-elements that may be signed. + * @param array $parentExtensions An optional array of extensions from the parent element. * * @return SAMLParser[] Array of SAMLParser instances. */ @@ -1050,8 +1047,11 @@ class SAMLParser ]; // Some extensions may get inherited from a parent element - if (($element instanceof EntityDescriptor || $element instanceof EntitiesDescriptor) - && !empty($parentExtensions['RegistrationInfo'])) { + if ( + ($element instanceof EntityDescriptor + || $element instanceof EntitiesDescriptor) + && !empty($parentExtensions['RegistrationInfo']) + ) { $ret['RegistrationInfo'] = $parentExtensions['RegistrationInfo']; } @@ -1062,14 +1062,21 @@ class SAMLParser } // Entity Attributes are only allowed at entity level extensions and not at RoleDescriptor level - if ($element instanceof EntityDescriptor || - $element instanceof EntitiesDescriptor) { + if ( + $element instanceof EntityDescriptor + || $element instanceof EntitiesDescriptor + ) { if ($e instanceof RegistrationInfo) { // Registration Authority cannot be overridden (warn only if override attempts to change the value) - if (isset($ret['RegistrationInfo']['registrationAuthority']) - && $ret['RegistrationInfo']['registrationAuthority'] !== $e->getRegistrationAuthority()) { - Logger::warning('Invalid attempt to override registrationAuthority \''. - $ret['RegistrationInfo']['registrationAuthority']."' with '{$e->getRegistrationAuthority()}'"); + if ( + isset($ret['RegistrationInfo']['registrationAuthority']) + && $ret['RegistrationInfo']['registrationAuthority'] !== $e->getRegistrationAuthority() + ) { + Logger::warning( + 'Invalid attempt to override registrationAuthority \'' + . $ret['RegistrationInfo']['registrationAuthority'] + . "' with '{$e->getRegistrationAuthority()}'" + ); } else { $ret['RegistrationInfo']['registrationAuthority'] = $e->getRegistrationAuthority(); } @@ -1090,9 +1097,9 @@ class SAMLParser // attribute names that is not URI is prefixed as this: '{nameformat}name' $name = $attrName; if ($attrNameFormat === null) { - $name = '{'.Constants::NAMEFORMAT_UNSPECIFIED.'}'.$attr->getName(); + $name = '{' . Constants::NAMEFORMAT_UNSPECIFIED . '}' . $attr->getName(); } elseif ($attrNameFormat !== Constants::NAMEFORMAT_URI) { - $name = '{'.$attrNameFormat.'}'.$attrName; + $name = '{' . $attrNameFormat . '}' . $attrName; } $values = []; @@ -1123,7 +1130,8 @@ class SAMLParser $ret['UIInfo']['Keywords'][$language] = $keywords; } foreach ($e->getLogo() as $uiItem) { - if (!($uiItem instanceof Logo) + if ( + !($uiItem instanceof Logo) || ($uiItem->getUrl() === null) || ($uiItem->getHeight() === null) || ($uiItem->getWidth() === null) @@ -1464,7 +1472,7 @@ class SAMLParser $certFile = Utils\Config::getCertPath($cert); if (!file_exists($certFile)) { throw new \Exception( - 'Could not find certificate file ['.$certFile.'], which is needed to validate signature' + 'Could not find certificate file [' . $certFile . '], which is needed to validate signature' ); } $certData = file_get_contents($certFile); @@ -1550,7 +1558,7 @@ class SAMLParser } } } - Logger::debug('Fingerprint was ['.$fingerprint.'] not one of ['.join(', ', $candidates).']'); + Logger::debug('Fingerprint was [' . $fingerprint . '] not one of [' . join(', ', $candidates) . ']'); return false; } } diff --git a/lib/SimpleSAML/Metadata/Signer.php b/lib/SimpleSAML/Metadata/Signer.php index 28824c0599ba5e1a225421b86853ecce55d1ef81..c676e967ec204a942dbe82fecafcc2da4e84cb23 100644 --- a/lib/SimpleSAML/Metadata/Signer.php +++ b/lib/SimpleSAML/Metadata/Signer.php @@ -33,16 +33,18 @@ class Signer private static function findKeyCert($config, $entityMetadata, $type) { // first we look for metadata.privatekey and metadata.certificate in the metadata - if (array_key_exists('metadata.sign.privatekey', $entityMetadata) + if ( + array_key_exists('metadata.sign.privatekey', $entityMetadata) || array_key_exists('metadata.sign.certificate', $entityMetadata) ) { - if (!array_key_exists('metadata.sign.privatekey', $entityMetadata) + if ( + !array_key_exists('metadata.sign.privatekey', $entityMetadata) || !array_key_exists('metadata.sign.certificate', $entityMetadata) ) { throw new \Exception( - 'Missing either the "metadata.sign.privatekey" or the'. - ' "metadata.sign.certificate" configuration option in the metadata for'. - ' the '.$type.' "'.$entityMetadata['entityid'].'". If one of'. + 'Missing either the "metadata.sign.privatekey" or the' . + ' "metadata.sign.certificate" configuration option in the metadata for' . + ' the ' . $type . ' "' . $entityMetadata['entityid'] . '". If one of' . ' these options is specified, then the other must also be specified.' ); } @@ -65,9 +67,9 @@ class Signer if ($privatekey !== null || $certificate !== null) { if ($privatekey === null || $certificate === null) { throw new \Exception( - 'Missing either the "metadata.sign.privatekey" or the'. - ' "metadata.sign.certificate" configuration option in the global'. - ' configuration. If one of these options is specified, then the other'. + 'Missing either the "metadata.sign.privatekey" or the' . + ' "metadata.sign.certificate" configuration option in the global' . + ' configuration. If one of these options is specified, then the other' . ' must also be specified.' ); } @@ -82,16 +84,18 @@ class Signer } // as a last resort we attempt to use the privatekey and certificate option from the metadata - if (array_key_exists('privatekey', $entityMetadata) + if ( + array_key_exists('privatekey', $entityMetadata) || array_key_exists('certificate', $entityMetadata) ) { - if (!array_key_exists('privatekey', $entityMetadata) + if ( + !array_key_exists('privatekey', $entityMetadata) || !array_key_exists('certificate', $entityMetadata) ) { throw new \Exception( - 'Both the "privatekey" and the "certificate" option must'. - ' be set in the metadata for the '.$type.' "'. - $entityMetadata['entityid'].'" before it is possible to sign metadata'. + 'Both the "privatekey" and the "certificate" option must' . + ' be set in the metadata for the ' . $type . ' "' . + $entityMetadata['entityid'] . '" before it is possible to sign metadata' . ' from this entity.' ); } @@ -109,8 +113,8 @@ class Signer } throw new \Exception( - 'Could not find what key & certificate should be used to sign the metadata'. - ' for the '.$type.' "'.$entityMetadata['entityid'].'".' + 'Could not find what key & certificate should be used to sign the metadata' . + ' for the ' . $type . ' "' . $entityMetadata['entityid'] . '".' ); } @@ -132,8 +136,8 @@ class Signer if (array_key_exists('metadata.sign.enable', $entityMetadata)) { if (!is_bool($entityMetadata['metadata.sign.enable'])) { throw new \Exception( - 'Invalid value for the "metadata.sign.enable" configuration option for'. - ' the '.$type.' "'.$entityMetadata['entityid'].'". This option'. + 'Invalid value for the "metadata.sign.enable" configuration option for' . + ' the ' . $type . ' "' . $entityMetadata['entityid'] . '". This option' . ' should be a boolean.' ); } @@ -168,8 +172,8 @@ class Signer if (array_key_exists('metadata.sign.algorithm', $entityMetadata)) { if (!is_string($entityMetadata['metadata.sign.algorithm'])) { throw new Error\CriticalConfigurationError( - "Invalid value for the 'metadata.sign.algorithm' configuration option for the ".$type. - "'".$entityMetadata['entityid']."'. This option has restricted values" + "Invalid value for the 'metadata.sign.algorithm' configuration option for the " . $type . + "'" . $entityMetadata['entityid'] . "'. This option has restricted values" ); } $alg = $entityMetadata['metadata.sign.algorithm']; @@ -234,7 +238,7 @@ class Signer $keyFile = 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' + 'Could not find private key file [' . $keyFile . '], which is needed to sign the metadata' ); } $keyData = file_get_contents($keyFile); @@ -242,7 +246,7 @@ class Signer $certFile = 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' + 'Could not find certificate file [' . $certFile . '], which is needed to sign the metadata' ); } $certData = file_get_contents($certFile); @@ -267,7 +271,7 @@ class Signer // get the EntityDescriptor node we should sign /** @var \DOMElement $rootNode */ $rootNode = $xml->firstChild; - $rootNode->setAttribute('ID', '_'.hash('sha256', $metadataString)); + $rootNode->setAttribute('ID', '_' . hash('sha256', $metadataString)); // sign the metadata with our private key $objXMLSecDSig = new XMLSecurityDSig(); diff --git a/lib/SimpleSAML/Metadata/Sources/MDQ.php b/lib/SimpleSAML/Metadata/Sources/MDQ.php index 60d4c01f2e3cd08bb373c1e36a7b1af994ff17e1..3b8431a14d82712f36d987048da20bc909e97aa1 100644 --- a/lib/SimpleSAML/Metadata/Sources/MDQ.php +++ b/lib/SimpleSAML/Metadata/Sources/MDQ.php @@ -77,7 +77,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource assert(is_array($config)); if (!array_key_exists('server', $config)) { - throw new \Exception(__CLASS__.": the 'server' configuration option is not set."); + throw new \Exception(__CLASS__ . ": the 'server' configuration option is not set."); } else { $this->server = $config['server']; } @@ -140,7 +140,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource } $cachekey = sha1($entityId); - return $this->cacheDir.'/'.$set.'-'.$cachekey.'.cached.xml'; + return $this->cacheDir . '/' . $set . '-' . $cachekey . '.cached.xml'; } @@ -168,9 +168,9 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource return null; } if (!is_readable($cachefilename)) { - throw new \Exception(__CLASS__.': could not read cache file for entity ['.$cachefilename.']'); + throw new \Exception(__CLASS__ . ': could not read cache file for entity [' . $cachefilename . ']'); } - Logger::debug(__CLASS__.': reading cache ['.$entityId.'] => ['.$cachefilename.']'); + Logger::debug(__CLASS__ . ': reading cache [' . $entityId . '] => [' . $cachefilename . ']'); /* Ensure that this metadata isn't older that the cachelength option allows. This * must be verified based on the file, since this option may be changed after the @@ -178,7 +178,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource */ $stat = stat($cachefilename); if ($stat['mtime'] + $this->cacheLength <= time()) { - Logger::debug(__CLASS__.': cache file older that the cachelength option allows.'); + Logger::debug(__CLASS__ . ': cache file older that the cachelength option allows.'); return null; } @@ -187,17 +187,17 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource /** @var array $error */ $error = error_get_last(); throw new \Exception( - __CLASS__.': error reading metadata from cache file "'.$cachefilename.'": '.$error['message'] + __CLASS__ . ': error reading metadata from cache file "' . $cachefilename . '": ' . $error['message'] ); } $data = unserialize($rawData); if ($data === false) { - throw new \Exception(__CLASS__.': error unserializing cached data from file "'.$cachefilename.'".'); + throw new \Exception(__CLASS__ . ': error unserializing cached data from file "' . $cachefilename . '".'); } if (!is_array($data)) { - throw new \Exception(__CLASS__.': Cached metadata from "'.$cachefilename.'" wasn\'t an array.'); + throw new \Exception(__CLASS__ . ': Cached metadata from "' . $cachefilename . '" wasn\'t an array.'); } return $data; @@ -226,9 +226,9 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource $cachefilename = $this->getCacheFilename($set, $entityId); if (!is_writable(dirname($cachefilename))) { - throw new \Exception(__CLASS__.': could not write cache file for entity ['.$cachefilename.']'); + throw new \Exception(__CLASS__ . ': could not write cache file for entity [' . $cachefilename . ']'); } - Logger::debug(__CLASS__.': Writing cache ['.$entityId.'] => ['.$cachefilename.']'); + Logger::debug(__CLASS__ . ': Writing cache [' . $entityId . '] => [' . $cachefilename . ']'); file_put_contents($cachefilename, serialize($data)); } @@ -260,7 +260,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource return $ret[0]; default: - Logger::warning(__CLASS__.': unknown metadata set: \''.$set.'\'.'); + Logger::warning(__CLASS__ . ': unknown metadata set: \'' . $set . '\'.'); } return null; @@ -290,7 +290,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource assert(is_string($index)); assert(is_string($set)); - Logger::info(__CLASS__.': loading metadata entity ['.$index.'] from ['.$set.']'); + Logger::info(__CLASS__ . ': loading metadata entity [' . $index . '] from [' . $set . ']'); // read from cache if possible try { @@ -308,14 +308,14 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource if (isset($data)) { // metadata found in cache and not expired - Logger::debug(__CLASS__.': using cached metadata for: '.$index.'.'); + Logger::debug(__CLASS__ . ': using cached metadata for: ' . $index . '.'); return $data; } // look at Metadata Query Protocol: https://github.com/iay/md-query/blob/master/draft-young-md-query.txt - $mdq_url = $this->server.'/entities/'.urlencode($index); + $mdq_url = $this->server . '/entities/' . urlencode($index); - Logger::debug(__CLASS__.': downloading metadata for "'.$index.'" from ['.$mdq_url.']'); + Logger::debug(__CLASS__ . ': downloading metadata for "' . $index . '" from [' . $mdq_url . ']'); try { $xmldata = Utils\HTTP::fetch($mdq_url); } catch (\Exception $e) { @@ -325,34 +325,36 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource if (empty($xmldata)) { $error = error_get_last(); - Logger::info('Unable to fetch metadata for "'.$index.'" from '.$mdq_url.': '. + Logger::info('Unable to fetch metadata for "' . $index . '" from ' . $mdq_url . ': ' . (is_array($error) ? $error['message'] : 'no error available')); return null; } /** @var string $xmldata */ $entity = SAMLParser::parseString($xmldata); - Logger::debug(__CLASS__.': completed parsing of ['.$mdq_url.']'); + Logger::debug(__CLASS__ . ': completed parsing of [' . $mdq_url . ']'); if ($this->validateFingerprint !== null) { - if (!$entity->validateFingerprint( - $this->validateFingerprint, - $this->validateFingerprintAlgorithm - )) { - throw new \Exception(__CLASS__.': error, could not verify signature for entity: '.$index.'".'); + if ( + !$entity->validateFingerprint( + $this->validateFingerprint, + $this->validateFingerprintAlgorithm + ) + ) { + throw new \Exception(__CLASS__ . ': error, could not verify signature for entity: ' . $index . '".'); } } $data = self::getParsedSet($entity, $set); if ($data === null) { - throw new \Exception(__CLASS__.': no metadata for set "'.$set.'" available from "'.$index.'".'); + throw new \Exception(__CLASS__ . ': no metadata for set "' . $set . '" available from "' . $index . '".'); } try { $this->writeToCache($set, $index, $data); } catch (\Exception $e) { // Proceed without writing to cache - Logger::error('Error writing MDQ result to cache: '.$e->getMessage()); + Logger::error('Error writing MDQ result to cache: ' . $e->getMessage()); } return $data; diff --git a/lib/SimpleSAML/Module.php b/lib/SimpleSAML/Module.php index 61986c276c6b918c84e62ee2f2be2ed4791e8650..01de00c534acaf4031b1522abed53909ab925f11 100644 --- a/lib/SimpleSAML/Module.php +++ b/lib/SimpleSAML/Module.php @@ -85,8 +85,8 @@ class Module */ public static function getModuleDir($module) { - $baseDir = dirname(dirname(dirname(__FILE__))).'/modules'; - $moduleDir = $baseDir.'/'.$module; + $baseDir = dirname(dirname(dirname(__FILE__))) . '/modules'; + $moduleDir = $baseDir . '/' . $module; return $moduleDir; } @@ -154,7 +154,7 @@ class Module } if (!self::isModuleEnabled($module)) { - throw new Error\NotFound('The module \''.$module.'\' was either not found, or wasn\'t enabled.'); + throw new Error\NotFound('The module \'' . $module . '\' was either not found, or wasn\'t enabled.'); } /* Make sure that the request isn't suspicious (contains references to current directory or parent directory or @@ -170,11 +170,18 @@ class Module $config = Configuration::getInstance(); // rebuild REQUEST_URI and SCRIPT_NAME just in case we need to. This is needed for server aliases and rewrites - $translated_uri = $config->getBasePath().'module.php/'.$module.'/'.$url; + $translated_uri = $config->getBasePath() . 'module.php/' . $module . '/' . $url; $request->server->set('REQUEST_URI', $translated_uri); - $request->server->set('SCRIPT_NAME', $config->getBasePath().'module.php'); - $request->initialize($request->query->all(), $request->request->all(), $request->attributes->all(), - $request->cookies->all(), $request->files->all(), $request->server->all(), $request->getContent()); + $request->server->set('SCRIPT_NAME', $config->getBasePath() . 'module.php'); + $request->initialize( + $request->query->all(), + $request->request->all(), + $request->attributes->all(), + $request->cookies->all(), + $request->files->all(), + $request->server->all(), + $request->getContent() + ); if ($config->getBoolean('usenewui', false) === true) { $router = new Router($module); @@ -187,7 +194,7 @@ class Module } } - $moduleDir = self::getModuleDir($module).'/www/'; + $moduleDir = self::getModuleDir($module) . '/www/'; // check for '.php/' in the path, the presence of which indicates that another php-script should handle the // request @@ -195,7 +202,7 @@ class Module $newURL = substr($url, 0, $phpPos + 4); $param = substr($url, $phpPos + 4); - if (is_file($moduleDir.$newURL)) { + if (is_file($moduleDir . $newURL)) { /* $newPath points to a normal file. Point execution to that file, and save the remainder of the path * in PATH_INFO. */ @@ -206,12 +213,12 @@ class Module } } - $path = $moduleDir.$url; + $path = $moduleDir . $url; if ($path[strlen($path) - 1] === '/') { // path ends with a slash - directory reference. Attempt to find index file in directory foreach (self::$indexFiles as $if) { - if (file_exists($path.$if)) { + if (file_exists($path . $if)) { $path .= $if; break; } @@ -227,7 +234,7 @@ class Module if (!file_exists($path)) { // file not found - Logger::info('Could not find file \''.$path.'\'.'); + Logger::info('Could not find file \'' . $path . '\'.'); throw new Error\NotFound('The URL wasn\'t found in the module.'); } @@ -241,7 +248,7 @@ class Module */ $script = "/$module/$url"; if (strpos($request->getScriptName(), $script) === false) { - $request->server->set('SCRIPT_NAME', $request->getScriptName().'/'.$module.'/'.$url); + $request->server->set('SCRIPT_NAME', $request->getScriptName() . '/' . $module . '/' . $url); } require($path); @@ -267,7 +274,7 @@ class Module $contentType = mime_content_type($path); } else { // mime_content_type doesn't exist. Return a default MIME type - Logger::warning('Unable to determine mime content type of file: '.$path); + Logger::warning('Unable to determine mime content type of file: ' . $path); $contentType = 'application/octet-stream'; } } @@ -324,19 +331,20 @@ class Module throw new \Exception("Invalid module.enable value for the '$module' module."); } - if (assert_options(ASSERT_ACTIVE) && - !file_exists($moduleDir.'/default-enable') && - !file_exists($moduleDir.'/default-disable') + if ( + assert_options(ASSERT_ACTIVE) + && !file_exists($moduleDir . '/default-enable') + && !file_exists($moduleDir . '/default-disable') ) { Logger::error("Missing default-enable or default-disable file for the module $module"); } - if (file_exists($moduleDir.'/enable')) { + if (file_exists($moduleDir . '/enable')) { self::$module_info[$module]['enabled'] = true; return true; } - if (!file_exists($moduleDir.'/disable') && file_exists($moduleDir.'/default-enable')) { + if (!file_exists($moduleDir . '/disable') && file_exists($moduleDir . '/default-enable')) { self::$module_info[$module]['enabled'] = true; return true; } @@ -363,7 +371,7 @@ class Module $dh = scandir($path); if ($dh === false) { - throw new \Exception('Unable to open module directory "'.$path.'".'); + throw new \Exception('Unable to open module directory "' . $path . '".'); } foreach ($dh as $f) { @@ -371,7 +379,7 @@ class Module continue; } - if (!is_dir($path.'/'.$f)) { + if (!is_dir($path . '/' . $f)) { continue; } @@ -417,13 +425,13 @@ class Module } else { // should be a module // make sure empty types are handled correctly - $type = (empty($type)) ? '\\' : '\\'.$type.'\\'; + $type = (empty($type)) ? '\\' : '\\' . $type . '\\'; - $className = 'SimpleSAML\\Module\\'.$tmp[0].$type.$tmp[1]; + $className = 'SimpleSAML\\Module\\' . $tmp[0] . $type . $tmp[1]; if (!class_exists($className)) { // check for the old-style class names $type = str_replace('\\', '_', $type); - $oldClassName = 'sspmod_'.$tmp[0].$type.$tmp[1]; + $oldClassName = 'sspmod_' . $tmp[0] . $type . $tmp[1]; if (!class_exists($oldClassName)) { throw new \Exception("Could not resolve '$id': no class named '$className' or '$oldClassName'."); @@ -434,7 +442,8 @@ class Module if ($subclass !== null && !is_subclass_of($className, $subclass)) { throw new \Exception( - 'Could not resolve \''.$id.'\': The class \''.$className.'\' isn\'t a subclass of \''.$subclass.'\'.' + 'Could not resolve \'' . $id . '\': The class \'' . $className + . '\' isn\'t a subclass of \'' . $subclass . '\'.' ); } @@ -457,7 +466,7 @@ class Module assert(is_string($resource)); assert($resource[0] !== '/'); - $url = Utils\HTTP::getBaseURL().'module.php/'.$resource; + $url = Utils\HTTP::getBaseURL() . 'module.php/' . $resource; if (!empty($parameters)) { $url = Utils\HTTP::addURLParameters($url, $parameters); } @@ -480,7 +489,7 @@ class Module return self::$modules[$module]['hooks']; } - $hook_dir = self::getModuleDir($module).'/hooks'; + $hook_dir = self::getModuleDir($module) . '/hooks'; if (!is_dir($hook_dir)) { return []; } @@ -496,8 +505,8 @@ class Module continue; } $hook_name = $matches[1]; - $hook_func = $module.'_hook_'.$hook_name; - $hooks[$hook_name] = ['file' => $hook_dir.'/'.$file, 'func' => $hook_func]; + $hook_func = $module . '_hook_' . $hook_name; + $hooks[$hook_name] = ['file' => $hook_dir . '/' . $file, 'func' => $hook_func]; } return $hooks; } @@ -537,7 +546,7 @@ class Module require_once(self::$module_info[$module]['hooks'][$hook]['file']); if (!is_callable(self::$module_info[$module]['hooks'][$hook]['func'])) { - throw new Error\Exception('Invalid hook \''.$hook.'\' for module \''.$module.'\'.'); + throw new Error\Exception('Invalid hook \'' . $hook . '\' for module \'' . $module . '\'.'); } $fn = self::$module_info[$module]['hooks'][$hook]['func']; diff --git a/lib/SimpleSAML/Module/ControllerResolver.php b/lib/SimpleSAML/Module/ControllerResolver.php index 633b7d861d8f1a09018b709f02aaea665f5217d3..3e06745b1ed3a0e5ec5ac491be9ee3abbb6a5b30 100644 --- a/lib/SimpleSAML/Module/ControllerResolver.php +++ b/lib/SimpleSAML/Module/ControllerResolver.php @@ -7,7 +7,6 @@ use SimpleSAML\Configuration; use SimpleSAML\Error\Exception; use SimpleSAML\Module; use SimpleSAML\Session; - use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -75,7 +74,7 @@ class ControllerResolver extends SymfonyControllerResolver implements ArgumentRe ['url' => '.*/$'] ); $this->routes->add('trailing-slash', $redirect); - $this->routes->addPrefix('/'.$this->module); + $this->routes->addPrefix('/' . $this->module); } catch (FileLocatorFileNotFoundException $e) { } } @@ -160,7 +159,7 @@ class ControllerResolver extends SymfonyControllerResolver implements ArgumentRe $args[] = null; } - throw new Exception('Missing value for argument '.$argName.'. This is probably a bug.'); + throw new Exception('Missing value for argument ' . $argName . '. This is probably a bug.'); } return $args; diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php index c4a32d6aa1a158b228d46a45774422afe0aeae12..8b54ae5f298d69b1f184762728de4e4ba3bddffe 100644 --- a/lib/SimpleSAML/Session.php +++ b/lib/SimpleSAML/Session.php @@ -150,7 +150,7 @@ class Session implements \Serializable, Utils\ClearableState $this->setConfiguration(Configuration::getInstance()); if (php_sapi_name() === 'cli' || defined('STDIN')) { - $this->trackid = 'CL'.bin2hex(openssl_random_pseudo_bytes(4)); + $this->trackid = 'CL' . bin2hex(openssl_random_pseudo_bytes(4)); Logger::setTrackId($this->trackid); $this->transient = $transient; return; @@ -158,7 +158,7 @@ class Session implements \Serializable, Utils\ClearableState if ($transient) { // transient session - $this->trackid = 'TR'.bin2hex(openssl_random_pseudo_bytes(4)); + $this->trackid = 'TR' . bin2hex(openssl_random_pseudo_bytes(4)); Logger::setTrackId($this->trackid); $this->transient = true; } else { @@ -265,7 +265,7 @@ class Session implements \Serializable, Utils\ClearableState * it. */ self::useTransientSession(); - Logger::error('Error loading session: '.$e->getMessage()); + Logger::error('Error loading session: ' . $e->getMessage()); if ($e instanceof Error\Exception) { $cause = $e->getCause(); if ($cause instanceof \Exception) { @@ -305,7 +305,7 @@ class Session implements \Serializable, Utils\ClearableState $c->toArray() ); } - Logger::error('Error creating session: '.$e->getMessage()); + Logger::error('Error creating session: ' . $e->getMessage()); } // we must have a session now, either regular or transient @@ -594,7 +594,7 @@ class Session implements \Serializable, Utils\ClearableState assert(is_string($authority)); assert(is_array($data) || $data === null); - Logger::debug('Session: doLogin("'.$authority.'")'); + Logger::debug('Session: doLogin("' . $authority . '")'); $this->markDirty(); @@ -647,8 +647,11 @@ class Session implements \Serializable, Utils\ClearableState $this->authToken = Utils\Random::generateID(); $sessionHandler = SessionHandler::getSessionHandler(); - if (!$this->transient && (!empty($data['RememberMe']) || $this->rememberMeExpire !== null) && - self::$config->getBoolean('session.rememberme.enable', false) + if ( + !$this->transient + && (!empty($data['RememberMe']) + || $this->rememberMeExpire !== null) + && self::$config->getBoolean('session.rememberme.enable', false) ) { $this->setRememberMeExpire(); } else { @@ -666,7 +669,7 @@ class Session implements \Serializable, Utils\ClearableState */ unset($this->authToken); unset($this->authData[$authority]); - Logger::error('Cannot set authentication token cookie: '.$e->getMessage()); + Logger::error('Cannot set authentication token cookie: ' . $e->getMessage()); throw $e; } } @@ -682,10 +685,10 @@ class Session implements \Serializable, Utils\ClearableState */ public function doLogout($authority) { - Logger::debug('Session: doLogout('.var_export($authority, true).')'); + Logger::debug('Session: doLogout(' . var_export($authority, true) . ')'); if (!isset($this->authData[$authority])) { - Logger::debug('Session: Already logged out of '.$authority.'.'); + Logger::debug('Session: Already logged out of ' . $authority . '.'); return; } @@ -723,7 +726,7 @@ class Session implements \Serializable, Utils\ClearableState $functionname = $handler[1]; throw new \Exception( - 'Logout handler is not a valid function: '.$classname.'::'. + 'Logout handler is not a valid function: ' . $classname . '::' . $functionname ); } @@ -750,18 +753,18 @@ class Session implements \Serializable, Utils\ClearableState if (!isset($this->authData[$authority])) { Logger::debug( - 'Session: '.var_export($authority, true). + 'Session: ' . var_export($authority, true) . ' not valid because we are not authenticated.' ); return false; } if ($this->authData[$authority]['Expire'] <= time()) { - Logger::debug('Session: '.var_export($authority, true).' not valid because it is expired.'); + Logger::debug('Session: ' . var_export($authority, true) . ' not valid because it is expired.'); return false; } - Logger::debug('Session: Valid session found with '.var_export($authority, true).'.'); + Logger::debug('Session: Valid session found with ' . var_export($authority, true) . '.'); return true; } @@ -832,7 +835,7 @@ class Session implements \Serializable, Utils\ClearableState if (!is_callable($logout_handler)) { throw new \Exception( - 'Logout handler is not a valid function: '.$classname.'::'. + 'Logout handler is not a valid function: ' . $classname . '::' . $functionname ); } @@ -892,7 +895,7 @@ class Session implements \Serializable, Utils\ClearableState if ($timeout !== null) { if ($timeout <= 0) { throw new \Exception( - 'The value of the session.datastore.timeout'. + 'The value of the session.datastore.timeout' . ' configuration option should be a positive integer.' ); } diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php index f2ccb8ded9bb3b0d5da3d474c1c49394a0c7f16e..1a6175a1940c0ed7a3d2bd0c4144f929db9a2b83 100644 --- a/lib/SimpleSAML/SessionHandlerPHP.php +++ b/lib/SimpleSAML/SessionHandlerPHP.php @@ -51,8 +51,8 @@ class SessionHandlerPHP extends SessionHandler if (session_status() === PHP_SESSION_ACTIVE) { if (session_name() === $this->cookie_name || $this->cookie_name === null) { Logger::warning( - 'There is already a PHP session with the same name as SimpleSAMLphp\'s session, or the '. - "'session.phpsession.cookiename' configuration option is not set. Make sure to set ". + 'There is already a PHP session with the same name as SimpleSAMLphp\'s session, or the ' . + "'session.phpsession.cookiename' configuration option is not set. Make sure to set " . "SimpleSAMLphp's cookie name with a value not used by any other applications." ); } @@ -90,7 +90,7 @@ class SessionHandlerPHP extends SessionHandler } else { /* in older versions of PHP we need a nasty hack to set RFC6265bis SameSite attribute */ if ($params['samesite'] !== null and !preg_match('/;\s+samesite/i', $params['path'])) { - $params['path'] .= '; SameSite='.$params['samesite']; + $params['path'] .= '; SameSite=' . $params['samesite']; } session_set_cookie_params( $params['lifetime'], diff --git a/lib/SimpleSAML/SessionHandlerStore.php b/lib/SimpleSAML/SessionHandlerStore.php index 89c7c16c45184214ffaf2051b72a969588b162fe..7406a5be6efee13bb8381bc6f51699ec63637fc0 100644 --- a/lib/SimpleSAML/SessionHandlerStore.php +++ b/lib/SimpleSAML/SessionHandlerStore.php @@ -1,6 +1,5 @@ <?php - /** * Session storage in the data store. * diff --git a/lib/SimpleSAML/Store/Memcache.php b/lib/SimpleSAML/Store/Memcache.php index 515ca953046f209264252dd080c34478a87da9b9..2a8da49a79f39c3b08e43b10202f3348f7fd44ad 100644 --- a/lib/SimpleSAML/Store/Memcache.php +++ b/lib/SimpleSAML/Store/Memcache.php @@ -42,7 +42,7 @@ class Memcache extends Store assert(is_string($type)); assert(is_string($key)); - return \SimpleSAML\Memcache::get($this->prefix.'.'.$type.'.'.$key); + return \SimpleSAML\Memcache::get($this->prefix . '.' . $type . '.' . $key); } @@ -65,7 +65,7 @@ class Memcache extends Store $expire = 0; } - \SimpleSAML\Memcache::set($this->prefix.'.'.$type.'.'.$key, $value, $expire); + \SimpleSAML\Memcache::set($this->prefix . '.' . $type . '.' . $key, $value, $expire); } @@ -81,6 +81,6 @@ class Memcache extends Store assert(is_string($type)); assert(is_string($key)); - \SimpleSAML\Memcache::delete($this->prefix.'.'.$type.'.'.$key); + \SimpleSAML\Memcache::delete($this->prefix . '.' . $type . '.' . $key); } } diff --git a/lib/SimpleSAML/Store/SQL.php b/lib/SimpleSAML/Store/SQL.php index 3ec9caa4cc9c55312c2dbed0a26bd21d8ac1c44a..cb7f0321f987c8c4e31fdeb6cd82cbeaec583d0f 100644 --- a/lib/SimpleSAML/Store/SQL.php +++ b/lib/SimpleSAML/Store/SQL.php @@ -62,7 +62,7 @@ class SQL extends Store try { $this->pdo = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { - throw new \Exception("Database error: ".$e->getMessage()); + throw new \Exception("Database error: " . $e->getMessage()); } $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); @@ -86,10 +86,10 @@ class SQL extends Store $this->tableVersions = []; try { - $fetchTableVersion = $this->pdo->query('SELECT _name, _version FROM '.$this->prefix.'_tableVersion'); + $fetchTableVersion = $this->pdo->query('SELECT _name, _version FROM ' . $this->prefix . '_tableVersion'); } catch (PDOException $e) { $this->pdo->exec( - 'CREATE TABLE '.$this->prefix. + 'CREATE TABLE ' . $this->prefix . '_tableVersion (_name VARCHAR(30) NOT NULL UNIQUE, _version INTEGER NOT NULL)' ); return; @@ -121,12 +121,12 @@ class SQL extends Store */ $table_updates = [ [ - 'CREATE TABLE '.$this->prefix. - '_kvstore (_type VARCHAR(30) NOT NULL, _key VARCHAR(50) NOT NULL, _value '.$text_t. + 'CREATE TABLE ' . $this->prefix . + '_kvstore (_type VARCHAR(30) NOT NULL, _key VARCHAR(50) NOT NULL, _value ' . $text_t . ' NOT NULL, _expire TIMESTAMP, PRIMARY KEY (_key, _type))', $this->driver === 'sqlite' ? - 'CREATE INDEX '.$this->prefix.'_kvstore_expire ON '.$this->prefix.'_kvstore (_expire)' : - 'ALTER TABLE '.$this->prefix.'_kvstore ADD INDEX '.$this->prefix.'_kvstore_expire (_expire)' + 'CREATE INDEX ' . $this->prefix . '_kvstore_expire ON ' . $this->prefix . '_kvstore (_expire)' : + 'ALTER TABLE ' . $this->prefix . '_kvstore ADD INDEX ' . $this->prefix . '_kvstore_expire (_expire)' ], /** * This upgrade removes the default NOT NULL constraint on the _expire field in MySQL. @@ -138,15 +138,15 @@ class SQL extends Store * Read the index */ [ - 'CREATE TABLE '.$this->prefix. - '_kvstore_new (_type VARCHAR(30) NOT NULL, _key VARCHAR(50) NOT NULL, _value '.$text_t. + 'CREATE TABLE ' . $this->prefix . + '_kvstore_new (_type VARCHAR(30) NOT NULL, _key VARCHAR(50) NOT NULL, _value ' . $text_t . ' NOT NULL, _expire TIMESTAMP NULL, PRIMARY KEY (_key, _type))', - 'INSERT INTO '.$this->prefix.'_kvstore_new SELECT * FROM '.$this->prefix.'_kvstore', - 'DROP TABLE '.$this->prefix.'_kvstore', - 'ALTER TABLE '.$this->prefix.'_kvstore_new RENAME TO '.$this->prefix.'_kvstore', + 'INSERT INTO ' . $this->prefix . '_kvstore_new SELECT * FROM ' . $this->prefix . '_kvstore', + 'DROP TABLE ' . $this->prefix . '_kvstore', + 'ALTER TABLE ' . $this->prefix . '_kvstore_new RENAME TO ' . $this->prefix . '_kvstore', $this->driver === 'sqlite' ? - 'CREATE INDEX '.$this->prefix.'_kvstore_expire ON '.$this->prefix.'_kvstore (_expire)' : - 'ALTER TABLE '.$this->prefix.'_kvstore ADD INDEX '.$this->prefix.'_kvstore_expire (_expire)' + 'CREATE INDEX ' . $this->prefix . '_kvstore_expire ON ' . $this->prefix . '_kvstore (_expire)' : + 'ALTER TABLE ' . $this->prefix . '_kvstore ADD INDEX ' . $this->prefix . '_kvstore_expire (_expire)' ] ]; @@ -201,7 +201,7 @@ class SQL extends Store assert(is_int($version)); $this->insertOrUpdate( - $this->prefix.'_tableVersion', + $this->prefix . '_tableVersion', ['_name'], ['_name' => $name, '_version' => $version] ); @@ -223,17 +223,17 @@ class SQL extends Store { assert(is_string($table)); - $colNames = '('.implode(', ', array_keys($data)).')'; - $values = 'VALUES(:'.implode(', :', array_keys($data)).')'; + $colNames = '(' . implode(', ', array_keys($data)) . ')'; + $values = 'VALUES(:' . implode(', :', array_keys($data)) . ')'; switch ($this->driver) { case 'mysql': - $query = 'REPLACE INTO '.$table.' '.$colNames.' '.$values; + $query = 'REPLACE INTO ' . $table . ' ' . $colNames . ' ' . $values; $query = $this->pdo->prepare($query); $query->execute($data); break; case 'sqlite': - $query = 'INSERT OR REPLACE INTO '.$table.' '.$colNames.' '.$values; + $query = 'INSERT OR REPLACE INTO ' . $table . ' ' . $colNames . ' ' . $values; $query = $this->pdo->prepare($query); $query->execute($data); break; @@ -243,7 +243,7 @@ class SQL extends Store $condData = []; foreach ($data as $col => $value) { - $tmp = $col.' = :'.$col; + $tmp = $col . ' = :' . $col; if (in_array($col, $keys, true)) { $condCols[] = $tmp; @@ -253,21 +253,22 @@ class SQL extends Store } } - $selectQuery = 'SELECT * FROM '.$table.' WHERE '.implode(' AND ', $condCols); + $selectQuery = 'SELECT * FROM ' . $table . ' WHERE ' . implode(' AND ', $condCols); $selectQuery = $this->pdo->prepare($selectQuery); $selectQuery->execute($condData); if ($selectQuery->rowCount() > 0) { // Update - $insertOrUpdateQuery = 'UPDATE '.$table.' SET '.implode(',', $updateCols).' WHERE '.implode(' AND ', $condCols); + $insertOrUpdateQuery = 'UPDATE ' . $table . ' SET ' . implode(',', $updateCols); + $insertOrUpdateQuery .= ' WHERE ' . implode(' AND ', $condCols); $insertOrUpdateQuery = $this->pdo->prepare($insertOrUpdateQuery); } else { // Insert - $insertOrUpdateQuery = 'INSERT INTO '.$table.' '.$colNames.' '.$values; + $insertOrUpdateQuery = 'INSERT INTO ' . $table . ' ' . $colNames . ' ' . $values; $insertOrUpdateQuery = $this->pdo->prepare($insertOrUpdateQuery); } $insertOrUpdateQuery->execute($data); - break; + break; } } @@ -280,7 +281,7 @@ class SQL extends Store { Logger::debug('store.sql: Cleaning key-value store.'); - $query = 'DELETE FROM '.$this->prefix.'_kvstore WHERE _expire < :now'; + $query = 'DELETE FROM ' . $this->prefix . '_kvstore WHERE _expire < :now'; $params = ['now' => gmdate('Y-m-d H:i:s')]; $query = $this->pdo->prepare($query); @@ -305,7 +306,7 @@ class SQL extends Store $key = sha1($key); } - $query = 'SELECT _value FROM '.$this->prefix. + $query = 'SELECT _value FROM ' . $this->prefix . '_kvstore WHERE _type = :type AND _key = :key AND (_expire IS NULL OR _expire > :now)'; $params = ['type' => $type, 'key' => $key, 'now' => gmdate('Y-m-d H:i:s')]; @@ -368,7 +369,7 @@ class SQL extends Store '_expire' => $expire, ]; - $this->insertOrUpdate($this->prefix.'_kvstore', ['_type', '_key'], $data); + $this->insertOrUpdate($this->prefix . '_kvstore', ['_type', '_key'], $data); } @@ -393,7 +394,7 @@ class SQL extends Store '_key' => $key, ]; - $query = 'DELETE FROM '.$this->prefix.'_kvstore WHERE _type=:_type AND _key=:_key'; + $query = 'DELETE FROM ' . $this->prefix . '_kvstore WHERE _type=:_type AND _key=:_key'; $query = $this->pdo->prepare($query); $query->execute($data); } diff --git a/lib/SimpleSAML/Utils/Attributes.php b/lib/SimpleSAML/Utils/Attributes.php index c84f86b3e300f3b1dcd99b3fca7d7f356c2db9e1..09e346ab6ebda4af279ed0b977477b5a04815340 100644 --- a/lib/SimpleSAML/Utils/Attributes.php +++ b/lib/SimpleSAML/Utils/Attributes.php @@ -30,18 +30,18 @@ class Attributes { if (!is_array($attributes)) { throw new \InvalidArgumentException( - 'The attributes array is not an array, it is: '.print_r($attributes, true).'.' + 'The attributes array is not an array, it is: ' . print_r($attributes, true) . '.' ); } if (!is_string($expected)) { throw new \InvalidArgumentException( - 'The expected attribute is not a string, it is: '.print_r($expected, true).'.' + 'The expected attribute is not a string, it is: ' . print_r($expected, true) . '.' ); } if (!array_key_exists($expected, $attributes)) { - throw new Error\Exception("No such attribute '".$expected."' found."); + throw new Error\Exception("No such attribute '" . $expected . "' found."); } $attribute = $attributes[$expected]; @@ -50,7 +50,7 @@ class Attributes } if (count($attribute) === 0) { - throw new Error\Exception("Empty attribute '".$expected."'.'"); + throw new Error\Exception("Empty attribute '" . $expected . "'.'"); } elseif (count($attribute) > 1) { if ($allow_multiple === false) { throw new \SimpleSAML\Error\Exception( @@ -83,14 +83,14 @@ class Attributes { if (!is_array($attributes)) { throw new \InvalidArgumentException( - 'The attributes array is not an array, it is: '.print_r($attributes, true).'".' + 'The attributes array is not an array, it is: ' . print_r($attributes, true) . '".' ); } $newAttrs = []; foreach ($attributes as $name => $values) { if (!is_string($name)) { - throw new \InvalidArgumentException('Invalid attribute name: "'.print_r($name, true).'".'); + throw new \InvalidArgumentException('Invalid attribute name: "' . print_r($name, true) . '".'); } $values = Arrays::arrayize($values); @@ -98,7 +98,7 @@ class Attributes foreach ($values as $value) { if (!is_string($value)) { throw new \InvalidArgumentException( - 'Invalid attribute value for attribute '.$name.': "'.print_r($value, true).'".' + 'Invalid attribute value for attribute ' . $name . ': "' . print_r($value, true) . '".' ); } } diff --git a/lib/SimpleSAML/Utils/Config.php b/lib/SimpleSAML/Utils/Config.php index ca25cc12462ac07d3b924cc4b200289e04520ae7..01f5f50c1d4a1bb36309cf974947f5fd524cb637 100644 --- a/lib/SimpleSAML/Utils/Config.php +++ b/lib/SimpleSAML/Utils/Config.php @@ -68,7 +68,7 @@ class Config */ public static function getConfigDir() { - $configDir = dirname(dirname(dirname(__DIR__))).'/config'; + $configDir = dirname(dirname(dirname(__DIR__))) . '/config'; /** @var string|false $configDirEnv */ $configDirEnv = getenv('SIMPLESAMLPHP_CONFIG_DIR'); @@ -80,7 +80,7 @@ class Config if (!is_dir($configDirEnv)) { throw new \InvalidArgumentException( sprintf( - 'Config directory specified by environment variable SIMPLESAMLPHP_CONFIG_DIR is not a '. + 'Config directory specified by environment variable SIMPLESAMLPHP_CONFIG_DIR is not a ' . 'directory. Given: "%s"', $configDirEnv ) diff --git a/lib/SimpleSAML/Utils/Config/Metadata.php b/lib/SimpleSAML/Utils/Config/Metadata.php index c179f18ce44fee21361fb431a7dced063886e01d..2eae7e00c29b7b1a30b9d0c18923eb6900c95a43 100644 --- a/lib/SimpleSAML/Utils/Config/Metadata.php +++ b/lib/SimpleSAML/Utils/Config/Metadata.php @@ -111,21 +111,22 @@ class Metadata // check the type if (!isset($contact['contactType']) || !in_array($contact['contactType'], self::$VALID_CONTACT_TYPES, true)) { $types = join(', ', array_map( - /** - * @param string $t - * @return string - */ + /** + * @param string $t + * @return string + */ function ($t) { - return '"'.$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 . "."); } // check attributes is an associative array if (isset($contact['attributes'])) { - if (empty($contact['attributes']) + if ( + empty($contact['attributes']) || !is_array($contact['attributes']) || count(array_filter(array_keys($contact['attributes']), 'is_string')) === 0 ) { @@ -154,24 +155,33 @@ class Metadata } // check givenName - if (isset($contact['givenName']) && ( - empty($contact['givenName']) || !is_string($contact['givenName']) + if ( + isset($contact['givenName']) + && ( + empty($contact['givenName']) + || !is_string($contact['givenName']) ) ) { 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']) + if ( + isset($contact['surName']) + && ( + empty($contact['surName']) + || !is_string($contact['surName']) ) ) { 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']) + if ( + isset($contact['company']) + && ( + empty($contact['company']) + || !is_string($contact['company']) ) ) { throw new \InvalidArgumentException('"company" must be a string and cannot be empty.'); @@ -179,8 +189,12 @@ class Metadata // check emailAddress if (isset($contact['emailAddress'])) { - if (empty($contact['emailAddress']) || - !(is_string($contact['emailAddress']) || is_array($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.'); } @@ -195,8 +209,12 @@ class Metadata // check telephoneNumber if (isset($contact['telephoneNumber'])) { - if (empty($contact['telephoneNumber']) || - !(is_string($contact['telephoneNumber']) || is_array($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.' diff --git a/lib/SimpleSAML/Utils/Crypto.php b/lib/SimpleSAML/Utils/Crypto.php index 68261f90ee936234b5c0bc2a4b3926b842213e6b..13161059249e14a062a189000bf5e76b62a7dcc4 100644 --- a/lib/SimpleSAML/Utils/Crypto.php +++ b/lib/SimpleSAML/Utils/Crypto.php @@ -25,7 +25,7 @@ class Crypto * * @see \SimpleSAML\Utils\Crypto::aesDecrypt() */ - private static function _aesDecrypt($ciphertext, $secret) + private static function aesDecryptInternal($ciphertext, $secret) { if (!is_string($ciphertext)) { throw new \InvalidArgumentException( @@ -51,7 +51,7 @@ class Crypto $msg = mb_substr($ciphertext, 48, $len - 48, '8bit'); // authenticate the ciphertext - if (self::secureCompare(hash_hmac('sha256', $iv.$msg, substr($key, 64, 64), true), $hmac)) { + if (self::secureCompare(hash_hmac('sha256', $iv . $msg, substr($key, 64, 64), true), $hmac)) { $plaintext = openssl_decrypt( $msg, 'AES-256-CBC', @@ -83,7 +83,7 @@ class Crypto */ public static function aesDecrypt($ciphertext) { - return self::_aesDecrypt($ciphertext, Config::getSecretSalt()); + return self::aesDecryptInternal($ciphertext, Config::getSecretSalt()); } @@ -99,7 +99,7 @@ class Crypto * * @see \SimpleSAML\Utils\Crypto::aesEncrypt() */ - private static function _aesEncrypt($data, $secret) + private static function aesEncryptInternal($data, $secret) { if (!is_string($data)) { throw new \InvalidArgumentException('Input parameter "$data" must be a string.'); @@ -130,7 +130,7 @@ class Crypto } // return the ciphertext with proper authentication - return hash_hmac('sha256', $iv.$ciphertext, substr($key, 64, 64), true).$iv.$ciphertext; + return hash_hmac('sha256', $iv . $ciphertext, substr($key, 64, 64), true) . $iv . $ciphertext; } @@ -148,7 +148,7 @@ class Crypto */ public static function aesEncrypt($data) { - return self::_aesEncrypt($data, Config::getSecretSalt()); + return self::aesEncryptInternal($data, Config::getSecretSalt()); } @@ -162,9 +162,9 @@ class Crypto */ public static function der2pem($der, $type = 'CERTIFICATE') { - return "-----BEGIN ".$type."-----\n". - chunk_split(base64_encode($der), 64, "\n"). - "-----END ".$type."-----\n"; + return "-----BEGIN " . $type . "-----\n" . + chunk_split(base64_encode($der), 64, "\n") . + "-----END " . $type . "-----\n"; } @@ -201,7 +201,7 @@ class Crypto throw new \InvalidArgumentException('Invalid input parameters.'); } - $file = $metadata->getString($prefix.'privatekey', null); + $file = $metadata->getString($prefix . 'privatekey', null); if ($file === null) { // no private key found if ($required) { @@ -217,15 +217,15 @@ class Crypto $data = @file_get_contents($file); if ($data === false) { - throw new Error\Exception('Unable to load private key from file "'.$file.'"'); + throw new Error\Exception('Unable to load private key from file "' . $file . '"'); } $ret = [ 'PEM' => $data, ]; - if ($metadata->hasValue($prefix.'privatekey_pass')) { - $ret['password'] = $metadata->getString($prefix.'privatekey_pass'); + if ($metadata->hasValue($prefix . 'privatekey_pass')) { + $ret['password'] = $metadata->getString($prefix . 'privatekey_pass'); } return $ret; @@ -281,8 +281,8 @@ class Crypto continue; } $certData = $key['X509Certificate']; - $pem = "-----BEGIN CERTIFICATE-----\n". - chunk_split($certData, 64). + $pem = "-----BEGIN CERTIFICATE-----\n" . + chunk_split($certData, 64) . "-----END CERTIFICATE-----\n"; $certFingerprint = strtolower(sha1(base64_decode($certData))); @@ -293,9 +293,9 @@ class Crypto ]; } // no valid key found - } elseif ($metadata->hasValue($prefix.'certFingerprint')) { + } elseif ($metadata->hasValue($prefix . 'certFingerprint')) { // we only have a fingerprint available - $fps = $metadata->getArrayizeString($prefix.'certFingerprint'); + $fps = $metadata->getArrayizeString($prefix . 'certFingerprint'); // normalize fingerprint(s) - lowercase and no colons foreach ($fps as &$fp) { @@ -352,8 +352,8 @@ class Crypto * This function hashes a password with a given algorithm. * * @param string $password The password to hash. - * @param string|null $algorithm @deprecated The hashing algorithm, uppercase, optionally prepended with 'S' (salted). See - * hash_algos() for a complete list of hashing algorithms. + * @param string|null $algorithm @deprecated The hashing algorithm, uppercase, optionally + * prepended with 'S' (salted). See hash_algos() for a complete list of hashing algorithms. * @param string|null $salt @deprecated An optional salt to use. * * @return string The hashed password. @@ -374,9 +374,9 @@ class Crypto } // hash w/o salt if (in_array(strtolower($algorithm), hash_algos(), true)) { - $alg_str = '{'.str_replace('SHA1', 'SHA', $algorithm).'}'; // LDAP compatibility + $alg_str = '{' . str_replace('SHA1', 'SHA', $algorithm) . '}'; // LDAP compatibility $hash = hash(strtolower($algorithm), $password, true); - return $alg_str.base64_encode($hash); + return $alg_str . base64_encode($hash); } // hash w/ salt if ($salt === null) { @@ -388,11 +388,11 @@ class Crypto if ($algorithm[0] == 'S' && in_array(substr(strtolower($algorithm), 1), hash_algos(), true)) { $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); + $alg_str = '{' . str_replace('SSHA1', 'SSHA', $algorithm) . '}'; // LDAP compatibility + $hash = hash($alg, $password . $salt, true); + return $alg_str . base64_encode($hash . $salt); } - throw new Error\Exception('Hashing algorithm \''.strtolower($algorithm).'\' is not supported'); + throw new Error\Exception('Hashing algorithm \'' . strtolower($algorithm) . '\' is not supported'); } else { if (!is_string($password)) { throw new \InvalidArgumentException('Invalid input parameter.'); @@ -464,7 +464,7 @@ class Crypto $salt = substr(base64_decode($matches[2]), $hash_length); return self::secureCompare($hash, self::pwHash($password, $alg, $salt)); } - throw new Error\Exception('Hashing algorithm \''.strtolower($alg).'\' is not supported'); + throw new Error\Exception('Hashing algorithm \'' . strtolower($alg) . '\' is not supported'); } else { return $hash === $password; } diff --git a/lib/SimpleSAML/Utils/EMail.php b/lib/SimpleSAML/Utils/EMail.php index 9d25b7cd709a43dfd768da554fd119cd4ff436fc..062244679a36c1da2d3b64fe4a995aa2385ecdba 100644 --- a/lib/SimpleSAML/Utils/EMail.php +++ b/lib/SimpleSAML/Utils/EMail.php @@ -4,7 +4,6 @@ namespace SimpleSAML\Utils; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; - use SimpleSAML\Configuration; use SimpleSAML\Logger; use SimpleSAML\XHTML\Template; @@ -91,7 +90,7 @@ class EMail * @param mixed $v * @return array */ - function($v) { + function ($v) { return is_array($v) ? $v : [$v]; }, $data @@ -170,9 +169,8 @@ class EMail // set the host (required) if (isset($transportOptions['host'])) { $this->mail->Host = $transportOptions['host']; - } - // throw an exception otherwise - else { + } else { + // throw an exception otherwise throw new \InvalidArgumentException("Missing Required Email Transport Parameter 'host'"); } @@ -218,7 +216,9 @@ class EMail } break; default: - throw new \InvalidArgumentException("Invalid Mail Transport Method - Check 'mail.transport.method' Configuration Option"); + throw new \InvalidArgumentException( + "Invalid Mail Transport Method - Check 'mail.transport.method' Configuration Option" + ); } } @@ -275,7 +275,7 @@ pre { </head> <body> <div class="container" style="background: #fafafa; border: 1px solid #eee; margin: 2em; padding: .6em;"> -'.$this->text.' +' . $this->text . ' </div> </body> </html>'; @@ -283,7 +283,10 @@ pre { $t = new Template($config, $template); $twig = $t->getTwig(); if (!isset($twig)) { - throw new \Exception('Even though we explicitly configure that we want Twig, the Template class does not give us Twig. This is a bug.'); + throw new \Exception( + 'Even though we explicitly configure that we want Twig,' + . ' the Template class does not give us Twig. This is a bug.' + ); } $result = $twig->render($template, [ 'subject' => $this->mail->Subject, diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php index 52cae76ed9a07ec3bdd8489533005e09333a81e1..016f09e0e0c8eaaf7f411343496af1a76a1d601d 100644 --- a/lib/SimpleSAML/Utils/HTTP.php +++ b/lib/SimpleSAML/Utils/HTTP.php @@ -41,7 +41,7 @@ class HTTP $session_id = $session->getSessionId(); // encrypt the session ID and the random ID - $info = base64_encode(Crypto::aesEncrypt($session_id.':'.$id)); + $info = base64_encode(Crypto::aesEncrypt($session_id . ':' . $id)); $url = Module::getModuleURL('core/postredirect.php', ['RedirInfo' => $info]); return preg_replace('#^https:#', 'http:', $url); @@ -120,7 +120,7 @@ class HTTP $port = strval($port); if ($port !== $default_port) { - return ':'.$port; + return ':' . $port; } return ''; } @@ -188,8 +188,9 @@ class HTTP * 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' + if ( + $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1' + && $_SERVER['REQUEST_METHOD'] === 'POST' ) { $code = 303; } else { @@ -202,7 +203,7 @@ class HTTP if (!headers_sent()) { // set the location header - header('Location: '.$url, true, $code); + header('Location: ' . $url, true, $code); // disable caching of this response header('Pragma: no-cache'); @@ -210,20 +211,20 @@ class HTTP } // show a minimal web page with a clickable link to the URL - echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; + 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 ' "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 ' <meta http-equiv="refresh" content="0;URL=\''.htmlspecialchars($url).'\'">'."\n"; + echo ' <meta http-equiv="content-type" content="text/html; charset=utf-8">' . "\n"; + echo ' <meta http-equiv="refresh" content="0;URL=\'' . htmlspecialchars($url) . '\'">' . "\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>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>'; @@ -357,7 +358,7 @@ class HTTP $url = self::normalizeURL($url); if (!self::isValidURL($url)) { - throw new Error\Exception('Invalid URL: '.$url); + throw new Error\Exception('Invalid URL: ' . $url); } // get the white list of domains @@ -371,18 +372,24 @@ class HTTP $hostname = $components['host']; // check for userinfo - if ((isset($components['user']) && strpos($components['user'], '\\') !== false) || - (isset($components['pass']) && strpos($components['pass'], '\\') !== false) + if ( + (isset($components['user']) + && strpos($components['user'], '\\') !== false) + || (isset($components['pass']) + && strpos($components['pass'], '\\') !== false) ) { - throw new Error\Exception('Invalid URL: '.$url); + throw new Error\Exception('Invalid URL: ' . $url); } // allow URLs with standard ports specified (non-standard ports must then be allowed explicitly) - if (isset($components['port']) && - (($components['scheme'] === 'http' && $components['port'] !== 80) || - ($components['scheme'] === 'https' && $components['port'] !== 443)) + if ( + isset($components['port']) + && (($components['scheme'] === 'http' + && $components['port'] !== 80) + || ($components['scheme'] === 'https' + && $components['port'] !== 443)) ) { - $hostname = $hostname.':'.$components['port']; + $hostname = $hostname . ':' . $components['port']; } $self_host = self::getSelfHostWithNonStandardPort(); @@ -409,7 +416,7 @@ class HTTP // throw exception due to redirection to untrusted site if (!$trusted) { - throw new Error\Exception('URL not allowed: '.$url); + throw new Error\Exception('URL not allowed: ' . $url); } } return $url; @@ -450,7 +457,7 @@ class HTTP } $proxy_auth = $config->getString('proxy.auth', false); if ($proxy_auth !== false) { - $context['http']['header'] = "Proxy-Authorization: Basic ".base64_encode($proxy_auth); + $context['http']['header'] = "Proxy-Authorization: Basic " . base64_encode($proxy_auth); } if (!isset($context['http']['request_fulluri'])) { $context['http']['request_fulluri'] = true; @@ -463,7 +470,8 @@ class HTTP * These controls will force the same value for both fields. * Marco Ferrante (marco@csita.unige.it), Nov 2012 */ - if (preg_match('#^https#i', $url) + if ( + preg_match('#^https#i', $url) && defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME ) { @@ -484,7 +492,7 @@ class HTTP $data = @file_get_contents($url, false, $context); if ($data === false) { $error = error_get_last(); - throw new Error\Exception('Error fetching '.var_export($url, true).':'. + throw new Error\Exception('Error fetching ' . var_export($url, true) . ':' . (is_array($error) ? $error['message'] : 'no error available')); } @@ -605,7 +613,7 @@ class HTTP $script = array_pop($path); // get the portion of the URI up to the script, i.e.: /simplesaml/some/directory/script.php - if (!preg_match('#^/(?:[^/]+/)*'.$script.'#', $_SERVER['REQUEST_URI'], $matches)) { + if (!preg_match('#^/(?:[^/]+/)*' . $script . '#', $_SERVER['REQUEST_URI'], $matches)) { return '/'; } $uri_s = explode('/', $matches[0]); @@ -617,7 +625,7 @@ class HTTP array_pop($file_s); } // we are now left with the minimum part of the URI that does not match anything in the file system, use it - return join('/', $uri_s).'/'; + return join('/', $uri_s) . '/'; } @@ -637,10 +645,11 @@ class HTTP if (preg_match('#^https?://.*/?$#D', $baseURL, $matches)) { // full URL in baseurlpath, override local server values - return rtrim($baseURL, '/').'/'; - } elseif ((preg_match('#^/?([^/]?.*/)$#D', $baseURL, $matches)) || - (preg_match('#^\*(.*)/$#D', $baseURL, $matches)) || - ($baseURL === '') + return rtrim($baseURL, '/') . '/'; + } elseif ( + (preg_match('#^/?([^/]?.*/)$#D', $baseURL, $matches)) + || (preg_match('#^\*(.*)/$#D', $baseURL, $matches)) + || ($baseURL === '') ) { // get server values $protocol = 'http'; @@ -651,7 +660,7 @@ class HTTP $port = self::getServerPort(); $path = $globalConfig->getBasePath(); - return $protocol.$hostname.$port.$path; + return $protocol . $hostname . $port . $path; } else { /* * Invalid 'baseurlpath'. We cannot recover from this, so throw a critical exception and try to be graceful @@ -660,7 +669,7 @@ class HTTP $c = $globalConfig->toArray(); $c['baseurlpath'] = self::guessBasePath(); throw new Error\CriticalConfigurationError( - 'Invalid value for \'baseurlpath\' in config.php. Valid format is in the form: '. + '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 \'/\'.', null, $c @@ -681,7 +690,7 @@ class HTTP public static function getFirstPathElement($leadingSlash = true) { if (preg_match('|^/(.*?)/|', $_SERVER['SCRIPT_NAME'], $matches)) { - return ($leadingSlash ? '/' : '').$matches[1]; + return ($leadingSlash ? '/' : '') . $matches[1]; } return ''; } @@ -776,7 +785,7 @@ class HTTP $baseurl = explode("/", self::getBaseURL()); $elements = array_slice($baseurl, 3 - count($baseurl), count($baseurl) - 4); $path = implode("/", $elements); - return self::getSelfHostWithNonStandardPort()."/".$path; + return self::getSelfHostWithNonStandardPort() . "/" . $path; } @@ -803,7 +812,7 @@ class HTTP // make sure we got a string from realpath() $cur_path = is_string($cur_path) ? $cur_path : ''; // find the path to the current script relative to the www/ directory of SimpleSAMLphp - $rel_path = str_replace($baseDir.'www'.DIRECTORY_SEPARATOR, '', $cur_path); + $rel_path = str_replace($baseDir . 'www' . DIRECTORY_SEPARATOR, '', $cur_path); // convert that relative path to an HTTP query $url_path = str_replace(DIRECTORY_SEPARATOR, '/', $rel_path); // find where the relative path starts in the current request URI @@ -835,17 +844,17 @@ class HTTP $protocol = parse_url($appurl, PHP_URL_SCHEME); $hostname = parse_url($appurl, PHP_URL_HOST); $port = parse_url($appurl, PHP_URL_PORT); - $port = !empty($port) ? ':'.$port : ''; + $port = !empty($port) ? ':' . $port : ''; } else { // no base URL specified for app, just use the current URL $protocol = self::getServerHTTPS() ? 'https' : 'http'; $hostname = self::getServerHost(); $port = self::getServerPort(); } - return $protocol.'://'.$hostname.$port.$_SERVER['REQUEST_URI']; + return $protocol . '://' . $hostname . $port . $_SERVER['REQUEST_URI']; } - return self::getBaseURL().$url_path.substr($_SERVER['REQUEST_URI'], $uri_pos + strlen($url_path)); + return self::getBaseURL() . $url_path . substr($_SERVER['REQUEST_URI'], $uri_pos + strlen($url_path)); } @@ -925,7 +934,7 @@ class HTTP // verify that the URL is to a http or https site if (!preg_match('@^https?://@i', $url)) { - throw new \InvalidArgumentException('Invalid URL: '.$url); + throw new \InvalidArgumentException('Invalid URL: ' . $url); } return $url; @@ -1069,10 +1078,10 @@ class HTTP } if (!preg_match('/^((((\w+:)\/\/[^\/]+)(\/[^?#]*))(?:\?[^#]*)?)(?:#.*)?/', $base, $baseParsed)) { - throw new \InvalidArgumentException('Unable to parse base url: '.$base); + throw new \InvalidArgumentException('Unable to parse base url: ' . $base); } - $baseDir = dirname($baseParsed[5].'filename'); + $baseDir = dirname($baseParsed[5] . 'filename'); $baseScheme = $baseParsed[4]; $baseHost = $baseParsed[3]; $basePath = $baseParsed[2]; @@ -1083,17 +1092,17 @@ class HTTP } if (substr($url, 0, 2) === '//') { - return $baseScheme.$url; + return $baseScheme . $url; } if ($url[0] === '/') { - return $baseHost.$url; + return $baseHost . $url; } if ($url[0] === '?') { - return $basePath.$url; + return $basePath . $url; } if ($url[0] === '#') { - return $baseQuery.$url; + return $baseQuery . $url; } // we have a relative path. Remove query string/fragment and save it as $tail @@ -1119,7 +1128,7 @@ class HTTP $dir = System::resolvePath($dir, $baseDir); - return $baseHost.$dir.$tail; + return $baseHost . $dir . $tail; } @@ -1141,10 +1150,13 @@ class HTTP */ 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 + 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.'); } @@ -1222,8 +1234,8 @@ class HTTP } } else { /* in older versions of PHP we need a nasty hack to set RFC6265bis SameSite attribute */ - if ($params['samesite'] !== null and !preg_match('/;\s+samesite/i', $params['path'])) { - $params['path'] .= '; SameSite='.$params['samesite']; + if ($params['samesite'] !== null && !preg_match('/;\s+samesite/i', $params['path'])) { + $params['path'] .= '; SameSite=' . $params['samesite']; } if ($params['raw']) { $success = @setrawcookie( diff --git a/lib/SimpleSAML/Utils/Random.php b/lib/SimpleSAML/Utils/Random.php index 6ed304e45c6d4c99d03625b7853f2f95a8471947..7072d76f09f4058869ed41542f545d4d5f0674d7 100644 --- a/lib/SimpleSAML/Utils/Random.php +++ b/lib/SimpleSAML/Utils/Random.php @@ -25,6 +25,6 @@ class Random */ public static function generateID() { - return '_'.bin2hex(openssl_random_pseudo_bytes((int) ((self::ID_LENGTH - 1) / 2))); + return '_' . bin2hex(openssl_random_pseudo_bytes((int) ((self::ID_LENGTH - 1) / 2))); } } diff --git a/lib/SimpleSAML/Utils/System.php b/lib/SimpleSAML/Utils/System.php index 6607edd6e9dd11470312fcf9bcbeb6fa5b1b9d4a..26b0e992f0afc6fcd9d03559571bfc04e850d21b 100644 --- a/lib/SimpleSAML/Utils/System.php +++ b/lib/SimpleSAML/Utils/System.php @@ -78,7 +78,7 @@ class System $tempDir = rtrim( $globalConfig->getString( 'tempdir', - sys_get_temp_dir().DIRECTORY_SEPARATOR.'simplesaml' + sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'simplesaml' ), DIRECTORY_SEPARATOR ); @@ -87,7 +87,7 @@ class System if (!mkdir($tempDir, 0700, true)) { $error = error_get_last(); throw new Error\Exception( - 'Error creating temporary directory "'.$tempDir.'": '. + 'Error creating temporary directory "' . $tempDir . '": ' . (is_array($error) ? $error['message'] : 'no error available') ); } @@ -96,7 +96,7 @@ class System $stat = lstat($tempDir); if ($stat['uid'] !== posix_getuid()) { throw new Error\Exception( - 'Temporary directory "'.$tempDir.'" does not belong to the current user.' + 'Temporary directory "' . $tempDir . '" does not belong to the current user.' ); } } @@ -147,7 +147,7 @@ class System $ret = $base; } - if (static::pathContainsStreamWrapper($path)){ + if (static::pathContainsStreamWrapper($path)) { $ret = $path; } else { $path = explode('/', $path); @@ -196,13 +196,13 @@ class System throw new \InvalidArgumentException('Invalid input parameters'); } - $tmpFile = self::getTempDir().DIRECTORY_SEPARATOR.rand(); + $tmpFile = self::getTempDir() . DIRECTORY_SEPARATOR . rand(); $res = @file_put_contents($tmpFile, $data); if ($res === false) { $error = error_get_last(); throw new Error\Exception( - 'Error saving file "'.$tmpFile.'": '. + 'Error saving file "' . $tmpFile . '": ' . (is_array($error) ? $error['message'] : 'no error available') ); } @@ -213,7 +213,7 @@ class System $error = error_get_last(); //$error = (is_array($error) ? $error['message'] : 'no error available'); throw new Error\Exception( - 'Error changing file mode of "'.$tmpFile.'": '. + 'Error changing file mode of "' . $tmpFile . '": ' . (is_array($error) ? $error['message'] : 'no error available') ); } @@ -223,7 +223,7 @@ class System unlink($tmpFile); $error = error_get_last(); throw new Error\Exception( - 'Error moving "'.$tmpFile.'" to "'.$filename.'": '. + 'Error moving "' . $tmpFile . '" to "' . $filename . '": ' . (is_array($error) ? $error['message'] : 'no error available') ); } diff --git a/lib/SimpleSAML/Utils/Time.php b/lib/SimpleSAML/Utils/Time.php index 9f0c690f8d5b1eb413b9a627401b892c9e411a2e..1889423680507cfa8eed82e8323cfd74cf1b5f98 100644 --- a/lib/SimpleSAML/Utils/Time.php +++ b/lib/SimpleSAML/Utils/Time.php @@ -97,10 +97,10 @@ class Time } // parse the duration. We use a very strict pattern - $durationRegEx = '#^(-?)P(?:(?:(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)'. + $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); + throw new \InvalidArgumentException('Invalid ISO 8601 duration: ' . $duration); } $durYears = (empty($matches[2]) ? 0 : (int) $matches[2]); diff --git a/lib/SimpleSAML/Utils/XML.php b/lib/SimpleSAML/Utils/XML.php index c517b0db8e440b98965c023fe9245a50e5474427..4b6c3cdfbd6b90972359418c3f674e9774564eb2 100644 --- a/lib/SimpleSAML/Utils/XML.php +++ b/lib/SimpleSAML/Utils/XML.php @@ -56,12 +56,14 @@ class XML $debug = Configuration::getInstance()->getArrayize('debug', ['validatexml' => false]); $enabled = Configuration::getInstance()->getBoolean('debug.validatexml', false); - if (!(in_array('validatexml', $debug, true) // implicitly enabled - || (array_key_exists('validatexml', $debug) && $debug['validatexml'] === true) + if ( + !(in_array('validatexml', $debug, true) // implicitly enabled + || (array_key_exists('validatexml', $debug) + && $debug['validatexml'] === true) // explicitly enabled // TODO: deprecate this option and remove it in 2.0 - || $enabled // old 'debug.validatexml' configuration option - )) { + || $enabled) // old 'debug.validatexml' configuration option + ) { // XML validation is disabled return; } @@ -109,12 +111,15 @@ class XML // see if debugging is enabled for SAML messages $debug = Configuration::getInstance()->getArrayize('debug', ['saml' => false]); - if (!(in_array('saml', $debug, true) // implicitly enabled - || (array_key_exists('saml', $debug) && $debug['saml'] === true) + if ( + !(in_array('saml', $debug, true) // implicitly enabled + || (array_key_exists('saml', $debug) + && $debug['saml'] === true) // explicitly enabled // TODO: deprecate the old style and remove it in 2.0 - || (array_key_exists(0, $debug) && $debug[0] === true) // old style 'debug' - )) { + || (array_key_exists(0, $debug) + && $debug[0] === true)) // old style 'debug' + ) { // debugging messages is disabled return; } @@ -222,10 +227,10 @@ class XML /* Element contains only child nodes - add indentation before each one, and * format child elements. */ - $childIndentation = $indentBase.' '; + $childIndentation = $indentBase . ' '; foreach ($childNodes as $node) { // add indentation before node - $root->insertBefore(new DOMText("\n".$childIndentation), $node); + $root->insertBefore(new DOMText("\n" . $childIndentation), $node); // format child elements if ($node instanceof \DOMElement) { @@ -234,7 +239,7 @@ class XML } // add indentation before closing tag - $root->appendChild(new DOMText("\n".$indentBase)); + $root->appendChild(new DOMText("\n" . $indentBase)); } @@ -331,7 +336,7 @@ class XML /** @var \DOMElement $child */ $child = $element->childNodes->item($i); if (!($child instanceof DOMText)) { - throw new Error\Exception($element->localName.' contained a non-text child node.'); + throw new Error\Exception($element->localName . ' contained a non-text child node.'); } $txt .= $child->wholeText; @@ -387,7 +392,7 @@ class XML // check if it is a valid shortcut if (!array_key_exists($nsURI, $shortcuts)) { - throw new \InvalidArgumentException('Unknown namespace shortcut: '.$nsURI); + throw new \InvalidArgumentException('Unknown namespace shortcut: ' . $nsURI); } // expand the shortcut @@ -442,7 +447,7 @@ class XML $config = Configuration::getInstance(); /** @var string $schemaPath */ $schemaPath = $config->resolvePath('schemas'); - $schemaFile = $schemaPath.'/'.$schema; + $schemaFile = $schemaPath . '/' . $schema; $res = $dom->schemaValidate($schemaFile); if ($res) { diff --git a/lib/SimpleSAML/XHTML/IdPDisco.php b/lib/SimpleSAML/XHTML/IdPDisco.php index 39d5f9c22a0fa67ed79152ae308ce933804c8e9a..c7f37b43f09ed687960c46c3ea8bef6d70d0f80d 100644 --- a/lib/SimpleSAML/XHTML/IdPDisco.php +++ b/lib/SimpleSAML/XHTML/IdPDisco.php @@ -141,7 +141,7 @@ class IdPDisco $this->returnIdParam = $_GET['returnIDParam']; } - $this->log('returnIdParam initially set to ['.$this->returnIdParam.']'); + $this->log('returnIdParam initially set to [' . $this->returnIdParam . ']'); if (!array_key_exists('return', $_GET)) { throw new \Exception('Missing parameter: return'); @@ -155,7 +155,7 @@ class IdPDisco $this->isPassive = true; } } - $this->log('isPassive initially set to ['.($this->isPassive ? 'TRUE' : 'FALSE').']'); + $this->log('isPassive initially set to [' . ($this->isPassive ? 'TRUE' : 'FALSE') . ']'); if (array_key_exists('IdPentityID', $_GET)) { $this->setIdPentityID = $_GET['IdPentityID']; @@ -178,7 +178,7 @@ class IdPDisco */ protected function log($message) { - Logger::info('idpDisco.'.$this->instance.': '.$message); + Logger::info('idpDisco.' . $this->instance . ': ' . $message); } @@ -194,7 +194,7 @@ class IdPDisco */ protected function getCookie($name) { - $prefixedName = 'idpdisco_'.$this->instance.'_'.$name; + $prefixedName = 'idpdisco_' . $this->instance . '_' . $name; if (array_key_exists($prefixedName, $_COOKIE)) { return $_COOKIE[$prefixedName]; } else { @@ -215,7 +215,7 @@ class IdPDisco */ protected function setCookie($name, $value) { - $prefixedName = 'idpdisco_'.$this->instance.'_'.$name; + $prefixedName = 'idpdisco_' . $this->instance . '_' . $name; $params = [ // we save the cookies for 90 days @@ -258,7 +258,7 @@ class IdPDisco } } - $this->log('Unable to validate IdP entity id ['.$idp.'].'); + $this->log('Unable to validate IdP entity id [' . $idp . '].'); // the entity id wasn't valid return null; @@ -370,14 +370,14 @@ class IdPDisco { $idp = $this->getPreviousIdP(); if ($idp !== null) { - $this->log('Preferred IdP from previous use ['.$idp.'].'); + $this->log('Preferred IdP from previous use [' . $idp . '].'); return $idp; } $idp = $this->getFromCIDRhint(); if (!empty($idp)) { - $this->log('Preferred IdP from CIDR hint ['.$idp.'].'); + $this->log('Preferred IdP from CIDR hint [' . $idp . '].'); return $idp; } @@ -395,7 +395,7 @@ class IdPDisco { assert(is_string($idp)); - $this->log('Choice made ['.$idp.'] Setting cookie.'); + $this->log('Choice made [' . $idp . '] Setting cookie.'); $this->setCookie('lastidp', $idp); } @@ -447,7 +447,7 @@ class IdPDisco // check if the user has saved an choice earlier $idp = $this->getSavedIdP(); if ($idp !== null) { - $this->log('Using saved choice ['.$idp.'].'); + $this->log('Using saved choice [' . $idp . '].'); return $idp; } @@ -520,7 +520,7 @@ class IdPDisco if ($idp !== null) { $extDiscoveryStorage = $this->config->getString('idpdisco.extDiscoveryStorage', null); if ($extDiscoveryStorage !== null) { - $this->log('Choice made ['.$idp.'] (Forwarding to external discovery storage)'); + $this->log('Choice made [' . $idp . '] (Forwarding to external discovery storage)'); Utils\HTTP::redirectTrustedURL($extDiscoveryStorage, [ 'entityID' => $this->spEntityId, 'IdPentityID' => $idp, @@ -530,7 +530,8 @@ class IdPDisco ]); } else { $this->log( - 'Choice made ['.$idp.'] (Redirecting the user back. returnIDParam='.$this->returnIdParam.')' + 'Choice made [' . $idp . '] (Redirecting the user back. returnIDParam=' + . $this->returnIdParam . ')' ); Utils\HTTP::redirectTrustedURL($this->returnURL, [$this->returnIdParam => $idp]); } @@ -567,8 +568,8 @@ class IdPDisco if (sizeof($idpintersection) == 1) { $this->log( - 'Choice made ['.$idpintersection[0].'] (Redirecting the user back. returnIDParam='. - $this->returnIdParam.')' + 'Choice made [' . $idpintersection[0] . '] (Redirecting the user back. returnIDParam=' . + $this->returnIdParam . ')' ); Utils\HTTP::redirectTrustedURL( $this->returnURL, diff --git a/lib/SimpleSAML/XHTML/Template.php b/lib/SimpleSAML/XHTML/Template.php index dc885c2f46e6b31a2210182074cc4a0e3f62bf8d..95681168a1ceb6c0a8dab5552964034059e1d595 100644 --- a/lib/SimpleSAML/XHTML/Template.php +++ b/lib/SimpleSAML/XHTML/Template.php @@ -9,17 +9,15 @@ namespace SimpleSAML\XHTML; * @package SimpleSAMLphp */ -use SimpleSAML\TwigConfigurableI18n\Twig\Environment as Twig_Environment; -use SimpleSAML\TwigConfigurableI18n\Twig\Extensions\Extension\I18n as Twig_Extensions_Extension_I18n; - use SimpleSAML\Configuration; use SimpleSAML\Locale\Language; use SimpleSAML\Locale\Localization; use SimpleSAML\Locale\Translate; use SimpleSAML\Logger; use SimpleSAML\Module; +use SimpleSAML\TwigConfigurableI18n\Twig\Environment as Twig_Environment; +use SimpleSAML\TwigConfigurableI18n\Twig\Extensions\Extension\I18n as Twig_Extensions_Extension_I18n; use SimpleSAML\Utils; - use Symfony\Component\HttpFoundation\Response; use Twig\Loader\FilesystemLoader; use Twig\TwigFilter; @@ -147,8 +145,10 @@ class Template extends Response if ($this->useNewUI) { // check if we need to attach a theme controller $controller = $this->configuration->getString('theme.controller', false); - if ($controller && class_exists($controller) && - in_array(TemplateControllerInterface::class, class_implements($controller)) + if ( + $controller + && class_exists($controller) + && in_array(TemplateControllerInterface::class, class_implements($controller)) ) { /** @var \SimpleSAML\XHTML\TemplateControllerInterface $this->controller */ $this->controller = new $controller(); @@ -173,12 +173,12 @@ class Template extends Response { $baseDir = $this->configuration->getBaseDir(); if (is_null($module)) { - $file = $baseDir.'www/assets/'.$asset; + $file = $baseDir . 'www/assets/' . $asset; $basePath = $this->configuration->getBasePath(); - $path = $basePath.'assets/'.$asset; + $path = $basePath . 'assets/' . $asset; } else { - $file = $baseDir.'modules/'.$module.'/www/assets/'.$asset; - $path = Module::getModuleUrl($module.'/assets/'.$asset); + $file = $baseDir . 'modules/' . $module . '/www/assets/' . $asset; + $path = Module::getModuleUrl($module . '/assets/' . $asset); } if (!file_exists($file)) { @@ -192,7 +192,7 @@ class Template extends Response } $tag = substr(hash('md5', $tag), 0, 5); - return $path.'?tag='.$tag; + return $path . '?tag=' . $tag; } @@ -228,7 +228,7 @@ class Template extends Response } if ($this->useNewUI || ($this->theme['module'] !== null)) { - return $templateName.'.twig'; + return $templateName . '.twig'; } return $templateName; } @@ -246,7 +246,7 @@ class Template extends Response // get namespace if any list($namespace, $filename) = $this->findModuleAndTemplateName($filename); - $this->twig_template = ($namespace !== null) ? '@'.$namespace.'/'.$filename : $filename; + $this->twig_template = ($namespace !== null) ? '@' . $namespace . '/' . $filename : $filename; $loader = new TemplateLoader(); $templateDirs = $this->findThemeTemplateDirs(); if ($this->module && $this->module != 'core') { @@ -291,7 +291,7 @@ class Template extends Response // abort if twig template does not exist if (!$loader->exists($this->twig_template)) { - throw new \Exception('Template-file \"'.$this->template.'\" does not exist.'); + throw new \Exception('Template-file \"' . $this->template . '\" does not exist.'); } // load extra i18n domains @@ -363,25 +363,25 @@ class Template extends Response } // setup directories & namespaces - $themeDir = Module::getModuleDir($this->theme['module']).'/themes/'.$this->theme['name']; + $themeDir = Module::getModuleDir($this->theme['module']) . '/themes/' . $this->theme['name']; $subdirs = scandir($themeDir); if (empty($subdirs)) { // no subdirectories in the theme directory, nothing to do here // this is probably wrong, log a message - Logger::warning('Empty theme directory for theme "'.$this->theme['name'].'".'); + Logger::warning('Empty theme directory for theme "' . $this->theme['name'] . '".'); return []; } $themeTemplateDirs = []; foreach ($subdirs as $entry) { // discard anything that's not a directory. Expression is negated to profit from lazy evaluation - if (!($entry !== '.' && $entry !== '..' && is_dir($themeDir.'/'.$entry))) { + if (!($entry !== '.' && $entry !== '..' && is_dir($themeDir . '/' . $entry))) { continue; } // set correct name for the default namespace $ns = ($entry === 'default') ? FilesystemLoader::MAIN_NAMESPACE : $entry; - $themeTemplateDirs[] = [$ns => $themeDir.'/'.$entry]; + $themeTemplateDirs[] = [$ns => $themeDir . '/' . $entry]; } return $themeTemplateDirs; } @@ -398,13 +398,13 @@ class Template extends Response private function getModuleTemplateDir($module) { if (!Module::isModuleEnabled($module)) { - throw new \InvalidArgumentException('The module \''.$module.'\' is not enabled.'); + throw new \InvalidArgumentException('The module \'' . $module . '\' is not enabled.'); } $moduledir = Module::getModuleDir($module); // check if module has a /templates dir, if so, append - $templatedir = $moduledir.'/templates'; + $templatedir = $moduledir . '/templates'; if (!is_dir($templatedir)) { - throw new \InvalidArgumentException('The module \''.$module.'\' has no templates directory.'); + throw new \InvalidArgumentException('The module \'' . $module . '\' has no templates directory.'); } return $templatedir; } @@ -587,52 +587,52 @@ class Template extends Response if ($this->theme['module'] !== null) { // .../module/<themeModule>/themes/<themeName>/<templateModule>/<templateName> - $filename = Module::getModuleDir($this->theme['module']). - '/themes/'.$this->theme['name'].'/'.$templateModule.'/'.$templateName; + $filename = Module::getModuleDir($this->theme['module']) . + '/themes/' . $this->theme['name'] . '/' . $templateModule . '/' . $templateName; } elseif ($templateModule !== 'default') { // .../module/<templateModule>/templates/<templateName> - $filename = Module::getModuleDir($templateModule).'/templates/'.$templateName; + $filename = Module::getModuleDir($templateModule) . '/templates/' . $templateName; } else { // .../templates/<theme>/<templateName> $base = $this->configuration->getPathValue('templatedir', 'templates/') ?: 'templates/'; - $filename = $base.$templateName; + $filename = $base . $templateName; } $filename = $this->normalizeTemplateName($filename); foreach ($extensions as $extension) { - if (file_exists($filename.$extension)) { - return $filename.$extension; + if (file_exists($filename . $extension)) { + return $filename . $extension; } } // not found in current theme Logger::debug( - $_SERVER['PHP_SELF'].' - Template: Could not find template file ['.$template.'] at ['. - $filename.'] - now trying the base template' + $_SERVER['PHP_SELF'] . ' - Template: Could not find template file [' . $template . '] at [' . + $filename . '] - now trying the base template' ); // try default theme if ($templateModule !== 'default') { // .../module/<templateModule>/templates/<templateName> - $filename = Module::getModuleDir($templateModule).'/templates/'.$templateName; + $filename = Module::getModuleDir($templateModule) . '/templates/' . $templateName; } else { // .../templates/<templateName> $base = $this->configuration->getPathValue('templatedir', 'templates/') ?: 'templates/'; - $filename = $base.'/'.$templateName; + $filename = $base . '/' . $templateName; } $filename = $this->normalizeTemplateName($filename); foreach ($extensions as $extension) { - if (file_exists($filename.$extension)) { - return $filename.$extension; + if (file_exists($filename . $extension)) { + return $filename . $extension; } } // not found in default template if ($throw_exception) { // log error and throw exception - $error = 'Template: Could not find template file ['.$template.'] at ['.$filename.']'; - Logger::critical($_SERVER['PHP_SELF'].' - '.$error); + $error = 'Template: Could not find template file [' . $template . '] at [' . $filename . ']'; + Logger::critical($_SERVER['PHP_SELF'] . ' - ' . $error); throw new \Exception($error); } else { diff --git a/lib/SimpleSAML/XHTML/TemplateLoader.php b/lib/SimpleSAML/XHTML/TemplateLoader.php index 14231bb9feabdf84cc5312cb47022d17ae259364..8fcb45ed85d02f146a7efbd48929c5eeec9e9571 100644 --- a/lib/SimpleSAML/XHTML/TemplateLoader.php +++ b/lib/SimpleSAML/XHTML/TemplateLoader.php @@ -68,13 +68,13 @@ class TemplateLoader extends \Twig\Loader\FilesystemLoader public static function getModuleTemplateDir($module) { if (!Module::isModuleEnabled($module)) { - throw new \InvalidArgumentException('The module \''.$module.'\' is not enabled.'); + throw new \InvalidArgumentException('The module \'' . $module . '\' is not enabled.'); } $moduledir = Module::getModuleDir($module); // check if module has a /templates dir, if so, append - $templatedir = $moduledir.'/templates'; + $templatedir = $moduledir . '/templates'; if (!is_dir($templatedir)) { - throw new \InvalidArgumentException('The module \''.$module.'\' has no templates directory.'); + throw new \InvalidArgumentException('The module \'' . $module . '\' has no templates directory.'); } return $templatedir; } diff --git a/lib/SimpleSAML/XML/Errors.php b/lib/SimpleSAML/XML/Errors.php index 9871571904d8ed8aacbce0283baf93d091d1085a..40af03a1cc03d3ac9e69b59a76d3daf9455d86f3 100644 --- a/lib/SimpleSAML/XML/Errors.php +++ b/lib/SimpleSAML/XML/Errors.php @@ -113,8 +113,11 @@ class Errors public static function formatError($error) { assert($error instanceof LibXMLError); - return 'level='.$error->level.',code='.$error->code.',line='.$error->line.',col='.$error->column. - ',msg='.trim($error->message); + return 'level=' . $error->level + . ',code=' . $error->code + . ',line=' . $error->line + . ',col=' . $error->column + . ',msg=' . trim($error->message); } @@ -134,7 +137,7 @@ class Errors $ret = ''; foreach ($errors as $error) { - $ret .= self::formatError($error)."\n"; + $ret .= self::formatError($error) . "\n"; } return $ret; diff --git a/lib/SimpleSAML/XML/Parser.php b/lib/SimpleSAML/XML/Parser.php index 2e5713d158fbd1a0fe3fd70b36de3a3c0e50ccfa..073faa93ee297f1e7b73701e8c4aec4829a702fc 100644 --- a/lib/SimpleSAML/XML/Parser.php +++ b/lib/SimpleSAML/XML/Parser.php @@ -36,7 +36,7 @@ class Parser // Traverse all existing namespaces in element $namespaces = $element->getNamespaces(); foreach ($namespaces as $prefix => $ns) { - $element[(($prefix === '') ? 'xmlns' : 'xmlns:'.$prefix)] = $ns; + $element[(($prefix === '') ? 'xmlns' : 'xmlns:' . $prefix)] = $ns; } /* Create a new parser with the xml document where the namespace definitions @@ -79,7 +79,7 @@ class Parser if (!is_array($result) || empty($result)) { if ($required) { throw new \Exception( - 'Could not get value from XML document using the following XPath expression: '.$xpath + 'Could not get value from XML document using the following XPath expression: ' . $xpath ); } else { return null; diff --git a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php index 4289a82deb0bbfb87f247883fb1a7477b293675c..899e195574e16778ba3d1683702ab75c781f0b95 100644 --- a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php +++ b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php @@ -80,10 +80,10 @@ class AuthnRequest $issuer = $this->getIssuer(); assert($issuer !== null); - $url = $desturl.'?'. - 'providerId='.urlencode($issuer). - '&shire='.urlencode($shire). - (isset($target) ? '&target='.urlencode($target) : ''); + $url = $desturl . '?' . + 'providerId=' . urlencode($issuer) . + '&shire=' . urlencode($shire) . + (isset($target) ? '&target=' . urlencode($target) : ''); return $url; } } diff --git a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php index 69b798f544fd47c90de41a94ac317b23fa197c75..f50045d8f6f5a0f678ba63f8f035c49a15f504d3 100644 --- a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php +++ b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php @@ -146,7 +146,7 @@ class AuthnResponse $this->validator->validateCA(Utils\Config::getCertPath($md->getString('caFile'))); } else { throw new Error\Exception( - 'Missing certificate in Shibboleth 1.3 IdP Remote metadata for identity provider ['.$issuer.'].' + 'Missing certificate in Shibboleth 1.3 IdP Remote metadata for identity provider [' . $issuer . '].' ); } @@ -260,7 +260,7 @@ class AuthnResponse if ($start && $end) { if (!self::checkDateConditions($start, $end)) { - error_log('Date check failed ... (from '.$start.' to '.$end.')'); + error_log('Date check failed ... (from ' . $start . ' to ' . $end . ')'); continue; } } @@ -280,7 +280,7 @@ class AuthnResponse $name = $parentNode->getAttribute('AttributeName'); if ($attribute->hasAttribute('Scope')) { - $scopePart = '@'.$attribute->getAttribute('Scope'); + $scopePart = '@' . $attribute->getAttribute('Scope'); } else { $scopePart = ''; } @@ -296,10 +296,10 @@ class AuthnResponse if ($base64) { $encodedvalues = explode('_', $value); foreach ($encodedvalues as $v) { - $attributes[$name][] = base64_decode($v).$scopePart; + $attributes[$name][] = base64_decode($v) . $scopePart; } } else { - $attributes[$name][] = $value.$scopePart; + $attributes[$name][] = $value . $scopePart; } } } @@ -385,18 +385,18 @@ class AuthnResponse $namequalifier = $sp->getString('NameQualifier', $spEntityId); $nameid = Utils\Random::generateID(); $subjectNode = - '<Subject>'. - '<NameIdentifier'. - ' Format="urn:mace:shibboleth:1.0:nameIdentifier"'. - ' NameQualifier="'.htmlspecialchars($namequalifier).'"'. - '>'. - htmlspecialchars($nameid). - '</NameIdentifier>'. - '<SubjectConfirmation>'. - '<ConfirmationMethod>'. - 'urn:oasis:names:tc:SAML:1.0:cm:bearer'. - '</ConfirmationMethod>'. - '</SubjectConfirmation>'. + '<Subject>' . + '<NameIdentifier' . + ' Format="urn:mace:shibboleth:1.0:nameIdentifier"' . + ' NameQualifier="' . htmlspecialchars($namequalifier) . '"' . + '>' . + htmlspecialchars($nameid) . + '</NameIdentifier>' . + '<SubjectConfirmation>' . + '<ConfirmationMethod>' . + 'urn:oasis:names:tc:SAML:1.0:cm:bearer' . + '</ConfirmationMethod>' . + '</SubjectConfirmation>' . '</Subject>'; $encodedattributes = ''; @@ -418,25 +418,25 @@ class AuthnResponse $response = '<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:xsd="http://www.w3.org/2001/XMLSchema" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" IssueInstant="'.$issueInstant.'" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" IssueInstant="' . $issueInstant . '" MajorVersion="1" MinorVersion="1" - Recipient="'.htmlspecialchars($shire).'" ResponseID="'.$id.'"> + Recipient="' . htmlspecialchars($shire) . '" ResponseID="' . $id . '"> <Status> <StatusCode Value="samlp:Success" /> </Status> <Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" - AssertionID="'.$assertionid.'" IssueInstant="'.$issueInstant.'" - Issuer="'.htmlspecialchars($idp->getString('entityid')).'" MajorVersion="1" MinorVersion="1"> - <Conditions NotBefore="'.$notBefore.'" NotOnOrAfter="'.$assertionExpire.'"> + AssertionID="' . $assertionid . '" IssueInstant="' . $issueInstant . '" + Issuer="' . htmlspecialchars($idp->getString('entityid')) . '" MajorVersion="1" MinorVersion="1"> + <Conditions NotBefore="' . $notBefore . '" NotOnOrAfter="' . $assertionExpire . '"> <AudienceRestrictionCondition> - <Audience>'.htmlspecialchars($audience).'</Audience> + <Audience>' . htmlspecialchars($audience) . '</Audience> </AudienceRestrictionCondition> </Conditions> - <AuthenticationStatement AuthenticationInstant="'.$issueInstant.'" - AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:unspecified">'. - $subjectNode.' + <AuthenticationStatement AuthenticationInstant="' . $issueInstant . '" + AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:unspecified">' . + $subjectNode . ' </AuthenticationStatement> - '.$encodedattributes.' + ' . $encodedattributes . ' </Assertion> </Response>'; @@ -466,7 +466,7 @@ class AuthnResponse $scoped = false; } - $attr = '<Attribute AttributeName="'.htmlspecialchars($name). + $attr = '<Attribute AttributeName="' . htmlspecialchars($name) . '" AttributeNamespace="urn:mace:shibboleth:1.0:attributeNamespace:uri">'; foreach ($values as $value) { $scopePart = ''; @@ -474,7 +474,7 @@ class AuthnResponse $tmp = explode('@', $value, 2); if (count($tmp) === 2) { $value = $tmp[0]; - $scopePart = ' Scope="'.htmlspecialchars($tmp[1]).'"'; + $scopePart = ' Scope="' . htmlspecialchars($tmp[1]) . '"'; } } @@ -482,7 +482,7 @@ class AuthnResponse $value = base64_encode($value); } - $attr .= '<AttributeValue'.$scopePart.'>'.htmlspecialchars($value).'</AttributeValue>'; + $attr .= '<AttributeValue' . $scopePart . '>' . htmlspecialchars($value) . '</AttributeValue>'; } $attr .= '</Attribute>'; diff --git a/lib/SimpleSAML/XML/Signer.php b/lib/SimpleSAML/XML/Signer.php index 09144e196f629b8ec0356e964e80c6ed70aa285d..bae8a0ce4f5a713ce05ed0dcd86fa571423d2ae3 100644 --- a/lib/SimpleSAML/XML/Signer.php +++ b/lib/SimpleSAML/XML/Signer.php @@ -138,11 +138,11 @@ class Signer } if (!file_exists($keyFile)) { - throw new \Exception('Could not find private key file "'.$keyFile.'".'); + throw new \Exception('Could not find private key file "' . $keyFile . '".'); } $keyData = file_get_contents($keyFile); if ($keyData === false) { - throw new \Exception('Unable to read private key file "'.$keyFile.'".'); + throw new \Exception('Unable to read private key file "' . $keyFile . '".'); } $privatekey = ['PEM' => $keyData]; @@ -202,12 +202,12 @@ class Signer } if (!file_exists($certFile)) { - throw new \Exception('Could not find certificate file "'.$certFile.'".'); + throw new \Exception('Could not find certificate file "' . $certFile . '".'); } $cert = file_get_contents($certFile); if ($cert === false) { - throw new \Exception('Unable to read certificate file "'.$certFile.'".'); + throw new \Exception('Unable to read certificate file "' . $certFile . '".'); } $this->certificate = $cert; } @@ -251,12 +251,12 @@ class Signer } if (!file_exists($certFile)) { - throw new \Exception('Could not find extra certificate file "'.$certFile.'".'); + throw new \Exception('Could not find extra certificate file "' . $certFile . '".'); } $certificate = file_get_contents($certFile); if ($certificate === false) { - throw new \Exception('Unable to read extra certificate file "'.$certFile.'".'); + throw new \Exception('Unable to read extra certificate file "' . $certFile . '".'); } $this->extraCertificates[] = $certificate; diff --git a/lib/SimpleSAML/XML/Validator.php b/lib/SimpleSAML/XML/Validator.php index 2d118452584c811645a6ab4dc36201e678c82d87..0e201c88984a74b077aab0a2c0ddc6a42e1e7518 100644 --- a/lib/SimpleSAML/XML/Validator.php +++ b/lib/SimpleSAML/XML/Validator.php @@ -115,7 +115,7 @@ class Validator $certificate = $objKey->getX509Certificate(); if ($certificate === null) { // Wasn't signed with an X509 certificate - throw new \Exception('Message wasn\'t signed with an X509 certificate,'. + throw new \Exception('Message wasn\'t signed with an X509 certificate,' . ' and no public key was provided in the metadata.'); } @@ -211,7 +211,7 @@ class Validator $certFingerprint = self::calculateX509Fingerprint($certificate); if ($certFingerprint === null) { // Couldn't calculate fingerprint from X509 certificate. Should not happen. - throw new \Exception('Unable to calculate fingerprint from X509'. + throw new \Exception('Unable to calculate fingerprint from X509' . ' certificate. Maybe it isn\'t an X509 certificate?'); } @@ -225,8 +225,8 @@ class Validator } // None of the fingerprints matched. Throw an exception describing the error. - throw new \Exception('Invalid fingerprint of certificate. Expected one of ['. - implode('], [', $fingerprints).'], but got ['.$certFingerprint.']'); + throw new \Exception('Invalid fingerprint of certificate. Expected one of [' . + implode('], [', $fingerprints) . '], but got [' . $certFingerprint . ']'); } @@ -337,7 +337,7 @@ class Validator $errors = ''; // Log errors while (($error = openssl_error_string()) !== false) { - $errors .= ' ['.$error.']'; + $errors .= ' [' . $error . ']'; } if ($res !== true) { @@ -374,7 +374,7 @@ class Validator $cmdline = ''; foreach ($command as $c) { - $cmdline .= escapeshellarg($c).' '; + $cmdline .= escapeshellarg($c) . ' '; } $cmdline .= '2>&1'; @@ -384,7 +384,7 @@ class Validator ]; $process = proc_open($cmdline, $descSpec, $pipes); if (!is_resource($process)) { - throw new \Exception('Failed to execute verification command: '.$cmdline); + throw new \Exception('Failed to execute verification command: ' . $cmdline); } if (fwrite($pipes[0], $certificate) === false) { @@ -396,7 +396,7 @@ class Validator while (!feof($pipes[1])) { $line = trim(fgets($pipes[1])); if (strlen($line) > 0) { - $out .= ' ['.$line.']'; + $out .= ' [' . $line . ']'; } } fclose($pipes[1]); @@ -427,21 +427,21 @@ class Validator assert(is_string($caFile)); if (!file_exists($caFile)) { - throw new \Exception('Could not load CA file: '.$caFile); + throw new \Exception('Could not load CA file: ' . $caFile); } - Logger::debug('Validating certificate against CA file: '.var_export($caFile, true)); + Logger::debug('Validating certificate against CA file: ' . var_export($caFile, true)); $resBuiltin = self::validateCABuiltIn($certificate, $caFile); if ($resBuiltin !== true) { - Logger::debug('Failed to validate with internal function: '.var_export($resBuiltin, true)); + Logger::debug('Failed to validate with internal function: ' . var_export($resBuiltin, true)); $resExternal = self::validateCAExec($certificate, $caFile); if ($resExternal !== true) { - 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:'.var_export($resBuiltin, true). - ' External result:'.var_export($resExternal, true)); + 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:' . var_export($resBuiltin, true) . + ' External result:' . var_export($resExternal, true)); } } diff --git a/lib/_autoload.php b/lib/_autoload.php index 245acd1e5561f4e1f7b1bc2fe270909b07997d36..e44c70f9774efcbb9815442d8d716445034592d1 100644 --- a/lib/_autoload.php +++ b/lib/_autoload.php @@ -9,12 +9,12 @@ */ // SSP is loaded as a separate project -if (file_exists(dirname(dirname(__FILE__)).'/vendor/autoload.php')) { - require_once dirname(dirname(__FILE__)).'/vendor/autoload.php'; +if (file_exists(dirname(dirname(__FILE__)) . '/vendor/autoload.php')) { + require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; } else { // SSP is loaded as a library - if (file_exists(dirname(dirname(__FILE__)).'/../../autoload.php')) { - require_once dirname(dirname(__FILE__)).'/../../autoload.php'; + if (file_exists(dirname(dirname(__FILE__)) . '/../../autoload.php')) { + require_once dirname(dirname(__FILE__)) . '/../../autoload.php'; } else { throw new Exception('Unable to load Composer autoloader'); } diff --git a/lib/_autoload_modules.php b/lib/_autoload_modules.php index 80cae14f95e87e132022dbdd1b5c678bdda88921..765dfd899bdba52dca796c719755ade6a0478767 100644 --- a/lib/_autoload_modules.php +++ b/lib/_autoload_modules.php @@ -21,7 +21,7 @@ function temporaryLoader($class) { // handle the upgrade to the latest version of XMLSecLibs using namespaces if (strstr($class, 'XMLSec') && !strstr($class, '\\RobRichards\\XMLSecLibs\\')) { - $new = '\\RobRichards\\XMLSecLibs\\'.$class; + $new = '\\RobRichards\\XMLSecLibs\\' . $class; if (class_exists($new, true)) { class_alias($new, $class); SimpleSAML\Logger::warning("The class '$class' is now using namespaces, please use '$new'."); @@ -53,7 +53,7 @@ function temporaryLoader($class) // try to load it from the corresponding file $path = explode('_', $class); - $file = dirname(__FILE__).DIRECTORY_SEPARATOR.join(DIRECTORY_SEPARATOR, $path).'.php'; + $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . join(DIRECTORY_SEPARATOR, $path) . '.php'; if (file_exists($file)) { require_once $file; } @@ -111,7 +111,7 @@ function sspmodAutoloadPSR0($className) return; } - $file = \SimpleSAML\Module::getModuleDir($module).'/lib/'.join('/', $path).'.php'; + $file = \SimpleSAML\Module::getModuleDir($module) . '/lib/' . join('/', $path) . '.php'; if (!file_exists($file)) { return; } @@ -120,13 +120,14 @@ function sspmodAutoloadPSR0($className) if (!class_exists($className, false) && !interface_exists($className, false)) { // the file exists, but the class is not defined. Is it using namespaces? $nspath = join('\\', $path); - if (class_exists('SimpleSAML\\Module\\'.$module.'\\'.$nspath) || - interface_exists('SimpleSAML\\Module\\'.$module.'\\'.$nspath) + if ( + class_exists('SimpleSAML\\Module\\' . $module . '\\' . $nspath) + || interface_exists('SimpleSAML\\Module\\' . $module . '\\' . $nspath) ) { // the class has been migrated, create an alias and warn about it \SimpleSAML\Logger::warning( - "The class or interface '$className' is now using namespaces, please use 'SimpleSAML\\Module\\". - $module."\\".$nspath."' instead." + "The class or interface '$className' is now using namespaces, please use 'SimpleSAML\\Module\\" . + $module . "\\" . $nspath . "' instead." ); class_alias("SimpleSAML\\Module\\$module\\$nspath", $className); } @@ -162,7 +163,7 @@ function sspmodAutoloadPSR4($className) return; // module not enabled, avoid giving out any information at all } - $file = \SimpleSAML\Module::getModuleDir($module).'/lib/'.implode('/', $elements).'.php'; + $file = \SimpleSAML\Module::getModuleDir($module) . '/lib/' . implode('/', $elements) . '.php'; if (file_exists($file)) { require_once($file); diff --git a/modules/admin/lib/ConfigController.php b/modules/admin/lib/ConfigController.php index 8d2c0758f40ee604a80be7a294f6bea2c4af2675..604b53e3dcfe9c7741c35671d48b9931361eba00 100644 --- a/modules/admin/lib/ConfigController.php +++ b/modules/admin/lib/ConfigController.php @@ -21,6 +21,7 @@ use Symfony\Component\HttpFoundation\Request; class ConfigController { const LATEST_VERSION_STATE_KEY = 'core:latest_simplesamlphp_version'; + const RELEASES_API = 'https://api.github.com/repos/simplesamlphp/simplesamlphp/releases/latest'; /** @var \SimpleSAML\Configuration */ @@ -336,9 +337,9 @@ class ConfigController // make sure we're using HTTPS if (!Utils\HTTP::isHTTPS()) { $warnings[] = Translate::noop( - '<strong>You are not using HTTPS</strong> to protect communications with your users. HTTP works fine '. - 'for testing purposes, but in a production environment you should use HTTPS. <a '. - 'href="https://simplesamlphp.org/docs/stable/simplesamlphp-maintenance">Read more about the '. + '<strong>You are not using HTTPS</strong> to protect communications with your users. HTTP works fine ' . + 'for testing purposes, but in a production environment you should use HTTPS. <a ' . + 'href="https://simplesamlphp.org/docs/stable/simplesamlphp-maintenance">Read more about the ' . 'maintenance of SimpleSAMLphp</a>.' ); } @@ -346,9 +347,9 @@ class ConfigController // make sure we have a secret salt set if ($this->config->getValue('secretsalt') === 'defaultsecretsalt') { $warnings[] = Translate::noop( - '<strong>The configuration uses the default secret salt</strong>. Make sure to modify the <code>'. - 'secretsalt</code> option in the SimpleSAMLphp configuration in production environments. <a '. - 'href="https://simplesamlphp.org/docs/stable/simplesamlphp-install">Read more about the '. + '<strong>The configuration uses the default secret salt</strong>. Make sure to modify the <code>' . + 'secretsalt</code> option in the SimpleSAMLphp configuration in production environments. <a ' . + 'href="https://simplesamlphp.org/docs/stable/simplesamlphp-install">Read more about the ' . 'maintenance of SimpleSAMLphp</a>.' ); } @@ -358,7 +359,7 @@ class ConfigController $len = ini_get('suhosin.get.max_value_length'); if (empty($len) || $len < 2048) { $warnings[] = Translate::noop( - 'The length of query parameters is limited by the PHP Suhosin extension. Please increase the '. + 'The length of query parameters is limited by the PHP Suhosin extension. Please increase the ' . '<code>suhosin.get.max_value_length</code> option in your php.ini to at least 2048 bytes.' ); } @@ -397,7 +398,7 @@ class ConfigController if ($latest && version_compare($this->config->getVersion(), ltrim($latest['tag_name'], 'v'), 'lt')) { $warnings[] = [ Translate::noop( - 'You are running an outdated version of SimpleSAMLphp. Please update to <a href="'. + 'You are running an outdated version of SimpleSAMLphp. Please update to <a href="' . '%latest%">the latest version</a> as soon as possible.' ), [ diff --git a/modules/admin/lib/FederationController.php b/modules/admin/lib/FederationController.php index fb83c2e6279b48c33825c6a548ee39a96486033f..a6d81e45ed392f91e93858c66d773d665cc425b9 100644 --- a/modules/admin/lib/FederationController.php +++ b/modules/admin/lib/FederationController.php @@ -173,7 +173,7 @@ class FederationController $saml2entities = []; if (count($idps) > 1) { foreach ($idps as $index => $idp) { - $idp['url'] = Module::getModuleURL('saml/2/idp/metadata/'.$idp['auth']); + $idp['url'] = Module::getModuleURL('saml/2/idp/metadata/' . $idp['auth']); $idp['metadata-set'] = 'saml20-idp-hosted'; $idp['metadata-index'] = $index; $idp['metadata_array'] = SAML2_IdP::getHostedMetadata($idp['entityid']); @@ -181,7 +181,7 @@ class FederationController } } else { $saml2entities['saml20-idp'] = $this->mdHandler->getMetaDataCurrent('saml20-idp-hosted'); - $saml2entities['saml20-idp']['url'] = Utils\HTTP::getBaseURL().'saml2/idp/metadata.php'; + $saml2entities['saml20-idp']['url'] = Utils\HTTP::getBaseURL() . 'saml2/idp/metadata.php'; $saml2entities['saml20-idp']['metadata_array'] = SAML2_IdP::getHostedMetadata( $this->mdHandler->getMetaDataCurrentEntityID('saml20-idp-hosted') @@ -204,7 +204,7 @@ class FederationController $entities[$index] = $entity; } } catch (\Exception $e) { - Logger::error('Federation: Error loading saml20-idp: '.$e->getMessage()); + Logger::error('Federation: Error loading saml20-idp: ' . $e->getMessage()); } } @@ -215,7 +215,7 @@ class FederationController $shib13entities = []; if (count($idps) > 1) { foreach ($idps as $index => $idp) { - $idp['url'] = Module::getModuleURL('saml/1.1/idp/metadata/'.$idp['auth']); + $idp['url'] = Module::getModuleURL('saml/1.1/idp/metadata/' . $idp['auth']); $idp['metadata-set'] = 'shib13-idp-hosted'; $idp['metadata-index'] = $index; $idp['metadata_array'] = SAML1_IdP::getHostedMetadata($idp['entityid']); @@ -223,12 +223,10 @@ class FederationController } } else { $shib13entities['shib13-idp'] = $this->mdHandler->getMetaDataCurrent('shib13-idp-hosted'); - $shib13entities['shib13-idp']['url'] = Utils\HTTP::getBaseURL(). - 'shib13/idp/metadata.php'; - $shib13entities['shib13-idp']['metadata_array'] = - SAML1_IdP::getHostedMetadata( - $this->mdHandler->getMetaDataCurrentEntityID('shib13-idp-hosted') - ); + $shib13entities['shib13-idp']['url'] = Utils\HTTP::getBaseURL() . 'shib13/idp/metadata.php'; + $shib13entities['shib13-idp']['metadata_array'] = SAML1_IdP::getHostedMetadata( + $this->mdHandler->getMetaDataCurrentEntityID('shib13-idp-hosted') + ); } foreach ($shib13entities as $index => $entity) { @@ -247,7 +245,7 @@ class FederationController $entities[$index] = $entity; } } catch (\Exception $e) { - Logger::error('Federation: Error loading shib13-idp: '.$e->getMessage()); + Logger::error('Federation: Error loading shib13-idp: ' . $e->getMessage()); } } @@ -258,7 +256,7 @@ class FederationController $adfsentities = []; if (count($idps) > 1) { foreach ($idps as $index => $idp) { - $idp['url'] = Module::getModuleURL('adfs/idp/metadata/'.$idp['auth']); + $idp['url'] = Module::getModuleURL('adfs/idp/metadata/' . $idp['auth']); $idp['metadata-set'] = 'adfs-idp-hosted'; $idp['metadata-index'] = $index; $idp['metadata_array'] = ADFS_IdP::getHostedMetadata($idp['entityid']); @@ -267,10 +265,9 @@ class FederationController } else { $adfsentities['adfs-idp'] = $this->mdHandler->getMetaDataCurrent('adfs-idp-hosted'); $adfsentities['adfs-idp']['url'] = Module::getModuleURL('adfs/idp/metadata.php'); - $adfsentities['adfs-idp']['metadata_array'] = - ADFS_IdP::getHostedMetadata( - $this->mdHandler->getMetaDataCurrentEntityID('adfs-idp-hosted') - ); + $adfsentities['adfs-idp']['metadata_array'] = ADFS_IdP::getHostedMetadata( + $this->mdHandler->getMetaDataCurrentEntityID('adfs-idp-hosted') + ); } foreach ($adfsentities as $index => $entity) { @@ -289,7 +286,7 @@ class FederationController $entities[$index] = $entity; } } catch (\Exception $e) { - Logger::error('Federation: Error loading adfs-idp: '.$e->getMessage()); + Logger::error('Federation: Error loading adfs-idp: ' . $e->getMessage()); } } @@ -337,7 +334,7 @@ class FederationController /** @var \SimpleSAML\Module\saml\Auth\Source\SP $source */ foreach (Auth\Source::getSourcesOfType('saml:SP') as $source) { $metadata = $source->getHostedMetadata(); - if (isset($metadata['keys']) ) { + if (isset($metadata['keys'])) { $certificates = $metadata['keys']; if (count($metadata['keys']) === 1) { $cert = array_pop($metadata['keys']); @@ -429,11 +426,14 @@ class FederationController continue; } - // remove the entityDescriptor element because it is unused, and only makes the output harder to read + /** + * remove the entityDescriptor element because it is unused, + * and only makes the output harder to read + */ unset($entityMetadata['entityDescriptor']); - $text .= '$metadata['.var_export($entityId, true).'] = '. - var_export($entityMetadata, true).";\n"; + $text .= '$metadata[' . var_export($entityId, true) . '] = ' + . var_export($entityMetadata, true) . ";\n"; } $entities = $text; } diff --git a/modules/admin/lib/TestController.php b/modules/admin/lib/TestController.php index ee81541aacb850b9b8a05cab5c739c8a7877a47f..ac4afebcd6374ef5b4cef182b4d868002ebff057 100644 --- a/modules/admin/lib/TestController.php +++ b/modules/admin/lib/TestController.php @@ -66,7 +66,7 @@ class TestController } else { $authsource = new Auth\Simple($as); if (!is_null($request->query->get('logout'))) { - $authsource->logout($this->config->getBasePath().'logout.php'); + $authsource->logout($this->config->getBasePath() . 'logout.php'); } elseif (!is_null($request->query->get(Auth\State::EXCEPTION_PARAM))) { // This is just a simple example of an error /** @var array $state */ @@ -76,7 +76,7 @@ class TestController } if (!$authsource->isAuthenticated()) { - $url = Module::getModuleURL('admin/test/'.$as, []); + $url = Module::getModuleURL('admin/test/' . $as, []); $params = [ 'ErrorURL' => $url, 'ReturnTo' => $url, @@ -86,7 +86,9 @@ class TestController $attributes = $authsource->getAttributes(); $authData = $authsource->getAuthDataArray(); - $nameId = !is_null($authsource->getAuthData('saml:sp:NameID')) ? $authsource->getAuthData('saml:sp:NameID') : false; + $nameId = !is_null($authsource->getAuthData('saml:sp:NameID')) + ? $authsource->getAuthData('saml:sp:NameID') + : false; $t = new Template($this->config, 'admin:status.twig', 'attributes'); $t->data = [ @@ -94,7 +96,7 @@ class TestController 'attributesHtml' => $this->getAttributesHTML($t, $attributes, ''), 'authData' => $authData, 'nameid' => $nameId, - 'logouturl' => Utils\HTTP::getSelfURLNoQuery().'?as='.urlencode($as).'&logout', + 'logouturl' => Utils\HTTP::getSelfURLNoQuery() . '?as=' . urlencode($as) . '&logout', ]; if ($nameId !== false) { @@ -121,7 +123,7 @@ class TestController $list = ["NameID" => [$translator->t('{status:subject_notset}')]]; /** @var string $notset */ $notset = $translator->t('{status:subject_notset}'); - $result .= "<p>NameID: <span class=\"notset\">".$notset."</span></p>"; + $result .= "<p>NameID: <span class=\"notset\">" . $notset . "</span></p>"; } else { $list = [ "NameId" => [$nameId->getValue()], @@ -141,7 +143,7 @@ class TestController $list['SPProvidedID'] = [$nameId->getSPProvidedID()]; } } - return $result.$this->getAttributesHTML($t, $list, ''); + return $result . $this->getAttributesHTML($t, $list, ''); } @@ -155,45 +157,47 @@ class TestController { $alternate = ['pure-table-odd', 'pure-table-even']; $i = 0; - $parentStr = (strlen($nameParent) > 0) ? strtolower($nameParent).'_' : ''; - $str = (strlen($nameParent) > 0) ? '<table class="pure-table pure-table-attributes" summary="attribute overview">' : - '<table id="table_with_attributes" class="pure-table pure-table-attributes" summary="attribute overview">'; + $parentStr = (strlen($nameParent) > 0) ? strtolower($nameParent) . '_' : ''; + $str = (strlen($nameParent) > 0) + ? '<table class="pure-table pure-table-attributes" summary="attribute overview">' + : '<table id="table_with_attributes" class="pure-table pure-table-attributes"' + . ' summary="attribute overview">'; foreach ($attributes as $name => $value) { $nameraw = $name; $trans = $t->getTranslator(); - $name = $trans->getAttributeTranslation($parentStr.$nameraw); + $name = $trans->getAttributeTranslation($parentStr . $nameraw); if (preg_match('/^child_/', $nameraw)) { $parentName = preg_replace('/^child_/', '', $nameraw); foreach ($value as $child) { - $str .= '<tr class="odd"><td colspan="2" style="padding: 2em">'. - $this->getAttributesHTML($t, $child, $parentName).'</td></tr>'; + $str .= '<tr class="odd"><td colspan="2" style="padding: 2em">' . + $this->getAttributesHTML($t, $child, $parentName) . '</td></tr>'; } } else { if (sizeof($value) > 1) { - $str .= '<tr class="'.$alternate[($i++ % 2)].'"><td class="attrname">'; + $str .= '<tr class="' . $alternate[($i++ % 2)] . '"><td class="attrname">'; if ($nameraw !== $name) { - $str .= htmlspecialchars($name).'<br/>'; + $str .= htmlspecialchars($name) . '<br/>'; } - $str .= '<code>'.htmlspecialchars($nameraw).'</code>'; + $str .= '<code>' . htmlspecialchars($nameraw) . '</code>'; $str .= '</td><td class="attrvalue"><ul>'; foreach ($value as $listitem) { if ($nameraw === 'jpegPhoto') { - $str .= '<li><img src="data:image/jpeg;base64,'.htmlspecialchars($listitem).'" /></li>'; + $str .= '<li><img src="data:image/jpeg;base64,' . htmlspecialchars($listitem) . '" /></li>'; } else { - $str .= '<li>'.$this->present_assoc($listitem).'</li>'; + $str .= '<li>' . $this->presentAssoc($listitem) . '</li>'; } } $str .= '</ul></td></tr>'; } elseif (isset($value[0])) { - $str .= '<tr class="'.$alternate[($i++ % 2)].'"><td class="attrname">'; + $str .= '<tr class="' . $alternate[($i++ % 2)] . '"><td class="attrname">'; if ($nameraw !== $name) { - $str .= htmlspecialchars($name).'<br/>'; + $str .= htmlspecialchars($name) . '<br/>'; } - $str .= '<code>'.htmlspecialchars($nameraw).'</code>'; + $str .= '<code>' . htmlspecialchars($nameraw) . '</code>'; $str .= '</td>'; if ($nameraw === 'jpegPhoto') { - $str .= '<td class="attrvalue"><img src="data:image/jpeg;base64,'.htmlspecialchars($value[0]). - '" /></td></tr>'; + $str .= '<td class="attrvalue"><img src="data:image/jpeg;base64,' . htmlspecialchars($value[0]) + . '" /></td></tr>'; } elseif (is_a($value[0], 'DOMNodeList')) { // try to see if we have a NameID here /** @var \DOMNodeList $value [0] */ @@ -204,15 +208,15 @@ class TestController if (!($elem->localName === 'NameID' && $elem->namespaceURI === Constants::NS_SAML)) { continue; } - $str .= $this->present_eptid($trans, new NameID($elem)); + $str .= $this->presentEptid($trans, new NameID($elem)); break; // we only support one NameID here } $str .= '</td></tr>'; } elseif (is_a($value[0], '\SAML2\XML\saml\NameID')) { - $str .= $this->present_eptid($trans, $value[0]); + $str .= $this->presentEptid($trans, $value[0]); $str .= '</td></tr>'; } else { - $str .= '<td class="attrvalue">'.htmlspecialchars($value[0]).'</td></tr>'; + $str .= '<td class="attrvalue">' . htmlspecialchars($value[0]) . '</td></tr>'; } } } @@ -227,12 +231,12 @@ class TestController * @param array|string $attr * @return string */ - private function present_list($attr) + private function presentList($attr) { if (is_array($attr) && count($attr) > 1) { $str = '<ul>'; foreach ($attr as $value) { - $str .= '<li>'.htmlspecialchars(strval($attr)).'</li>'; + $str .= '<li>' . htmlspecialchars(strval($attr)) . '</li>'; } $str .= '</ul>'; return $str; @@ -246,12 +250,12 @@ class TestController * @param array|string $attr * @return string */ - private function present_assoc($attr) + private function presentAssoc($attr) { if (is_array($attr)) { $str = '<dl>'; foreach ($attr as $key => $value) { - $str .= "\n".'<dt>'.htmlspecialchars($key).'</dt><dd>'.$this->present_list($value).'</dd>'; + $str .= "\n" . '<dt>' . htmlspecialchars($key) . '</dt><dd>' . $this->presentList($value) . '</dd>'; } $str .= '</dl>'; return $str; @@ -266,7 +270,7 @@ class TestController * @param \SAML2\XML\saml\NameID $nameID * @return string */ - private function present_eptid(Translate $t, NameID $nameID) + private function presentEptid(Translate $t, NameID $nameID) { $eptid = [ 'NameID' => [$nameID->getValue()], @@ -285,6 +289,6 @@ class TestController if ($nameID->getSPProvidedID() !== null) { $eptid['SPProvidedID'] = [$nameID->getSPProvidedID()]; } - return '<td class="attrvalue">'.$this->present_assoc($eptid); + return '<td class="attrvalue">' . $this->presentAssoc($eptid); } } diff --git a/modules/core/hooks/hook_sanitycheck.php b/modules/core/hooks/hook_sanitycheck.php index b71dd1912881bd90d4e8a0ad7f5d62d5d7cf2f87..7e401a0dc5e7abdfb0f8157419b51018d1c00fe1 100644 --- a/modules/core/hooks/hook_sanitycheck.php +++ b/modules/core/hooks/hook_sanitycheck.php @@ -29,7 +29,7 @@ function core_hook_sanitycheck(&$hookinfo) if (version_compare(phpversion(), '5.6', '>=')) { $hookinfo['info'][] = '[core] You are running a PHP version suitable for SimpleSAMLphp.'; } else { - $hookinfo['errors'][] = '[core] You are running an old PHP installation. '. + $hookinfo['errors'][] = '[core] You are running an old PHP installation. ' . 'Please check the requirements for your SimpleSAMLphp version and upgrade.'; } @@ -43,7 +43,7 @@ function core_hook_sanitycheck(&$hookinfo) if (isset($i['dependencies']) && is_array($i['dependencies'])) { foreach ($i['dependencies'] as $dep) { if (!in_array($dep, $availmodules, true)) { - $hookinfo['errors'][] = '[core] Module dependency not met: '.$mi.' requires '.$dep; + $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 b1da4993d92bd8ce0739e149080c21aaeb8d733d..dac755fe601e98912624f0379b0e5c86590daafd 100644 --- a/modules/core/lib/ACL.php +++ b/modules/core/lib/ACL.php @@ -35,7 +35,7 @@ class ACL foreach ($acl as $rule) { if (!is_array($rule)) { - throw new Error\Exception('Invalid rule in access control list: '.var_export($rule, true)); + throw new Error\Exception('Invalid rule in access control list: ' . var_export($rule, true)); } if (count($rule) === 0) { throw new Error\Exception('Empty rule in access control list.'); @@ -44,7 +44,7 @@ class ACL $action = array_shift($rule); if ($action !== 'allow' && $action !== 'deny') { throw new Error\Exception( - 'Invalid action in rule in access control list: '.var_export($action, true) + 'Invalid action in rule in access control list: ' . var_export($action, true) ); } } @@ -63,7 +63,7 @@ class ACL $config = Configuration::getOptionalConfig('acl.php'); if (!$config->hasValue($id)) { - throw new Error\Exception('No ACL with id '.var_export($id, true).' in config/acl.php.'); + throw new Error\Exception('No ACL with id ' . var_export($id, true) . ' in config/acl.php.'); } return $config->getArray($id); @@ -124,7 +124,7 @@ class ACL case 'or': return self::opOr($attributes, $rule); default: - throw new Error\Exception('Invalid ACL operation: '.var_export($op, true)); + throw new Error\Exception('Invalid ACL operation: ' . var_export($op, true)); } } diff --git a/modules/core/lib/Auth/Process/AttributeAdd.php b/modules/core/lib/Auth/Process/AttributeAdd.php index 06fdb41bdd2af46e5305f80d4112918ff6700327..33f419cd3ded36157df74df2212e440ea00c14f1 100644 --- a/modules/core/lib/Auth/Process/AttributeAdd.php +++ b/modules/core/lib/Auth/Process/AttributeAdd.php @@ -44,7 +44,7 @@ class AttributeAdd extends \SimpleSAML\Auth\ProcessingFilter if ($values === '%replace') { $this->replace = true; } else { - throw new \Exception('Unknown flag: '.var_export($values, true)); + throw new \Exception('Unknown flag: ' . var_export($values, true)); } continue; } @@ -54,7 +54,9 @@ class AttributeAdd extends \SimpleSAML\Auth\ProcessingFilter } foreach ($values as $value) { if (!is_string($value)) { - throw new \Exception('Invalid value for attribute '.$name.': '.var_export($values, true)); + throw new \Exception( + 'Invalid value for attribute ' . $name . ': ' . var_export($values, true) + ); } } diff --git a/modules/core/lib/Auth/Process/AttributeAlter.php b/modules/core/lib/Auth/Process/AttributeAlter.php index 5212e6938728332dde270c49524095216474d087..710254db6303469a7d1d7c2a945703b0d854f767 100644 --- a/modules/core/lib/Auth/Process/AttributeAlter.php +++ b/modules/core/lib/Auth/Process/AttributeAlter.php @@ -73,7 +73,7 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter } elseif ($value === '%remove') { $this->remove = true; } else { - throw new Error\Exception('Unknown flag : '.var_export($value, true)); + throw new Error\Exception('Unknown flag : ' . var_export($value, true)); } continue; } elseif ($name === 'pattern') { @@ -116,8 +116,9 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter } if (!$this->replace && !$this->remove && $this->replacement === false) { - throw new Error\Exception("'replacement' must be set if neither '%replace' nor ". - "'%remove' are set."); + throw new Error\Exception( + "'replacement' must be set if neither '%replace' nor " . "'%remove' are set." + ); } if (!$this->replace && $this->replacement === null) { diff --git a/modules/core/lib/Auth/Process/AttributeCopy.php b/modules/core/lib/Auth/Process/AttributeCopy.php index 0dd53c8fade1080e5f87b5d5e8a357b858760973..f6b9a55ae074ebf4c8b8d13869d9d0a7af5aa7f1 100644 --- a/modules/core/lib/Auth/Process/AttributeCopy.php +++ b/modules/core/lib/Auth/Process/AttributeCopy.php @@ -40,11 +40,11 @@ class AttributeCopy extends \SimpleSAML\Auth\ProcessingFilter foreach ($config as $source => $destination) { if (!is_string($source)) { - throw new \Exception('Invalid source attribute name: '.var_export($source, true)); + throw new \Exception('Invalid source attribute name: ' . var_export($source, true)); } if (!is_string($destination) && !is_array($destination)) { - throw new \Exception('Invalid destination attribute name: '.var_export($destination, true)); + throw new \Exception('Invalid destination attribute name: ' . var_export($destination, true)); } $this->map[$source] = $destination; diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php index 864324b268c0140d2673d6a63e86b45c53242b0e..2767a9555d0ee7ff571ee4f23b44113d49821cd8 100644 --- a/modules/core/lib/Auth/Process/AttributeLimit.php +++ b/modules/core/lib/Auth/Process/AttributeLimit.php @@ -45,18 +45,18 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter $this->isDefault = (bool) $value; } elseif (is_int($index)) { if (!is_string($value)) { - throw new Error\Exception('AttributeLimit: Invalid attribute name: '. + throw new Error\Exception('AttributeLimit: Invalid attribute name: ' . var_export($value, true)); } $this->allowedAttributes[] = $value; } elseif (is_string($index)) { if (!is_array($value)) { - throw new Error\Exception('AttributeLimit: Values for '. - var_export($index, true).' must be specified in an array.'); + throw new Error\Exception('AttributeLimit: Values for ' . + var_export($index, true) . ' must be specified in an array.'); } $this->allowedAttributes[$index] = $value; } else { - throw new Error\Exception('AttributeLimit: Invalid option: '.var_export($index, true)); + throw new Error\Exception('AttributeLimit: Invalid option: ' . var_export($index, true)); } } } @@ -119,8 +119,8 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter if (array_key_exists($name, $allowedAttributes)) { // but it is an index of the array if (!is_array($allowedAttributes[$name])) { - throw new Error\Exception('AttributeLimit: Values for '. - var_export($name, true).' must be specified in an array.'); + throw new Error\Exception('AttributeLimit: Values for ' . + var_export($name, true) . ' must be specified in an array.'); } $attributes[$name] = $this->filterAttributeValues($attributes[$name], $allowedAttributes[$name]); if (!empty($attributes[$name])) { diff --git a/modules/core/lib/Auth/Process/AttributeMap.php b/modules/core/lib/Auth/Process/AttributeMap.php index f4b79d2494a38de517a7a30c59e7d8ad35ff7efa..a007d38052457f9b345bf09d64d7e567ce93db9c 100644 --- a/modules/core/lib/Auth/Process/AttributeMap.php +++ b/modules/core/lib/Auth/Process/AttributeMap.php @@ -53,11 +53,11 @@ class AttributeMap extends \SimpleSAML\Auth\ProcessingFilter } if (!is_string($origName)) { - throw new \Exception('Invalid attribute name: '.var_export($origName, true)); + throw new \Exception('Invalid attribute name: ' . var_export($origName, true)); } if (!is_string($newName) && !is_array($newName)) { - throw new \Exception('Invalid attribute name: '.var_export($newName, true)); + throw new \Exception('Invalid attribute name: ' . var_export($newName, true)); } $this->map[$origName] = $newName; @@ -89,20 +89,20 @@ class AttributeMap extends \SimpleSAML\Auth\ProcessingFilter if (!Module::isModuleEnabled($m[0])) { throw new \Exception("Module '$m[0]' is not enabled."); } - $filePath = Module::getModuleDir($m[0]).'/attributemap/'.$m[1].'.php'; + $filePath = Module::getModuleDir($m[0]) . '/attributemap/' . $m[1] . '.php'; } else { $attributenamemapdir = $config->getPathValue('attributenamemapdir', 'attributemap/') ?: 'attributemap/'; - $filePath = $attributenamemapdir.$fileName.'.php'; + $filePath = $attributenamemapdir . $fileName . '.php'; } if (!file_exists($filePath)) { - throw new \Exception('Could not find attribute map file: '.$filePath); + throw new \Exception('Could not find attribute map file: ' . $filePath); } $attributemap = null; include($filePath); if (!is_array($attributemap)) { - throw new \Exception('Attribute map file "'.$filePath.'" didn\'t define an attribute map.'); + throw new \Exception('Attribute map file "' . $filePath . '" didn\'t define an attribute map.'); } if ($this->duplicate) { diff --git a/modules/core/lib/Auth/Process/AttributeRealm.php b/modules/core/lib/Auth/Process/AttributeRealm.php index 58533a7cd64d3a216fe01223f3fe79b0683a9237..81a71235d05f2e78af050839f67ecc861e77ae6e 100644 --- a/modules/core/lib/Auth/Process/AttributeRealm.php +++ b/modules/core/lib/Auth/Process/AttributeRealm.php @@ -48,8 +48,8 @@ class AttributeRealm extends \SimpleSAML\Auth\ProcessingFilter assert(array_key_exists('Attributes', $request)); if (!array_key_exists('UserID', $request)) { - throw new \Exception('core:AttributeRealm: Missing UserID for this user. Please'. - ' check the \'userid.attribute\' option in the metadata against the'. + throw new \Exception('core:AttributeRealm: Missing UserID for this user. Please' . + ' check the \'userid.attribute\' option in the metadata against the' . ' attributes provided by the authentication source.'); } $userID = $request['UserID']; diff --git a/modules/core/lib/Auth/Process/AttributeValueMap.php b/modules/core/lib/Auth/Process/AttributeValueMap.php index 82ed34a3df667b11f5b0d4abdd396f029272b611..7c41cf412db8e473a91b10df8ecf3853e8ab885f 100644 --- a/modules/core/lib/Auth/Process/AttributeValueMap.php +++ b/modules/core/lib/Auth/Process/AttributeValueMap.php @@ -68,7 +68,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter } else { // unknown configuration option, log it and ignore the error Logger::warning( - "AttributeValueMap: unknown configuration flag '".var_export($value, true)."'" + "AttributeValueMap: unknown configuration flag '" . var_export($value, true) . "'" ); } continue; diff --git a/modules/core/lib/Auth/Process/Cardinality.php b/modules/core/lib/Auth/Process/Cardinality.php index 023f4c57ab60cb862d7597c79a36fb3a4e77a4c1..113cc6b622773e766746b3368c8c5aa496ffd013 100644 --- a/modules/core/lib/Auth/Process/Cardinality.php +++ b/modules/core/lib/Auth/Process/Cardinality.php @@ -48,7 +48,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter } if (!is_string($attribute)) { - throw new Error\Exception('Invalid attribute name: '.var_export($attribute, true)); + throw new Error\Exception('Invalid attribute name: ' . var_export($attribute, true)); } $this->cardinality[$attribute] = ['warn' => false]; @@ -70,23 +70,26 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter /* sanity check the rules */ if (!array_key_exists('min', $this->cardinality[$attribute])) { $this->cardinality[$attribute]['min'] = 0; - } elseif (!is_int($this->cardinality[$attribute]['min']) || - $this->cardinality[$attribute]['min'] < 0 + } elseif ( + !is_int($this->cardinality[$attribute]['min']) + || $this->cardinality[$attribute]['min'] < 0 ) { - throw new Error\Exception('Minimum cardinality must be a positive integer: '. + throw new Error\Exception('Minimum cardinality must be a positive integer: ' . var_export($attribute, true)); } - if (array_key_exists('max', $this->cardinality[$attribute]) && - !is_int($this->cardinality[$attribute]['max']) + if ( + array_key_exists('max', $this->cardinality[$attribute]) + && !is_int($this->cardinality[$attribute]['max']) ) { - throw new Error\Exception('Maximum cardinality must be a positive integer: '. + throw new Error\Exception('Maximum cardinality must be a positive integer: ' . var_export($attribute, true)); } - if (array_key_exists('min', $this->cardinality[$attribute]) && - array_key_exists('max', $this->cardinality[$attribute]) && - $this->cardinality[$attribute]['min'] > $this->cardinality[$attribute]['max'] + if ( + array_key_exists('min', $this->cardinality[$attribute]) + && array_key_exists('max', $this->cardinality[$attribute]) + && $this->cardinality[$attribute]['min'] > $this->cardinality[$attribute]['max'] ) { - throw new Error\Exception('Minimum cardinality must be less than maximium: '. + throw new Error\Exception('Minimum cardinality must be less than maximium: ' . var_export($attribute, true)); } @@ -115,7 +118,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter $entityid = $request['Source']['entityid']; } if (in_array($entityid, $this->ignoreEntities, true)) { - Logger::debug('Cardinality: Ignoring assertions from '.$entityid); + Logger::debug('Cardinality: Ignoring assertions from ' . $entityid); return; } diff --git a/modules/core/lib/Auth/Process/CardinalitySingle.php b/modules/core/lib/Auth/Process/CardinalitySingle.php index 1d1e39baea212223c20406ebafe910d9f24881c0..a9f08001c7779fdb095e2eed9458f60115749d8d 100644 --- a/modules/core/lib/Auth/Process/CardinalitySingle.php +++ b/modules/core/lib/Auth/Process/CardinalitySingle.php @@ -88,11 +88,12 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter assert(is_array($request)); assert(array_key_exists("Attributes", $request)); - if (array_key_exists('Source', $request) && - array_key_exists('entityid', $request['Source']) && - in_array($request['Source']['entityid'], $this->ignoreEntities, true) + if ( + array_key_exists('Source', $request) + && array_key_exists('entityid', $request['Source']) + && in_array($request['Source']['entityid'], $this->ignoreEntities, true) ) { - Logger::debug('CardinalitySingle: Ignoring assertions from '.$request['Source']['entityid']); + Logger::debug('CardinalitySingle: Ignoring assertions from ' . $request['Source']['entityid']); return; } diff --git a/modules/core/lib/Auth/Process/ExtendIdPSession.php b/modules/core/lib/Auth/Process/ExtendIdPSession.php index 7c6aa746a97dbc013e621dd40663abadb99229f4..b582561e0ea85730975ebebe56f47b35aa1b383e 100644 --- a/modules/core/lib/Auth/Process/ExtendIdPSession.php +++ b/modules/core/lib/Auth/Process/ExtendIdPSession.php @@ -42,8 +42,10 @@ class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter // If remember me is active $rememberMeExpire = $session->getRememberMeExpire(); - if (!empty($state['RememberMe']) && $rememberMeExpire !== null && - $globalConfig->getBoolean('session.rememberme.enable', false) + if ( + !empty($state['RememberMe']) + && $rememberMeExpire !== null + && $globalConfig->getBoolean('session.rememberme.enable', false) ) { $session->setRememberMeExpire(); return; diff --git a/modules/core/lib/Auth/Process/GenerateGroups.php b/modules/core/lib/Auth/Process/GenerateGroups.php index 206433cd5ec322adcdfecfe96bb5b0ec1e41bd85..a6e2257e774b5afa20a09805d8127c1cab756569 100644 --- a/modules/core/lib/Auth/Process/GenerateGroups.php +++ b/modules/core/lib/Auth/Process/GenerateGroups.php @@ -42,7 +42,7 @@ class GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter // Validate configuration foreach ($config as $attributeName) { if (!is_string($attributeName)) { - throw new \Exception('Invalid attribute name for core:GenerateGroups filter: '. + throw new \Exception('Invalid attribute name for core:GenerateGroups filter: ' . var_export($attributeName, true)); } } @@ -67,21 +67,21 @@ class GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter $realm = self::getRealm($attributes); if ($realm !== null) { - $groups[] = 'realm-'.$realm; + $groups[] = 'realm-' . $realm; } foreach ($this->generateGroupsFrom as $name) { if (!array_key_exists($name, $attributes)) { - Logger::debug('GenerateGroups - attribute \''.$name.'\' not found.'); + Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.'); // Attribute not present continue; } foreach ($attributes[$name] as $value) { $value = self::escapeIllegalChars($value); - $groups[] = $name.'-'.$value; + $groups[] = $name . '-' . $value; if ($realm !== null) { - $groups[] = $name.'-'.$realm.'-'.$value; + $groups[] = $name . '-' . $realm . '-' . $value; } } } diff --git a/modules/core/lib/Auth/Process/LanguageAdaptor.php b/modules/core/lib/Auth/Process/LanguageAdaptor.php index 64cef588417175d160f661cb6d6c1226d98c8481..85271d1659b8b6094b6d7a8be1f00e6e8ff4baf2 100644 --- a/modules/core/lib/Auth/Process/LanguageAdaptor.php +++ b/modules/core/lib/Auth/Process/LanguageAdaptor.php @@ -57,10 +57,10 @@ class LanguageAdaptor extends \SimpleSAML\Auth\ProcessingFilter $lang = Language::getLanguageCookie(); if (isset($attrlang)) { - Logger::debug('LanguageAdaptor: Language in attribute was set ['.$attrlang.']'); + Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']'); } if (isset($lang)) { - Logger::debug('LanguageAdaptor: Language in session was set ['.$lang.']'); + Logger::debug('LanguageAdaptor: Language in session was set [' . $lang . ']'); } if (isset($attrlang) && !isset($lang)) { diff --git a/modules/core/lib/Auth/Process/PHP.php b/modules/core/lib/Auth/Process/PHP.php index 77d8266affc46a9998cfb74d9278d660013e04a8..fcf6e738aed078620c913b05147df83c6d177a0f 100644 --- a/modules/core/lib/Auth/Process/PHP.php +++ b/modules/core/lib/Auth/Process/PHP.php @@ -46,6 +46,8 @@ class PHP extends \SimpleSAML\Auth\ProcessingFilter * * @param array &$request The current request * @return void + * + * @scrutinizer ignore-unused */ public function process(&$request) { @@ -57,9 +59,7 @@ class PHP extends \SimpleSAML\Auth\ProcessingFilter * @param array &$state */ $function = /** @return void */ function ( - /** @scrutinizer ignore-unused */ array &$attributes, - /** @scrutinizer ignore-unused */ array &$state ) { eval($this->code); diff --git a/modules/core/lib/Auth/Process/ScopeAttribute.php b/modules/core/lib/Auth/Process/ScopeAttribute.php index 22bfa90aa0a87ff17e3726c07a4bab98bbfa1707..bc05f95388c74049428153b1428e9120fdc61d0a 100644 --- a/modules/core/lib/Auth/Process/ScopeAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeAttribute.php @@ -97,7 +97,7 @@ class ScopeAttribute extends \SimpleSAML\Auth\ProcessingFilter } foreach ($attributes[$this->sourceAttribute] as $value) { - $value = $value.'@'.$scope; + $value = $value . '@' . $scope; if (in_array($value, $attributes[$this->targetAttribute], true)) { // Already present diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php index 54c9aa4cbf02a1c6d84257763e088b19041bf25a..cc8411e311849198510d15d1b37325392d6c1ce7 100644 --- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php @@ -52,7 +52,7 @@ class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter $cfg = Configuration::loadFromArray($config, 'ScopeFromAttribute'); $this->targetAttribute = $cfg->getString('targetAttribute'); $this->sourceAttribute = $cfg->getString('sourceAttribute'); - } // end constructor + } /** @@ -88,12 +88,12 @@ class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter $attributes[$this->targetAttribute] = []; $scope = substr($sourceAttrVal, $scopeIndex + 1); $attributes[$this->targetAttribute][] = $scope; - Logger::debug('ScopeFromAttribute: Inserted new attribute '. - $this->targetAttribute.', with scope '.$scope); + Logger::debug( + 'ScopeFromAttribute: Inserted new attribute ' . $this->targetAttribute . ', with scope ' . $scope + ); } else { - Logger::warning('ScopeFromAttribute: The configured source attribute '. - $this->sourceAttribute.' does not have a scope. Did not add attribute '. - $this->targetAttribute.'.'); + Logger::warning('ScopeFromAttribute: The configured source attribute ' . $this->sourceAttribute + . ' does not have a scope. Did not add attribute ' . $this->targetAttribute . '.'); } - } // end process + } } diff --git a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php index 862e0c0d03782b8e589ab076e73026bc02e02336..63d0a62d89f4a3af52fdd8a0111c884e11869fed 100644 --- a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php +++ b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php @@ -92,10 +92,10 @@ class StatisticsWithAttribute extends \SimpleSAML\Auth\ProcessingFilter if (!array_key_exists('PreviousSSOTimestamp', $state)) { // The user hasn't authenticated with this SP earlier in this session - Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '.$logAttribute); + Logger::stats($isPassive . $this->typeTag . '-first ' . $dest . ' ' . $source . ' ' . $logAttribute); } - Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute); + Logger::stats($isPassive . $this->typeTag . ' ' . $dest . ' ' . $source . ' ' . $logAttribute); } /** diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php index 1ad7d20280ff346d69b1727f7ddbc1b692102eb0..950f02f9ba3a5c8a3420fb6f215546b98f4fba53 100644 --- a/modules/core/lib/Auth/Process/TargetedID.php +++ b/modules/core/lib/Auth/Process/TargetedID.php @@ -93,15 +93,15 @@ class TargetedID extends \SimpleSAML\Auth\ProcessingFilter if ($this->attribute === null) { if (!array_key_exists('UserID', $state)) { - throw new \Exception('core:TargetedID: Missing UserID for this user. Please'. - ' check the \'userid.attribute\' option in the metadata against the'. + throw new \Exception('core:TargetedID: Missing UserID for this user. Please' . + ' check the \'userid.attribute\' option in the metadata against the' . ' attributes provided by the authentication source.'); } $userID = $state['UserID']; } else { if (!array_key_exists($this->attribute, $state['Attributes'])) { - throw new \Exception('core:TargetedID: Missing attribute \''.$this->attribute. + throw new \Exception('core:TargetedID: Missing attribute \'' . $this->attribute . '\', which is needed to generate the targeted ID.'); } @@ -123,10 +123,10 @@ class TargetedID extends \SimpleSAML\Auth\ProcessingFilter $dstID = ''; } - $uidData = 'uidhashbase'.$secretSalt; - $uidData .= strlen($srcID).':'.$srcID; - $uidData .= strlen($dstID).':'.$dstID; - $uidData .= strlen($userID).':'.$userID; + $uidData = 'uidhashbase' . $secretSalt; + $uidData .= strlen($srcID) . ':' . $srcID; + $uidData .= strlen($dstID) . ':' . $dstID; + $uidData .= strlen($userID) . ':' . $userID; $uidData .= $secretSalt; $uid = hash('sha1', $uidData); @@ -168,12 +168,12 @@ class TargetedID extends \SimpleSAML\Auth\ProcessingFilter if (array_key_exists('metadata-set', $metadata)) { $set = $metadata['metadata-set']; - $id .= 'set'.strlen($set).':'.$set; + $id .= 'set' . strlen($set) . ':' . $set; } if (array_key_exists('entityid', $metadata)) { $entityid = $metadata['entityid']; - $id .= 'set'.strlen($entityid).':'.$entityid; + $id .= 'set' . strlen($entityid) . ':' . $entityid; } return $id; diff --git a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php index d79783e86ff9c08c3ada39ed957680aebf37e6ed..5c5352d1b1bb070837b36b29fea7ac502e1afd1a 100644 --- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php +++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php @@ -47,8 +47,8 @@ class WarnShortSSOInterval extends \SimpleSAML\Auth\ProcessingFilter $entityId = 'UNKNOWN'; } - Logger::warning('WarnShortSSOInterval: Only '.$timeDelta. - ' seconds since last SSO for this user from the SP '.var_export($entityId, true)); + Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta . + ' seconds since last SSO for this user from the SP ' . var_export($entityId, true)); // Save state and redirect $id = Auth\State::saveState($state, 'core:short_sso_interval'); diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php index b3477aafe3acec9ee5da338f233f8a33b493577b..90104e5f14d2999a5b0b04f2fccfc3672c62f2fa 100644 --- a/modules/core/lib/Auth/UserPassBase.php +++ b/modules/core/lib/Auth/UserPassBase.php @@ -303,7 +303,7 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source /** @var \SimpleSAML\Module\core\Auth\UserPassBase|null $source */ $source = Auth\Source::getById($state[self::AUTHID]); if ($source === null) { - throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]); + throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } /* @@ -315,11 +315,11 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source try { $attributes = $source->login($username, $password); } catch (\Exception $e) { - Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.'); + Logger::stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); throw $e; } - Logger::stats('User \''.$username.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']); + Logger::stats('User \'' . $username . '\' successfully authenticated from ' . $_SERVER['REMOTE_ADDR']); // Save the attributes we received from the login-function in the $state-array assert(is_array($attributes)); diff --git a/modules/core/lib/Auth/UserPassOrgBase.php b/modules/core/lib/Auth/UserPassOrgBase.php index 552e9165023713a4b267dbab88546fcd8120350d..8271c8809b14eb5076a7dcdc7651f92b749cef3b 100644 --- a/modules/core/lib/Auth/UserPassOrgBase.php +++ b/modules/core/lib/Auth/UserPassOrgBase.php @@ -4,6 +4,7 @@ namespace SimpleSAML\Module\core\Auth; use SimpleSAML\Auth; use SimpleSAML\Error; +use SimpleSAML\Logger; use SimpleSAML\Module; use SimpleSAML\Utils; @@ -287,7 +288,7 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source /** @var \SimpleSAML\Module\core\Auth\UserPassOrgBase|null $source */ $source = Auth\Source::getById($state[self::AUTHID]); if ($source === null) { - throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]); + throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } $orgMethod = $source->getUsernameOrgMethod(); @@ -308,11 +309,14 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source try { $attributes = $source->login($username, $password, $organization); } catch (\Exception $e) { - \SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.'); + Logger::stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); throw $e; } - \SimpleSAML\Logger::stats('User \''.$username.'\' at \''.$organization.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']); + Logger::stats( + 'User \'' . $username . '\' at \'' . $organization + . '\' successfully authenticated from ' . $_SERVER['REMOTE_ADDR'] + ); // Add the selected Org to the state $state[self::ORGID] = $organization; @@ -346,7 +350,7 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source /** @var \SimpleSAML\Module\core\Auth\UserPassOrgBase|null $source */ $source = Auth\Source::getById($state[self::AUTHID]); if ($source === null) { - throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]); + throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } $orgMethod = $source->getUsernameOrgMethod(); diff --git a/modules/core/lib/Controller.php b/modules/core/lib/Controller.php index 913fe4ec7b2c9e783dd28b673e7817c0316844e0..a9737edb47cf44ab2cd0930f39cb743d5bddd3de 100644 --- a/modules/core/lib/Controller.php +++ b/modules/core/lib/Controller.php @@ -78,7 +78,7 @@ class Controller $auth = $this->factory->create($as); if (!$auth->isAuthenticated()) { // not authenticated, start auth with specified source - return new RedirectResponse(Module::getModuleURL('core/login/'.urlencode($as))); + return new RedirectResponse(Module::getModuleURL('core/login/' . urlencode($as))); } $attributes = $auth->getAttributes(); @@ -95,7 +95,7 @@ class Controller : false; $t->data['authData'] = $auth->getAuthDataArray(); $t->data['trackid'] = $session->getTrackID(); - $t->data['logouturl'] = Module::getModuleURL('core/logout/'.urlencode($as)); + $t->data['logouturl'] = Module::getModuleURL('core/logout/' . urlencode($as)); $t->data['remaining'] = $this->session->getAuthData($as, 'Expire') - time(); $t->setStatusCode(200); @@ -157,11 +157,11 @@ class Controller } if ($auth->isAuthenticated()) { - return new RedirectResponse(Module::getModuleURL('core/account/'.$as)); + return new RedirectResponse(Module::getModuleURL('core/account/' . $as)); } // we're not logged in, start auth - $url = Module::getModuleURL('core/login/'.$as); + $url = Module::getModuleURL('core/login/' . $as); $params = array( 'ErrorURL' => $url, 'ReturnTo' => $url, @@ -182,6 +182,6 @@ class Controller public function logout($as) { $auth = new Auth\Simple($as); - return new RunnableResponse([$auth, 'logout'], [$this->config->getBasePath().'logout.php']); + return new RunnableResponse([$auth, 'logout'], [$this->config->getBasePath() . 'logout.php']); } } diff --git a/modules/core/lib/Stats/Output/File.php b/modules/core/lib/Stats/Output/File.php index 00913cdf24f66e5671901d39648f974753e7815e..30a97e1722cfe45f7d204f8053b00efc7f894f9c 100644 --- a/modules/core/lib/Stats/Output/File.php +++ b/modules/core/lib/Stats/Output/File.php @@ -43,7 +43,7 @@ class File extends \SimpleSAML\Stats\Output throw new \Exception('Missing "directory" option for core:File'); } if (!is_dir($logDir)) { - throw new \Exception('Could not find log directory: '.var_export($logDir, true)); + throw new \Exception('Could not find log directory: ' . var_export($logDir, true)); } $this->logDir = $logDir; } @@ -64,10 +64,10 @@ class File extends \SimpleSAML\Stats\Output $this->file = null; } - $fileName = $this->logDir.'/'.$date.'.log'; + $fileName = $this->logDir . '/' . $date . '.log'; $fh = @fopen($fileName, 'a'); if ($fh === false) { - throw new Error\Exception('Error opening log file: '.var_export($fileName, true)); + throw new Error\Exception('Error opening log file: ' . var_export($fileName, true)); } // Disable output buffering @@ -91,7 +91,7 @@ class File extends \SimpleSAML\Stats\Output $time = $data['time']; $milliseconds = (int) (($time - (int) $time) * 1000); - $timestamp = gmdate('Y-m-d\TH:i:s', $time).sprintf('.%03dZ', $milliseconds); + $timestamp = gmdate('Y-m-d\TH:i:s', $time) . sprintf('.%03dZ', $milliseconds); $outDate = substr($timestamp, 0, 10); // The date-part of the timstamp @@ -99,7 +99,7 @@ class File extends \SimpleSAML\Stats\Output $this->openLog($outDate); } - $line = $timestamp.' '.json_encode($data)."\n"; + $line = $timestamp . ' ' . json_encode($data) . "\n"; /** @psalm-suppress PossiblyNullArgument */ fwrite($this->file, $line); } diff --git a/modules/core/lib/Stats/Output/Log.php b/modules/core/lib/Stats/Output/Log.php index 0bf5603131d16d313ab419be952452835e797a23..0175c2328a9bd5a548cd5531cd4fa6328496f2d9 100644 --- a/modules/core/lib/Stats/Output/Log.php +++ b/modules/core/lib/Stats/Output/Log.php @@ -30,7 +30,7 @@ class Log extends \SimpleSAML\Stats\Output $logLevel = $config->getString('level', 'notice'); $this->logger = [Logger::class, $logLevel]; if (!is_callable($this->logger)) { - throw new \Exception('Invalid log level: '.var_export($logLevel, true)); + throw new \Exception('Invalid log level: ' . var_export($logLevel, true)); } } @@ -44,6 +44,6 @@ class Log extends \SimpleSAML\Stats\Output public function emit(array $data) { $str_data = json_encode($data); - call_user_func($this->logger, 'EVENT '.$str_data); + call_user_func($this->logger, 'EVENT ' . $str_data); } } diff --git a/modules/core/lib/Storage/SQLPermanentStorage.php b/modules/core/lib/Storage/SQLPermanentStorage.php index 6bce0baf22f484f389f5dc38a7343063e85284b1..1ff18f8ab344a8ad58879a4b8ebb2e6aa09845d4 100644 --- a/modules/core/lib/Storage/SQLPermanentStorage.php +++ b/modules/core/lib/Storage/SQLPermanentStorage.php @@ -35,17 +35,17 @@ class SQLPermanentStorage $datadir = $config->getPathValue('datadir', 'data/') ?: 'data/'; if (!is_dir($datadir)) { - throw new \Exception('Data directory ['.$datadir.'] does not exist'); + throw new \Exception('Data directory [' . $datadir . '] does not exist'); } elseif (!is_writable($datadir)) { - throw new \Exception('Data directory ['.$datadir.'] is not writable'); + throw new \Exception('Data directory [' . $datadir . '] is not writable'); } - $sqllitedir = $datadir.'sqllite/'; + $sqllitedir = $datadir . 'sqllite/'; if (!is_dir($sqllitedir)) { mkdir($sqllitedir); } - $dbfile = 'sqlite:'.$sqllitedir.$name.'.sqlite'; + $dbfile = 'sqlite:' . $sqllitedir . $name . '.sqlite'; if ($this->db = new PDO($dbfile)) { $q = @$this->db->query('SELECT key1 FROM data LIMIT 1'); if ($q === false) { @@ -63,7 +63,7 @@ class SQLPermanentStorage '); } } else { - throw new \Exception('Error creating SQL lite database ['.$dbfile.'].'); + throw new \Exception('Error creating SQL lite database [' . $dbfile . '].'); } } @@ -98,13 +98,14 @@ class SQLPermanentStorage { $expire = is_null($duration) ? null : (time() + $duration); - $query = "INSERT INTO data (key1, key2, type, created, updated, expire, value)". + $query = "INSERT INTO data (key1, key2, type, created, updated, expire, value)" . " VALUES(:key1, :key2, :type, :created, :updated, :expire, :value)"; $prepared = $this->db->prepare($query); $data = [':key1' => $key1, ':key2' => $key2, ':type' => $type, ':created' => time(), ':updated' => time(), ':expire' => $expire, - ':value' => serialize($value)]; + ':value' => serialize($value) + ]; $prepared->execute($data); $results = $prepared->fetchAll(PDO::FETCH_ASSOC); return $results; @@ -123,12 +124,13 @@ class SQLPermanentStorage { $expire = is_null($duration) ? null : (time() + $duration); - $query = "UPDATE data SET updated = :updated, value = :value, ". + $query = "UPDATE data SET updated = :updated, value = :value, " . "expire = :expire WHERE key1 = :key1 AND key2 = :key2 AND type = :type"; $prepared = $this->db->prepare($query); $data = [':key1' => $key1, ':key2' => $key2, ':type' => $type, ':updated' => time(), - ':expire' => $expire, ':value' => serialize($value)]; + ':expire' => $expire, ':value' => serialize($value) + ]; $prepared->execute($data); $results = $prepared->fetchAll(PDO::FETCH_ASSOC); return $results; @@ -144,7 +146,7 @@ class SQLPermanentStorage public function get($type = null, $key1 = null, $key2 = null) { $conditions = $this->getCondition($type, $key1, $key2); - $query = 'SELECT * FROM data WHERE '.$conditions; + $query = 'SELECT * FROM data WHERE ' . $conditions; $prepared = $this->db->prepare($query); $prepared->execute(); @@ -202,7 +204,7 @@ class SQLPermanentStorage public function getList($type = null, $key1 = null, $key2 = null) { $conditions = $this->getCondition($type, $key1, $key2); - $query = 'SELECT * FROM data WHERE '.$conditions; + $query = 'SELECT * FROM data WHERE ' . $conditions; $prepared = $this->db->prepare($query); $prepared->execute(); @@ -233,7 +235,7 @@ class SQLPermanentStorage } $conditions = $this->getCondition($type, $key1, $key2); - $query = 'SELECT DISTINCT :whichKey FROM data WHERE '.$conditions; + $query = 'SELECT DISTINCT :whichKey FROM data WHERE ' . $conditions; $prepared = $this->db->prepare($query); $data = ['whichKey' => $whichKey]; $prepared->execute($data); @@ -291,16 +293,16 @@ class SQLPermanentStorage { $conditions = []; if (!is_null($type)) { - $conditions[] = "type = ".$this->db->quote($type); + $conditions[] = "type = " . $this->db->quote($type); } if (!is_null($key1)) { - $conditions[] = "key1 = ".$this->db->quote($key1); + $conditions[] = "key1 = " . $this->db->quote($key1); } if (!is_null($key2)) { - $conditions[] = "key2 = ".$this->db->quote($key2); + $conditions[] = "key2 = " . $this->db->quote($key2); } - $conditions[] = "(expire IS NULL OR expire >= ".time().")"; + $conditions[] = "(expire IS NULL OR expire >= " . time() . ")"; return join(' AND ', $conditions); } } diff --git a/modules/core/www/authenticate.php b/modules/core/www/authenticate.php index 03b461fcdd384622347666b2d2aa91c3523477e6..4658cb151c4291d0b1c7c7851488dc5a9373d62e 100644 --- a/modules/core/www/authenticate.php +++ b/modules/core/www/authenticate.php @@ -14,7 +14,7 @@ $asId = (string) $_REQUEST['as']; $as = new \SimpleSAML\Auth\Simple($asId); if (array_key_exists('logout', $_REQUEST)) { - $as->logout($config->getBasePath().'logout.php'); + $as->logout($config->getBasePath() . 'logout.php'); } if (array_key_exists(\SimpleSAML\Auth\State::EXCEPTION_PARAM, $_REQUEST)) { @@ -47,5 +47,5 @@ $t->data['header'] = '{status:header_saml20_sp}'; $t->data['attributes'] = $attributes; $t->data['authData'] = $authData; $t->data['nameid'] = !is_null($as->getAuthData('saml:sp:NameID')) ? $as->getAuthData('saml:sp:NameID') : false; -$t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery().'?as='.urlencode($asId).'&logout'; +$t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery() . '?as=' . urlencode($asId) . '&logout'; $t->show(); diff --git a/modules/core/www/cardinality_error.php b/modules/core/www/cardinality_error.php index 7ce8cce96fa7d28d356f1fbba523e781447e471b..cb76a072ef90ba7fb08b0fb01a3228c1b4b57e36 100644 --- a/modules/core/www/cardinality_error.php +++ b/modules/core/www/cardinality_error.php @@ -14,8 +14,8 @@ $id = $_REQUEST['StateId']; $state = \SimpleSAML\Auth\State::loadState($id, 'core:cardinality'); $session = \SimpleSAML\Session::getSessionFromRequest(); -\SimpleSAML\Logger::stats('core:cardinality:error '.$state['Destination']['entityid'].' '.$state['saml:sp:IdP']. - ' '.implode(',', array_keys($state['core:cardinality:errorAttributes']))); +\SimpleSAML\Logger::stats('core:cardinality:error ' . $state['Destination']['entityid'] + . ' ' . $state['saml:sp:IdP'] . ' ' . implode(',', array_keys($state['core:cardinality:errorAttributes']))); $globalConfig = \SimpleSAML\Configuration::getInstance(); $t = new \SimpleSAML\XHTML\Template($globalConfig, 'core:cardinality_error.tpl.php'); @@ -24,7 +24,7 @@ if (isset($state['Source']['auth'])) { $t->data['LogoutURL'] = \SimpleSAML\Module::getModuleURL( 'core/authenticate.php', ['as' => $state['Source']['auth']] - )."&logout"; + ) . "&logout"; } header('HTTP/1.0 403 Forbidden'); $t->show(); diff --git a/modules/core/www/frontpage_config.php b/modules/core/www/frontpage_config.php index 3ed2fffce938bdd2935a31f66584f3fac84ef6fa..2ede138cdccdaa4015e786c938c008857b9d489b 100644 --- a/modules/core/www/frontpage_config.php +++ b/modules/core/www/frontpage_config.php @@ -36,12 +36,12 @@ $links_auth = []; $links_federation = []; $links_config[] = [ - 'href' => \SimpleSAML\Utils\HTTP::getBaseURL().'admin/hostnames.php', + 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/hostnames.php', 'text' => '{core:frontpage:link_diagnostics}' ]; $links_config[] = [ - 'href' => \SimpleSAML\Utils\HTTP::getBaseURL().'admin/phpinfo.php', + 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/phpinfo.php', 'text' => '{core:frontpage:link_phpinfo}' ]; @@ -53,7 +53,7 @@ $allLinks = [ 'federation' => &$links_federation, ]; \SimpleSAML\Module::callHooks('frontpage', $allLinks); -\SimpleSAML\Logger::debug('The "frontpage" hook has been deprecated for the configuration page. Implement the '. +\SimpleSAML\Logger::debug('The "frontpage" hook has been deprecated for the configuration page. Implement the ' . '"configpage" hook instead.'); // Check for updates. Store the remote result in the session so we @@ -67,7 +67,7 @@ if ($config->getBoolean('admin.checkforupdates', true) && $current !== 'master') if (!$latest) { $api_url = 'https://api.github.com/repos/simplesamlphp/simplesamlphp/releases'; - $ch = curl_init($api_url.'/latest'); + $ch = curl_init($api_url . '/latest'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'SimpleSAMLphp'); curl_setopt($ch, CURLOPT_TIMEOUT, 2); @@ -123,7 +123,7 @@ if (\SimpleSAML\Module::isModuleEnabled('radius')) { $funcmatrix = []; $funcmatrix[] = [ 'required' => 'required', - 'descr' => 'PHP Version >= 5.6. You run: '.phpversion(), + 'descr' => 'PHP Version >= 5.6. You run: ' . phpversion(), 'enabled' => version_compare(phpversion(), '5.6', '>=') ]; foreach ($functionchecks as $func => $descr) { diff --git a/modules/core/www/frontpage_federation.php b/modules/core/www/frontpage_federation.php index 6376d06e65cff838f565b581a0ab91bb8e3bb64a..72e98ea8cd39c3d90fce32d384bda90396470210 100644 --- a/modules/core/www/frontpage_federation.php +++ b/modules/core/www/frontpage_federation.php @@ -27,7 +27,7 @@ if ($config->getBoolean('idpdisco.enableremember', false)) { $links_federation[] = [ - 'href' => \SimpleSAML\Utils\HTTP::getBaseURL().'admin/metadata-converter.php', + 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/metadata-converter.php', 'text' => '{core:frontpage:link_xmlconvert}', ]; @@ -59,24 +59,24 @@ if ($config->getBoolean('enable.saml20-idp', false) === true) { try { $metaentries['hosted']['saml20-idp'] = $metadata->getMetaDataCurrent('saml20-idp-hosted'); $metaentries['hosted']['saml20-idp']['metadata-url'] = - $config->getBasePath().'saml2/idp/metadata.php?output=xhtml'; + $config->getBasePath() . 'saml2/idp/metadata.php?output=xhtml'; if ($isadmin) { $metaentries['remote']['saml20-sp-remote'] = $metadata->getList('saml20-sp-remote', true); } } catch (Exception $e) { - \SimpleSAML\Logger::error('Federation: Error loading saml20-idp: '.$e->getMessage()); + \SimpleSAML\Logger::error('Federation: Error loading saml20-idp: ' . $e->getMessage()); } } if ($config->getBoolean('enable.shib13-idp', false) === true) { try { $metaentries['hosted']['shib13-idp'] = $metadata->getMetaDataCurrent('shib13-idp-hosted'); $metaentries['hosted']['shib13-idp']['metadata-url'] = - $config->getBasePath().'shib13/idp/metadata.php?output=xhtml'; + $config->getBasePath() . 'shib13/idp/metadata.php?output=xhtml'; if ($isadmin) { $metaentries['remote']['shib13-sp-remote'] = $metadata->getList('shib13-sp-remote', true); } } catch (Exception $e) { - \SimpleSAML\Logger::error('Federation: Error loading shib13-idp: '.$e->getMessage()); + \SimpleSAML\Logger::error('Federation: Error loading shib13-idp: ' . $e->getMessage()); } } if ($config->getBoolean('enable.adfs-idp', false) === true) { @@ -90,7 +90,7 @@ if ($config->getBoolean('enable.adfs-idp', false) === true) { $metaentries['remote']['adfs-sp-remote'] = $metadata->getList('adfs-sp-remote', true); } } catch (Exception $e) { - \SimpleSAML\Logger::error('Federation: Error loading adfs-idp: '.$e->getMessage()); + \SimpleSAML\Logger::error('Federation: Error loading adfs-idp: ' . $e->getMessage()); } } diff --git a/modules/core/www/idp/logout-iframe-done.php b/modules/core/www/idp/logout-iframe-done.php index 7725754e48b0e10d2b3e468274b640a42ed41a93..92733d00ad5d692c7b512c674cd57b55506a36fc 100644 --- a/modules/core/www/idp/logout-iframe-done.php +++ b/modules/core/www/idp/logout-iframe-done.php @@ -22,7 +22,7 @@ if (!isset($_REQUEST['cancel'])) { // find the status of all SPs foreach ($SPs as $assocId => &$sp) { - $spId = 'logout-iframe-'.sha1($assocId); + $spId = 'logout-iframe-' . sha1($assocId); if (isset($_REQUEST[$spId])) { $spStatus = $_REQUEST[$spId]; @@ -42,13 +42,13 @@ foreach ($SPs as $assocId => $sp) { if ($sp['core:Logout-IFrame:State'] === 'completed') { $idp->terminateAssociation($assocId); } else { - \SimpleSAML\Logger::warning('Unable to terminate association with '.var_export($assocId, true).'.'); + \SimpleSAML\Logger::warning('Unable to terminate association with ' . var_export($assocId, true) . '.'); if (isset($sp['saml:entityID'])) { $spId = $sp['saml:entityID']; } else { $spId = $assocId; } - \SimpleSAML\Logger::stats('slo-iframe-fail '.$spId); + \SimpleSAML\Logger::stats('slo-iframe-fail ' . $spId); \SimpleSAML\Stats::log('core:idp:logout-iframe:spfail', ['sp' => $spId]); $state['core:Failed'] = true; } diff --git a/modules/core/www/idp/logout-iframe.php b/modules/core/www/idp/logout-iframe.php index ea0024942a2158205a7c12d60d46d25c7a5e813f..8f38c891f3984e3f09fc1879a70467d2cb425358 100644 --- a/modules/core/www/idp/logout-iframe.php +++ b/modules/core/www/idp/logout-iframe.php @@ -14,7 +14,7 @@ if (isset($_REQUEST['type'])) { } if ($type !== 'embed') { - \SimpleSAML\Logger::stats('slo-iframe '.$type); + \SimpleSAML\Logger::stats('slo-iframe ' . $type); \SimpleSAML\Stats::log('core:idp:logout-iframe:page', ['type' => $type]); } diff --git a/modules/core/www/loginuserpass.php b/modules/core/www/loginuserpass.php index ce14bf1ed0dcfc6968966e86fc37d6ca507fe2c0..5db61c91fcb9a52cb2a4ec4764bd51e0c106973b 100644 --- a/modules/core/www/loginuserpass.php +++ b/modules/core/www/loginuserpass.php @@ -21,14 +21,14 @@ $state = \SimpleSAML\Auth\State::loadState($authStateId, \SimpleSAML\Module\core $source = \SimpleSAML\Auth\Source::getById($state[\SimpleSAML\Module\core\Auth\UserPassBase::AUTHID]); if ($source === null) { throw new \Exception( - 'Could not find authentication source with id '.$state[\SimpleSAML\Module\core\Auth\UserPassBase::AUTHID] + 'Could not find authentication source with id ' . $state[\SimpleSAML\Module\core\Auth\UserPassBase::AUTHID] ); } if (array_key_exists('username', $_REQUEST)) { $username = $_REQUEST['username']; -} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId().'-username', $_COOKIE)) { - $username = $_COOKIE[$source->getAuthId().'-username']; +} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId() . '-username', $_COOKIE)) { + $username = $_COOKIE[$source->getAuthId() . '-username']; } elseif (isset($state['core:username'])) { $username = (string) $state['core:username']; } else { @@ -67,7 +67,7 @@ if (!empty($_REQUEST['username']) || !empty($password)) { } else { $params['expire'] = time() - 300; } - \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId().'-username', $username, $params, false); + \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId() . '-username', $username, $params, false); } if ($source->isRememberMeEnabled()) { @@ -115,7 +115,7 @@ if (array_key_exists('forcedUsername', $state)) { $t->data['rememberUsernameChecked'] = $source->getRememberUsernameChecked(); $t->data['rememberMeEnabled'] = $source->isRememberMeEnabled(); $t->data['rememberMeChecked'] = $source->isRememberMeChecked(); - if (isset($_COOKIE[$source->getAuthId().'-username'])) { + if (isset($_COOKIE[$source->getAuthId() . '-username'])) { $t->data['rememberUsernameChecked'] = true; } } diff --git a/modules/core/www/loginuserpassorg.php b/modules/core/www/loginuserpassorg.php index e9423c71c9e0c6184a7c844350d2d3cec1cbf704..fd65a15dbe1eb1643a4de571e33b4317c6a84cad 100644 --- a/modules/core/www/loginuserpassorg.php +++ b/modules/core/www/loginuserpassorg.php @@ -22,7 +22,7 @@ $state = \SimpleSAML\Auth\State::loadState($authStateId, \SimpleSAML\Module\core $source = \SimpleSAML\Auth\Source::getById($state[\SimpleSAML\Module\core\Auth\UserPassOrgBase::AUTHID]); if ($source === null) { throw new \Exception( - 'Could not find authentication source with id '.$state[\SimpleSAML\Module\core\Auth\UserPassOrgBase::AUTHID] + 'Could not find authentication source with id ' . $state[\SimpleSAML\Module\core\Auth\UserPassOrgBase::AUTHID] ); } @@ -30,8 +30,8 @@ $organizations = \SimpleSAML\Module\core\Auth\UserPassOrgBase::listOrganizations if (array_key_exists('username', $_REQUEST)) { $username = $_REQUEST['username']; -} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId().'-username', $_COOKIE)) { - $username = $_COOKIE[$source->getAuthId().'-username']; +} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId() . '-username', $_COOKIE)) { + $username = $_COOKIE[$source->getAuthId() . '-username']; } elseif (isset($state['core:username'])) { $username = (string) $state['core:username']; } else { @@ -46,10 +46,11 @@ if (array_key_exists('password', $_REQUEST)) { if (array_key_exists('organization', $_REQUEST)) { $organization = $_REQUEST['organization']; -} elseif ($source->getRememberOrganizationEnabled() && - array_key_exists($source->getAuthId().'-organization', $_COOKIE) - ) { - $organization = $_COOKIE[$source->getAuthId().'-organization']; +} elseif ( + $source->getRememberOrganizationEnabled() + && array_key_exists($source->getAuthId() . '-organization', $_COOKIE) +) { + $organization = $_COOKIE[$source->getAuthId() . '-organization']; } elseif (isset($state['core:organization'])) { $organization = (string) $state['core:organization']; } else { @@ -77,7 +78,7 @@ if ($organizations === null || !empty($organization)) { $params['expire'] = time() - 300; } - \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId().'-username', $username, $params, false); + \SimpleSAML\Utils\HTTP::setCookie($source->getAuthId() . '-username', $username, $params, false); } if ($source->getRememberOrganizationEnabled()) { @@ -89,7 +90,7 @@ if ($organizations === null || !empty($organization)) { $params['expire'] = time() - 300; } setcookie( - $source->getAuthId().'-organization', + $source->getAuthId() . '-organization', $organization, $params['expire'], $params['path'], @@ -135,12 +136,12 @@ $t->data['rememberUsernameEnabled'] = $source->getRememberUsernameEnabled(); $t->data['rememberUsernameChecked'] = $source->getRememberUsernameChecked(); $t->data['rememberMeEnabled'] = false; $t->data['rememberMeChecked'] = false; -if (isset($_COOKIE[$source->getAuthId().'-username'])) { +if (isset($_COOKIE[$source->getAuthId() . '-username'])) { $t->data['rememberUsernameChecked'] = true; } $t->data['rememberOrganizationEnabled'] = $source->getRememberOrganizationEnabled(); $t->data['rememberOrganizationChecked'] = $source->getRememberOrganizationChecked(); -if (isset($_COOKIE[$source->getAuthId().'-organization'])) { +if (isset($_COOKIE[$source->getAuthId() . '-organization'])) { $t->data['rememberOrganizationChecked'] = true; } $t->data['errorcode'] = $errorCode; diff --git a/modules/core/www/show_metadata.php b/modules/core/www/show_metadata.php index e8f3bf223e91b45cad24bda780d99983a0e9ef75..ffad6572b2a3d9ed30e46d02420b276bfefc5649 100644 --- a/modules/core/www/show_metadata.php +++ b/modules/core/www/show_metadata.php @@ -12,11 +12,13 @@ if (!array_key_exists('entityid', $_REQUEST)) { if (!array_key_exists('set', $_REQUEST)) { throw new Exception('required parameter [set] missing'); } -if (!in_array( - $_REQUEST['set'], - ['saml20-idp-remote', 'saml20-sp-remote', 'shib13-idp-remote', 'shib13-sp-remote'], - true -)) { +if ( + !in_array( + $_REQUEST['set'], + ['saml20-idp-remote', 'saml20-sp-remote', 'shib13-idp-remote', 'shib13-sp-remote'], + true + ) +) { throw new Exception('Invalid set'); } diff --git a/modules/cron/bin/cron.php b/modules/cron/bin/cron.php index 61e690e0fd05f42be515dd2f5ff4cc208e6829ed..436397fd296f60cc0265ad5c36fe6f460d83cedf 100755 --- a/modules/cron/bin/cron.php +++ b/modules/cron/bin/cron.php @@ -11,12 +11,12 @@ $baseDir = dirname(dirname(dirname(dirname(__FILE__)))); // Add library autoloader. -require_once($baseDir.'/lib/_autoload.php'); +require_once($baseDir . '/lib/_autoload.php'); if (!SimpleSAML\Module::isModuleEnabled('cron')) { echo "You need to enable the cron module before this script can be used.\n"; echo "You can enable it by running the following command:\n"; - echo ' echo >"'.$baseDir.'/modules/cron/enable'."\"\n"; + echo ' echo >"' . $baseDir . '/modules/cron/enable' . "\"\n"; exit(1); } @@ -35,7 +35,7 @@ if (!array_key_exists('t', $options)) { $tag = $options['t']; $cron = new SimpleSAML\Module\cron\Cron(); if (!$cron->isValidTag($tag)) { - echo "Invalid tag option '$tag'.\n"; + echo "Invalid tag option '$tag' . \n"; exit(2); } diff --git a/modules/cron/hooks/hook_cron.php b/modules/cron/hooks/hook_cron.php index eb4718275f11e04da59d7f5f8c0b4e292f0ec3ec..a135360764f5f724e545e2c9df274c3c3e9d9fb6 100644 --- a/modules/cron/hooks/hook_cron.php +++ b/modules/cron/hooks/hook_cron.php @@ -15,6 +15,6 @@ function cron_hook_cron(&$croninfo) $cronconfig = \SimpleSAML\Configuration::getConfig('module_cron.php'); if ($cronconfig->getValue('debug_message', true)) { - $croninfo['summary'][] = 'Cron did run tag ['.$croninfo['tag'].'] at '.date(DATE_RFC822); + $croninfo['summary'][] = 'Cron did run tag [' . $croninfo['tag'] . '] at ' . date(DATE_RFC822); } } diff --git a/modules/cron/hooks/hook_frontpage.php b/modules/cron/hooks/hook_frontpage.php index 9a0401a275bb7dab7987008b725f7dc6a20e730e..2de5d22e2ff803d1b0c1752a6319773b6d7cdce3 100644 --- a/modules/cron/hooks/hook_frontpage.php +++ b/modules/cron/hooks/hook_frontpage.php @@ -16,4 +16,3 @@ function cron_hook_frontpage(&$links) 'text' => '{cron:cron:link_cron}', ]; } - diff --git a/modules/cron/lib/Cron.php b/modules/cron/lib/Cron.php index bbaa4e7c34300c1763c51a9d395cd6683e3abfb6..32143157624bf168fc4bb694cf9831400901b03f 100644 --- a/modules/cron/lib/Cron.php +++ b/modules/cron/lib/Cron.php @@ -51,7 +51,7 @@ class Cron Module::callHooks('cron', $croninfo); foreach ($summary as $s) { - Logger::debug('Cron - Summary: '.$s); + Logger::debug('Cron - Summary: ' . $s); } return $croninfo; diff --git a/modules/cron/www/cron.php b/modules/cron/www/cron.php index 2f0dae8b5113a3e3b41da929e1046bcde3c5fb70..2afe851fbc9230f1fff10eaabf122f5dbaadca19 100644 --- a/modules/cron/www/cron.php +++ b/modules/cron/www/cron.php @@ -12,7 +12,7 @@ if (!is_null($cronconfig->getValue('key'))) { $cron = new \SimpleSAML\Module\cron\Cron(); if (!$cron->isValidTag($_REQUEST['tag'])) { - SimpleSAML\Logger::error('Cron - Illegal tag ['.$_REQUEST['tag'].'].'); + SimpleSAML\Logger::error('Cron - Illegal tag [' . $_REQUEST['tag'] . '].'); exit; } diff --git a/modules/exampleauth/lib/Auth/Source/External.php b/modules/exampleauth/lib/Auth/Source/External.php index c4c71f2bba7ec71d812c7a0802ce7464396ee941..0642e3e77b6330f9df84a4ef8e63db9a0a963756 100644 --- a/modules/exampleauth/lib/Auth/Source/External.php +++ b/modules/exampleauth/lib/Auth/Source/External.php @@ -218,7 +218,7 @@ class External extends \SimpleSAML\Auth\Source * The only way this should fail is if we remove or rename the authentication source * while the user is at the login page. */ - throw new Error\Exception('Could not find authentication source with id '.$state[self::AUTHID]); + throw new Error\Exception('Could not find authentication source with id ' . $state[self::AUTHID]); } /* diff --git a/modules/exampleauth/lib/Auth/Source/StaticSource.php b/modules/exampleauth/lib/Auth/Source/StaticSource.php index 1a29fcd2fb46b807aa1618a4ba7f8c832b1bfc2e..8d0dc72e141d0d93e982e2c659489fea4300f0f1 100644 --- a/modules/exampleauth/lib/Auth/Source/StaticSource.php +++ b/modules/exampleauth/lib/Auth/Source/StaticSource.php @@ -40,8 +40,8 @@ class StaticSource extends \SimpleSAML\Auth\Source try { $this->attributes = Utils\Attributes::normalizeAttributesArray($config); } catch (\Exception $e) { - throw new \Exception('Invalid attributes for authentication source '. - $this->authId.': '.$e->getMessage()); + 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 4761e65da870cae7cac1eaf33e9817176aee5878..30239a6c2943a327d4382199a6aeb83e0f73ebea 100644 --- a/modules/exampleauth/lib/Auth/Source/UserPass.php +++ b/modules/exampleauth/lib/Auth/Source/UserPass.php @@ -46,14 +46,14 @@ class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase foreach ($config as $userpass => $attributes) { if (!is_string($userpass)) { throw new \Exception( - 'Invalid <username>:<password> for authentication source '.$this->authId.': '.$userpass + 'Invalid <username>:<password> for authentication source ' . $this->authId . ': ' . $userpass ); } $userpass = explode(':', $userpass, 2); if (count($userpass) !== 2) { throw new \Exception( - 'Invalid <username>:<password> for authentication source '.$this->authId.': '.$userpass[0] + 'Invalid <username>:<password> for authentication source ' . $this->authId . ': ' . $userpass[0] ); } $username = $userpass[0]; @@ -62,10 +62,10 @@ class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase try { $attributes = Utils\Attributes::normalizeAttributesArray($attributes); } catch (\Exception $e) { - throw new \Exception('Invalid attributes for user '.$username. - ' in authentication source '.$this->authId.': '.$e->getMessage()); + throw new \Exception('Invalid attributes for user ' . $username . + ' in authentication source ' . $this->authId . ': ' . $e->getMessage()); } - $this->users[$username.':'.$password] = $attributes; + $this->users[$username . ':' . $password] = $attributes; } } @@ -88,7 +88,7 @@ class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase assert(is_string($username)); assert(is_string($password)); - $userpass = $username.':'.$password; + $userpass = $username . ':' . $password; if (!array_key_exists($userpass, $this->users)) { throw new Error\Error('WRONGUSERPASS'); } diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php index 02a017cfcaefa66dfb3e2c8b22e8818f4393c655..85d723588a1aa4743c15af3386ff81d7379324f4 100644 --- a/modules/multiauth/lib/Auth/Source/MultiAuth.php +++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php @@ -195,7 +195,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source $state[self::SOURCESID] ); if ($as === null || !in_array($authId, $valid_sources, true)) { - throw new \Exception('Invalid authentication source: '.$authId); + throw new \Exception('Invalid authentication source: ' . $authId); } // Save the selected authentication source for the logout process. @@ -238,7 +238,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source $source = Auth\Source::getById($authId); if ($source === null) { - throw new \Exception('Invalid authentication source during logout: '.$authId); + throw new \Exception('Invalid authentication source during logout: ' . $authId); } // Then, do the logout on it $source->logout($state); @@ -258,7 +258,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source { assert(is_string($source)); - $cookieName = 'multiauth_source_'.$this->authId; + $cookieName = 'multiauth_source_' . $this->authId; $config = Configuration::getInstance(); $params = [ @@ -282,7 +282,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source */ public function getPreviousSource() { - $cookieName = 'multiauth_source_'.$this->authId; + $cookieName = 'multiauth_source_' . $this->authId; if (array_key_exists($cookieName, $_COOKIE)) { return $_COOKIE[$cookieName]; } else { diff --git a/modules/portal/hooks/hook_htmlinject.php b/modules/portal/hooks/hook_htmlinject.php index e23e0d1e1fdd2d4fdb911580c2b14ff873b23df5..7939763eee71a042a4c7cf68e5b3dc6ad1249393 100644 --- a/modules/portal/hooks/hook_htmlinject.php +++ b/modules/portal/hooks/hook_htmlinject.php @@ -39,8 +39,8 @@ function portal_hook_htmlinject(&$hookinfo) $hookinfo['jquery']['css'] = true; // Header - $hookinfo['pre'][] = '<div id="portalmenu" class="ui-tabs ui-widget ui-widget-content ui-corner-all">'. - $portal->getMenu($hookinfo['page']). + $hookinfo['pre'][] = '<div id="portalmenu" class="ui-tabs ui-widget ui-widget-content ui-corner-all">' . + $portal->getMenu($hookinfo['page']) . '<div id="portalcontent" class="ui-tabs-panel ui-widget-content ui-corner-bottom">'; // Footer diff --git a/modules/portal/lib/Portal.php b/modules/portal/lib/Portal.php index 0bbf78a7f4a6a330db2107973d38f99d0ba4ba7a..e7308758f5deda9052c067511433424211a750c1 100644 --- a/modules/portal/lib/Portal.php +++ b/modules/portal/lib/Portal.php @@ -86,7 +86,7 @@ class Portal $tabset = $this->getTabset($thispage); $logininfo = $this->getLoginInfo($t, $thispage); $classes = 'tabset_tabs ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'; - $text = '<ul class="'.$classes.'">'; + $text = '<ul class="' . $classes . '">'; foreach ($this->pages as $pageid => $page) { if (isset($tabset) && !in_array($pageid, $tabset, true)) { continue; @@ -103,19 +103,19 @@ class Portal $name = $t->t($name); if (!isset($page['href'])) { - $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">'. - $name.'</a></li>'; + $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">' . + $name . '</a></li>'; } elseif ($pageid === $thispage) { - $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">'. - $name.'</a></li>'; + $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">' . + $name . '</a></li>'; } else { - $text .= '<li class="ui-state-default ui-corner-top"><a href="'.$page['href'].'">'. - $name.'</a></li>'; + $text .= '<li class="ui-state-default ui-corner-top"><a href="' . $page['href'] . '">' . + $name . '</a></li>'; } } $text .= '</ul>'; if (!empty($logininfo)) { - $text .= '<p class="logininfo" style="text-align: right; margin: 0px">'.$logininfo.'</p>'; + $text .= '<p class="logininfo" style="text-align: right; margin: 0px">' . $logininfo . '</p>'; } return $text; } diff --git a/modules/saml/hooks/hook_metadata_hosted.php b/modules/saml/hooks/hook_metadata_hosted.php index 3237a3b5091ed5a70036f99e75346c3d348773b5..569a6803197881b9239b48738956ac9a6b58b0a2 100644 --- a/modules/saml/hooks/hook_metadata_hosted.php +++ b/modules/saml/hooks/hook_metadata_hosted.php @@ -28,7 +28,7 @@ function saml_hook_metadata_hosted(&$metadataHosted) 'entityid' => $source->getEntityId(), 'metadata-index' => $source->getEntityId(), 'metadata-set' => 'saml20-sp-hosted', - 'metadata-url' => $source->getMetadataURL().'?output=xhtml', + 'metadata-url' => $source->getMetadataURL() . '?output=xhtml', 'name' => $name, ]; diff --git a/modules/saml/lib/Auth/Process/AttributeNameID.php b/modules/saml/lib/Auth/Process/AttributeNameID.php index 7c747c0ad9424fb593d44c3567e1e696be35a70d..b8e1b8889b31c08a475370ed15e888d34467f7f0 100644 --- a/modules/saml/lib/Auth/Process/AttributeNameID.php +++ b/modules/saml/lib/Auth/Process/AttributeNameID.php @@ -56,14 +56,14 @@ class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator { if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) { Logger::warning( - 'Missing attribute '.var_export($this->attribute, true). + 'Missing attribute ' . var_export($this->attribute, true) . ' on user - not generating attribute NameID.' ); return null; } if (count($state['Attributes'][$this->attribute]) > 1) { Logger::warning( - 'More than one value in attribute '.var_export($this->attribute, true). + 'More than one value in attribute ' . var_export($this->attribute, true) . ' on user - not generating attribute NameID.' ); return null; @@ -73,7 +73,7 @@ class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator if (empty($value)) { Logger::warning( - 'Empty value in attribute '.var_export($this->attribute, true). + 'Empty value in attribute ' . var_export($this->attribute, true) . ' on user - not generating attribute NameID.' ); return null; diff --git a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php index 535ae1f0b8cc8bf3a7d5bba98046041743729516..7e6259c5892f769af03dd689a01371fe281b0eb1 100644 --- a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php +++ b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php @@ -99,8 +99,8 @@ class ExpectedAuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter protected function unauthorized(&$request) { Logger::error( - 'ExpectedAuthnContextClassRef: Invalid authentication context: '.strval($this->AuthnContextClassRef). - '. Accepted values are: '.var_export($this->accepted, true) + 'ExpectedAuthnContextClassRef: Invalid authentication context: ' . strval($this->AuthnContextClassRef) . + '. Accepted values are: ' . var_export($this->accepted, true) ); $id = Auth\State::saveState($request, 'saml:ExpectedAuthnContextClassRef:unauthorized'); diff --git a/modules/saml/lib/Auth/Process/NameIDAttribute.php b/modules/saml/lib/Auth/Process/NameIDAttribute.php index e0522f53d608796dcbbc5a1a497b1c7415280e03..5ed3e9800705202864e65504cb7c11a024b241a5 100644 --- a/modules/saml/lib/Auth/Process/NameIDAttribute.php +++ b/modules/saml/lib/Auth/Process/NameIDAttribute.php @@ -91,7 +91,7 @@ class NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter $ret[] = '%'; break; default: - throw new Error\Exception('NameIDAttribute: Invalid replacement: "%'.$replacement.'"'); + throw new Error\Exception('NameIDAttribute: Invalid replacement: "%' . $replacement . '"'); } $pos = $next + 2; @@ -137,7 +137,7 @@ class NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter if ($isString) { $value .= $element; } else { - $value .= call_user_func([$rep, 'get'.$element]); + $value .= call_user_func([$rep, 'get' . $element]); } $isString = !$isString; } diff --git a/modules/saml/lib/Auth/Process/PersistentNameID.php b/modules/saml/lib/Auth/Process/PersistentNameID.php index a2fd9552f1f0deea7976397cb5cc8a51b7622e96..a98a0212ace8789fbe4146716e0bcf9a79132fa7 100644 --- a/modules/saml/lib/Auth/Process/PersistentNameID.php +++ b/modules/saml/lib/Auth/Process/PersistentNameID.php @@ -67,14 +67,14 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) { Logger::warning( - 'Missing attribute '.var_export($this->attribute, true). + 'Missing attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; } if (count($state['Attributes'][$this->attribute]) > 1) { Logger::warning( - 'More than one value in attribute '.var_export($this->attribute, true). + 'More than one value in attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; @@ -84,7 +84,7 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator if (empty($uid)) { Logger::warning( - 'Empty value in attribute '.var_export($this->attribute, true). + 'Empty value in attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; @@ -92,10 +92,10 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator $secretSalt = Utils\Config::getSecretSalt(); - $uidData = 'uidhashbase'.$secretSalt; - $uidData .= strlen($idpEntityId).':'.$idpEntityId; - $uidData .= strlen($spEntityId).':'.$spEntityId; - $uidData .= strlen($uid).':'.$uid; + $uidData = 'uidhashbase' . $secretSalt; + $uidData .= strlen($idpEntityId) . ':' . $idpEntityId; + $uidData .= strlen($spEntityId) . ':' . $spEntityId; + $uidData .= strlen($uid) . ':' . $uid; $uidData .= $secretSalt; return sha1($uidData); diff --git a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php index c40851018b79f90f13fa7c39c69b0c31a27da558..fc3decdbd73ce9ae0c9aec749ab9632205f55ed1 100644 --- a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php +++ b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php @@ -87,10 +87,9 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator */ protected function getValue(array &$state) { - if (!isset($state['saml:NameIDFormat']) && !$this->allowUnspecified) { Logger::debug( - 'SQLPersistentNameID: Request did not specify persistent NameID format, '. + 'SQLPersistentNameID: Request did not specify persistent NameID format, ' . 'not generating persistent NameID.' ); return null; @@ -100,12 +99,14 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator $state['saml:NameIDFormat'], $state['SPMetadata']['NameIDFormat'] ]); - if (count($validNameIdFormats) && !in_array($this->format, $validNameIdFormats, true) && - !$this->allowDifferent + if ( + count($validNameIdFormats) + && !in_array($this->format, $validNameIdFormats, true) + && !$this->allowDifferent ) { Logger::debug( - 'SQLPersistentNameID: SP expects different NameID format ('. - implode(', ', $validNameIdFormats).'), not generating persistent NameID.' + 'SQLPersistentNameID: SP expects different NameID format (' . + implode(', ', $validNameIdFormats) . '), not generating persistent NameID.' ); return null; } @@ -124,14 +125,14 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) { Logger::warning( - 'SQLPersistentNameID: Missing attribute '.var_export($this->attribute, true). + 'SQLPersistentNameID: Missing attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; } if (count($state['Attributes'][$this->attribute]) > 1) { Logger::warning( - 'SQLPersistentNameID: More than one value in attribute '.var_export($this->attribute, true). + 'SQLPersistentNameID: More than one value in attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; @@ -141,7 +142,7 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator if (empty($uid)) { Logger::warning( - 'Empty value in attribute '.var_export($this->attribute, true). + 'Empty value in attribute ' . var_export($this->attribute, true) . ' on user - not generating persistent NameID.' ); return null; @@ -150,8 +151,8 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator $value = \SimpleSAML\Module\saml\IdP\SQLNameID::get($idpEntityId, $spEntityId, $uid); if ($value !== null) { Logger::debug( - 'SQLPersistentNameID: Found persistent NameID '.var_export($value, true).' for user '. - var_export($uid, true).'.' + 'SQLPersistentNameID: Found persistent NameID ' . var_export($value, true) . ' for user ' . + var_export($uid, true) . '.' ); return $value; } @@ -168,8 +169,8 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator $value = bin2hex(openssl_random_pseudo_bytes(20)); Logger::debug( - 'SQLPersistentNameID: Created persistent NameID '.var_export($value, true).' for user '. - var_export($uid, true).'.' + 'SQLPersistentNameID: Created persistent NameID ' . var_export($value, true) . ' for user ' . + var_export($uid, true) . '.' ); \SimpleSAML\Module\saml\IdP\SQLNameID::add($idpEntityId, $spEntityId, $uid, $value); diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php index e6b4f759515a2cbdb04239ea2a97e2d096151ee9..c686968d8a4534eeb640761d410bffb3455f6913 100644 --- a/modules/saml/lib/Auth/Source/SP.php +++ b/modules/saml/lib/Auth/Source/SP.php @@ -6,7 +6,6 @@ use SAML2\AuthnRequest; use SAML2\Binding; use SAML2\Constants; use SAML2\XML\saml\NameID; - use SimpleSAML\Auth; use SimpleSAML\Configuration; use SimpleSAML\Error; @@ -88,7 +87,7 @@ class SP extends \SimpleSAML\Auth\Source $this->metadata = Configuration::loadFromArray( $config, - 'authsources['.var_export($this->authId, true).']' + 'authsources[' . var_export($this->authId, true) . ']' ); $this->entityId = $this->metadata->getString('entityID'); $this->idp = $this->metadata->getString('idp', null); @@ -108,7 +107,7 @@ class SP extends \SimpleSAML\Auth\Source */ public function getMetadataURL() { - return Module::getModuleURL('saml/sp/metadata.php/'.urlencode($this->authId)); + return Module::getModuleURL('saml/sp/metadata.php/' . urlencode($this->authId)); } @@ -290,8 +289,8 @@ class SP extends \SimpleSAML\Auth\Source assert(is_string($entityId)); if ($this->idp !== null && $this->idp !== $entityId) { - throw new Error\Exception('Cannot retrieve metadata for IdP '. - var_export($entityId, true).' because it isn\'t a valid IdP for this SP.'); + throw new Error\Exception('Cannot retrieve metadata for IdP ' . + var_export($entityId, true) . ' because it isn\'t a valid IdP for this SP.'); } $metadataHandler = MetaDataStorageHandler::getMetadataHandler(); @@ -301,7 +300,7 @@ class SP extends \SimpleSAML\Auth\Source return $metadataHandler->getMetaDataConfig($entityId, 'saml20-idp-remote'); } catch (\Exception $e) { // Metadata wasn't found - Logger::debug('getIdpMetadata: '.$e->getMessage()); + Logger::debug('getIdpMetadata: ' . $e->getMessage()); } // Not found in saml20-idp-remote, look in shib13-idp-remote @@ -309,11 +308,11 @@ class SP extends \SimpleSAML\Auth\Source return $metadataHandler->getMetaDataConfig($entityId, 'shib13-idp-remote'); } catch (\Exception $e) { // Metadata wasn't found - Logger::debug('getIdpMetadata: '.$e->getMessage()); + Logger::debug('getIdpMetadata: ' . $e->getMessage()); } // Not found - throw new Error\Exception('Could not find the metadata of an IdP with entity ID '. + throw new Error\Exception('Could not find the metadata of an IdP with entity ID ' . var_export($entityId, true)); } @@ -366,7 +365,7 @@ class SP extends \SimpleSAML\Auth\Source case Constants::BINDING_HTTP_POST: $acs = [ 'Binding' => Constants::BINDING_HTTP_POST, - 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/'.$this->getAuthId()), + 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->getAuthId()), ]; if (!in_array(Constants::NS_SAMLP, $this->protocols, true)) { $this->protocols[] = Constants::NS_SAMLP; @@ -375,7 +374,7 @@ class SP extends \SimpleSAML\Auth\Source case 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post': $acs = [ 'Binding' => 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post', - 'Location' => Module::getModuleURL('saml/sp/saml1-acs.php/'.$this->getAuthId()), + 'Location' => Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->getAuthId()), ]; if (!in_array('urn:oasis:names:tc:SAML:1.0:profiles:browser-post', $this->protocols, true)) { $this->protocols[] = 'urn:oasis:names:tc:SAML:1.1:protocol'; @@ -384,7 +383,7 @@ class SP extends \SimpleSAML\Auth\Source case Constants::BINDING_HTTP_ARTIFACT: $acs = [ 'Binding' => Constants::BINDING_HTTP_ARTIFACT, - 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/'.$this->getAuthId()), + 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->getAuthId()), ]; if (!in_array(Constants::NS_SAMLP, $this->protocols, true)) { $this->protocols[] = Constants::NS_SAMLP; @@ -394,7 +393,7 @@ class SP extends \SimpleSAML\Auth\Source $acs = [ 'Binding' => 'urn:oasis:names:tc:SAML:1.0:profiles:artifact-01', 'Location' => Module::getModuleURL( - 'saml/sp/saml1-acs.php/'.$this->getAuthId().'/artifact' + 'saml/sp/saml1-acs.php/' . $this->getAuthId() . '/artifact' ), ]; if (!in_array('urn:oasis:names:tc:SAML:1.1:protocol', $this->protocols, true)) { @@ -404,7 +403,7 @@ class SP extends \SimpleSAML\Auth\Source case Constants::BINDING_HOK_SSO: $acs = [ 'Binding' => Constants::BINDING_HOK_SSO, - 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/'.$this->getAuthId()), + 'Location' => Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->getAuthId()), 'hoksso:ProtocolBinding' => Constants::BINDING_HTTP_REDIRECT, ]; if (!in_array(Constants::NS_SAMLP, $this->protocols, true)) { @@ -438,7 +437,7 @@ class SP extends \SimpleSAML\Auth\Source Constants::BINDING_SOAP, ] ); - $location = Module::getModuleURL('saml/sp/saml2-logout.php/'.$this->getAuthId()); + $location = Module::getModuleURL('saml/sp/saml2-logout.php/' . $this->getAuthId()); $endpoints = []; foreach ($bindings as $binding) { @@ -481,15 +480,15 @@ class SP extends \SimpleSAML\Auth\Source } if ($useArtifact) { - $shire = Module::getModuleURL('saml/sp/saml1-acs.php/'.$this->authId.'/artifact'); + $shire = Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId . '/artifact'); } else { - $shire = Module::getModuleURL('saml/sp/saml1-acs.php/'.$this->authId); + $shire = Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId); } $url = $ar->createRedirect($idpEntityId, $shire); - Logger::debug('Starting SAML 1 SSO to '.var_export($idpEntityId, true). - ' from '.var_export($this->entityId, true).'.'); + Logger::debug('Starting SAML 1 SSO to ' . var_export($idpEntityId, true) . + ' from ' . var_export($this->entityId, true) . '.'); Utils\HTTP::redirectTrustedURL($url); } @@ -512,7 +511,7 @@ class SP extends \SimpleSAML\Auth\Source $ar = Module\saml\Message::buildAuthnRequest($this->metadata, $idpMetadata); - $ar->setAssertionConsumerServiceURL(Module::getModuleURL('saml/sp/saml2-acs.php/'.$this->authId)); + $ar->setAssertionConsumerServiceURL(Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->authId)); if (isset($state['\SimpleSAML\Auth\Source.ReturnURL'])) { $ar->setRelayState($state['\SimpleSAML\Auth\Source.ReturnURL']); @@ -521,7 +520,7 @@ class SP extends \SimpleSAML\Auth\Source $accr = null; if ($idpMetadata->getString('AuthnContextClassRef', false)) { $accr = Utils\Arrays::arrayize($idpMetadata->getString('AuthnContextClassRef')); - } else if (isset($state['saml:AuthnContextClassRef'])) { + } elseif (isset($state['saml:AuthnContextClassRef'])) { $accr = Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']); } @@ -529,13 +528,15 @@ class SP extends \SimpleSAML\Auth\Source $comp = Constants::COMPARISON_EXACT; if ($idpMetadata->getString('AuthnContextComparison', false)) { $comp = $idpMetadata->getString('AuthnContextComparison'); - } else if (isset($state['saml:AuthnContextComparison']) + } elseif ( + isset($state['saml:AuthnContextComparison']) && in_array($state['AuthnContextComparison'], [ Constants::COMPARISON_EXACT, Constants::COMPARISON_MINIMUM, Constants::COMPARISON_MAXIMUM, Constants::COMPARISON_BETTER, - ], true)) { + ], true) + ) { $comp = $state['saml:AuthnContextComparison']; } $ar->setRequestedAuthnContext(['AuthnContextClassRef' => $accr, 'Comparison' => $comp]); @@ -630,7 +631,7 @@ class SP extends \SimpleSAML\Auth\Source $requesterID[] = $state['core:SP']; } } else { - Logger::debug('Disabling samlp:Scoping for '.var_export($idpMetadata->getString('entityid'), true)); + Logger::debug('Disabling samlp:Scoping for ' . var_export($idpMetadata->getString('entityid'), true)); } $ar->setIDPList( @@ -656,7 +657,7 @@ class SP extends \SimpleSAML\Auth\Source $ar->setId($id); Logger::debug( - 'Sending SAML 2 AuthnRequest to '.var_export($idpMetadata->getString('entityid'), true) + 'Sending SAML 2 AuthnRequest to ' . var_export($idpMetadata->getString('entityid'), true) ); // Select appropriate SSO endpoint @@ -838,8 +839,6 @@ class SP extends \SimpleSAML\Auth\Source */ public function reauthenticate(array &$state) { - assert(is_array($state)); - $session = Session::getSessionFromRequest(); $data = $session->getAuthState($this->authId); if ($data === null) { @@ -851,8 +850,11 @@ class SP extends \SimpleSAML\Auth\Source } // check if we have an IDPList specified in the request - if (isset($state['saml:IDPList']) && sizeof($state['saml:IDPList']) > 0 && - !in_array($state['saml:sp:IdP'], $state['saml:IDPList'], true)) { + if ( + isset($state['saml:IDPList']) + && sizeof($state['saml:IDPList']) > 0 + && !in_array($state['saml:sp:IdP'], $state['saml:IDPList'], true) + ) { /* * The user has an existing, valid session. However, the SP * provided a list of IdPs it accepts for authentication, and @@ -892,7 +894,7 @@ class SP extends \SimpleSAML\Auth\Source * cancel the current SSO attempt. */ Logger::warning( - "Reauthentication after logout is needed. The IdP '${state['saml:sp:IdP']}' is not in the IDPList ". + "Reauthentication after logout is needed. The IdP '${state['saml:sp:IdP']}' is not in the IDPList " . "provided by the Service Provider '${state['core:SP']}'." ); @@ -1040,11 +1042,16 @@ class SP extends \SimpleSAML\Auth\Source $idpMetadata = $this->getIdPMetadata($idp); /** @var array $endpoint */ - $endpoint = $idpMetadata->getEndpointPrioritizedByBinding('SingleLogoutService', [ - Constants::BINDING_HTTP_REDIRECT, - Constants::BINDING_HTTP_POST], false); + $endpoint = $idpMetadata->getEndpointPrioritizedByBinding( + 'SingleLogoutService', + [ + Constants::BINDING_HTTP_REDIRECT, + Constants::BINDING_HTTP_POST + ], + false + ); if ($endpoint === false) { - Logger::info('No logout endpoint for IdP '.var_export($idp, true).'.'); + Logger::info('No logout endpoint for IdP ' . var_export($idp, true) . '.'); return; } @@ -1204,7 +1211,7 @@ class SP extends \SimpleSAML\Auth\Source /** @var \SimpleSAML\Module\saml\Auth\Source\SP $source */ $source = Auth\Source::getById($sourceId); if ($source === null) { - throw new \Exception('Could not find authentication source with id '.$sourceId); + throw new \Exception('Could not find authentication source with id ' . $sourceId); } // Register a callback that we can call if we receive a logout request from the IdP diff --git a/modules/saml/lib/Error.php b/modules/saml/lib/Error.php index 5612b05520bcd8bded03242a14f6fcb5e64b6528..50604b39ffbe82300be17666ba8c41792ddf2111 100644 --- a/modules/saml/lib/Error.php +++ b/modules/saml/lib/Error.php @@ -52,10 +52,10 @@ class Error extends \SimpleSAML\Error\Exception $st = self::shortStatus($status); if ($subStatus !== null) { - $st .= '/'.self::shortStatus($subStatus); + $st .= '/' . self::shortStatus($subStatus); } if ($statusMessage !== null) { - $st .= ': '.$statusMessage; + $st .= ': ' . $statusMessage; } parent::__construct($st, 0, $cause); @@ -133,7 +133,7 @@ class Error extends \SimpleSAML\Error\Exception $e = new self( \SAML2\Constants::STATUS_RESPONDER, null, - get_class($exception).': '.$exception->getMessage(), + get_class($exception) . ': ' . $exception->getMessage(), $exception ); } diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php index 720e4663d4b06f59b162aa6428b36ddae9aae57c..eca7ad6e8949d38dcb516956829eec04eab87714 100644 --- a/modules/saml/lib/IdP/SAML2.php +++ b/modules/saml/lib/IdP/SAML2.php @@ -57,10 +57,10 @@ class SAML2 $spEntityId = $spMetadata['entityid']; $spMetadata = Configuration::loadFromArray( $spMetadata, - '$metadata['.var_export($spEntityId, true).']' + '$metadata[' . var_export($spEntityId, true) . ']' ); - Logger::info('Sending SAML 2.0 Response to '.var_export($spEntityId, true)); + Logger::info('Sending SAML 2.0 Response to ' . var_export($spEntityId, true)); $requestId = $state['saml:RequestId']; $relayState = $state['saml:RelayState']; @@ -79,7 +79,7 @@ class SAML2 // create the session association (for logout) $association = [ - 'id' => 'saml:'.$spEntityId, + 'id' => 'saml:' . $spEntityId, 'Handler' => '\SimpleSAML\Module\saml\IdP\SAML2', 'Expires' => $assertion->getSessionNotOnOrAfter(), 'saml:entityID' => $spEntityId, @@ -134,7 +134,7 @@ class SAML2 $spEntityId = $spMetadata['entityid']; $spMetadata = Configuration::loadFromArray( $spMetadata, - '$metadata['.var_export($spEntityId, true).']' + '$metadata[' . var_export($spEntityId, true) . ']' ); $requestId = $state['saml:RequestId']; @@ -148,7 +148,7 @@ class SAML2 $error = \SimpleSAML\Module\saml\Error::fromException($exception); - Logger::warning("Returning error to SP with entity ID '".var_export($spEntityId, true)."'."); + Logger::warning("Returning error to SP with entity ID '" . var_export($spEntityId, true) . "'."); $exception->log(Logger::WARNING); $ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL); @@ -253,14 +253,14 @@ class SAML2 Logger::warning('Authentication request specifies invalid AssertionConsumerService:'); if ($AssertionConsumerServiceURL !== null) { - Logger::warning('AssertionConsumerServiceURL: '.var_export($AssertionConsumerServiceURL, true)); + Logger::warning('AssertionConsumerServiceURL: ' . var_export($AssertionConsumerServiceURL, true)); } if ($ProtocolBinding !== null) { - Logger::warning('ProtocolBinding: '.var_export($ProtocolBinding, true)); + Logger::warning('ProtocolBinding: ' . var_export($ProtocolBinding, true)); } if ($AssertionConsumerServiceIndex !== null) { Logger::warning( - 'AssertionConsumerServiceIndex: '.var_export($AssertionConsumerServiceIndex, true) + 'AssertionConsumerServiceIndex: ' . var_export($AssertionConsumerServiceIndex, true) ); } @@ -351,7 +351,7 @@ class SAML2 $idpInit = true; Logger::info( - 'SAML2.0 - IdP.SSOService: IdP initiated authentication: '.var_export($spEntityId, true) + 'SAML2.0 - IdP.SSOService: IdP initiated authentication: ' . var_export($spEntityId, true) ); } else { $binding = Binding::getCurrentBinding(); @@ -413,7 +413,7 @@ class SAML2 $idpInit = false; Logger::info( - 'SAML2.0 - IdP.SSOService: incoming authentication request: '.var_export($spEntityId, true) + 'SAML2.0 - IdP.SSOService: incoming authentication request: ' . var_export($spEntityId, true) ); } @@ -434,7 +434,7 @@ class SAML2 $consumerIndex ); if ($acsEndpoint === null) { - throw new \Exception('Unable to use any of the ACS endpoints found for SP \''.$spEntityId.'\''); + throw new \Exception('Unable to use any of the ACS endpoints found for SP \'' . $spEntityId . '\''); } $IDPList = array_unique(array_merge($IDPList, $spMetadata->getArrayizeString('IDPList', []))); @@ -504,7 +504,7 @@ class SAML2 { assert(is_string($relayState) || $relayState === null); - Logger::info('Sending SAML 2.0 LogoutRequest to: '.var_export($association['saml:entityID'], true)); + Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); $metadata = MetaDataStorageHandler::getMetadataHandler(); $idpMetadata = $idp->getConfig(); @@ -560,10 +560,10 @@ class SAML2 'Code' => Constants::STATUS_SUCCESS, 'SubCode' => Constants::STATUS_PARTIAL_LOGOUT, ]); - Logger::info('Sending logout response for partial logout to SP '.var_export($spEntityId, true)); + Logger::info('Sending logout response for partial logout to SP ' . var_export($spEntityId, true)); } else { $partial = false; - Logger::debug('Sending logout response to SP '.var_export($spEntityId, true)); + Logger::debug('Sending logout response to SP ' . var_export($spEntityId, true)); } Stats::log('saml:idp:LogoutResponse:sent', [ @@ -625,7 +625,7 @@ class SAML2 \SimpleSAML\Module\saml\Message::validateMessage($spMetadata, $idpMetadata, $message); if ($message instanceof LogoutResponse) { - Logger::info('Received SAML 2.0 LogoutResponse from: '.var_export($spEntityId, true)); + Logger::info('Received SAML 2.0 LogoutResponse from: ' . var_export($spEntityId, true)); $statsData = [ 'spEntityID' => $spEntityId, 'idpEntityID' => $idpMetadata->getString('entityid'), @@ -639,23 +639,23 @@ class SAML2 if (!$message->isSuccess()) { $logoutError = \SimpleSAML\Module\saml\Message::getResponseError($message); - Logger::warning('Unsuccessful logout. Status was: '.$logoutError); + Logger::warning('Unsuccessful logout. Status was: ' . $logoutError); } else { $logoutError = null; } - $assocId = 'saml:'.$spEntityId; + $assocId = 'saml:' . $spEntityId; $idp->handleLogoutResponse($assocId, $relayState, $logoutError); } elseif ($message instanceof LogoutRequest) { - Logger::info('Received SAML 2.0 LogoutRequest from: '.var_export($spEntityId, true)); + Logger::info('Received SAML 2.0 LogoutRequest from: ' . var_export($spEntityId, true)); Stats::log('saml:idp:LogoutRequest:recv', [ 'spEntityID' => $spEntityId, 'idpEntityID' => $idpMetadata->getString('entityid'), ]); $spStatsId = $spMetadata->getString('core:statistics-id', $spEntityId); - Logger::stats('saml20-idp-SLO spinit '.$spStatsId.' '.$idpMetadata->getString('entityid')); + Logger::stats('saml20-idp-SLO spinit ' . $spStatsId . ' ' . $idpMetadata->getString('entityid')); $state = [ 'Responder' => ['\SimpleSAML\Module\saml\IdP\SAML2', 'sendLogoutResponse'], @@ -664,10 +664,10 @@ class SAML2 'saml:RequestId' => $message->getId(), ]; - $assocId = 'saml:'.$spEntityId; + $assocId = 'saml:' . $spEntityId; $idp->handleLogoutRequest($state, $assocId); } else { - throw new Error\BadRequest('Unknown message received on logout endpoint: '.get_class($message)); + throw new Error\BadRequest('Unknown message received on logout endpoint: ' . get_class($message)); } } @@ -685,7 +685,7 @@ class SAML2 { assert(is_string($relayState) || $relayState === null); - Logger::info('Sending SAML 2.0 LogoutRequest to: '.var_export($association['saml:entityID'], true)); + Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); $metadata = MetaDataStorageHandler::getMetadataHandler(); $idpMetadata = $idp->getConfig(); @@ -836,7 +836,7 @@ class SAML2 $metadata['ArtifactResolutionService'][] = [ 'index' => 0, 'Binding' => Constants::BINDING_SOAP, - 'Location' => Utils\HTTP::getBaseURL().'saml2/idp/ArtifactResolutionService.php' + 'Location' => Utils\HTTP::getBaseURL() . 'saml2/idp/ArtifactResolutionService.php' ]; } @@ -847,7 +847,7 @@ class SAML2 [ 'hoksso:ProtocolBinding' => Constants::BINDING_HTTP_REDIRECT, 'Binding' => Constants::BINDING_HOK_SSO, - 'Location' => Utils\HTTP::getBaseURL().'saml2/idp/SSOService.php', + 'Location' => Utils\HTTP::getBaseURL() . 'saml2/idp/SSOService.php', ] ); } @@ -857,7 +857,7 @@ class SAML2 $metadata['SingleSignOnService'][] = [ 'index' => 0, 'Binding' => Constants::BINDING_SOAP, - 'Location' => Utils\HTTP::getBaseURL().'saml2/idp/SSOService.php', + 'Location' => Utils\HTTP::getBaseURL() . 'saml2/idp/SSOService.php', ]; } @@ -963,10 +963,10 @@ class SAML2 $secretSalt = Utils\Config::getSecretSalt(); - $uidData = 'uidhashbase'.$secretSalt; - $uidData .= strlen($idpEntityId).':'.$idpEntityId; - $uidData .= strlen($spEntityId).':'.$spEntityId; - $uidData .= strlen($attributeValue).':'.$attributeValue; + $uidData = 'uidhashbase' . $secretSalt; + $uidData .= strlen($idpEntityId) . ':' . $idpEntityId; + $uidData .= strlen($spEntityId) . ':' . $spEntityId; + $uidData .= strlen($attributeValue) . ':' . $attributeValue; $uidData .= $secretSalt; return hash('sha1', $uidData); @@ -975,7 +975,7 @@ class SAML2 $attributes = $state['Attributes']; if (!array_key_exists($attribute, $attributes)) { - Logger::error('Unable to add NameID: Missing '.var_export($attribute, true). + Logger::error('Unable to add NameID: Missing ' . var_export($attribute, true) . ' in the attributes of the user.'); return null; } @@ -1050,14 +1050,14 @@ class SAML2 break; case 'raw': if (is_string($value)) { - $doc = DOMDocumentFactory::fromString('<root>'.$value.'</root>'); + $doc = DOMDocumentFactory::fromString('<root>' . $value . '</root>'); $value = $doc->firstChild->childNodes; } assert($value instanceof DOMNodeList || $value instanceof NameID); break; default: - throw new Error\Exception('Invalid encoding for attribute '. - var_export($name, true).': '.var_export($encoding, true)); + throw new Error\Exception('Invalid encoding for attribute ' . + var_export($name, true) . ': ' . var_export($encoding, true)); } $ret[$name][] = $value; } @@ -1208,8 +1208,8 @@ class SAML2 $scd->addInfo($keyInfo); } else { throw new Error\Exception( - 'Error creating HoK assertion: No valid client certificate provided during TLS handshake '. - 'with IdP' + 'Error creating HoK assertion: No valid client certificate provided during ' + . 'TLS handshake with IdP' ); } } else { @@ -1336,12 +1336,12 @@ class SAML2 $key = $keys[0]; switch ($key['type']) { case 'X509Certificate': - $pemKey = "-----BEGIN CERTIFICATE-----\n". - chunk_split($key['X509Certificate'], 64). + $pemKey = "-----BEGIN CERTIFICATE-----\n" . + chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; break; default: - throw new Error\Exception('Unsupported encryption key type: '.$key['type']); + throw new Error\Exception('Unsupported encryption key type: ' . $key['type']); } // extract the public key from the certificate for encryption @@ -1349,8 +1349,8 @@ class SAML2 $key->loadKey($pemKey); } else { throw new Error\ConfigurationError( - 'Missing encryption key for entity `'.$spMetadata->getString('entityid').'`', - $spMetadata->getString('metadata-set').'.php', + 'Missing encryption key for entity `' . $spMetadata->getString('entityid') . '`', + $spMetadata->getString('metadata-set') . '.php', null ); } diff --git a/modules/saml/lib/IdP/SQLNameID.php b/modules/saml/lib/IdP/SQLNameID.php index 8ea3db41dc1d6bdbbe83e5d59afbcd83f5dce0eb..69fb3911cc2001404d410ff4a60e8032cb52b794 100644 --- a/modules/saml/lib/IdP/SQLNameID.php +++ b/modules/saml/lib/IdP/SQLNameID.php @@ -25,7 +25,7 @@ class SQLNameID return; } - $query = 'CREATE TABLE '.$store->prefix.'_saml_PersistentNameID ( + $query = 'CREATE TABLE ' . $store->prefix . '_saml_PersistentNameID ( _idp VARCHAR(256) NOT NULL, _sp VARCHAR(256) NOT NULL, _user VARCHAR(256) NOT NULL, @@ -34,8 +34,8 @@ class SQLNameID )'; $store->pdo->exec($query); - $query = 'CREATE INDEX '.$store->prefix.'_saml_PersistentNameID_idp_sp ON '; - $query .= $store->prefix.'_saml_PersistentNameID (_idp, _sp)'; + $query = 'CREATE INDEX ' . $store->prefix . '_saml_PersistentNameID_idp_sp ON '; + $query .= $store->prefix . '_saml_PersistentNameID (_idp, _sp)'; $store->pdo->exec($query); $store->setTableVersion('saml_PersistentNameID', 1); @@ -90,7 +90,7 @@ class SQLNameID '_value' => $value, ]; - $query = 'INSERT INTO '.$store->prefix; + $query = 'INSERT INTO ' . $store->prefix; $query .= '_saml_PersistentNameID (_idp, _sp, _user, _value) VALUES(:_idp, :_sp, :_user, :_value)'; $query = $store->pdo->prepare($query); $query->execute($params); @@ -119,7 +119,7 @@ class SQLNameID '_user' => $user, ]; - $query = 'SELECT _value FROM '.$store->prefix; + $query = 'SELECT _value FROM ' . $store->prefix; $query .= '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; $query = $store->pdo->prepare($query); $query->execute($params); @@ -156,7 +156,7 @@ class SQLNameID '_user' => $user, ]; - $query = 'DELETE FROM '.$store->prefix; + $query = 'DELETE FROM ' . $store->prefix; $query .= '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; $query = $store->pdo->prepare($query); $query->execute($params); @@ -182,7 +182,7 @@ class SQLNameID '_sp' => $spEntityId, ]; - $query = 'SELECT _user, _value FROM '.$store->prefix; + $query = 'SELECT _user, _value FROM ' . $store->prefix; $query .= '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp'; $query = $store->pdo->prepare($query); $query->execute($params); diff --git a/modules/saml/lib/Message.php b/modules/saml/lib/Message.php index 9d5c9275d983297bc17af5a4ff2bffb7fd8d5c44..ca15e50130b8089b1e65c4a5e35cf3e5c0f4bb23 100644 --- a/modules/saml/lib/Message.php +++ b/modules/saml/lib/Message.php @@ -145,16 +145,16 @@ class Message } /* We have found a matching fingerprint. */ - $pem = "-----BEGIN CERTIFICATE-----\n". - chunk_split($cert, 64). + $pem = "-----BEGIN CERTIFICATE-----\n" . + chunk_split($cert, 64) . "-----END CERTIFICATE-----\n"; return $pem; } - $candidates = "'".implode("', '", $candidates)."'"; - $fps = "'".implode("', '", $certFingerprints)."'"; - throw new SSP_Error\Exception('Unable to find a certificate matching the configured '. - 'fingerprint. Candidates: '.$candidates.'; certFingerprint: '.$fps.'.'); + $candidates = "'" . implode("', '", $candidates) . "'"; + $fps = "'" . implode("', '", $certFingerprints) . "'"; + throw new SSP_Error\Exception('Unable to find a certificate matching the configured ' . + 'fingerprint. Candidates: ' . $candidates . '; certFingerprint: ' . $fps . '.'); } @@ -177,17 +177,17 @@ class Message foreach ($keys as $key) { switch ($key['type']) { case 'X509Certificate': - $pemKeys[] = "-----BEGIN CERTIFICATE-----\n". - chunk_split($key['X509Certificate'], 64). + $pemKeys[] = "-----BEGIN CERTIFICATE-----\n" . + chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; break; default: - Logger::debug('Skipping unknown key type: '.$key['type']); + Logger::debug('Skipping unknown key type: ' . $key['type']); } } } elseif ($srcMetadata->hasValue('certFingerprint')) { Logger::notice( - "Validating certificates by fingerprint is deprecated. Please use ". + "Validating certificates by fingerprint is deprecated. Please use " . "certData or certificate options in your remote metadata configuration." ); @@ -204,19 +204,19 @@ class Message Logger::debug('No certificate in message when validating against fingerprint.'); return false; } else { - Logger::debug('Found '.count($certificates).' certificates in '.get_class($element)); + Logger::debug('Found ' . count($certificates) . ' certificates in ' . get_class($element)); } $pemCert = self::findCertificate($certFingerprint, $certificates); $pemKeys = [$pemCert]; } else { throw new SSP_Error\Exception( - 'Missing certificate in metadata for '. + 'Missing certificate in metadata for ' . var_export($srcMetadata->getString('entityid'), true) ); } - Logger::debug('Has '.count($pemKeys).' candidate keys for validation.'); + Logger::debug('Has ' . count($pemKeys) . ' candidate keys for validation.'); $lastException = null; foreach ($pemKeys as $i => $pem) { @@ -227,12 +227,12 @@ class Message // make sure that we have a valid signature on either the response or the assertion $res = $element->validate($key); if ($res) { - Logger::debug('Validation with key #'.$i.' succeeded.'); + Logger::debug('Validation with key #' . $i . ' succeeded.'); return true; } - Logger::debug('Validation with key #'.$i.' failed without exception.'); + Logger::debug('Validation with key #' . $i . ' failed without exception.'); } catch (\Exception $e) { - Logger::debug('Validation with key #'.$i.' failed with exception: '.$e->getMessage()); + Logger::debug('Validation with key #' . $i . ' failed with exception: ' . $e->getMessage()); $lastException = $e; } } @@ -400,7 +400,7 @@ class Message try { $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata); } catch (\Exception $e) { - throw new SSP_Error\Exception('Error decrypting assertion: '.$e->getMessage()); + throw new SSP_Error\Exception('Error decrypting assertion: ' . $e->getMessage()); } $blacklist = self::getBlacklistedAlgorithms($srcMetadata, $dstMetadata); @@ -409,10 +409,10 @@ class Message foreach ($keys as $i => $key) { try { $ret = $assertion->getAssertion($key, $blacklist); - Logger::debug('Decryption with key #'.$i.' succeeded.'); + Logger::debug('Decryption with key #' . $i . ' succeeded.'); return $ret; } catch (\Exception $e) { - Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage()); + Logger::debug('Decryption with key #' . $i . ' failed with exception: ' . $e->getMessage()); $lastException = $e; } } @@ -449,7 +449,7 @@ class Message try { $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata); } catch (\Exception $e) { - throw new SSP_Error\Exception('Error decrypting attributes: '.$e->getMessage()); + throw new SSP_Error\Exception('Error decrypting attributes: ' . $e->getMessage()); } $blacklist = self::getBlacklistedAlgorithms($srcMetadata, $dstMetadata); @@ -458,11 +458,11 @@ class Message foreach ($keys as $i => $key) { try { $assertion->decryptAttributes($key, $blacklist); - Logger::debug('Attribute decryption with key #'.$i.' succeeded.'); + Logger::debug('Attribute decryption with key #' . $i . ' succeeded.'); $error = false; break; } catch (\Exception $e) { - Logger::debug('Attribute decryption failed with exception: '.$e->getMessage()); + Logger::debug('Attribute decryption failed with exception: ' . $e->getMessage()); } } if ($error) { @@ -620,8 +620,8 @@ class Message $currentURL = 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 "'. - $msgDestination.'", current URL is "'.$currentURL.'".'); + throw new \Exception('Destination in response doesn\'t match the current URL. Destination is "' . + $msgDestination . '", current URL is "' . $currentURL . '".'); } $responseSigned = self::checkSign($idpMetadata, $response); @@ -714,9 +714,11 @@ class Message if ($validAudiences !== null) { $spEntityId = $spMetadata->getString('entityid'); if (!in_array($spEntityId, $validAudiences, true)) { - $candidates = '['.implode('], [', $validAudiences).']'; - throw new SSP_Error\Exception('This SP ['.$spEntityId. - '] is not a valid audience for the assertion. Candidates were: '.$candidates); + $candidates = '[' . implode('], [', $validAudiences) . ']'; + throw new SSP_Error\Exception( + 'This SP [' . $spEntityId . + '] is not a valid audience for the assertion. Candidates were: ' . $candidates + ); } } @@ -726,7 +728,7 @@ class Message foreach ($assertion->getSubjectConfirmation() as $sc) { $method = $sc->getMethod(); if (!in_array($method, $validSCMethods, true)) { - $lastError = 'Invalid Method on SubjectConfirmation: '.var_export($method, true); + $lastError = 'Invalid Method on SubjectConfirmation: ' . var_export($method, true); continue; } @@ -740,7 +742,7 @@ class Message continue; } if ($method === Constants::CM_HOK && !$hok) { - $lastError = 'Holder-of-Key SubjectConfirmation received, '. + $lastError = 'Holder-of-Key SubjectConfirmation received, ' . 'but the Holder-of-Key profile is not enabled.'; continue; } @@ -760,8 +762,8 @@ class Message $clientCert = $_SERVER['SSL_CLIENT_CERT']; $pattern = '/^-----BEGIN CERTIFICATE-----([^-]*)^-----END CERTIFICATE-----/m'; if (!preg_match($pattern, $clientCert, $matches)) { - $lastError = 'Error while looking for client certificate during TLS handshake with SP, the client '. - 'certificate does not have the expected structure'; + $lastError = 'Error while looking for client certificate during TLS handshake with SP, ' . + 'the client certificate does not have the expected structure'; continue; } // we have a valid client certificate from the browser @@ -774,7 +776,7 @@ class Message } } if (count($keyInfo) != 1) { - $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:KeyInfo> element in '. + $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:KeyInfo> element in ' . '<SubjectConfirmationData> allowed'; continue; } @@ -786,7 +788,7 @@ class Message } } if (count($x509data) != 1) { - $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:X509Data> element in '. + $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:X509Data> element in ' . '<ds:KeyInfo> within <SubjectConfirmationData> allowed'; continue; } @@ -798,14 +800,14 @@ class Message } } if (count($x509cert) != 1) { - $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:X509Certificate> element in '. + $lastError = 'Error validating Holder-of-Key assertion: Only one <ds:X509Certificate> element in ' . '<ds:X509Data> within <SubjectConfirmationData> allowed'; continue; } $HoKCertificate = $x509cert[0]->getCertificate(); if ($HoKCertificate !== $clientCert) { - $lastError = 'Provided client certificate does not match the certificate bound to the '. + $lastError = 'Provided client certificate does not match the certificate bound to the ' . 'Holder-of-Key assertion'; continue; } @@ -819,35 +821,38 @@ class Message $notBefore = $scd->getNotBefore(); if (is_int($notBefore) && $notBefore > time() + 60) { - $lastError = 'NotBefore in SubjectConfirmationData is in the future: '.$notBefore; + $lastError = 'NotBefore in SubjectConfirmationData is in the future: ' . $notBefore; continue; } $notOnOrAfter = $scd->getNotOnOrAfter(); if (is_int($notOnOrAfter) && $notOnOrAfter <= time() - 60) { - $lastError = 'NotOnOrAfter in SubjectConfirmationData is in the past: '.$notOnOrAfter; + $lastError = 'NotOnOrAfter in SubjectConfirmationData is in the past: ' . $notOnOrAfter; continue; } $recipient = $scd->getRecipient(); if ($recipient !== null && $recipient !== $currentURL) { - $lastError = 'Recipient in SubjectConfirmationData does not match the current URL. Recipient is '. - var_export($recipient, true).', current URL is '.var_export($currentURL, true).'.'; + $lastError = 'Recipient in SubjectConfirmationData does not match the current URL. Recipient is ' . + var_export($recipient, true) . ', current URL is ' . var_export($currentURL, true) . '.'; continue; } $inResponseTo = $scd->getInResponseTo(); - if ($inResponseTo !== null && $response->getInResponseTo() !== null && - $inResponseTo !== $response->getInResponseTo() + if ( + $inResponseTo !== null + && $response->getInResponseTo() !== null + && $inResponseTo !== $response->getInResponseTo() ) { - $lastError = 'InResponseTo in SubjectConfirmationData does not match the Response. Response has '. - var_export($response->getInResponseTo(), true). - ', SubjectConfirmationData has '.var_export($inResponseTo, true).'.'; + $lastError = 'InResponseTo in SubjectConfirmationData does not match the Response. Response has ' . + var_export($response->getInResponseTo(), true) . + ', SubjectConfirmationData has ' . var_export($inResponseTo, true) . '.'; continue; } $found = true; break; } if (!$found) { - throw new SSP_Error\Exception('Error validating SubjectConfirmation in Assertion: '.$lastError); - } // as far as we can tell, the assertion is valid + throw new SSP_Error\Exception('Error validating SubjectConfirmation in Assertion: ' . $lastError); + } + // as far as we can tell, the assertion is valid // maybe we need to base64 decode the attributes in the assertion? if ($idpMetadata->getBoolean('base64attributes', false)) { @@ -869,7 +874,7 @@ class Message try { $keys = self::getDecryptionKeys($idpMetadata, $spMetadata); } catch (\Exception $e) { - throw new SSP_Error\Exception('Error decrypting NameID: '.$e->getMessage()); + throw new SSP_Error\Exception('Error decrypting NameID: ' . $e->getMessage()); } $blacklist = self::getBlacklistedAlgorithms($idpMetadata, $spMetadata); @@ -878,11 +883,11 @@ class Message foreach ($keys as $i => $key) { try { $assertion->decryptNameId($key, $blacklist); - Logger::debug('Decryption with key #'.$i.' succeeded.'); + Logger::debug('Decryption with key #' . $i . ' succeeded.'); $lastException = null; break; } catch (\Exception $e) { - Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage()); + Logger::debug('Decryption with key #' . $i . ' failed with exception: ' . $e->getMessage()); $lastException = $e; } } @@ -918,8 +923,8 @@ class Message foreach ($keys as $key) { switch ($key['type']) { case 'X509Certificate': - $pemKey = "-----BEGIN CERTIFICATE-----\n". - chunk_split($key['X509Certificate'], 64). + $pemKey = "-----BEGIN CERTIFICATE-----\n" . + chunk_split($key['X509Certificate'], 64) . "-----END CERTIFICATE-----\n"; $key = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, ['type' => 'public']); $key->loadKey($pemKey); @@ -927,7 +932,7 @@ class Message } } - throw new SSP_Error\Exception('No supported encryption key in '. + throw new SSP_Error\Exception('No supported encryption key in ' . var_export($metadata->getString('entityid'), true)); } } diff --git a/modules/saml/lib/SP/LogoutStore.php b/modules/saml/lib/SP/LogoutStore.php index f60fe2a133cd9d96a341dc4daf4cf764f623fb18..df1bff1c41ade577959bac25110715d17239d942 100644 --- a/modules/saml/lib/SP/LogoutStore.php +++ b/modules/saml/lib/SP/LogoutStore.php @@ -36,10 +36,11 @@ class LogoutStore switch ($store->driver) { case 'pgsql': // This does not affect the NOT NULL constraint - $update = ['ALTER TABLE '.$store->prefix. - '_saml_LogoutStore ALTER COLUMN _expire TIMESTAMP']; + $update = [ + 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _expire TIMESTAMP' + ]; break; - case 'sqlite': + case 'sqlite': /** * Because SQLite does not support field alterations, the approach is to: * Create a new table without the proper column size @@ -49,19 +50,25 @@ class LogoutStore * Read the index */ $update = [ - 'CREATE TABLE '.$store->prefix.'_saml_LogoutStore_new (_authSource VARCHAR(255) NOT NULL,'. - '_nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, _expire DATETIME NOT NULL,'. + 'CREATE TABLE ' . $store->prefix . '_saml_LogoutStore_new (' . + '_authSource VARCHAR(255) NOT NULL, _nameId VARCHAR(40) NOT NULL' . + ', _sessionIndex VARCHAR(50) NOT NULL, _expire DATETIME NOT NULL,' . '_sessionId VARCHAR(50) NOT NULL, UNIQUE (_authSource, _nameID, _sessionIndex))', - 'INSERT INTO '.$store->prefix.'_saml_LogoutStore_new SELECT * FROM '.$store->prefix.'_saml_LogoutStore', - 'DROP TABLE '.$store->prefix.'_saml_LogoutStore', - 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore_new RENAME TO '.$store->prefix.'_saml_LogoutStore', - 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_expire ON '.$store->prefix.'_saml_LogoutStore (_expire)', - 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_nameId ON '.$store->prefix.'_saml_LogoutStore (_authSource, _nameId)' + 'INSERT INTO ' . $store->prefix . '_saml_LogoutStore_new SELECT * FROM ' . + $store->prefix . '_saml_LogoutStore', + 'DROP TABLE ' . $store->prefix . '_saml_LogoutStore', + 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore_new RENAME TO ' . + $store->prefix . '_saml_LogoutStore', + 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ' . + $store->prefix . '_saml_LogoutStore (_expire)', + 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ' . + $store->prefix . '_saml_LogoutStore (_authSource, _nameId)' ]; break; default: - $update = ['ALTER TABLE '.$store->prefix. - '_saml_LogoutStore MODIFY _expire DATETIME NOT NULL']; + $update = [ + 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore MODIFY _expire DATETIME NOT NULL' + ]; break; } @@ -70,28 +77,32 @@ class LogoutStore $store->pdo->exec($query); } } catch (\Exception $e) { - Logger::warning('Database error: '.var_export($store->pdo->errorInfo(), true)); + Logger::warning('Database error: ' . var_export($store->pdo->errorInfo(), true)); return; } $store->setTableVersion('saml_LogoutStore', 4); return; - } elseif ($tableVer === 2) { - // TableVersion 3 fixes the indexes that were set to 255 in version 2; they cannot be larger than 191 on MySQL + /** + * TableVersion 3 fixes the indexes that were set to 255 in version 2; + * they cannot be larger than 191 on MySQL + */ if ($store->driver === 'mysql') { // Drop old indexes - $query = 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore DROP INDEX '.$store->prefix.'_saml_LogoutStore_nameId'; + $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore DROP INDEX ' . + $store->prefix . '_saml_LogoutStore_nameId'; $store->pdo->exec($query); - $query = 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore DROP INDEX _authSource'; + $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore DROP INDEX _authSource'; $store->pdo->exec($query); // Create new indexes - $query = 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_nameId ON '; - $query .= $store->prefix.'_saml_LogoutStore (_authSource(191), _nameId)'; + $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON '; + $query .= $store->prefix . '_saml_LogoutStore (_authSource(191), _nameId)'; $store->pdo->exec($query); - $query = 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore ADD UNIQUE KEY (_authSource(191), _nameID, _sessionIndex)'; + $query = 'ALTER TABLE ' . $store->prefix . + '_saml_LogoutStore ADD UNIQUE KEY (_authSource(191), _nameID, _sessionIndex)'; $store->pdo->exec($query); } @@ -102,10 +113,11 @@ class LogoutStore switch ($store->driver) { case 'pgsql': // This does not affect the NOT NULL constraint - $update = ['ALTER TABLE '.$store->prefix. + $update = [ + 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _authSource TYPE VARCHAR(255)']; break; - case 'sqlite': + case 'sqlite': /** * Because SQLite does not support field alterations, the approach is to: * Create a new table without the proper column size @@ -115,23 +127,33 @@ class LogoutStore * Read the index */ $update = [ - 'CREATE TABLE '.$store->prefix.'_saml_LogoutStore_new (_authSource VARCHAR(255) NOT NULL,'. - '_nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, _expire TIMESTAMP NOT NULL,'. - '_sessionId VARCHAR(50) NOT NULL, UNIQUE (_authSource, _nameID, _sessionIndex))', - 'INSERT INTO '.$store->prefix.'_saml_LogoutStore_new SELECT * FROM '.$store->prefix.'_saml_LogoutStore', - 'DROP TABLE '.$store->prefix.'_saml_LogoutStore', - 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore_new RENAME TO '.$store->prefix.'_saml_LogoutStore', - 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_expire ON '.$store->prefix.'_saml_LogoutStore (_expire)', - 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_nameId ON '.$store->prefix.'_saml_LogoutStore (_authSource, _nameId)' + 'CREATE TABLE ' . $store->prefix . + '_saml_LogoutStore_new (_authSource VARCHAR(255) NOT NULL,' . + '_nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, ' . + '_expire TIMESTAMP NOT NULL, _sessionId VARCHAR(50) NOT NULL, UNIQUE ' . + '(_authSource, _nameID, _sessionIndex))', + 'INSERT INTO ' . $store->prefix . '_saml_LogoutStore_new SELECT * FROM ' . + $store->prefix . '_saml_LogoutStore', + 'DROP TABLE ' . $store->prefix . '_saml_LogoutStore', + 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore_new RENAME TO ' . + $store->prefix . '_saml_LogoutStore', + 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ' . + $store->prefix . '_saml_LogoutStore (_expire)', + 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ' . + $store->prefix . '_saml_LogoutStore (_authSource, _nameId)' ]; break; case 'mysql': - $update = ['ALTER TABLE '.$store->prefix. - '_saml_LogoutStore MODIFY _authSource VARCHAR(191) NOT NULL']; + $update = [ + 'ALTER TABLE ' . $store->prefix . + '_saml_LogoutStore MODIFY _authSource VARCHAR(191) NOT NULL' + ]; break; default: - $update = ['ALTER TABLE '.$store->prefix. - '_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL']; + $update = [ + 'ALTER TABLE ' . $store->prefix . + '_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL' + ]; break; } @@ -140,29 +162,30 @@ class LogoutStore $store->pdo->exec($query); } } catch (\Exception $e) { - Logger::warning('Database error: '.var_export($store->pdo->errorInfo(), true)); + Logger::warning('Database error: ' . var_export($store->pdo->errorInfo(), true)); return; } $store->setTableVersion('saml_LogoutStore', 2); return; } - $query = 'CREATE TABLE '.$store->prefix.'_saml_LogoutStore ( - _authSource VARCHAR('.($store->driver === 'mysql' ? '191' : '255').') NOT NULL, + $query = 'CREATE TABLE ' . $store->prefix . '_saml_LogoutStore ( + _authSource VARCHAR(' . ($store->driver === 'mysql' ? '191' : '255') . ') NOT NULL, _nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, _expire ' . ($store->driver === 'pgsql' ? 'TIMESTAMP' : 'DATETIME') . ' NOT NULL, _sessionId VARCHAR(50) NOT NULL, - UNIQUE (_authSource'.($store->driver === 'mysql' ? '(191)' : '').', _nameID, _sessionIndex) + UNIQUE (_authSource' . ($store->driver === 'mysql' ? '(191)' : '') . ', _nameID, _sessionIndex) )'; $store->pdo->exec($query); - $query = 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_expire ON '; - $query .= $store->prefix.'_saml_LogoutStore (_expire)'; + $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON '; + $query .= $store->prefix . '_saml_LogoutStore (_expire)'; $store->pdo->exec($query); - $query = 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_nameId ON '; - $query .= $store->prefix.'_saml_LogoutStore (_authSource'.($store->driver === 'mysql' ? '(191)' : '').', _nameId)'; + $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON '; + $query .= $store->prefix . '_saml_LogoutStore (_authSource' . ($store->driver === 'mysql' ? '(191)' : '') . + ', _nameId)'; $store->pdo->exec($query); $store->setTableVersion('saml_LogoutStore', 4); @@ -179,7 +202,7 @@ class LogoutStore { Logger::debug('saml.LogoutStore: Cleaning logout store.'); - $query = 'DELETE FROM '.$store->prefix.'_saml_LogoutStore WHERE _expire < :now'; + $query = 'DELETE FROM ' . $store->prefix . '_saml_LogoutStore WHERE _expire < :now'; $params = ['now' => gmdate('Y-m-d H:i:s')]; $query = $store->pdo->prepare($query); @@ -226,7 +249,7 @@ class LogoutStore '_sessionId' => $sessionId, ]; $store->insertOrUpdate( - $store->prefix.'_saml_LogoutStore', + $store->prefix . '_saml_LogoutStore', ['_authSource', '_nameId', '_sessionIndex'], $data ); @@ -255,8 +278,8 @@ class LogoutStore ]; // We request the columns in lowercase in order to be compatible with PostgreSQL - $query = 'SELECT _sessionIndex AS _sessionindex, _sessionId AS _sessionid FROM '.$store->prefix; - $query .= '_saml_LogoutStore'.' WHERE _authSource = :_authSource AND _nameId = :_nameId AND _expire >= :now'; + $query = 'SELECT _sessionIndex AS _sessionindex, _sessionId AS _sessionid FROM ' . $store->prefix; + $query .= '_saml_LogoutStore WHERE _authSource = :_authSource AND _nameId = :_nameId AND _expire >= :now'; $query = $store->pdo->prepare($query); $query->execute($params); @@ -285,7 +308,7 @@ class LogoutStore $res = []; foreach ($sessionIndexes as $sessionIndex) { - $sessionId = $store->get('saml.LogoutStore', $nameId.':'.$sessionIndex); + $sessionId = $store->get('saml.LogoutStore', $nameId . ':' . $sessionIndex); if ($sessionId === null) { continue; } @@ -358,7 +381,7 @@ class LogoutStore if ($store instanceof Store\SQL) { self::addSessionSQL($store, $authId, $strNameId, $sessionIndex, $expire, $sessionId); } else { - $store->set('saml.LogoutStore', $strNameId.':'.$sessionIndex, $sessionId, $expire); + $store->set('saml.LogoutStore', $strNameId . ':' . $sessionIndex, $sessionId, $expire); } } @@ -437,7 +460,7 @@ class LogoutStore } Logger::info( - 'saml.LogoutStore: Logging out of session with trackId ['.$session->getTrackID().'].' + 'saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackID() . '].' ); $session->doLogout($authId); $numLoggedOut += 1; diff --git a/modules/saml/www/idp/certs.php b/modules/saml/www/idp/certs.php index 7d4ba82aff3ce8edf27965a18e67319d5e9b204e..5f11e7461db7d38fccabcf090d65fe5996ecfa35 100644 --- a/modules/saml/www/idp/certs.php +++ b/modules/saml/www/idp/certs.php @@ -32,7 +32,7 @@ switch ($_SERVER['PATH_INFO']) { default: throw new \SimpleSAML\Error\NotFound('Unknown certificate.'); } -header('Content-Disposition: attachment; filename='.substr($_SERVER['PATH_INFO'], 1)); +header('Content-Disposition: attachment; filename=' . substr($_SERVER['PATH_INFO'], 1)); header('Content-Type: application/x-x509-ca-cert'); echo $certInfo['PEM']; diff --git a/modules/saml/www/sp/discoresp.php b/modules/saml/www/sp/discoresp.php index 8d1ab65d5837b4adf7fb223bd921b7dd29bf1817..ec944c3ed8ed6e15bf997f2cf8b2e671980f4fe5 100644 --- a/modules/saml/www/sp/discoresp.php +++ b/modules/saml/www/sp/discoresp.php @@ -21,7 +21,7 @@ $sourceId = $state['saml:sp:AuthId']; $source = \SimpleSAML\Auth\Source::getById($sourceId); if ($source === null) { - throw new Exception('Could not find authentication source with id '.$sourceId); + throw new Exception('Could not find authentication source with id ' . $sourceId); } if (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) { throw new \SimpleSAML\Error\Exception('Source type changed?'); diff --git a/modules/saml/www/sp/metadata.php b/modules/saml/www/sp/metadata.php index 220d3018167e4f3d00969507cd65914773b162cb..b13d86fed33df9cadcc69736232f554d5e5b9adb 100644 --- a/modules/saml/www/sp/metadata.php +++ b/modules/saml/www/sp/metadata.php @@ -33,7 +33,7 @@ $slosvcdefault = [ ]; $slob = $spconfig->getArray('SingleLogoutServiceBinding', $slosvcdefault); -$slol = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-logout.php/'.$sourceId); +$slol = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-logout.php/' . $sourceId); foreach ($slob as $binding) { if ($binding == \SAML2\Constants::BINDING_SOAP && !($store instanceof \SimpleSAML\Store\SQL)) { @@ -67,35 +67,37 @@ foreach ($assertionsconsumerservices as $services) { switch ($services) { case 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST': $acsArray['Binding'] = \SAML2\Constants::BINDING_HTTP_POST; - $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/'.$sourceId); + $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $sourceId); if (!in_array(\SAML2\Constants::NS_SAMLP, $supported_protocols, true)) { $supported_protocols[] = \SAML2\Constants::NS_SAMLP; } break; case 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post': $acsArray['Binding'] = 'urn:oasis:names:tc:SAML:1.0:profiles:browser-post'; - $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/'.$sourceId); + $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $sourceId); if (!in_array('urn:oasis:names:tc:SAML:1.1:protocol', $supported_protocols, true)) { $supported_protocols[] = 'urn:oasis:names:tc:SAML:1.1:protocol'; } break; case 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact': $acsArray['Binding'] = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'; - $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/'.$sourceId); + $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $sourceId); if (!in_array(\SAML2\Constants::NS_SAMLP, $supported_protocols, true)) { $supported_protocols[] = \SAML2\Constants::NS_SAMLP; } break; case 'urn:oasis:names:tc:SAML:1.0:profiles:artifact-01': $acsArray['Binding'] = 'urn:oasis:names:tc:SAML:1.0:profiles:artifact-01'; - $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/'.$sourceId.'/artifact'); + $acsArray['Location'] = \SimpleSAML\Module::getModuleURL( + 'saml/sp/saml1-acs.php/' . $sourceId . '/artifact' + ); if (!in_array('urn:oasis:names:tc:SAML:1.1:protocol', $supported_protocols, true)) { $supported_protocols[] = 'urn:oasis:names:tc:SAML:1.1:protocol'; } break; case 'urn:oasis:names:tc:SAML:2.0:profiles:holder-of-key:SSO:browser': $acsArray['Binding'] = 'urn:oasis:names:tc:SAML:2.0:profiles:holder-of-key:SSO:browser'; - $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/'.$sourceId); + $acsArray['Location'] = \SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $sourceId); $acsArray['hoksso:ProtocolBinding'] = \SAML2\Constants::BINDING_HTTP_REDIRECT; if (!in_array(\SAML2\Constants::NS_SAMLP, $supported_protocols, true)) { $supported_protocols[] = \SAML2\Constants::NS_SAMLP; @@ -276,7 +278,8 @@ if (array_key_exists('output', $_REQUEST) && $_REQUEST['output'] == 'xhtml') { $t->data['header'] = 'saml20-sp'; // TODO: Replace with headerString in 2.0 $t->data['headerString'] = \SimpleSAML\Locale\Translate::noop('metadata_saml20-sp'); $t->data['metadata'] = htmlspecialchars($xml); - $t->data['metadataflat'] = '$metadata['.var_export($entityId, true).'] = '.var_export($metaArray20, true).';'; + $t->data['metadataflat'] = '$metadata[' . var_export($entityId, true) + . '] = ' . var_export($metaArray20, true) . ';'; $t->data['metaurl'] = $source->getMetadataURL(); $t->show(); } else { diff --git a/modules/saml/www/sp/saml2-acs.php b/modules/saml/www/sp/saml2-acs.php index 23a4de7da41cce4f7c9bdfa5f14be0c0817591ae..4d05bf2b8ecf0fe4defa5d0fc2a0598c1c126ced 100644 --- a/modules/saml/www/sp/saml2-acs.php +++ b/modules/saml/www/sp/saml2-acs.php @@ -92,7 +92,7 @@ if (!empty($stateId)) { $state = \SimpleSAML\Auth\State::loadState($stateId, 'saml:sp:sso'); } catch (Exception $e) { // something went wrong, - SimpleSAML\Logger::warning('Could not load state specified by InResponseTo: '.$e->getMessage(). + SimpleSAML\Logger::warning('Could not load state specified by InResponseTo: ' . $e->getMessage() . ' Processing response as unsolicited.'); } } @@ -112,7 +112,9 @@ if ($state) { $idpMetadata = $source->getIdPMetadata($issuer); $idplist = $idpMetadata->getArrayize('IDPList', []); if (!in_array($state['ExpectedIssuer'], $idplist, true)) { - SimpleSAML\Logger::warning('The issuer of the response not match to the identity provider we sent the request to.'); + SimpleSAML\Logger::warning( + 'The issuer of the response not match to the identity provider we sent the request to.' + ); } } } else { @@ -129,7 +131,7 @@ if ($state) { ]; } -SimpleSAML\Logger::debug('Received SAML2 Response from '.var_export($issuer, true).'.'); +SimpleSAML\Logger::debug('Received SAML2 Response from ' . var_export($issuer, true) . '.'); if (is_null($idpMetadata)) { $idpMetadata = $source->getIdPmetadata($issuer); diff --git a/modules/saml/www/sp/saml2-logout.php b/modules/saml/www/sp/saml2-logout.php index 9f835d370616abae7d0fc4638f6e0fac770aea3b..61950a71e17664bee2945037254192de434040ae 100644 --- a/modules/saml/www/sp/saml2-logout.php +++ b/modules/saml/www/sp/saml2-logout.php @@ -15,7 +15,7 @@ $sourceId = substr($_SERVER['PATH_INFO'], 1); /** @var \SimpleSAML\Module\saml\Auth\Source\SP $source */ $source = \SimpleSAML\Auth\Source::getById($sourceId); if ($source === null) { - throw new \Exception('Could not find authentication source with id '.$sourceId); + throw new \Exception('Could not find authentication source with id ' . $sourceId); } elseif (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) { throw new \SimpleSAML\Error\Exception('Source type changed?'); } @@ -69,7 +69,7 @@ if ($message instanceof \SAML2\LogoutResponse) { if (!$message->isSuccess()) { \SimpleSAML\Logger::warning( - 'Unsuccessful logout. Status was: '.\SimpleSAML\Module\saml\Message::getResponseError($message) + 'Unsuccessful logout. Status was: ' . \SimpleSAML\Module\saml\Message::getResponseError($message) ); } @@ -77,14 +77,14 @@ if ($message instanceof \SAML2\LogoutResponse) { $state['saml:sp:LogoutStatus'] = $message->getStatus(); \SimpleSAML\Auth\Source::completeLogout($state); } elseif ($message instanceof \SAML2\LogoutRequest) { - \SimpleSAML\Logger::debug('module/saml2/sp/logout: Request from '.$idpEntityId); - \SimpleSAML\Logger::stats('saml20-idp-SLO idpinit '.$spEntityId.' '.$idpEntityId); + \SimpleSAML\Logger::debug('module/saml2/sp/logout: Request from ' . $idpEntityId); + \SimpleSAML\Logger::stats('saml20-idp-SLO idpinit ' . $spEntityId . ' ' . $idpEntityId); if ($message->isNameIdEncrypted()) { try { $keys = \SimpleSAML\Module\saml\Message::getDecryptionKeys($idpMetadata, $spMetadata); } catch (\Exception $e) { - throw new \SimpleSAML\Error\Exception('Error decrypting NameID: '.$e->getMessage()); + throw new \SimpleSAML\Error\Exception('Error decrypting NameID: ' . $e->getMessage()); } $blacklist = \SimpleSAML\Module\saml\Message::getBlacklistedAlgorithms($idpMetadata, $spMetadata); @@ -93,11 +93,11 @@ if ($message instanceof \SAML2\LogoutResponse) { foreach ($keys as $i => $key) { try { $message->decryptNameId($key, $blacklist); - \SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.'); + \SimpleSAML\Logger::debug('Decryption with key #' . $i . ' succeeded.'); $lastException = null; break; } catch (\Exception $e) { - \SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage()); + \SimpleSAML\Logger::debug('Decryption with key #' . $i . ' failed with exception: ' . $e->getMessage()); $lastException = $e; } } @@ -122,7 +122,7 @@ if ($message instanceof \SAML2\LogoutResponse) { $lr->setInResponseTo($message->getId()); if ($numLoggedOut < count($sessionIndexes)) { - \SimpleSAML\Logger::warning('Logged out of '.$numLoggedOut.' of '.count($sessionIndexes).' sessions.'); + \SimpleSAML\Logger::warning('Logged out of ' . $numLoggedOut . ' of ' . count($sessionIndexes) . ' sessions.'); } /** @var array $dst */ @@ -147,5 +147,5 @@ if ($message instanceof \SAML2\LogoutResponse) { $binding->send($lr); } else { - throw new \SimpleSAML\Error\BadRequest('Unknown message received on logout endpoint: '.get_class($message)); + throw new \SimpleSAML\Error\BadRequest('Unknown message received on logout endpoint: ' . get_class($message)); } diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000000000000000000000000000000000000..e0fac90e0145fe8c3f549ac84e1359c2e3edebb7 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,37 @@ +<?xml version="1.0"?> +<ruleset name="SimpleSAMLphp ruleset"> + <description> + By default it is less stringent about long lines than other coding standards + </description> + + <!-- Use this to exclude paths. You can have multiple patterns --> + <!--<exclude-pattern>*/tests/*</exclude-pattern>--> + <!--<exclude-pattern>*/other/*</exclude-pattern>--> + <exclude-pattern>lib/SimpleSAML/Auth/LDAP.php</exclude-pattern> + <exclude-pattern>lib/SimpleSAML/Auth/TimeLimitedToken.php</exclude-pattern> + <exclude-pattern>lib/SimpleSAML/Bindings/Shib13/*</exclude-pattern> + <exclude-pattern>lib/SimpleSAML/Utilities.php</exclude-pattern> + <exclude-pattern>lib/SimpleSAML/XML/Shib13/*</exclude-pattern> + <exclude-pattern>modules/*/templates/*.tpl.php</exclude-pattern> + <exclude-pattern>modules/saml/lib/IdP/SAML1.php</exclude-pattern> + <exclude-pattern>modules/saml/www/sp/saml1-acs.php</exclude-pattern> + <exclude-pattern>templates/*.tpl.php</exclude-pattern> + <exclude-pattern>tests/lib/SimpleSAML/Auth/TimeLimitedTokenTest.php</exclude-pattern> + <exclude-pattern>tests/Utils/Stubs/*</exclude-pattern> + + <!-- This is the rule we inherit from. If you want to exlude some specific rules, see the docs on how to do that --> + <rule ref="PSR12"/> + + <!-- Lines can be a little bit longer before they break the build --> + <rule ref="Generic.Files.LineLength"> + <properties> + <property name="lineLimit" value="120"/> + <property name="absoluteLineLimit" value="130"/> + </properties> + </rule> + + <rule ref="PSR1.Methods.CamelCapsMethodName"> + <exclude-pattern>lib/SimpleSAML/XHTML/Template.php</exclude-pattern> + </rule> +</ruleset> + diff --git a/tests/BuiltInServer.php b/tests/BuiltInServer.php index 143e35fdf69ca008aad628d312af9838a9ae45a1..5bb7beed720336faf2105526c89708bea13076ef 100644 --- a/tests/BuiltInServer.php +++ b/tests/BuiltInServer.php @@ -1,4 +1,9 @@ <?php + +namespace SimpleSAML\Test; + +use SimpleSAML\Utils\System; + /** * An extremely simple class to start and stop PHP's built-in server, with the possibility to specify the document * root and the "router" file to run for every request. @@ -7,10 +12,6 @@ * @package SimpleSAMLphp */ -namespace SimpleSAML\Test; - -use SimpleSAML\Utils\System; - class BuiltInServer { /** @@ -59,7 +60,7 @@ class BuiltInServer if (!is_null($docroot)) { $this->docroot = $docroot; } else { - $this->docroot = dirname(dirname(__FILE__)).'/www/'; + $this->docroot = dirname(dirname(__FILE__)) . '/www/'; } // Rationalize docroot @@ -72,8 +73,8 @@ class BuiltInServer * Start the built-in server in a random port. * * This method will wait up to 5 seconds for the server to start. When it returns an address, it is guaranteed that - * the server has started and is listening for connections. If it returns the default value on the other hand, there will be no - * guarantee that the server started properly. + * the server has started and is listening for connections. If it returns the default value on the other hand, + * there will be no guarantee that the server started properly. * * @return string The address where the server is listening for connections, or false if the server failed to start * for some reason. @@ -83,11 +84,12 @@ class BuiltInServer public function start() { $port = mt_rand(1025, 65535); - $this->address = 'localhost:'.$port; + $this->address = 'localhost:' . $port; if (System::getOS() === System::WINDOWS) { $command = sprintf( - 'powershell $proc = start-process php -ArgumentList (\'-S %s\', \'-t %s\', \'%s\') -Passthru; Write-output $proc.Id;', + 'powershell $proc = start-process php -ArgumentList (\'-S %s\', \'-t %s\', \'%s\') ' + . '-Passthru; Write-output $proc.Id;', $this->address, $this->docroot, $this->router @@ -135,10 +137,10 @@ class BuiltInServer { if ($this->pid === 0) { return; - } else if (System::getOS() === System::WINDOWS) { - exec('taskkill /PID '.$this->pid); + } elseif (System::getOS() === System::WINDOWS) { + exec('taskkill /PID ' . $this->pid); } else { - exec('kill '.$this->pid); + exec('kill ' . $this->pid); } $this->pid = 0; } @@ -174,9 +176,9 @@ class BuiltInServer */ public function setRouter($router) { - $file = dirname(dirname(__FILE__)).'/tests/routers/'.$router.'.php'; + $file = dirname(dirname(__FILE__)) . '/tests/routers/' . $router . '.php'; if (!file_exists($file)) { - throw new \InvalidArgumentException('Unknown router "'.$router.'".'); + throw new \InvalidArgumentException('Unknown router "' . $router . '".'); } $this->router = $file; } @@ -194,8 +196,8 @@ class BuiltInServer public function get($query, $parameters, $curlopts = []) { $ch = curl_init(); - $url = 'http://'.$this->address.$query; - $url .= (!empty($parameters)) ? '?'.http_build_query($parameters) : ''; + $url = 'http://' . $this->address . $query; + $url .= (!empty($parameters)) ? '?' . http_build_query($parameters) : ''; curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, diff --git a/tests/SigningTestCase.php b/tests/SigningTestCase.php index c561fa598aa36f3fedda4e6ab3005581cb09794f..80baba3c421a8002c73c5ef6bc639a191eb67511 100644 --- a/tests/SigningTestCase.php +++ b/tests/SigningTestCase.php @@ -1,17 +1,17 @@ <?php -/** - * A test case that provides a certificate directory with public and private - * keys. - * - * @package SimpleSAMLphp - */ namespace SimpleSAML\Test; +use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; -use \org\bovigo\vfs\vfsStream; +/** + * A test case that provides a certificate directory with public and private + * keys. + * + * @package SimpleSAMLphp + */ class SigningTestCase extends TestCase { // openssl genrsa -out ca.key.pem 2048 @@ -199,11 +199,11 @@ NOWDOC; ); $this->root_directory = vfsStream::url(self::ROOTDIRNAME); - $this->certdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTCERTDIR; - $this->ca_private_key_file = $this->certdir.DIRECTORY_SEPARATOR.self::CA_PRIVATE_KEY; - $this->ca_certificate_file = $this->certdir.DIRECTORY_SEPARATOR.self::CA_CERTIFICATE; - $this->good_private_key_file = $this->certdir.DIRECTORY_SEPARATOR.self::GOOD_PRIVATE_KEY; - $this->good_certificate_file = $this->certdir.DIRECTORY_SEPARATOR.self::GOOD_CERTIFICATE; + $this->certdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTCERTDIR; + $this->ca_private_key_file = $this->certdir . DIRECTORY_SEPARATOR . self::CA_PRIVATE_KEY; + $this->ca_certificate_file = $this->certdir . DIRECTORY_SEPARATOR . self::CA_CERTIFICATE; + $this->good_private_key_file = $this->certdir . DIRECTORY_SEPARATOR . self::GOOD_PRIVATE_KEY; + $this->good_certificate_file = $this->certdir . DIRECTORY_SEPARATOR . self::GOOD_CERTIFICATE; $this->config = \SimpleSAML\Configuration::loadFromArray([ 'certdir' => $this->certdir, diff --git a/tests/Utils/ClearStateTestCase.php b/tests/Utils/ClearStateTestCase.php index fc713731ceb59e5e8f93aa74249a160fb53f0c14..7db826e37c940e9e62d183eccbb8872bd14bd081 100644 --- a/tests/Utils/ClearStateTestCase.php +++ b/tests/Utils/ClearStateTestCase.php @@ -2,8 +2,6 @@ namespace SimpleSAML\Test\Utils; -include(dirname(__FILE__).'/StateClearer.php'); - use PHPUnit\Framework\TestCase; /** diff --git a/tests/Utils/ExitTestException.php b/tests/Utils/ExitTestException.php new file mode 100644 index 0000000000000000000000000000000000000000..02c0bb544d4bd20c3554e19c57bdcde578335dd0 --- /dev/null +++ b/tests/Utils/ExitTestException.php @@ -0,0 +1,32 @@ +<?php + +namespace SimpleSAML\Test\Utils; + +/** + * Custom Exception to throw to terminate a TestCase. + */ +class ExitTestException extends \Exception +{ + /** @var array */ + private $testResult; + + + /** + * @param array $testResult + * @return void + */ + public function __construct(array $testResult) + { + parent::__construct("ExitTestException", 0, null); + $this->testResult = $testResult; + } + + + /** + * @return array + */ + public function getTestResult() + { + return $this->testResult; + } +} diff --git a/tests/Utils/ReduceSpillOverTest.php b/tests/Utils/ReduceSpillOverTest.php index c53ba6f7ddcfa0feaf6937d293395b2d9e470038..a84b93be5c369b18d63f85224a3843e7152e65ba 100644 --- a/tests/Utils/ReduceSpillOverTest.php +++ b/tests/Utils/ReduceSpillOverTest.php @@ -17,7 +17,7 @@ class ReduceSpillOverTest extends ClearStateTestCase $_SERVER['QUERY_STRING'] = 'a=b'; \SimpleSAML\Configuration::loadFromArray(['a' => 'b'], '[ARRAY]', 'simplesaml'); $this->assertEquals('b', \SimpleSAML\Configuration::getInstance()->getString('a')); - putenv('SIMPLESAMLPHP_CONFIG_DIR='.__DIR__); + putenv('SIMPLESAMLPHP_CONFIG_DIR=' . __DIR__); } diff --git a/tests/Utils/SpTester.php b/tests/Utils/SpTester.php new file mode 100644 index 0000000000000000000000000000000000000000..a4151b75ada7e2dbcd3f57887bbe4568764b9d36 --- /dev/null +++ b/tests/Utils/SpTester.php @@ -0,0 +1,55 @@ +<?php + +namespace SimpleSAML\Test\Utils; + +use ReflectionObject; +use SAML2\AuthnRequest; +use SAML2\Binding; +use SimpleSAML\Configuration; + +/** + * Wrap the SSP \SimpleSAML\Module\saml\Auth\Source\SP class + * - Use introspection to make startSSO2Test available + * - Override sendSAML2AuthnRequest() to catch the AuthnRequest being sent + */ +class SpTester extends \SimpleSAML\Module\saml\Auth\Source\SP +{ + /** + * @param array $info + * @param array $config + * @return void + */ + public function __construct($info, $config) + { + parent::__construct($info, $config); + } + + + /** + * @return void + */ + public function startSSO2Test(Configuration $idpMetadata, array $state) + { + $reflector = new ReflectionObject($this); + $method = $reflector->getMethod('startSSO2'); + $method->setAccessible(true); + $method->invoke($this, $idpMetadata, $state); + } + + + /** + * override the method that sends the request to avoid sending anything + * @return void + */ + public function sendSAML2AuthnRequest(array &$state, Binding $binding, AuthnRequest $ar) + { + // Exit test. Continuing would mean running into a assert(FALSE) + throw new ExitTestException( + [ + 'state' => $state, + 'binding' => $binding, + 'ar' => $ar, + ] + ); + } +} diff --git a/tests/Utils/StateClearer.php b/tests/Utils/StateClearer.php index 56412bcf5cdc9273afd914171e2d0163b941d27a..ec5258819e840cb533130082d41567e1735541e8 100644 --- a/tests/Utils/StateClearer.php +++ b/tests/Utils/StateClearer.php @@ -17,7 +17,12 @@ class StateClearer * Class that implement \SimpleSAML\Utils\ClearableState and should have clearInternalState called between tests * @var array */ - private $clearableState = ['SimpleSAML\Configuration', 'SimpleSAML\Metadata\MetaDataStorageHandler', 'SimpleSAML\Store', 'SimpleSAML\Session']; + private $clearableState = [ + 'SimpleSAML\Configuration', + 'SimpleSAML\Metadata\MetaDataStorageHandler', + 'SimpleSAML\Store', + 'SimpleSAML\Session' + ]; /** * Environmental variables to unset diff --git a/tests/Utils/TestAuthSource.php b/tests/Utils/TestAuthSource.php new file mode 100644 index 0000000000000000000000000000000000000000..924c9690fed7ab33bba2d7664d3d730ad7e446df --- /dev/null +++ b/tests/Utils/TestAuthSource.php @@ -0,0 +1,15 @@ +<?php + +namespace SimpleSAML\Test\Utils; + +use SimpleSAML\Auth\Source; + +class TestAuthSource extends Source +{ + /** + * @return void + */ + public function authenticate(&$state) + { + } +} diff --git a/tests/Utils/TestAuthSourceFactory.php b/tests/Utils/TestAuthSourceFactory.php new file mode 100644 index 0000000000000000000000000000000000000000..a3df2d8c3cffd3822248d016198548e867dcb741 --- /dev/null +++ b/tests/Utils/TestAuthSourceFactory.php @@ -0,0 +1,16 @@ +<?php + +namespace SimpleSAML\Test\Utils; + +use SimpleSAML\Auth\SourceFactory; + +class TestAuthSourceFactory implements SourceFactory +{ + /** + * @return \SimpleSAML\Test\Utils\TestAuthSource + */ + public function create(array $info, array $config) + { + return new TestAuthSource($info, $config); + } +} diff --git a/tests/_autoload_modules.php b/tests/_autoload_modules.php index 8b1da33e75d710431af4e35ba0330a62b7aa32df..172ec16243bd99dcf0c9037c9fa4887f859c8c3c 100644 --- a/tests/_autoload_modules.php +++ b/tests/_autoload_modules.php @@ -32,8 +32,8 @@ function sspmodTestClassAutoloadPSR4($className) // this is a SimpleSAMLphp module test class following PSR-4 $module = array_shift($elements); - $moduleTestDir = __DIR__ .'/modules/'.$module; - $file = $moduleTestDir .'/lib/'.implode('/', $elements).'.php'; + $moduleTestDir = __DIR__ . '/modules/' . $module; + $file = $moduleTestDir . '/lib/' . implode('/', $elements) . '.php'; if (file_exists($file)) { require_once($file); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 82ed397dc1f01a6d83f49ee20bbb44c2dff15267..4ec9274b9b08c126d52bc3286c5b9c877eed2a4e 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,7 +1,7 @@ <?php $projectRoot = dirname(__DIR__); -require_once($projectRoot.'/vendor/autoload.php'); +require_once($projectRoot . '/vendor/autoload.php'); // Current SSP autoloader can't resolve classes from the tests folder. -include($projectRoot.'/tests/Utils/ClearStateTestCase.php'); +include($projectRoot . '/tests/Utils/ClearStateTestCase.php'); diff --git a/tests/lib/SimpleSAML/Auth/SourceTest.php b/tests/lib/SimpleSAML/Auth/SourceTest.php index 57585ec8346882ee44aec1b12d6a2d01656fe986..26c382c54dc4ae799f8a26f275fab5c159726a9d 100644 --- a/tests/lib/SimpleSAML/Auth/SourceTest.php +++ b/tests/lib/SimpleSAML/Auth/SourceTest.php @@ -2,8 +2,9 @@ namespace SimpleSAML\Test\Auth; -use SimpleSAML\Auth\SourceFactory; use SimpleSAML\Test\Utils\ClearStateTestCase; +use SimpleSAML\Test\Utils\TestAuthSource; +use SimpleSAML\Test\Utils\TestAuthSourceFactory; /** * Tests for \SimpleSAML\Auth\Source @@ -20,32 +21,11 @@ class SourceTest extends ClearStateTestCase $method->setAccessible(true); // test direct instantiation of the auth source object - $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]); - $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource); + $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Utils\TestAuthSource']]); + $this->assertInstanceOf('SimpleSAML\Test\Utils\TestAuthSource', $authSource); // test instantiation via an auth source factory - $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]); - $this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource); - } -} - -class TestAuthSource extends \SimpleSAML\Auth\Source -{ - /** - * @return void - */ - public function authenticate(&$state) - { - } -} - -class TestAuthSourceFactory implements SourceFactory -{ - /** - * @return \SimpleSAML\Test\Auth\TestAuthSource - */ - public function create(array $info, array $config) - { - return new TestAuthSource($info, $config); + $authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Utils\TestAuthSourceFactory']]); + $this->assertInstanceOf('SimpleSAML\Test\Utils\TestAuthSource', $authSource); } } diff --git a/tests/lib/SimpleSAML/Auth/StateTest.php b/tests/lib/SimpleSAML/Auth/StateTest.php index 38d8058621aeabd887ec679548f28d23c857b9d3..6d1c2a52ea392143bd72a1a1bb54cc451b2d4a84 100644 --- a/tests/lib/SimpleSAML/Auth/StateTest.php +++ b/tests/lib/SimpleSAML/Auth/StateTest.php @@ -30,7 +30,7 @@ class StateTest extends TestCase $this->assertEquals( $expected, \SimpleSAML\Auth\State::getPersistentAuthData($state), - 'Mandatory state attributes did not survive as expected'.print_r($expected, true) + 'Mandatory state attributes did not survive as expected' . print_r($expected, true) ); // check missing mandatory parameters diff --git a/tests/lib/SimpleSAML/ConfigurationTest.php b/tests/lib/SimpleSAML/ConfigurationTest.php index 7ee701055101441f1346fa3b59f08a687743ef48..fcc463003573bc37dde1b02a24029c10fb2d5e0c 100644 --- a/tests/lib/SimpleSAML/ConfigurationTest.php +++ b/tests/lib/SimpleSAML/ConfigurationTest.php @@ -231,17 +231,17 @@ class ConfigurationTest extends \SimpleSAML\Test\Utils\ClearStateTestCase public function testGetBaseDir() { $c = Configuration::loadFromArray([]); - $this->assertEquals($c->getBaseDir(), dirname(dirname(dirname(dirname(__FILE__)))).DIRECTORY_SEPARATOR); + $this->assertEquals($c->getBaseDir(), dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR); $c = Configuration::loadFromArray([ - 'basedir' => DIRECTORY_SEPARATOR.'basedir', + 'basedir' => DIRECTORY_SEPARATOR . 'basedir', ]); - $this->assertEquals($c->getBaseDir(), DIRECTORY_SEPARATOR.'basedir'.DIRECTORY_SEPARATOR); + $this->assertEquals($c->getBaseDir(), DIRECTORY_SEPARATOR . 'basedir' . DIRECTORY_SEPARATOR); $c = Configuration::loadFromArray([ - 'basedir' => DIRECTORY_SEPARATOR.'basedir'.DIRECTORY_SEPARATOR, + 'basedir' => DIRECTORY_SEPARATOR . 'basedir' . DIRECTORY_SEPARATOR, ]); - $this->assertEquals($c->getBaseDir(), DIRECTORY_SEPARATOR.'basedir'.DIRECTORY_SEPARATOR); + $this->assertEquals($c->getBaseDir(), DIRECTORY_SEPARATOR . 'basedir' . DIRECTORY_SEPARATOR); } @@ -831,7 +831,7 @@ class ConfigurationTest extends \SimpleSAML\Test\Utils\ClearStateTestCase $this->fail('Failed to detect invalid endpoint binding.'); } catch (\Exception $e) { $this->assertEquals( - '[ARRAY][\'SingleLogoutService\']:Could not find a supported SingleLogoutService '.'endpoint.', + '[ARRAY][\'SingleLogoutService\']:Could not find a supported SingleLogoutService ' . 'endpoint.', $e->getMessage() ); } diff --git a/tests/lib/SimpleSAML/DatabaseTest.php b/tests/lib/SimpleSAML/DatabaseTest.php index f30db8ed49d928156f034356a62d3c3068b16ed9..0e98f91577166ad8462e153c8caa7a0dbff1d51f 100644 --- a/tests/lib/SimpleSAML/DatabaseTest.php +++ b/tests/lib/SimpleSAML/DatabaseTest.php @@ -227,7 +227,7 @@ class DatabaseTest extends TestCase $table = "saml20_idp_hosted"; $pftable = $this->db->applyPrefix($table); - $this->assertEquals($prefix.$table, $pftable, "Did not properly apply the table prefix"); + $this->assertEquals($prefix . $table, $pftable, "Did not properly apply the table prefix"); } @@ -242,7 +242,7 @@ class DatabaseTest extends TestCase public function querying() { $table = $this->db->applyPrefix("sspdbt"); - $this->assertEquals($this->config->getString('database.prefix')."sspdbt", $table); + $this->assertEquals($this->config->getString('database.prefix') . "sspdbt", $table); $this->db->write( "CREATE TABLE IF NOT EXISTS $table (ssp_key INT(16) NOT NULL, ssp_value TEXT NOT NULL)" @@ -277,7 +277,7 @@ class DatabaseTest extends TestCase { $this->expectException(\Exception::class); $table = $this->db->applyPrefix("sspdbt"); - $this->assertEquals($this->config->getString('database.prefix')."sspdbt", $table); + $this->assertEquals($this->config->getString('database.prefix') . "sspdbt", $table); $this->db->read("SELECT * FROM $table"); } diff --git a/tests/lib/SimpleSAML/Locale/LocalizationTest.php b/tests/lib/SimpleSAML/Locale/LocalizationTest.php index bfc55457f5f7f2445bc629559f5188a261effeb8..e68e1928b4728ff907bcddb4c769e634da234808 100644 --- a/tests/lib/SimpleSAML/Locale/LocalizationTest.php +++ b/tests/lib/SimpleSAML/Locale/LocalizationTest.php @@ -3,8 +3,8 @@ namespace SimpleSAML\Test\Locale; use PHPUnit\Framework\TestCase; +use SimpleSAML\Configuration; use SimpleSAML\Locale\Localization; -use \SimpleSAML\Configuration; class LocalizationTest extends TestCase { diff --git a/tests/lib/SimpleSAML/Locale/TranslateTest.php b/tests/lib/SimpleSAML/Locale/TranslateTest.php index c8d47718e337a5bc81e6c7abc834f1ce89c15aab..c8209f97e571c03773b462aaeecb47588e8af245 100644 --- a/tests/lib/SimpleSAML/Locale/TranslateTest.php +++ b/tests/lib/SimpleSAML/Locale/TranslateTest.php @@ -32,7 +32,7 @@ class TranslateTest extends TestCase $testString = 'Blablabla'; // $fallbackdefault = true - $result = 'not translated ('.$testString.')'; + $result = 'not translated (' . $testString . ')'; $this->assertEquals($result, $t->t($testString)); // $fallbackdefault = false, should be a noop diff --git a/tests/lib/SimpleSAML/Metadata/MetaDataStorageSourceTest.php b/tests/lib/SimpleSAML/Metadata/MetaDataStorageSourceTest.php index 45e57c5ff1aa554b57cc44db095b85a7a09122f7..323446eabefadfcd0818042b06393c96a40fd020 100644 --- a/tests/lib/SimpleSAML/Metadata/MetaDataStorageSourceTest.php +++ b/tests/lib/SimpleSAML/Metadata/MetaDataStorageSourceTest.php @@ -17,7 +17,7 @@ class MetaDataStorageSourceTest extends \PHPUnit\Framework\TestCase public function testBadXMLSource() { $this->expectException(\Exception::class); - \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type"=>"xml", "foo"=>"baa"]); + \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type" => "xml", "foo" => "baa"]); } @@ -32,7 +32,7 @@ class MetaDataStorageSourceTest extends \PHPUnit\Framework\TestCase <EntityDescriptor ID=\"_12345678-90ab-cdef-1234-567890abcdef\" entityID=\"https://saml.idp/entityid\" xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\"> </EntityDescriptor> "; - \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type"=>"xml", "xml"=>$strTestXML]); + \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type" => "xml", "xml" => $strTestXML]); } @@ -44,11 +44,17 @@ class MetaDataStorageSourceTest extends \PHPUnit\Framework\TestCase { $testEntityId = "https://saml.idp/entityid"; $strTestXML = self::generateIdpMetadataXml($testEntityId); + // The primary test here is that - in contrast to the others above - this loads without error // As a secondary thing, check that the entity ID from the static source provided can be extracted - $source = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type"=>"xml", "xml"=>$strTestXML]); + $source = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type" => "xml", "xml" => $strTestXML]); $idpSet = $source->getMetadataSet("saml20-idp-remote"); - $this->assertArrayHasKey($testEntityId, $idpSet, "Did not extract expected IdP entity ID from static XML source"); + $this->assertArrayHasKey( + $testEntityId, + $idpSet, + "Did not extract expected IdP entity ID from static XML source" + ); + // Finally verify that a different entity ID does not get loaded $this->assertCount(1, $idpSet, "Unexpectedly got metadata for an alternate entity than that defined"); } @@ -74,7 +80,7 @@ class MetaDataStorageSourceTest extends \PHPUnit\Framework\TestCase $xml2 </EntitiesDescriptor> "; - $source = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type"=>"xml", "xml"=>$strTestXML]); + $source = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(["type" => "xml", "xml" => $strTestXML]); // search that is a single entity $entities = $source->getMetaDataForEntities([$entityId2], "saml20-idp-remote"); $this->assertCount(1, $entities, 'Only 1 entity loaded'); diff --git a/tests/lib/SimpleSAML/Metadata/SAMLBuilderTest.php b/tests/lib/SimpleSAML/Metadata/SAMLBuilderTest.php index 7d30d2161dba13016a36601c9094e5c0934e64e5..34dd59c7defa65ce93eb626b8455425a1a89153d 100644 --- a/tests/lib/SimpleSAML/Metadata/SAMLBuilderTest.php +++ b/tests/lib/SimpleSAML/Metadata/SAMLBuilderTest.php @@ -283,8 +283,9 @@ class SAMLBuilderTest extends TestCase $samlBuilder->addMetadata($set, $metadata); $entityDescriptorXml = $samlBuilder->getEntityDescriptorText(); + $protocols = implode(' ', $metadata['protocols']); $this->assertRegExp( - '/<md:AttributeAuthorityDescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:2.0:protocol">/', + '/<md:AttributeAuthorityDescriptor protocolSupportEnumeration="' . $protocols . '">/', $entityDescriptorXml ); } diff --git a/tests/lib/SimpleSAML/Metadata/SAMLParserTest.php b/tests/lib/SimpleSAML/Metadata/SAMLParserTest.php index 79f5120c3862893866a768452adc62a6a17ceb8a..0d44c75cd39e049facd4428244441ef0936aecf0 100644 --- a/tests/lib/SimpleSAML/Metadata/SAMLParserTest.php +++ b/tests/lib/SimpleSAML/Metadata/SAMLParserTest.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Test\Metadata; -require_once(__DIR__.'/../../../SigningTestCase.php'); +require_once(__DIR__ . '/../../../SigningTestCase.php'); use PHPUnit\Framework\TestCase; use RobRichards\XMLSecLibs\XMLSecurityDSig; @@ -182,7 +182,7 @@ XML * @param string $expected_fingerprint * @return void */ - public function _testValidateFingerprint($algo, $expected_fingerprint) + private function validateFingerprint($algo, $expected_fingerprint) { $doc = $this->makeTestDocument(); $entities = \SimpleSAML\Metadata\SAMLParser::parseDescriptorsElement($doc->documentElement); @@ -199,7 +199,7 @@ XML */ public function testValidateFingerprintSHA1() { - $this->_testValidateFingerprint( + $this->validateFingerprint( XMLSecurityDSig::SHA1, 'A7:FB:75:22:57:88:A1:B0:D0:29:0A:4B:D1:EA:0C:01:F8:98:44:A0' ); @@ -211,7 +211,7 @@ XML */ public function testValidateFingerprintSHA256() { - $this->_testValidateFingerprint( + $this->validateFingerprint( XMLSecurityDSig::SHA256, '3E:04:6B:2C:13:B5:02:FB:FC:93:66:EE:6C:A3:D1:BB:B8:9E:D8:38:03' . ':96:C5:C0:EC:95:D5:C9:F6:C1:D5:FC' @@ -224,7 +224,7 @@ XML */ public function testValidateFingerprintSHA384() { - $this->_testValidateFingerprint( + $this->validateFingerprint( XMLSecurityDSig::SHA384, '38:87:CC:59:54:CF:ED:FC:71:B6:21:F3:8A:52:76:EF:30:C8:8C:A0:38' . ':48:77:87:58:14:A0:B3:55:EF:48:9C:B4:B3:44:1F:B7:BB:FC:28:65' . @@ -238,7 +238,7 @@ XML */ public function testValidateFingerprintSHA512() { - $this->_testValidateFingerprint( + $this->validateFingerprint( XMLSecurityDSig::SHA512, '72:6C:51:01:A1:E9:76:D8:61:C4:B2:4F:AC:0B:64:7D:0D:4E:B7:DC:B3' . ':4A:92:23:51:A6:DC:A5:A1:9A:A5:DD:43:F5:05:6A:B7:7D:83:1F:B6:' . @@ -294,7 +294,7 @@ XML 'width' => 17, ], [ - 'url' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', + 'url' => 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', 'height' => 2, 'width' => 1, ], @@ -323,7 +323,7 @@ XML <mdui:PrivacyStatementURL xml:lang="en">https://localhost/privacypolicy</mdui:PrivacyStatementURL> <mdui:InformationURL xml:lang="en">https://localhost/information</mdui:InformationURL> <mdui:Logo width="17" height="16">https://localhost/logo</mdui:Logo> - <mdui:Logo width="1" height="2">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=</mdui:Logo> + <mdui:Logo width="1" height="2">data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==</mdui:Logo> </mdui:UIInfo> <mdui:DiscoHints> <mdui:IPHint>127.0.0.1</mdui:IPHint> @@ -345,9 +345,21 @@ XML // Various MDUI elements are accessible /** @var array $metadata */ $metadata = $entities['theEntityID']->getMetadata20IdP(); - $this->assertEquals($expected['scope'], $metadata['scope'], 'shibmd:Scope elements not reflected in parsed metadata'); - $this->assertEquals($expected['UIInfo'], $metadata['UIInfo'], 'mdui:UIInfo elements not reflected in parsed metadata'); - $this->assertEquals($expected['DiscoHints'], $metadata['DiscoHints'], 'mdui:DiscoHints elements not reflected in parsed metadata'); + $this->assertEquals( + $expected['scope'], + $metadata['scope'], + 'shibmd:Scope elements not reflected in parsed metadata' + ); + $this->assertEquals( + $expected['UIInfo'], + $metadata['UIInfo'], + 'mdui:UIInfo elements not reflected in parsed metadata' + ); + $this->assertEquals( + $expected['DiscoHints'], + $metadata['DiscoHints'], + 'mdui:DiscoHints elements not reflected in parsed metadata' + ); $this->assertEquals($expected['name'], $metadata['name']); } } diff --git a/tests/lib/SimpleSAML/ModuleTest.php b/tests/lib/SimpleSAML/ModuleTest.php index fa57828498d2f92255482f062760476cdc4d5971..3c2558d2a1318de9ea5e14c7aae016de29aa5b61 100644 --- a/tests/lib/SimpleSAML/ModuleTest.php +++ b/tests/lib/SimpleSAML/ModuleTest.php @@ -26,7 +26,7 @@ class ModuleTest extends TestCase { // test for the most basic functionality $this->assertEquals( - dirname(dirname(dirname(dirname(__FILE__)))).'/modules/module', + dirname(dirname(dirname(dirname(__FILE__)))) . '/modules/module', Module::getModuleDir('module') ); } diff --git a/tests/lib/SimpleSAML/SessionHandlerPHPTest.php b/tests/lib/SimpleSAML/SessionHandlerPHPTest.php index 43bc2bef11aa6f6a11feff5f8707aaa27af0ca40..1ae63c4449e239946220e45182e5e296a3a299e8 100644 --- a/tests/lib/SimpleSAML/SessionHandlerPHPTest.php +++ b/tests/lib/SimpleSAML/SessionHandlerPHPTest.php @@ -167,9 +167,9 @@ class SessionHandlerPHPTest extends ClearStateTestCase $sh->restorePrevious(); $headers = xdebug_get_headers(); - $this->assertContains('PHPSESSID='.$sid, $headers[0]); + $this->assertContains('PHPSESSID=' . $sid, $headers[0]); $this->assertContains('SimpleSAML=Restore;', $headers[1]); - $this->assertContains('PHPSESSID='.$sid, $headers[2]); + $this->assertContains('PHPSESSID=' . $sid, $headers[2]); $this->assertEquals($headers[0], $headers[2]); } diff --git a/tests/lib/SimpleSAML/StoreTest.php b/tests/lib/SimpleSAML/StoreTest.php index 92e4b212cb2a55866bcdf61c41454a9916e5c237..8b95bede1b5df91ea9b11e914f24f34ff5051aae 100644 --- a/tests/lib/SimpleSAML/StoreTest.php +++ b/tests/lib/SimpleSAML/StoreTest.php @@ -3,7 +3,6 @@ namespace SimpleSAML\Test; use PHPUnit\Framework\TestCase; - use SimpleSAML\Configuration; use SimpleSAML\Error\CriticalConfigurationError; use SimpleSAML\Store; @@ -11,8 +10,8 @@ use SimpleSAML\Store; /** * Tests for the Store abstract class. * - * For the full copyright and license information, please view the LICENSE file that was distributed with this source - * code. + * For the full copyright and license information, please view the LICENSE file that was + * distributed with this source code. * * @author Sergio Gómez <sergio@uco.es> * @package simplesamlphp/simplesamlphp @@ -26,8 +25,7 @@ class StoreTest extends TestCase */ public function defaultStore() { - Configuration::loadFromArray([ - ], '[ARRAY]', 'simplesaml'); + Configuration::loadFromArray([], '[ARRAY]', 'simplesaml'); /** @var false $store */ $store = Store::getInstance(); @@ -43,8 +41,7 @@ class StoreTest extends TestCase */ public function phpSessionStore() { - Configuration::loadFromArray([ - ], '[ARRAY]', 'simplesaml'); + Configuration::loadFromArray([], '[ARRAY]', 'simplesaml'); /** @var false $store */ $store = Store::getInstance(); diff --git a/tests/lib/SimpleSAML/Utils/AttributesTest.php b/tests/lib/SimpleSAML/Utils/AttributesTest.php index 3ca7c1f04d3d67dda78da848f1ee6f706c2239c8..3cf15731b0c6c91fd68ba6547c04f356b0f5ad68 100644 --- a/tests/lib/SimpleSAML/Utils/AttributesTest.php +++ b/tests/lib/SimpleSAML/Utils/AttributesTest.php @@ -26,7 +26,7 @@ class AttributesTest extends TestCase $expected = 'string'; $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - 'The attributes array is not an array, it is: '.print_r($attributes, true).'.' + 'The attributes array is not an array, it is: ' . print_r($attributes, true) . '.' ); Attributes::getExpectedAttribute($attributes, $expected); } @@ -45,7 +45,7 @@ class AttributesTest extends TestCase $expected = false; $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - 'The expected attribute is not a string, it is: '.print_r($expected, true).'.' + 'The expected attribute is not a string, it is: ' . print_r($expected, true) . '.' ); Attributes::getExpectedAttribute($attributes, $expected); } @@ -82,7 +82,7 @@ class AttributesTest extends TestCase ]; $expected = 'missing'; $this->expectException(\SimpleSAML\Error\Exception::class); - $this->expectExceptionMessage("No such attribute '".$expected."' found."); + $this->expectExceptionMessage("No such attribute '" . $expected . "' found."); Attributes::getExpectedAttribute($attributes, $expected); } @@ -99,7 +99,7 @@ class AttributesTest extends TestCase ]; $expected = 'attribute'; $this->expectException(\SimpleSAML\Error\Exception::class); - $this->expectExceptionMessage("Empty attribute '".$expected."'.'"); + $this->expectExceptionMessage("Empty attribute '" . $expected . "'.'"); Attributes::getExpectedAttribute($attributes, $expected); } diff --git a/tests/lib/SimpleSAML/Utils/Config/MetadataTest.php b/tests/lib/SimpleSAML/Utils/Config/MetadataTest.php index 78e51aefb43b2bd5134dca6ed0339ea3fddaf714..dfeda95fa6b72482797d4f49b736dc4988f72bf3 100644 --- a/tests/lib/SimpleSAML/Utils/Config/MetadataTest.php +++ b/tests/lib/SimpleSAML/Utils/Config/MetadataTest.php @@ -271,7 +271,10 @@ class MetadataTest extends TestCase { // Test null or unset $nameIdPolicy = null; - $this->assertEquals(['Format' => \SAML2\Constants::NAMEID_TRANSIENT], Metadata::parseNameIdPolicy($nameIdPolicy)); + $this->assertEquals( + ['Format' => \SAML2\Constants::NAMEID_TRANSIENT], + Metadata::parseNameIdPolicy($nameIdPolicy) + ); // Test false $nameIdPolicy = false; @@ -279,7 +282,10 @@ class MetadataTest extends TestCase // Test string $nameIdPolicy = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'; - $this->assertEquals(['Format' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'], Metadata::parseNameIdPolicy($nameIdPolicy)); + $this->assertEquals( + ['Format' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'], + Metadata::parseNameIdPolicy($nameIdPolicy) + ); // Test array $nameIdPolicy = [ diff --git a/tests/lib/SimpleSAML/Utils/ConfigTest.php b/tests/lib/SimpleSAML/Utils/ConfigTest.php index 2e5777fcf3014bbbf9f5899b9f53c2ba4b6267ae..af66330d0224a52da14a1bfc508562ea6ccf1fbd 100644 --- a/tests/lib/SimpleSAML/Utils/ConfigTest.php +++ b/tests/lib/SimpleSAML/Utils/ConfigTest.php @@ -21,7 +21,7 @@ class ConfigTest extends TestCase putenv('SIMPLESAMLPHP_CONFIG_DIR'); $configDir = Config::getConfigDir(); - $this->assertEquals($configDir, dirname(dirname(dirname(dirname(__DIR__)))).'/config'); + $this->assertEquals($configDir, dirname(dirname(dirname(dirname(__DIR__)))) . '/config'); } @@ -31,7 +31,7 @@ class ConfigTest extends TestCase */ public function testEnvVariableConfigDir() { - putenv('SIMPLESAMLPHP_CONFIG_DIR='.__DIR__); + putenv('SIMPLESAMLPHP_CONFIG_DIR=' . __DIR__); $configDir = Config::getConfigDir(); $this->assertEquals($configDir, __DIR__); @@ -43,7 +43,7 @@ class ConfigTest extends TestCase */ public function testEnvRedirectVariableConfigDir() { - putenv('REDIRECT_SIMPLESAMLPHP_CONFIG_DIR='.__DIR__); + putenv('REDIRECT_SIMPLESAMLPHP_CONFIG_DIR=' . __DIR__); $configDir = Config::getConfigDir(); $this->assertEquals($configDir, __DIR__); @@ -56,8 +56,8 @@ class ConfigTest extends TestCase */ public function testEnvRedirectPriorityVariableConfigDir() { - putenv('SIMPLESAMLPHP_CONFIG_DIR='.dirname(__DIR__)); - putenv('REDIRECT_SIMPLESAMLPHP_CONFIG_DIR='.__DIR__); + putenv('SIMPLESAMLPHP_CONFIG_DIR=' . dirname(__DIR__)); + putenv('REDIRECT_SIMPLESAMLPHP_CONFIG_DIR=' . __DIR__); $configDir = Config::getConfigDir(); $this->assertEquals($configDir, dirname(__DIR__)); @@ -71,13 +71,13 @@ class ConfigTest extends TestCase public function testInvalidEnvVariableConfigDirThrowsException() { // I used a random hash to ensure this test directory is always invalid - $invalidDir = __DIR__.'/e9826ad19cbc4f5bf20c0913ffcd2ce6'; - putenv('SIMPLESAMLPHP_CONFIG_DIR='.$invalidDir); + $invalidDir = __DIR__ . '/e9826ad19cbc4f5bf20c0913ffcd2ce6'; + putenv('SIMPLESAMLPHP_CONFIG_DIR=' . $invalidDir); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( - 'Config directory specified by environment variable SIMPLESAMLPHP_CONFIG_DIR is not a directory. '. - 'Given: "'.$invalidDir.'"' + 'Config directory specified by environment variable SIMPLESAMLPHP_CONFIG_DIR is not a directory. ' . + 'Given: "' . $invalidDir . '"' ); Config::getConfigDir(); diff --git a/tests/lib/SimpleSAML/Utils/CryptoTest.php b/tests/lib/SimpleSAML/Utils/CryptoTest.php index e0f38cb12b24c50a21111e04fa9ff9828779d147..f865ef45c61084f0032eae90a2bb8b1f9d62d38f 100644 --- a/tests/lib/SimpleSAML/Utils/CryptoTest.php +++ b/tests/lib/SimpleSAML/Utils/CryptoTest.php @@ -2,12 +2,11 @@ namespace SimpleSAML\Test\Utils; +use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; use SimpleSAML\Utils\Crypto; -use \org\bovigo\vfs\vfsStream; - /** * Tests for SimpleSAML\Utils\Crypto. */ @@ -40,7 +39,7 @@ class CryptoTest extends TestCase ] ); $this->root_directory = vfsStream::url(self::ROOTDIRNAME); - $this->certdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTCERTDIR; + $this->certdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTCERTDIR; } @@ -53,7 +52,7 @@ class CryptoTest extends TestCase public function testAesDecryptBadInput() { $this->expectException(\InvalidArgumentException::class); - $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', '_aesDecrypt'); + $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', 'aesDecryptInternal'); $m->setAccessible(true); $m->invokeArgs(null, [[], 'SECRET']); @@ -69,7 +68,7 @@ class CryptoTest extends TestCase public function testAesEncryptBadInput() { $this->expectException(\InvalidArgumentException::class); - $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', '_aesEncrypt'); + $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', 'aesEncryptInternal'); $m->setAccessible(true); $m->invokeArgs(null, [[], 'SECRET']); @@ -90,11 +89,12 @@ class CryptoTest extends TestCase } $secret = 'SUPER_SECRET_SALT'; - $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', '_aesDecrypt'); + $m = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', 'aesDecryptInternal'); $m->setAccessible(true); $plaintext = 'SUPER_SECRET_TEXT'; - $ciphertext = 'uR2Yu0r4itInKx91D/l9y/08L5CIQyev9nAr27fh3Sshous4vbXRRcMcjqHDOrquD+2vqLyw7ygnbA9jA9TpB4hLZocvAWcTN8tyO82hiSY='; + $ciphertext = 'uR2Yu0r4itInKx91D/l9y/08L5CIQyev9nAr27fh3Sshous4' + . 'vbXRRcMcjqHDOrquD+2vqLyw7ygnbA9jA9TpB4hLZocvAWcTN8tyO82hiSY='; $this->assertEquals($plaintext, $m->invokeArgs(null, [base64_decode($ciphertext), $secret])); } @@ -113,8 +113,8 @@ class CryptoTest extends TestCase } $secret = 'SUPER_SECRET_SALT'; - $e = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', '_aesEncrypt'); - $d = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', '_aesDecrypt'); + $e = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', 'aesEncryptInternal'); + $d = new \ReflectionMethod('\SimpleSAML\Utils\Crypto', 'aesDecryptInternal'); $e->setAccessible(true); $d->setAccessible(true); @@ -210,8 +210,8 @@ PHP; $res = Crypto::pwHash($pw, $algorithm, $salt); /* - * echo -n "password""salt" | sha1sum | awk -v salt=$(echo -n "salt" | xxd -u -p) -F " " '{print $1 salt}' | xxd -r -p | base64 - * yI6cZwQadOA1e+/f+T+H3eCQQhRzYWx0 + * echo -n "password""salt" | sha1sum | awk -v salt=$(echo -n "salt" | xxd -u -p) + * -F " " '{print $1 salt}' | xxd -r -p | base64 yI6cZwQadOA1e+/f+T+H3eCQQhRzYWx0 */ $expected = "{SSHA}yI6cZwQadOA1e+/f+T+H3eCQQhRzYWx0"; @@ -311,7 +311,7 @@ PHP; { $this->expectException(\SimpleSAML\Error\Exception::class); $algorithm = "wtf"; - $hash = "{".$algorithm."}B64STRING"; + $hash = "{" . $algorithm . "}B64STRING"; Crypto::pwValid($hash, $algorithm); } @@ -389,7 +389,7 @@ PHP; */ public function testLoadPrivateKeyBasic() { - $filename = $this->certdir.DIRECTORY_SEPARATOR.'key'; + $filename = $this->certdir . DIRECTORY_SEPARATOR . 'key'; $data = 'data'; $config = new Configuration(['privatekey' => $filename], 'test'); $full_path = true; @@ -410,7 +410,7 @@ PHP; public function testLoadPrivateKeyPassword() { $password = 'password'; - $filename = $this->certdir.DIRECTORY_SEPARATOR.'key'; + $filename = $this->certdir . DIRECTORY_SEPARATOR . 'key'; $data = 'data'; $config = new Configuration( [ @@ -438,12 +438,12 @@ PHP; { $prefix = 'prefix'; $password = 'password'; - $filename = $this->certdir.DIRECTORY_SEPARATOR.'key'; + $filename = $this->certdir . DIRECTORY_SEPARATOR . 'key'; $data = 'data'; $config = new Configuration( [ - $prefix.'privatekey' => $filename, - $prefix.'privatekey_pass' => $password, + $prefix . 'privatekey' => $filename, + $prefix . 'privatekey_pass' => $password, ], 'test' ); diff --git a/tests/lib/SimpleSAML/Utils/EMailTestCase.php b/tests/lib/SimpleSAML/Utils/EMailTestCase.php index a79a60e0386ff7a00a15269fc68d6fe9730a65a6..89aa4fdd7a151b026fd1fe77d850171bda3ea0bd 100644 --- a/tests/lib/SimpleSAML/Utils/EMailTestCase.php +++ b/tests/lib/SimpleSAML/Utils/EMailTestCase.php @@ -2,9 +2,8 @@ namespace SimpleSAML\Test\Utils; -use SimpleSAML\Test\Utils\TestCase; - use SimpleSAML\Configuration; +use SimpleSAML\Test\Utils\TestCase; use SimpleSAML\Utils\EMail; /** @@ -68,7 +67,11 @@ class EMailTestCase extends ClearStateTestCase */ public function testMailContents($template) { - $mail = new EMail('subject-subject-subject-subject-subject-subject-subject', 'phpunit@simplesamlphp.org', 'phpunit@simplesamlphp.org'); + $mail = new EMail( + 'subject-subject-subject-subject-subject-subject-subject', + 'phpunit@simplesamlphp.org', + 'phpunit@simplesamlphp.org' + ); $mail->setText('text-text-text-text-text-text-text'); $mail->setData(['key-key-key-key-key-key-key' => 'value-value-value-value-value-value-value']); $result = $mail->generateBody($template); diff --git a/tests/lib/SimpleSAML/Utils/HTTPTest.php b/tests/lib/SimpleSAML/Utils/HTTPTest.php index 7e4683a079361fad7655f82bd4e50d32144eb641..504aaedf0a36c05479ac06642b58a1e846ee00c4 100644 --- a/tests/lib/SimpleSAML/Utils/HTTPTest.php +++ b/tests/lib/SimpleSAML/Utils/HTTPTest.php @@ -31,7 +31,7 @@ class HTTPTest extends ClearStateTestCase if (isset($addr['port']) && strval($addr['port']) !== $default_port) { $_SERVER['SERVER_PORT'] = strval($addr['port']); } - $_SERVER['REQUEST_URI'] = $addr['path'].'?'.$addr['query']; + $_SERVER['REQUEST_URI'] = $addr['path'] . '?' . $addr['query']; } @@ -72,20 +72,20 @@ class HTTPTest extends ClearStateTestCase 'foo' => 'bar', 'bar' => 'foo', ]; - $this->assertEquals($url.'?foo=bar&bar=foo', HTTP::addURLParameters($url, $params)); + $this->assertEquals($url . '?foo=bar&bar=foo', HTTP::addURLParameters($url, $params)); $url = 'http://example.com/?'; $params = [ 'foo' => 'bar', 'bar' => 'foo', ]; - $this->assertEquals($url.'foo=bar&bar=foo', HTTP::addURLParameters($url, $params)); + $this->assertEquals($url . 'foo=bar&bar=foo', HTTP::addURLParameters($url, $params)); $url = 'http://example.com/?foo=bar'; $params = [ 'bar' => 'foo', ]; - $this->assertEquals($url.'&bar=foo', HTTP::addURLParameters($url, $params)); + $this->assertEquals($url . '&bar=foo', HTTP::addURLParameters($url, $params)); } @@ -204,14 +204,14 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('https://example.com', HTTP::getSelfURLHost()); $this->assertEquals('https://example.com/app/script.php/some/path', HTTP::getSelfURLNoQuery()); $this->assertTrue(HTTP::isHTTPS()); - $this->assertEquals('https://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('https://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a request URI that doesn't match the current script $cfg = Configuration::loadFromArray([ 'baseurlpath' => 'https://example.org/simplesaml/', ], '[ARRAY]', 'simplesaml'); $baseDir = $cfg->getBaseDir(); - $_SERVER['SCRIPT_FILENAME'] = $baseDir.'www/module.php'; + $_SERVER['SCRIPT_FILENAME'] = $baseDir . 'www/module.php'; $this->setupEnvFromURL('http://www.example.com/protected/resource.asp?foo=bar'); $this->assertEquals('http://www.example.com/protected/resource.asp?foo=bar', HTTP::getSelfURL()); $this->assertEquals('http://www.example.com', HTTP::getSelfURLHost()); @@ -232,7 +232,7 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('https://example.com', HTTP::getSelfURLHost()); $this->assertEquals('https://example.com/simplesaml/module.php/module/file.php', HTTP::getSelfURLNoQuery()); $this->assertTrue(HTTP::isHTTPS()); - $this->assertEquals('https://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('https://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a valid, full URL, based on a full URL *without* a trailing slash in the configuration Configuration::loadFromArray([ @@ -245,7 +245,7 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('https://example.com', HTTP::getSelfURLHost()); $this->assertEquals('https://example.com/simplesaml/module.php/module/file.php', HTTP::getSelfURLNoQuery()); $this->assertTrue(HTTP::isHTTPS()); - $this->assertEquals('https://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('https://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a valid, full URL, based on a full URL *without* a path in the configuration Configuration::loadFromArray([ @@ -258,7 +258,7 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('https://example.com', HTTP::getSelfURLHost()); $this->assertEquals('https://example.com/module.php/module/file.php', HTTP::getSelfURLNoQuery()); $this->assertTrue(HTTP::isHTTPS()); - $this->assertEquals('https://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('https://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a valid, full URL, based on a relative path in the configuration Configuration::loadFromArray([ @@ -272,7 +272,7 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('http://www.example.org', HTTP::getSelfURLHost()); $this->assertEquals('http://www.example.org/simplesaml/module.php/module/file.php', HTTP::getSelfURLNoQuery()); $this->assertFalse(HTTP::isHTTPS()); - $this->assertEquals('http://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('http://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a valid, full URL, based on a relative path in the configuration and a non standard port Configuration::loadFromArray([ @@ -286,7 +286,7 @@ class HTTPTest extends ClearStateTestCase $this->assertEquals('http://example.org:8080', HTTP::getSelfURLHost()); $this->assertEquals('http://example.org:8080/simplesaml/module.php/module/file.php', HTTP::getSelfURLNoQuery()); $this->assertFalse(HTTP::isHTTPS()); - $this->assertEquals('http://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('http://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); // test a valid, full URL, based on a relative path in the configuration, a non standard port and HTTPS Configuration::loadFromArray([ @@ -303,7 +303,7 @@ class HTTPTest extends ClearStateTestCase HTTP::getSelfURLNoQuery() ); $this->assertTrue(HTTP::isHTTPS()); - $this->assertEquals('https://'.HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); + $this->assertEquals('https://' . HTTP::getSelfHostWithNonStandardPort(), HTTP::getSelfURLHost()); $_SERVER = $original; } @@ -472,8 +472,29 @@ class HTTPTest extends ClearStateTestCase $url = 'https://example.com/a?b=c'; $this->setupEnvFromURL($url); - HTTP::setCookie('TestCookie', 'value%20', ['expire'=> 2147483640, 'path'=>'/ourPath', 'domain'=>'example.com', 'secure'=>true, 'httponly'=>true]); - HTTP::setCookie('RawCookie', 'value%20', ['lifetime'=>100, 'path'=>'/ourPath', 'domain'=>'example.com', 'secure'=>true, 'httponly'=>true, 'raw'=>true]); + HTTP::setCookie( + 'TestCookie', + 'value%20', + [ + 'expire' => 2147483640, + 'path' => '/ourPath', + 'domain' => 'example.com', + 'secure' => true, + 'httponly' => true + ] + ); + HTTP::setCookie( + 'RawCookie', + 'value%20', + [ + 'lifetime' => 100, + 'path' => '/ourPath', + 'domain' => 'example.com', + 'secure' => true, + 'httponly' => true, + 'raw' => true + ] + ); $headers = xdebug_get_headers(); $this->assertContains('TestCookie=value%2520;', $headers[0]); diff --git a/tests/lib/SimpleSAML/Utils/SystemTest.php b/tests/lib/SimpleSAML/Utils/SystemTest.php index 92ac6f6e6c0074026deaad7455be3ae11d6e5f1e..d96fa62d1c5a18b2d1e730ab376e8ed1964bb198 100644 --- a/tests/lib/SimpleSAML/Utils/SystemTest.php +++ b/tests/lib/SimpleSAML/Utils/SystemTest.php @@ -2,12 +2,11 @@ namespace SimpleSAML\Test\Utils; +use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; use SimpleSAML\Utils\System; -use \org\bovigo\vfs\vfsStream; - /** * Tests for SimpleSAML\Utils\System. */ @@ -176,10 +175,10 @@ class SystemTest extends TestCase */ public function testWriteFileBasic() { - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTTEMPDIR; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTTEMPDIR; $config = $this->setConfigurationTempDir($tempdir); - $filename = $this->root_directory.DIRECTORY_SEPARATOR.'test'; + $filename = $this->root_directory . DIRECTORY_SEPARATOR . 'test'; System::writeFile($filename, ''); @@ -196,10 +195,10 @@ class SystemTest extends TestCase */ public function testWriteFileContents() { - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTTEMPDIR; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTTEMPDIR; $config = $this->setConfigurationTempDir($tempdir); - $filename = $this->root_directory.DIRECTORY_SEPARATOR.'test'; + $filename = $this->root_directory . DIRECTORY_SEPARATOR . 'test'; $contents = 'TEST'; System::writeFile($filename, $contents); @@ -220,10 +219,10 @@ class SystemTest extends TestCase */ public function testWriteFileMode() { - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTTEMPDIR; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTTEMPDIR; $config = $this->setConfigurationTempDir($tempdir); - $filename = $this->root_directory.DIRECTORY_SEPARATOR.'test'; + $filename = $this->root_directory . DIRECTORY_SEPARATOR . 'test'; $mode = 0666; System::writeFile($filename, '', $mode); @@ -244,7 +243,7 @@ class SystemTest extends TestCase */ public function testGetTempDirBasic() { - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTTEMPDIR; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTTEMPDIR; $config = $this->setConfigurationTempDir($tempdir); $res = System::getTempDir(); @@ -264,7 +263,7 @@ class SystemTest extends TestCase */ public function testGetTempDirNonExistant() { - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.'nonexistant'; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . 'nonexistant'; $config = $this->setConfigurationTempDir($tempdir); $res = System::getTempDir(); @@ -291,7 +290,7 @@ class SystemTest extends TestCase $bad_uid = posix_getuid() + 1; - $tempdir = $this->root_directory.DIRECTORY_SEPARATOR.self::DEFAULTTEMPDIR; + $tempdir = $this->root_directory . DIRECTORY_SEPARATOR . self::DEFAULTTEMPDIR; $config = $this->setConfigurationTempDir($tempdir); chown($tempdir, $bad_uid); diff --git a/tests/lib/SimpleSAML/Utils/XMLTest.php b/tests/lib/SimpleSAML/Utils/XMLTest.php index dfe64c1648b4402cf0af8310c31c76be0587c961..6923a897b6ccf76f336abd04ab19fa305b78d559 100644 --- a/tests/lib/SimpleSAML/Utils/XMLTest.php +++ b/tests/lib/SimpleSAML/Utils/XMLTest.php @@ -3,7 +3,6 @@ namespace SimpleSAML\Test\Utils; use PHPUnit\Framework\TestCase; - use SimpleSAML\Configuration; use SimpleSAML\Utils\XML; @@ -150,7 +149,7 @@ class XMLTest extends TestCase $element->appendChild(new \DOMText($data2)); $res = XML::getDOMText($element); - $expected = $data1.$data2.$data1.$data2; + $expected = $data1 . $data2 . $data1 . $data2; $this->assertEquals($expected, $res); } diff --git a/tests/lib/SimpleSAML/XML/ErrorsTest.php b/tests/lib/SimpleSAML/XML/ErrorsTest.php index fadc0ebc3a648c63f3cdb7e8e62c21b53a2d9b01..7332b566805ea7259890facab848d40ba256c23a 100644 --- a/tests/lib/SimpleSAML/XML/ErrorsTest.php +++ b/tests/lib/SimpleSAML/XML/ErrorsTest.php @@ -1,4 +1,10 @@ <?php + +namespace SimpleSAML\Test\XML; + +use PHPUnit\Framework\TestCase; +use SimpleSAML\XML\Errors; + /** * Tests for the SQL store. * @@ -8,12 +14,6 @@ * @author Sergio Gómez <sergio@uco.es> * @package simplesamlphp/simplesamlphp */ - -namespace SimpleSAML\Test\XML; - -use PHPUnit\Framework\TestCase; -use SimpleSAML\XML\Errors; - class ErrorsTest extends TestCase { /** diff --git a/tests/lib/SimpleSAML/XML/ParserTest.php b/tests/lib/SimpleSAML/XML/ParserTest.php index 35bc70c41bdfee889c9c8fafc0b5a0988bf5ffc0..5f7837c1726357ab80f1b5882b8efd401d4c3fc6 100644 --- a/tests/lib/SimpleSAML/XML/ParserTest.php +++ b/tests/lib/SimpleSAML/XML/ParserTest.php @@ -1,4 +1,10 @@ <?php + +namespace SimpleSAML\Test\XML; + +use PHPUnit\Framework\TestCase; +use SimpleSAML\XML\Parser; + /* * This file is part of the sgomezsimplesamlphp. * @@ -7,12 +13,6 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ - -namespace SimpleSAML\Test\XML; - -use PHPUnit\Framework\TestCase; -use SimpleSAML\XML\Parser; - class ParserTest extends TestCase { const XMLDOC = <<< XML diff --git a/tests/lib/SimpleSAML/XML/SignerTest.php b/tests/lib/SimpleSAML/XML/SignerTest.php index 32e8177bc0fd4bd6e41e1671c0e932f1dda7de03..e6c96e527dfd9255d1dfac9123ca831384853d04 100644 --- a/tests/lib/SimpleSAML/XML/SignerTest.php +++ b/tests/lib/SimpleSAML/XML/SignerTest.php @@ -2,14 +2,13 @@ namespace SimpleSAML\Test\XML; -require_once(__DIR__.'/../../../SigningTestCase.php'); - +use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; use SimpleSAML\Test\SigningTestCase; use SimpleSAML\XML\Signer; -use \org\bovigo\vfs\vfsStream; +require_once(__DIR__ . '/../../../SigningTestCase.php'); /** * Tests for SimpleSAML\XML\Signer. @@ -146,7 +145,7 @@ NOWDOC; */ public function testSignWithMultiCertificate() { - $this->other_certificate_file = $this->certdir.DIRECTORY_SEPARATOR.self::OTHER_CERTIFICATE; + $this->other_certificate_file = $this->certdir . DIRECTORY_SEPARATOR . self::OTHER_CERTIFICATE; $node = new \DOMDocument(); $node->loadXML('<?xml version="1.0"?><node>value</node>'); diff --git a/tests/lib/SimpleSAML/XML/ValidatorTest.php b/tests/lib/SimpleSAML/XML/ValidatorTest.php index bb9a117e781369fc916a8412f96d943875bdf37e..3baf620386f82379284d1b9d7ccfdc99a43d9a7f 100644 --- a/tests/lib/SimpleSAML/XML/ValidatorTest.php +++ b/tests/lib/SimpleSAML/XML/ValidatorTest.php @@ -2,14 +2,13 @@ namespace SimpleSAML\Test\XML; -require_once(__DIR__.'/../../../SigningTestCase.php'); +require_once(__DIR__ . '/../../../SigningTestCase.php'); +use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; -use \SimpleSAML\Test\SigningTestCase; -use \SimpleSAML\XML\Signer; -use \SimpleSAML\XML\Validator; - -use \org\bovigo\vfs\vfsStream; +use SimpleSAML\Test\SigningTestCase; +use SimpleSAML\XML\Signer; +use SimpleSAML\XML\Validator; /** * Tests for SimpleSAML\XML\Validator. @@ -51,7 +50,7 @@ class ValidatorTest extends SigningTestCase $result = $validator->getX509Certificate(); // getX509Certificate returns a certificate with a newline - $expected = $this->good_certificate."\n"; + $expected = $this->good_certificate . "\n"; $this->assertEquals($result, $expected); } @@ -222,7 +221,7 @@ class ValidatorTest extends SigningTestCase */ public function testValidateCertificateMissingCAFile() { - $ca_file = $this->ca_certificate_file.'NOT'; + $ca_file = $this->ca_certificate_file . 'NOT'; $this->expectException(\Exception::class); Validator::validateCertificate($this->good_certificate, $ca_file); diff --git a/tests/modules/core/lib/Auth/Process/TargetedIDTest.php b/tests/modules/core/lib/Auth/Process/TargetedIDTest.php index c4387bcb99c6d2bebad19718db7534ccdfdf4d0a..4987db93062040bb574fb52e086179503145ec2c 100644 --- a/tests/modules/core/lib/Auth/Process/TargetedIDTest.php +++ b/tests/modules/core/lib/Auth/Process/TargetedIDTest.php @@ -96,7 +96,9 @@ class TargetedIDTest extends TestCase // $attributes = $result['Attributes']; // $this->assertArrayHasKey('eduPersonTargetedID', $attributes); // $this->assertRegExp( -// '#^<saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2\.0:assertion" NameQualifier="urn:example:src:id" SPNameQualifier="joe" Format="urn:oasis:names:tc:SAML:2\.0:nameid-format:persistent">[0-9a-f]{40}</saml:NameID>$#', +// '#^<saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2\.0:assertion" NameQualifier="urn:example:src:id"' . +// ' SPNameQualifier="joe"' . +// ' Format="urn:oasis:names:tc:SAML:2\.0:nameid-format:persistent">[0-9a-f]{40}</saml:NameID>$#', // $attributes['eduPersonTargetedID'][0] // ); // } diff --git a/tests/modules/core/lib/Auth/UserPassBaseTest.php b/tests/modules/core/lib/Auth/UserPassBaseTest.php index 7cecfbfc9a3c05497eb2914a4f7599bacd2c0538..089f3c345217f9a0d8652e966e14fd4d19299113 100644 --- a/tests/modules/core/lib/Auth/UserPassBaseTest.php +++ b/tests/modules/core/lib/Auth/UserPassBaseTest.php @@ -23,7 +23,7 @@ class UserPassBaseTest extends \PHPUnit\Framework\TestCase ->setMethods(['login']) ->getMockForAbstractClass(); - /** + /** * @psalm-suppress InvalidArgument Remove when PHPunit 8 is in place * @psalm-suppress UndefinedMethod */ diff --git a/tests/modules/core/lib/ControllerTest.php b/tests/modules/core/lib/ControllerTest.php index 4d3c5be2a79df7176b2d0f4a1778735a0dcd62f5..e3a239d42e1916ab2014aa8137fe5ad3f1aa64e2 100644 --- a/tests/modules/core/lib/ControllerTest.php +++ b/tests/modules/core/lib/ControllerTest.php @@ -12,7 +12,6 @@ use SimpleSAML\Module\core\Controller; use SimpleSAML\Session; use SimpleSAML\Test\Utils\ClearStateTestCase; use SimpleSAML\XHTML\Template; - use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; @@ -174,7 +173,7 @@ class ControllerTest extends ClearStateTestCase 'Attributes' => ['uid' => ['test']], 'Authority' => 'example-userpass', 'AuthnInstant' => time(), - 'Expire' => time() + 8 * 60* 60 + 'Expire' => time() + 8 * 60 * 60 ] ]); @@ -252,7 +251,7 @@ class ControllerTest extends ClearStateTestCase 'Attributes' => ['uid' => ['test']], 'Authority' => 'example-userpass', 'AuthnInstant' => time(), - 'Expire' => time() + 8 * 60* 60 + 'Expire' => time() + 8 * 60 * 60 ] ]); $factory = new AuthenticationFactory($this->config, $session); diff --git a/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php b/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php index ee1217e405d5f45e8e6352663e39c7711df0f3a5..e629fad64b41085e4f5b3e7b1a9f51baf84979a2 100644 --- a/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php +++ b/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php @@ -32,7 +32,7 @@ class SQLPermanentStorageTest extends TestCase public static function tearDownAfterClass() { self::$sql = null; - unlink(sys_get_temp_dir().'/sqllite/test.sqlite'); + unlink(sys_get_temp_dir() . '/sqllite/test.sqlite'); } diff --git a/tests/modules/multiauth/lib/Auth/Source/MultiAuthTest.php b/tests/modules/multiauth/lib/Auth/Source/MultiAuthTest.php index 0d6633faacd08c941df8326e1ef3da290ae710ce..d3bf5b05d114b39cf7481270808e9b51e7af5892 100644 --- a/tests/modules/multiauth/lib/Auth/Source/MultiAuthTest.php +++ b/tests/modules/multiauth/lib/Auth/Source/MultiAuthTest.php @@ -20,7 +20,11 @@ class MultiAuthTest extends \SimpleSAML\Test\Utils\ClearStateTestCase */ public function setUp() { - $this->config = Configuration::loadFromArray(['module.enable' => ['multiauth' => true]], '[ARRAY]', 'simplesaml'); + $this->config = Configuration::loadFromArray( + ['module.enable' => ['multiauth' => true]], + '[ARRAY]', + 'simplesaml' + ); Configuration::setPreLoadedConfig($this->config, 'config.php'); $this->sourceConfig = Configuration::loadFromArray(array( diff --git a/tests/modules/saml/lib/Auth/Process/FilterScopesTest.php b/tests/modules/saml/lib/Auth/Process/FilterScopesTest.php index b81579982de7a3704eb65fef07afe5bcf28004b3..8805be13101198784f90e4b6c69f89cfa2a4c7aa 100644 --- a/tests/modules/saml/lib/Auth/Process/FilterScopesTest.php +++ b/tests/modules/saml/lib/Auth/Process/FilterScopesTest.php @@ -1,15 +1,15 @@ <?php + +namespace SimpleSAML\Test\Module\saml\Auth\Process; + +use PHPUnit\Framework\TestCase; + /** * Test for the saml:FilterScopes filter. * * @author Jaime Pérez Crespo, UNINETT AS <jaime.perez@uninett.no> * @package SimpleSAMLphp */ - -namespace SimpleSAML\Test\Module\saml\Auth\Process; - -use PHPUnit\Framework\TestCase; - class FilterScopesTest extends TestCase { /** diff --git a/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php b/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php index 12b2bbcd259675ea1cd7e1b5a4d27f8693b7b5d0..4e9ae9bf43c81501514d50fcd0947cedd6b8b560 100644 --- a/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php +++ b/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php @@ -10,7 +10,6 @@ namespace SimpleSAML\Test\Module\saml\Auth\Process; */ use PHPUnit\Framework\TestCase; - use SimpleSAML\Module\saml\Auth\Process\NameIDAttribute; use SAML2\XML\saml\NameID; use SAML2\Constants; diff --git a/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php b/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php index 147e5e35b7526975727ac3a421fa1563ed161b77..664c7f1cc064693a5364ee01004e2cdee7450ef1 100644 --- a/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php +++ b/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php @@ -5,89 +5,13 @@ namespace SimpleSAML\Test\Module\saml\Auth\Source; use InvalidArgumentException; use PHPUnit\Framework\TestCase; use SAML2\AuthnRequest; -use \SimpleSAML\Configuration; +use SimpleSAML\Configuration; use SimpleSAML\Module\saml\Error\NoAvailableIDP; use SimpleSAML\Module\saml\Error\NoSupportedIDP; use SimpleSAML\Test\Metadata\MetaDataStorageSourceTest; use SimpleSAML\Test\Utils\ClearStateTestCase; - -/** - * Custom Exception to throw to terminate a TestCase. - */ -class ExitTestException extends \Exception -{ - /** @var array */ - private $testResult; - - - /** - * @param array $testResult - * @return void - */ - public function __construct(array $testResult) - { - parent::__construct("ExitTestException", 0, null); - $this->testResult = $testResult; - } - - - /** - * @return array - */ - public function getTestResult() - { - return $this->testResult; - } -} - - -/** - * Wrap the SSP \SimpleSAML\Module\saml\Auth\Source\SP class - * - Use introspection to make startSSO2Test available - * - Override sendSAML2AuthnRequest() to catch the AuthnRequest being sent - */ -class SPTester extends \SimpleSAML\Module\saml\Auth\Source\SP -{ - /** - * @param array $info - * @param array $config - * @return void - */ - public function __construct($info, $config) - { - parent::__construct($info, $config); - } - - - /** - * @return void - */ - public function startSSO2Test(Configuration $idpMetadata, array $state) - { - $reflector = new \ReflectionObject($this); - $method = $reflector->getMethod('startSSO2'); - $method->setAccessible(true); - $method->invoke($this, $idpMetadata, $state); - } - - - /** - * override the method that sends the request to avoid sending anything - * @return void - */ - public function sendSAML2AuthnRequest(array &$state, \SAML2\Binding $binding, \SAML2\AuthnRequest $ar) - { - // Exit test. Continuing would mean running into a assert(FALSE) - throw new ExitTestException( - [ - 'state' => $state, - 'binding' => $binding, - 'ar' => $ar, - ] - ); - } -} - +use SimpleSAML\Test\Utils\ExitTestException; +use SimpleSAML\Test\Utils\SpTester; /** * Set of test cases for \SimpleSAML\Module\saml\Auth\Source\SP. @@ -141,21 +65,21 @@ class SPTest extends ClearStateTestCase 'signing' => true, 'type' => 'X509Certificate', 'X509Certificate' => - 'MIID3zCCAsegAwIBAgIJAMVC9xn1ZfsuMA0GCSqGSIb3DQEBCwUAMIGFMQswCQYDVQQGEwJOTDEQMA4GA1UECAwHVXRyZ'. - 'WNodDEQMA4GA1UEBwwHVXRyZWNodDEVMBMGA1UECgwMU1VSRm5ldCBCLlYuMRMwEQYDVQQLDApTVVJGY29uZXh0MSYwJA'. - 'YDVQQDDB1lbmdpbmUuc3VyZmNvbmV4dC5ubCAyMDE0MDUwNTAeFw0xNDA1MDUxNDIyMzVaFw0xOTA1MDUxNDIyMzVaMIG'. - 'FMQswCQYDVQQGEwJOTDEQMA4GA1UECAwHVXRyZWNodDEQMA4GA1UEBwwHVXRyZWNodDEVMBMGA1UECgwMU1VSRm5ldCBC'. - 'LlYuMRMwEQYDVQQLDApTVVJGY29uZXh0MSYwJAYDVQQDDB1lbmdpbmUuc3VyZmNvbmV4dC5ubCAyMDE0MDUwNTCCASIwD'. - 'QYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKthMDbB0jKHefPzmRu9t2h7iLP4wAXr42bHpjzTEk6gttHFb4l/hFiz1Y'. - 'BI88TjiH6hVjnozo/YHA2c51us+Y7g0XoS7653lbUN/EHzvDMuyis4Xi2Ijf1A/OUQfH1iFUWttIgtWK9+fatXoGUS6ti'. - 'rQvrzVh6ZstEp1xbpo1SF6UoVl+fh7tM81qz+Crr/Kroan0UjpZOFTwxPoK6fdLgMAieKSCRmBGpbJHbQ2xxbdykBBrBb'. - 'dfzIX4CDepfjE9h/40ldw5jRn3e392jrS6htk23N9BWWrpBT5QCk0kH3h/6F1Dm6TkyG9CDtt73/anuRkvXbeygI4wml9'. - 'bL3rE8CAwEAAaNQME4wHQYDVR0OBBYEFD+Ac7akFxaMhBQAjVfvgGfY8hNKMB8GA1UdIwQYMBaAFD+Ac7akFxaMhBQAjV'. - 'fvgGfY8hNKMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAC8L9D67CxIhGo5aGVu63WqRHBNOdo/FAGI7LUR'. - 'DFeRmG5nRw/VXzJLGJksh4FSkx7aPrxNWF1uFiDZ80EuYQuIv7bDLblK31ZEbdg1R9LgiZCdYSr464I7yXQY9o6FiNtSK'. - 'ZkQO8EsscJPPy/Zp4uHAnADWACkOUHiCbcKiUUFu66dX0Wr/v53Gekz487GgVRs8HEeT9MU1reBKRgdENR8PNg4rbQfLc'. - '3YQKLWK7yWnn/RenjDpuCiePj8N8/80tGgrNgK/6fzM3zI18sSywnXLswxqDb/J+jgVxnQ6MrsTf1urM8MnfcxG/82oHI'. - 'wfMh/sXPCZpo+DTLkhQxctJ3M=', + 'MIID3zCCAsegAwIBAgIJAMVC9xn1ZfsuMA0GCSqGSIb3DQEBCwUAMIGFMQswCQYDVQQGEwJOTDEQMA4GA1UECAwHVXR' . + 'yZWNodDEQMA4GA1UEBwwHVXRyZWNodDEVMBMGA1UECgwMU1VSRm5ldCBCLlYuMRMwEQYDVQQLDApTVVJGY29uZXh0MS' . + 'YwJAYDVQQDDB1lbmdpbmUuc3VyZmNvbmV4dC5ubCAyMDE0MDUwNTAeFw0xNDA1MDUxNDIyMzVaFw0xOTA1MDUxNDIyM' . + 'zVaMIGFMQswCQYDVQQGEwJOTDEQMA4GA1UECAwHVXRyZWNodDEQMA4GA1UEBwwHVXRyZWNodDEVMBMGA1UECgwMU1VS' . + 'Rm5ldCBCLlYuMRMwEQYDVQQLDApTVVJGY29uZXh0MSYwJAYDVQQDDB1lbmdpbmUuc3VyZmNvbmV4dC5ubCAyMDE0MDU' . + 'wNTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKthMDbB0jKHefPzmRu9t2h7iLP4wAXr42bHpjzTEk6gtt' . + 'HFb4l/hFiz1YBI88TjiH6hVjnozo/YHA2c51us+Y7g0XoS7653lbUN/EHzvDMuyis4Xi2Ijf1A/OUQfH1iFUWttIgtW' . + 'K9+fatXoGUS6tirQvrzVh6ZstEp1xbpo1SF6UoVl+fh7tM81qz+Crr/Kroan0UjpZOFTwxPoK6fdLgMAieKSCRmBGpb' . + 'JHbQ2xxbdykBBrBbdfzIX4CDepfjE9h/40ldw5jRn3e392jrS6htk23N9BWWrpBT5QCk0kH3h/6F1Dm6TkyG9CDtt73' . + '/anuRkvXbeygI4wml9bL3rE8CAwEAAaNQME4wHQYDVR0OBBYEFD+Ac7akFxaMhBQAjVfvgGfY8hNKMB8GA1UdIwQYMB' . + 'aAFD+Ac7akFxaMhBQAjVfvgGfY8hNKMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAC8L9D67CxIhGo5aG' . + 'Vu63WqRHBNOdo/FAGI7LURDFeRmG5nRw/VXzJLGJksh4FSkx7aPrxNWF1uFiDZ80EuYQuIv7bDLblK31ZEbdg1R9Lgi' . + 'ZCdYSr464I7yXQY9o6FiNtSKZkQO8EsscJPPy/Zp4uHAnADWACkOUHiCbcKiUUFu66dX0Wr/v53Gekz487GgVRs8HEe' . + 'T9MU1reBKRgdENR8PNg4rbQfLc3YQKLWK7yWnn/RenjDpuCiePj8N8/80tGgrNgK/6fzM3zI18sSywnXLswxqDb/J+j' . + 'gVxnQ6MrsTf1urM8MnfcxG/82oHIwfMh/sXPCZpo+DTLkhQxctJ3M=', ], ], ]; @@ -176,7 +100,7 @@ class SPTest extends ClearStateTestCase { $info = ['AuthId' => 'default-sp']; $config = []; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); /** @var \SAML2\AuthnRequest $ar */ $ar = null; @@ -334,7 +258,7 @@ class SPTest extends ClearStateTestCase $info = ['AuthId' => 'default-sp']; $config = []; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); $as->authenticate($state); } @@ -350,7 +274,7 @@ class SPTest extends ClearStateTestCase $xml = MetaDataStorageSourceTest::generateIdpMetadataXml($entityId); $c = [ 'metadata.sources' => [ - ["type"=>"xml", "xml"=>$xml], + ["type" => "xml", "xml" => $xml], ], ]; Configuration::loadFromArray($c, '', 'simplesaml'); @@ -362,7 +286,7 @@ class SPTest extends ClearStateTestCase $config = [ 'idp' => 'https://engine.surfconext.nl/authentication/idp/metadata' ]; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); $as->authenticate($state); } @@ -377,7 +301,7 @@ class SPTest extends ClearStateTestCase $xml = MetaDataStorageSourceTest::generateIdpMetadataXml($entityId); $c = [ 'metadata.sources' => [ - ["type"=>"xml", "xml"=>$xml], + ["type" => "xml", "xml" => $xml], ], ]; Configuration::loadFromArray($c, '', 'simplesaml'); @@ -389,7 +313,7 @@ class SPTest extends ClearStateTestCase $config = [ 'idp' => $entityId ]; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); try { $as->authenticate($state); $this->fail('Expected ExitTestException'); @@ -419,7 +343,7 @@ class SPTest extends ClearStateTestCase $xml = MetaDataStorageSourceTest::generateIdpMetadataXml($entityId); $c = [ 'metadata.sources' => [ - ["type"=>"xml", "xml"=>$xml], + ["type" => "xml", "xml" => $xml], ], ]; Configuration::loadFromArray($c, '', 'simplesaml'); @@ -429,7 +353,7 @@ class SPTest extends ClearStateTestCase $info = ['AuthId' => 'default-sp']; $config = []; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); try { $as->authenticate($state); $this->fail('Expected ExitTestException'); @@ -463,8 +387,8 @@ class SPTest extends ClearStateTestCase $xml1 = MetaDataStorageSourceTest::generateIdpMetadataXml($entityId1); $c = [ 'metadata.sources' => [ - ["type"=>"xml", "xml"=>$xml], - ["type"=>"xml", "xml"=>$xml1], + ["type" => "xml", "xml" => $xml], + ["type" => "xml", "xml" => $xml1], ], ]; Configuration::loadFromArray($c, '', 'simplesaml'); @@ -480,7 +404,7 @@ class SPTest extends ClearStateTestCase ]; // Http redirect util library requires a request_uri to be set. $_SERVER['REQUEST_URI'] = 'https://l.example.com/'; - $as = new SPTester($info, $config); + $as = new SpTester($info, $config); $as->authenticate($state); } } diff --git a/tests/modules/saml/lib/IdP/SAML2Test.php b/tests/modules/saml/lib/IdP/SAML2Test.php index cdd5d6df4ba44737d0e15907542e918e58fec8a5..cf3415680cc1b33d9036e324aa05c6708eb1897d 100644 --- a/tests/modules/saml/lib/IdP/SAML2Test.php +++ b/tests/modules/saml/lib/IdP/SAML2Test.php @@ -14,7 +14,7 @@ class SAML2Test extends ClearStateTestCase * @var array */ private $defaultExpectedAuthState = [ - 'Responder' =>['\SimpleSAML\Module\saml\IdP\SAML2', 'sendResponse'], + 'Responder' => ['\SimpleSAML\Module\saml\IdP\SAML2', 'sendResponse'], '\SimpleSAML\Auth\State.exceptionFunc' => ['\SimpleSAML\Module\saml\IdP\SAML2', 'handleAuthError'], 'saml:RelayState' => null, 'saml:RequestId' => null, @@ -195,7 +195,7 @@ EOT; // won't line up perfectly $_REQUEST = $_REQUEST + $queryParams; $_SERVER['HTTP_HOST'] = 'idp.examlple.com'; - $_SERVER['REQUEST_URI'] = '/saml2/idp/SSOService.php?'.http_build_query($queryParams); + $_SERVER['REQUEST_URI'] = '/saml2/idp/SSOService.php?' . http_build_query($queryParams); $state = []; diff --git a/tests/routers/configLoader.php b/tests/routers/configLoader.php index 57baa0a42f15355805609b437fac6d18c91dd009..9133ab10525fe4396af8b00727f235e44af15ae0 100644 --- a/tests/routers/configLoader.php +++ b/tests/routers/configLoader.php @@ -26,10 +26,10 @@ * unlink($file); */ -include_once(sys_get_temp_dir().'/'.getmypid().'.lock'); +include_once(sys_get_temp_dir() . '/' . getmypid() . '.lock'); // load SimpleSAMLphp's autoloader -require_once(dirname(__FILE__).'/../../vendor/autoload.php'); +require_once(dirname(__FILE__) . '/../../vendor/autoload.php'); // initialize configuration if (isset($config)) { diff --git a/tests/www/IndexTest.php b/tests/www/IndexTest.php index d2bec0f51dd0ecfb6544583a2c9d64350f8ecf5d..1da4d41b7ae031a3670f587fcde4368db83db63d 100644 --- a/tests/www/IndexTest.php +++ b/tests/www/IndexTest.php @@ -1,4 +1,12 @@ <?php + +namespace SimpleSAML\Test\Web; + +use PHPUnit\Framework\TestCase; +use SimpleSAML\Test\BuiltInServer; + +include(dirname(__FILE__) . '/../BuiltInServer.php'); + /** * Simple test for the www/index.php script. * @@ -7,14 +15,6 @@ * @author Jaime Pérez Crespo <jaime.perez@uninett.no> * @package SimpleSAMLphp */ - -namespace SimpleSAML\Test\Web; - -include(dirname(__FILE__).'/../BuiltInServer.php'); - -use PHPUnit\Framework\TestCase; -use \SimpleSAML\Test\BuiltInServer; - class IndexTest extends TestCase { /** @@ -48,7 +48,7 @@ class IndexTest extends TestCase $this->server_addr = $this->server->start(); $this->server_pid = $this->server->getPid(); - $this->shared_file = sys_get_temp_dir().'/'.$this->server_pid.'.lock'; + $this->shared_file = sys_get_temp_dir() . '/' . $this->server_pid . '.lock'; @unlink($this->shared_file); // remove it if it exists } @@ -60,7 +60,7 @@ class IndexTest extends TestCase protected function updateConfig(array $config) { @unlink($this->shared_file); - $config = "<?php\n\$config = ".var_export($config, true).";\n"; + $config = "<?php\n\$config = " . var_export($config, true) . ";\n"; file_put_contents($this->shared_file, $config); } @@ -106,7 +106,7 @@ class IndexTest extends TestCase ]); $this->assertEquals('302', $resp['code']); $this->assertEquals( - 'http://'.$this->server_addr.'/simplesaml/module.php/core/frontpage_welcome.php', + 'http://' . $this->server_addr . '/simplesaml/module.php/core/frontpage_welcome.php', $resp['headers']['Location'] ); } diff --git a/tests/www/RouterTest.php b/tests/www/RouterTest.php index c872bfb07f2bddda8e9e783bc53f7c7d1a4d066d..7b59957433dfb008d017a332c4f05f35f9868b05 100644 --- a/tests/www/RouterTest.php +++ b/tests/www/RouterTest.php @@ -30,10 +30,10 @@ class RouterTest extends TestCase foreach ($files as $file) { if (preg_match('/.(yml|yaml)$/', $file)) { try { - $value = $yaml->parse(file_get_contents('modules/'.$module.'/'.$file)); + $value = $yaml->parse(file_get_contents('modules/' . $module . '/' . $file)); $this->addToAssertionCount(1); } catch (ParseException $e) { - $this->fail($e->getMessage().' in '.$e->getFile().':'.$e->getLine()); + $this->fail($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); } } } diff --git a/tests/www/TemplateTest.php b/tests/www/TemplateTest.php index 3a8f2cd6d764a1a55c049ae6c3000c9c59b58d4b..7bba7931b924de212b5423e438963f4535445f5d 100644 --- a/tests/www/TemplateTest.php +++ b/tests/www/TemplateTest.php @@ -1,10 +1,4 @@ <?php -/** - * Simple test for syntax-checking Twig-templates. - * - * @author Tim van Dijen <tvdijen@gmail.com> - * @package SimpleSAMLphp - */ namespace SimpleSAML\Test\Web; @@ -14,6 +8,12 @@ use SimpleSAML\XHTML\Template; use SimpleSAML\Module; use Twig\Error\SyntaxError; +/** + * Simple test for syntax-checking Twig-templates. + * + * @author Tim van Dijen <tvdijen@gmail.com> + * @package SimpleSAMLphp + */ class TemplateTest extends TestCase { /** @@ -27,7 +27,7 @@ class TemplateTest extends TestCase ]); Configuration::setPreLoadedConfig($config); - $basedir = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'templates'; + $basedir = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'templates'; // Base templates $files = array_diff(scandir($basedir), ['.', '..']); @@ -39,7 +39,7 @@ class TemplateTest extends TestCase $t->show(); $this->addToAssertionCount(1); } catch (SyntaxError $e) { - $this->fail($e->getMessage().' in '.$e->getFile().':'.$e->getLine()); + $this->fail($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); } ob_end_clean(); } @@ -47,18 +47,18 @@ class TemplateTest extends TestCase // Module templates foreach (Module::getModules() as $module) { - $basedir = Module::getModuleDir($module).DIRECTORY_SEPARATOR.'templates'; + $basedir = Module::getModuleDir($module) . DIRECTORY_SEPARATOR . 'templates'; if (file_exists($basedir)) { $files = array_diff(scandir($basedir), ['.', '..']); foreach ($files as $file) { if (preg_match('/.twig$/', $file)) { - $t = new Template($config, $module.':'.$file); + $t = new Template($config, $module . ':' . $file); ob_start(); try { $t->show(); $this->addToAssertionCount(1); } catch (SyntaxError $e) { - $this->fail($e->getMessage().' in '.$e->getFile().':'.$e->getLine()); + $this->fail($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); } ob_end_clean(); }