diff --git a/modules/adfs/www/idp/prp.php b/modules/adfs/www/idp/prp.php index 1f5d85e2b9039013d89759d2550e6ebb7b0df3d3..da86ec88fcb96ef79effa02e3df81cca93d0ed97 100644 --- a/modules/adfs/www/idp/prp.php +++ b/modules/adfs/www/idp/prp.php @@ -11,7 +11,7 @@ $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler(); $idpEntityId = $metadata->getMetaDataCurrentEntityID('adfs-idp-hosted'); -$idp = \SimpleSAML\IdP::getById('adfs:' . $idpEntityId); +$idp = \SimpleSAML\IdP::getById('adfs:'.$idpEntityId); if (isset($_GET['wa'])) { if ($_GET['wa'] === 'wsignout1.0') { diff --git a/modules/authX509/lib/Auth/Process/ExpiryWarning.php b/modules/authX509/lib/Auth/Process/ExpiryWarning.php index 3457ff4b48c2d99ed49a8aee8340d36806b2b8fe..a5286c7bfd0e60663e9d1e1c4e8661e85b89cea5 100644 --- a/modules/authX509/lib/Auth/Process/ExpiryWarning.php +++ b/modules/authX509/lib/Auth/Process/ExpiryWarning.php @@ -80,17 +80,17 @@ class ExpiryWarning extends \SimpleSAML\Auth\ProcessingFilter } $validTo = $client_cert_data['validTo_time_t']; $now = time(); - $daysleft = (int)(($validTo - $now) / (24*60*60)); + $daysleft = (int) (($validTo - $now) / 86400); //24*60*60 if ($daysleft > $this->warndaysbefore) { // We have a certificate that will be valid for some time. Skip the warning return; } - \SimpleSAML\Logger::warning('authX509: user certificate expires in ' . $daysleft . ' days'); + \SimpleSAML\Logger::warning('authX509: user certificate expires in '.$daysleft.' days'); $state['daysleft'] = $daysleft; $state['renewurl'] = $this->renewurl; - /* Save state and redirect. */ + // Save state and redirect $id = \SimpleSAML\Auth\State::saveState($state, 'warning:expire'); $url = \SimpleSAML\Module::getModuleURL('authX509/expirywarning.php'); \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); diff --git a/modules/authX509/lib/Auth/Source/X509userCert.php b/modules/authX509/lib/Auth/Source/X509userCert.php index 402ebbefbada8b9cd0b57553052d23e99b1f54f6..2771979b8f628a009c512616ce13b4888380f009 100644 --- a/modules/authX509/lib/Auth/Source/X509userCert.php +++ b/modules/authX509/lib/Auth/Source/X509userCert.php @@ -54,7 +54,7 @@ class X509userCert extends \SimpleSAML\Auth\Source $this->ldapcf = new \SimpleSAML\Module\ldap\ConfigHelper( $config, - 'Authentication source ' . var_export($this->authId, true) + 'Authentication source '.var_export($this->authId, true) ); return; @@ -120,7 +120,7 @@ class X509userCert extends \SimpleSAML\Auth\Source // value is scalar if (array_key_exists($x509_attr, $client_cert_data['subject'])) { $value = $client_cert_data['subject'][$x509_attr]; - \SimpleSAML\Logger::info('authX509: cert '. $x509_attr.' = '.$value); + \SimpleSAML\Logger::info('authX509: cert '.$x509_attr.' = '.$value); $dn = $ldapcf->searchfordn($ldap_attr, $value, true); if ($dn !== null) { break; @@ -137,7 +137,8 @@ class X509userCert extends \SimpleSAML\Auth\Source return; } - if ($this->ldapusercert === null) { // do not check for certificate match + if ($this->ldapusercert === null) { + // do not check for certificate match $attributes = $ldapcf->getAttributes($dn); assert(is_array($attributes)); $state['Attributes'] = $attributes; diff --git a/modules/authX509/templates/X509error.php b/modules/authX509/templates/X509error.php index 089128a65de7c4093d47abc372b5e5eeaddd5bad..3eb08fd13ff8d353ad6a41c4a9ada97f9ddb7c47 100644 --- a/modules/authX509/templates/X509error.php +++ b/modules/authX509/templates/X509error.php @@ -24,18 +24,14 @@ if ($this->data['errorcode'] !== null) { <a href="<?php echo htmlspecialchars(\SimpleSAML\Utils\HTTP::getSelfURL()); ?>"> <?php echo $this->t('{login:login_button}'); ?> </a> - <?php -if(!empty($this->data['links'])) { - echo '<ul class="links" style="margin-top: 2em">'; - foreach($this->data['links'] AS $l) { - echo '<li><a href="' . htmlspecialchars($l['href']) . '">' . htmlspecialchars($this->t($l['text'])) . '</a></li>'; - } - echo '</ul>'; +if (!empty($this->data['links'])) { + echo '<ul class="links" style="margin-top: 2em">'; + foreach ($this->data['links'] as $l) { + echo '<li><a href="'.htmlspecialchars($l['href']).'">'.htmlspecialchars($this->t($l['text'])).'</a></li>'; + } + echo '</ul>'; } - - - $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/authX509/templates/X509warning.php b/modules/authX509/templates/X509warning.php index 704ed8865e2f1a5a9c767e7c8e127a882b03e088..dfe69cbbec7e3aa9af856eb03dccfa950eb3e0c1 100644 --- a/modules/authX509/templates/X509warning.php +++ b/modules/authX509/templates/X509warning.php @@ -14,12 +14,12 @@ $warning = $this->t('{authX509:X509warning:warning}', array( '%daysleft%' => htmlspecialchars($this->data['daysleft']), )); -if( $this->data['renewurl']) { - $warning .= " " . $this->t('{authX509:X509warning:renew_url}', array( +if ($this->data['renewurl']) { + $warning .= " ".$this->t('{authX509:X509warning:renew_url}', array( '%renewurl%' => $this->data['renewurl'], )); } else { - $warning .= " " . $this->t('{authX509:X509warning:renew}'); + $warning .= " ".$this->t('{authX509:X509warning:renew}'); } $this->data['header'] = $this->t('{authX509:X509warning:warning_header}'); @@ -34,7 +34,7 @@ $this->includeAtTemplateBase('includes/header.php'); <?php // Embed hidden fields... foreach ($this->data['data'] as $name => $value) { - echo('<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'); + echo '<input type="hidden" name="'.htmlspecialchars($name).'" value="'.htmlspecialchars($value).'" />'; } ?> <p><?php echo $warning; ?></p> diff --git a/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php b/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php index 0fe040ee453d5974a95e3625198624b3c24088f6..3a1c3175b126ffe392245a4105c16a12d7b0699d 100644 --- a/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php +++ b/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php @@ -47,32 +47,32 @@ namespace SimpleSAML\Module\authYubiKey\Auth\Process; class OTP2YubiPrefix extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Filter out YubiKey 'otp' attribute and replace it with - * a 'yubiPrefix' attribute that leaves out the dynamic part. - * - * @param array &$state The state we should update. - */ - public function process(&$state) { - assert(is_array($state)); - assert(array_key_exists('Attributes', $state)); - $attributes = $state['Attributes']; + /** + * Filter out YubiKey 'otp' attribute and replace it with + * a 'yubiPrefix' attribute that leaves out the dynamic part. + * + * @param array &$state The state we should update. + */ + public function process(&$state) + { + assert(is_array($state)); + assert(array_key_exists('Attributes', $state)); + $attributes = $state['Attributes']; - \SimpleSAML\Logger::debug('OTP2YubiPrefix: enter with attributes: ' . implode(',', array_keys($attributes))); + \SimpleSAML\Logger::debug('OTP2YubiPrefix: enter with attributes: '.implode(',', array_keys($attributes))); - $otps = $attributes['otp']; - $otp = $otps['0']; + $otps = $attributes['otp']; + $otp = $otps['0']; - $token_size = 32; - $identity = substr ($otp, 0, strlen ($otp) - $token_size); + $token_size = 32; + $identity = substr($otp, 0, strlen($otp) - $token_size); - $attributes['yubiPrefix'] = array($identity); + $attributes['yubiPrefix'] = array($identity); - \SimpleSAML\Logger::info('OTP2YubiPrefix: otp: ' . $otp . ' identity: ' . $identity . ' (otp keys: ' . implode(',', array_keys($otps)) . ')'); + \SimpleSAML\Logger::info('OTP2YubiPrefix: otp: '.$otp.' identity: '.$identity.' (otp keys: '.implode(',', array_keys($otps)).')'); - unset($attributes['otp']); - - \SimpleSAML\Logger::debug('OTP2YubiPrefix: leaving with attributes: ' . implode(',', array_keys($attributes))); - } + unset($attributes['otp']); + \SimpleSAML\Logger::debug('OTP2YubiPrefix: leaving with attributes: '.implode(',', array_keys($attributes))); + } } diff --git a/modules/authYubiKey/lib/Auth/Source/YubiKey.php b/modules/authYubiKey/lib/Auth/Source/YubiKey.php index fcd1726f322beedd61f40d1da7f280678d0a434a..b4377847369e6f3c06b3c9711f631b935b5f7919 100644 --- a/modules/authYubiKey/lib/Auth/Source/YubiKey.php +++ b/modules/authYubiKey/lib/Auth/Source/YubiKey.php @@ -165,7 +165,7 @@ class YubiKey extends \SimpleSAML\Auth\Source */ public static function getYubiKeyPrefix($otp) { - $uid = substr($otp, 0, strlen ($otp) - self::TOKENSIZE); + $uid = substr($otp, 0, strlen($otp) - self::TOKENSIZE); return $uid; } diff --git a/modules/authYubiKey/libextinc/Yubico.php b/modules/authYubiKey/libextinc/Yubico.php index c6b4f4a600e74c76ab94095056a076279a1038e5..12d2d8b4de0d167ecc5c584d07ea5029391930c3 100644 --- a/modules/authYubiKey/libextinc/Yubico.php +++ b/modules/authYubiKey/libextinc/Yubico.php @@ -1,44 +1,44 @@ <?php - /** - * Class for verifying Yubico One-Time-Passcodes - * - * LICENSE: - * - * Copyright (c) 2007, 2008 Simon Josefsson. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * o The names of the authors may not be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * @category Auth - * @package Auth_Yubico - * @author Simon Josefsson <simon@yubico.com> - * @copyright 2008 Simon Josefsson - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @version CVS: $Id: Yubico.php,v 1.7 2007-10-22 12:56:14 jas Exp $ - * @link http://yubico.com/ - */ +/** + * Class for verifying Yubico One-Time-Passcodes + * + * LICENSE: + * + * Copyright (c) 2007, 2008 Simon Josefsson. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * o Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * o Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * o The names of the authors may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @category Auth + * @package Auth_Yubico + * @author Simon Josefsson <simon@yubico.com> + * @copyright 2008 Simon Josefsson + * @license http://opensource.org/licenses/bsd-license.php New BSD License + * @version CVS: $Id: Yubico.php,v 1.7 2007-10-22 12:56:14 jas Exp $ + * @link http://yubico.com/ + */ /** * Class for verifying Yubico One-Time-Passcodes @@ -58,104 +58,104 @@ */ class Auth_Yubico { - /**#@+ - * @access private - */ - - /** - * Yubico client ID - * @var string - */ - private $_id; - - /** - * Yubico client key - * @var string - */ - private $_key; - - /** - * Response from server - * @var string - */ - private $_response; - - /** - * Constructor - * - * Sets up the object - * @param string $id The client identity - * @param string $key The client MAC key (optional) - * @access public - */ - public function __construct($id, $key = '') - { - $this->_id = $id; - $this->_key = base64_decode($key); - } - - /** - * Return the last data received from the server, if any. - * - * @return string Output from server. - * @access public - */ - public function getLastResponse() - { - return $this->_response; - } - - // TODO? Add functions to get parsed parts of server response? - - /** - * Verify Yubico OTP - * - * @param string $token Yubico OTP - * @return mixed PEAR error on error, true otherwise - * @access public - */ - public function verify($token) - { - $parameters = "id=" . $this->_id . "&otp=" . $token; - // Generate signature - if ($this->_key <> "") { - $signature = base64_encode(hash_hmac('sha1', $parameters, $this->_key, true)); - $parameters .= '&h=' . $signature; - } - /* Support https. */ - $url = "https://api.yubico.com/wsapi/verify?" . $parameters; - - $responseMsg = \SimpleSAML\Utils\HTTP::fetch($url); - - if (!preg_match("/status=([a-zA-Z0-9_]+)/", $responseMsg, $out)) { - throw new Exception('Could not parse response'); - } - - $status = $out[1]; - - /* Verify signature. */ - if ($this->_key <> "") { - $rows = explode("\r\n", $responseMsg); + /**#@+ + * @access private + */ + + /** + * Yubico client ID + * @var string + */ + private $_id; + + /** + * Yubico client key + * @var string + */ + private $_key; + + /** + * Response from server + * @var string + */ + private $_response; + + /** + * Constructor + * + * Sets up the object + * @param string $id The client identity + * @param string $key The client MAC key (optional) + * @access public + */ + public function __construct($id, $key = '') + { + $this->_id = $id; + $this->_key = base64_decode($key); + } + + /** + * Return the last data received from the server, if any. + * + * @return string Output from server. + * @access public + */ + public function getLastResponse() + { + return $this->_response; + } + + // TODO? Add functions to get parsed parts of server response? + + /** + * Verify Yubico OTP + * + * @param string $token Yubico OTP + * @return mixed PEAR error on error, true otherwise + * @access public + */ + public function verify($token) + { + $parameters = "id=".$this->_id."&otp=".$token; + // Generate signature + if ($this->_key <> "") { + $signature = base64_encode(hash_hmac('sha1', $parameters, $this->_key, true)); + $parameters .= '&h='.$signature; + } + // Support https + $url = "https://api.yubico.com/wsapi/verify?".$parameters; + + $responseMsg = \SimpleSAML\Utils\HTTP::fetch($url); + + if (!preg_match("/status=([a-zA-Z0-9_]+)/", $responseMsg, $out)) { + throw new Exception('Could not parse response'); + } + + $status = $out[1]; + + // Verify signature + if ($this->_key <> "") { + $rows = explode("\r\n", $responseMsg); $response = array(); foreach ($rows as $val) { - // = is also used in BASE64 encoding so we only replace the first = by # which is not used in BASE64 - $val = preg_replace('/=/', '#', $val, 1); - $row = explode("#", $val); - $response[$row[0]] = (isset($row[1])) ? $row[1] : ""; - } - - $check = 'status=' . $response['status'] . '&t='. $response['t']; - $checksignature = base64_encode(hash_hmac('sha1', $check, $this->_key, true)); - - if ($response['h'] != $checksignature) { - throw new Exception('Checked Signature failed'); - } - } - - if ($status != 'OK') { - throw new Exception('Status was not OK: ' . $status); - } - - return true; - } + // = is also used in BASE64 encoding so we only replace the first = by # which is not used in BASE64 + $val = preg_replace('/=/', '#', $val, 1); + $row = explode("#", $val); + $response[$row[0]] = (isset($row[1])) ? $row[1] : ""; + } + + $check = 'status='.$response['status'].'&t='.$response['t']; + $checksignature = base64_encode(hash_hmac('sha1', $check, $this->_key, true)); + + if ($response['h'] != $checksignature) { + throw new Exception('Checked Signature failed'); + } + } + + if ($status != 'OK') { + throw new Exception('Status was not OK: '.$status); + } + + return true; + } } diff --git a/modules/authfacebook/lib/Auth/Source/Facebook.php b/modules/authfacebook/lib/Auth/Source/Facebook.php index aec24d25fa4bb12a85ad0df029ab684b22a6f23e..40d5438561501e9f3004ef64c2f95b107dd683d2 100644 --- a/modules/authfacebook/lib/Auth/Source/Facebook.php +++ b/modules/authfacebook/lib/Auth/Source/Facebook.php @@ -76,8 +76,8 @@ class Facebook extends \SimpleSAML\Auth\Source $this->api_key = $cfgParse->getString('api_key'); $this->secret = $cfgParse->getString('secret'); - $this->req_perms = $cfgParse->getString('req_perms', NULL); - $this->user_fields = $cfgParse->getString('user_fields', NULL); + $this->req_perms = $cfgParse->getString('req_perms', null); + $this->user_fields = $cfgParse->getString('user_fields', null); } @@ -127,7 +127,7 @@ class Facebook extends \SimpleSAML\Auth\Source $attributes = array(); foreach ($info as $key => $value) { if (is_string($value) && !empty($value)) { - $attributes['facebook.'.$key] = array((string)$value); + $attributes['facebook.'.$key] = array((string) $value); } } @@ -137,7 +137,7 @@ class Facebook extends \SimpleSAML\Auth\Source $attributes['facebook_user'] = array($uid.'@facebook.com'); } - $attributes['facebook_targetedID'] = array('http://facebook.com!' . $uid); + $attributes['facebook_targetedID'] = array('http://facebook.com!'.$uid); $attributes['facebook_cn'] = array($info['name']); \SimpleSAML\Logger::debug('Facebook Returned Attributes: '.implode(", ", array_keys($attributes))); diff --git a/modules/authfacebook/lib/Facebook.php b/modules/authfacebook/lib/Facebook.php index edae09bd500904255337bddb2d2ebbc351728c2d..f5d123077db220012ddf6c549c3015e53dec939a 100644 --- a/modules/authfacebook/lib/Facebook.php +++ b/modules/authfacebook/lib/Facebook.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\authfacebook; -require_once(dirname(dirname(__FILE__)) . '/extlibinc/base_facebook.php'); +require_once(dirname(dirname(__FILE__)).'/extlibinc/base_facebook.php'); /** * Extends the BaseFacebook class with the intent of using @@ -11,152 +11,160 @@ require_once(dirname(dirname(__FILE__)) . '/extlibinc/base_facebook.php'); class Facebook extends \BaseFacebook { - const FBSS_COOKIE_NAME = 'fbss'; - - // We can set this to a high number because the main session - // expiration will trump this - const FBSS_COOKIE_EXPIRE = 31556926; // 1 year - - // Stores the shared session ID if one is set - protected $sharedSessionID; - - // SimpleSAMLphp state array - protected $ssp_state; - - // \SimpleSAML\Auth\State - protected $state; - - /** - * Identical to the parent constructor, except that - * we start a PHP session to store the user ID and - * access token if during the course of execution - * we discover them. - * - * @param Array $config the application configuration. Additionally - * accepts "sharedSession" as a boolean to turn on a secondary - * cookie for environments with a shared session (that is, your app - * shares the domain with other apps). - * @see BaseFacebook::__construct in base_facebook.php - */ - public function __construct(array $config, &$ssp_state) { - $this->ssp_state = &$ssp_state; - - parent::__construct($config); - if (!empty($config['sharedSession'])) { - $this->initSharedSession(); + const FBSS_COOKIE_NAME = 'fbss'; + + // We can set this to a high number because the main session + // expiration will trump this + const FBSS_COOKIE_EXPIRE = 31556926; // 1 year + + // Stores the shared session ID if one is set + protected $sharedSessionID; + + // SimpleSAMLphp state array + protected $ssp_state; + + // \SimpleSAML\Auth\State + protected $state; + + /** + * Identical to the parent constructor, except that + * we start a PHP session to store the user ID and + * access token if during the course of execution + * we discover them. + * + * @param Array $config the application configuration. Additionally + * accepts "sharedSession" as a boolean to turn on a secondary + * cookie for environments with a shared session (that is, your app + * shares the domain with other apps). + * @see BaseFacebook::__construct in base_facebook.php + */ + public function __construct(array $config, &$ssp_state) + { + $this->ssp_state = &$ssp_state; + + parent::__construct($config); + if (!empty($config['sharedSession'])) { + $this->initSharedSession(); + } } - } - - protected static $kSupportedKeys = - array('state', 'code', 'access_token', 'user_id'); - - protected function initSharedSession() { - $cookie_name = $this->getSharedSessionCookieName(); - if (isset($_COOKIE[$cookie_name])) { - $data = $this->parseSignedRequest($_COOKIE[$cookie_name]); - if (!empty($data) && !empty($data['domain']) && - self::isAllowedDomain($this->getHttpHost(), $data['domain'])) { - // good case - $this->sharedSessionID = $data['id']; - return; - } - // ignoring potentially unreachable data - } - // evil/corrupt/missing case - $base_domain = $this->getBaseDomain(); - $this->sharedSessionID = md5(uniqid(mt_rand(), true)); - $cookie_value = $this->makeSignedRequest( - array( - 'domain' => $base_domain, - 'id' => $this->sharedSessionID, - ) - ); - $_COOKIE[$cookie_name] = $cookie_value; - if (!headers_sent()) { - $expire = time() + self::FBSS_COOKIE_EXPIRE; - setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain); - } else { - // @codeCoverageIgnoreStart - \SimpleSAML\Logger::debug( - 'Shared session ID cookie could not be set! You must ensure you '. - 'create the Facebook instance before headers have been sent. This '. - 'will cause authentication issues after the first request.' - ); - // @codeCoverageIgnoreEnd + + protected static $kSupportedKeys = array('state', 'code', 'access_token', 'user_id'); + + protected function initSharedSession() + { + $cookie_name = $this->getSharedSessionCookieName(); + if (isset($_COOKIE[$cookie_name])) { + $data = $this->parseSignedRequest($_COOKIE[$cookie_name]); + if (!empty($data) && !empty($data['domain']) && + self::isAllowedDomain($this->getHttpHost(), $data['domain'])) { + // good case + $this->sharedSessionID = $data['id']; + return; + } + // ignoring potentially unreachable data + } + // evil/corrupt/missing case + $base_domain = $this->getBaseDomain(); + $this->sharedSessionID = md5(uniqid(mt_rand(), true)); + $cookie_value = $this->makeSignedRequest( + array( + 'domain' => $base_domain, + 'id' => $this->sharedSessionID, + ) + ); + $_COOKIE[$cookie_name] = $cookie_value; + if (!headers_sent()) { + $expire = time() + self::FBSS_COOKIE_EXPIRE; + setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain); + } else { + // @codeCoverageIgnoreStart + \SimpleSAML\Logger::debug( + 'Shared session ID cookie could not be set! You must ensure you '. + 'create the Facebook instance before headers have been sent. This '. + 'will cause authentication issues after the first request.' + ); + // @codeCoverageIgnoreEnd + } } - } - - /** - * Provides the implementations of the inherited abstract - * methods. The implementation uses PHP sessions to maintain - * a store for authorization codes, user ids, CSRF states, and - * access tokens. - */ - protected function setPersistentData($key, $value) { - if (!in_array($key, self::$kSupportedKeys)) { - \SimpleSAML\Logger::debug("Unsupported key passed to setPersistentData: " . var_export($key, TRUE)); - return; + + /** + * Provides the implementations of the inherited abstract + * methods. The implementation uses PHP sessions to maintain + * a store for authorization codes, user ids, CSRF states, and + * access tokens. + */ + protected function setPersistentData($key, $value) + { + if (!in_array($key, self::$kSupportedKeys)) { + \SimpleSAML\Logger::debug("Unsupported key passed to setPersistentData: ".var_export($key, true)); + return; + } + + $session_var_name = $this->constructSessionVariableName($key); + $this->ssp_state[$session_var_name] = $value; } - $session_var_name = $this->constructSessionVariableName($key); - $this->ssp_state[$session_var_name] = $value; - } + protected function getPersistentData($key, $default = false) + { + if (!in_array($key, self::$kSupportedKeys)) { + \SimpleSAML\Logger::debug("Unsupported key passed to getPersistentData: ".var_export($key, true)); + return $default; + } - protected function getPersistentData($key, $default = false) { - if (!in_array($key, self::$kSupportedKeys)) { - \SimpleSAML\Logger::debug("Unsupported key passed to getPersistentData: " . var_export($key, TRUE)); - return $default; + $session_var_name = $this->constructSessionVariableName($key); + return isset($this->ssp_state[$session_var_name]) ? $this->ssp_state[$session_var_name] : $default; } - $session_var_name = $this->constructSessionVariableName($key); - return isset($this->ssp_state[$session_var_name]) ? - $this->ssp_state[$session_var_name] : $default; - } + protected function clearPersistentData($key) + { + if (!in_array($key, self::$kSupportedKeys)) { + \SimpleSAML\Logger::debug("Unsupported key passed to clearPersistentData: ".var_export($key, true)); + return; + } + + $session_var_name = $this->constructSessionVariableName($key); + if (isset($this->ssp_state[$session_var_name])) { + unset($this->ssp_state[$session_var_name]); + } + } - protected function clearPersistentData($key) { - if (!in_array($key, self::$kSupportedKeys)) { - \SimpleSAML\Logger::debug("Unsupported key passed to clearPersistentData: " . var_export($key, TRUE)); - return; + protected function clearAllPersistentData() + { + foreach (self::$kSupportedKeys as $key) { + $this->clearPersistentData($key); + } + if ($this->sharedSessionID) { + $this->deleteSharedSessionCookie(); + } } - $session_var_name = $this->constructSessionVariableName($key); - if (isset($this->ssp_state[$session_var_name])) { - unset($this->ssp_state[$session_var_name]); + protected function deleteSharedSessionCookie() + { + $cookie_name = $this->getSharedSessionCookieName(); + unset($_COOKIE[$cookie_name]); + $base_domain = $this->getBaseDomain(); + setcookie($cookie_name, '', 1, '/', '.'.$base_domain); } - } - protected function clearAllPersistentData() { - foreach (self::$kSupportedKeys as $key) { - $this->clearPersistentData($key); + protected function getSharedSessionCookieName() + { + return self::FBSS_COOKIE_NAME.'_'.$this->getAppId(); } - if ($this->sharedSessionID) { - $this->deleteSharedSessionCookie(); + + protected function constructSessionVariableName($key) + { + $parts = array('authfacebook:authdata:fb', $this->getAppId(), $key); + if ($this->sharedSessionID) { + array_unshift($parts, $this->sharedSessionID); + } + return implode('_', $parts); } - } - - protected function deleteSharedSessionCookie() { - $cookie_name = $this->getSharedSessionCookieName(); - unset($_COOKIE[$cookie_name]); - $base_domain = $this->getBaseDomain(); - setcookie($cookie_name, '', 1, '/', '.'.$base_domain); - } - - protected function getSharedSessionCookieName() { - return self::FBSS_COOKIE_NAME . '_' . $this->getAppId(); - } - - protected function constructSessionVariableName($key) { - $parts = array('authfacebook:authdata:fb', $this->getAppId(), $key); - if ($this->sharedSessionID) { - array_unshift($parts, $this->sharedSessionID); + + protected function establishCSRFTokenState() + { + if ($this->state === null) { + $this->state = \SimpleSAML\Auth\State::getStateId($this->ssp_state); + $this->setPersistentData('state', $this->state); + } } - return implode('_', $parts); - } - - protected function establishCSRFTokenState() { - if ($this->state === null) { - $this->state = \SimpleSAML\Auth\State::getStateId($this->ssp_state); - $this->setPersistentData('state', $this->state); - } - } } diff --git a/modules/authfacebook/www/linkback.php b/modules/authfacebook/www/linkback.php index 4d856e5ff3ee536a5dbd27fc2ea29e75855be989..904b33ba26f1e7a56dd64524e4841105f03cc46f 100644 --- a/modules/authfacebook/www/linkback.php +++ b/modules/authfacebook/www/linkback.php @@ -15,13 +15,13 @@ if (array_key_exists('AuthState', $_REQUEST) && !empty($_REQUEST['AuthState'])) // Find authentication source if (!array_key_exists(\SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID, $state)) { - throw new \SimpleSAML\Error\BadRequest('No data in state for ' . \SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID); + throw new \SimpleSAML\Error\BadRequest('No data in state for '.\SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID); } $sourceId = $state[\SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID]; $source = \SimpleSAML\Auth\Source::getById($sourceId); if ($source === null) { - throw new \SimpleSAML\Error\BadRequest('Could not find authentication source with id ' . var_export($sourceId, TRUE)); + throw new \SimpleSAML\Error\BadRequest('Could not find authentication source with id '.var_export($sourceId, true)); } try { diff --git a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php index 892dcb7c7c6410180620e5c038674fb8d16391da..91b0003de744fdbe37a2d81683ae4ac836494afe 100644 --- a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php +++ b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\authlinkedin\Auth\Source; -require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/libextinc/OAuth.php'); +require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/oauth/libextinc/OAuth.php'); /** * Authenticate using LinkedIn. @@ -11,7 +11,7 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib * @package SimpleSAMLphp */ -class LinkedIn extends \SimpleSAML\Auth\Source +class LinkedIn extends \SimpleSAML\Auth\Source { /** * The string used to identify our states. @@ -42,13 +42,15 @@ class LinkedIn extends \SimpleSAML\Auth\Source // Call the parent constructor first, as required by the interface parent::__construct($info, $config); - if (!array_key_exists('key', $config)) + if (!array_key_exists('key', $config)) { throw new \Exception('LinkedIn authentication source is not properly configured: missing [key]'); + } $this->key = $config['key']; - if (!array_key_exists('secret', $config)) + if (!array_key_exists('secret', $config)) { throw new \Exception('LinkedIn authentication source is not properly configured: missing [secret]'); + } $this->secret = $config['secret']; @@ -75,19 +77,19 @@ class LinkedIn extends \SimpleSAML\Auth\Source $state[self::AUTHID] = $this->authId; $stateID = \SimpleSAML\Auth\State::getStateId($state); - \SimpleSAML\Logger::debug('authlinkedin auth state id = ' . $stateID); + \SimpleSAML\Logger::debug('authlinkedin auth state id = '.$stateID); $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); // Get the request token $requestToken = $consumer->getRequestToken( 'https://api.linkedin.com/uas/oauth/requestToken', - array('oauth_callback' => \SimpleSAML\Module::getModuleUrl('authlinkedin') . '/linkback.php?stateid=' . $stateID) + array('oauth_callback' => \SimpleSAML\Module::getModuleUrl('authlinkedin').'/linkback.php?stateid='.$stateID) ); \SimpleSAML\Logger::debug( - "Got a request token from the OAuth service provider [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]" + "Got a request token from the OAuth service provider [". + $requestToken->key."] with the secret [".$requestToken->secret."]" ); $state['authlinkedin:requestToken'] = $requestToken; @@ -100,15 +102,15 @@ class LinkedIn extends \SimpleSAML\Auth\Source } - public function finalStep(&$state) + public function finalStep(&$state) { $requestToken = $state['authlinkedin:requestToken']; $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); \SimpleSAML\Logger::debug( - "oauth: Using this request token [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]" + "oauth: Using this request token [". + $requestToken->key."] with the secret [".$requestToken->secret."]" ); // Replace the request token with an access token (via GET method) @@ -118,12 +120,12 @@ class LinkedIn extends \SimpleSAML\Auth\Source ); \SimpleSAML\Logger::debug( - "Got an access token from the OAuth service provider [" . - $accessToken->key . "] with the secret [" . $accessToken->secret . "]" + "Got an access token from the OAuth service provider [". + $accessToken->key."] with the secret [".$accessToken->secret."]" ); $userdata = $consumer->getUserInfo( - 'https://api.linkedin.com/v1/people/~:(' . $this->attributes . ')', + 'https://api.linkedin.com/v1/people/~:('.$this->attributes.')', $accessToken, array('http' => array('header' => 'x-li-format: json')) ); @@ -133,11 +135,11 @@ class LinkedIn extends \SimpleSAML\Auth\Source // TODO: pass accessToken: key, secret + expiry as attributes? if (array_key_exists('id', $userdata)) { - $attributes['linkedin_targetedID'] = array('http://linkedin.com!' . $userdata['id']); - $attributes['linkedin_user'] = array($userdata['id'] . '@linkedin.com'); + $attributes['linkedin_targetedID'] = array('http://linkedin.com!'.$userdata['id']); + $attributes['linkedin_user'] = array($userdata['id'].'@linkedin.com'); } - \SimpleSAML\Logger::debug('LinkedIn Returned Attributes: '. implode(", ",array_keys($attributes))); + \SimpleSAML\Logger::debug('LinkedIn Returned Attributes: '.implode(", ", array_keys($attributes))); $state['Attributes'] = $attributes; } @@ -174,9 +176,9 @@ class LinkedIn extends \SimpleSAML\Auth\Source $result = array(); foreach ($array as $key => $value) { if (is_array($value)) { - $result = $result + $this->flatten($value, $prefix . $key . '.'); + $result = $result + $this->flatten($value, $prefix.$key.'.'); } else { - $result[$prefix . $key] = array($value); + $result[$prefix.$key] = array($value); } } return $result; diff --git a/modules/authlinkedin/www/linkback.php b/modules/authlinkedin/www/linkback.php index 58770b8b45c85e251efc5a974a58e398bdfb615d..bc2abdca47e5872c428442b91a679948035497f4 100644 --- a/modules/authlinkedin/www/linkback.php +++ b/modules/authlinkedin/www/linkback.php @@ -13,7 +13,7 @@ $state = \SimpleSAML\Auth\State::loadState($_REQUEST['stateid'], \SimpleSAML\Mod if (array_key_exists('oauth_verifier', $_REQUEST)) { $state['authlinkedin:oauth_verifier'] = $_REQUEST['oauth_verifier']; } else { - throw new Exception('OAuth verifier not returned.');; + throw new Exception('OAuth verifier not returned.'); } // Find authentication source @@ -22,7 +22,7 @@ $sourceId = $state[\SimpleSAML\Module\authlinkedin\Auth\Source\LinkedIn::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); } $source->finalStep($state); diff --git a/modules/authorize/lib/Auth/Process/Authorize.php b/modules/authorize/lib/Auth/Process/Authorize.php index 8bac338e6352827d5a4db731d5e620e2d3135348..63b5770125273c3c4c6ca6dc1ae8f8cc6efb018c 100644 --- a/modules/authorize/lib/Auth/Process/Authorize.php +++ b/modules/authorize/lib/Auth/Process/Authorize.php @@ -12,125 +12,128 @@ namespace SimpleSAML\Module\authorize\Auth\Process; class Authorize extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Flag to deny/unauthorize the user a attribute filter IS found - * - * @var bool - */ - protected $deny = FALSE; - - /** - * Flag to turn the REGEX pattern matching on or off - * - * @var bool - */ - protected $regex = TRUE; - - /** - * Array of valid users. Each element is a regular expression. You should - * user \ to escape special chars, like '.' etc. - * - */ - protected $valid_attribute_values = array(); - - - /** - * Initialize this filter. - * Validate configuration parameters. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - - assert(is_array($config)); - - // Check for the deny option, get it and remove it - // Must be bool specifically, if not, it might be for a attrib filter below - if (isset($config['deny']) && is_bool($config['deny'])) { - $this->deny = $config['deny']; - unset($config['deny']); - } - - // Check for the regex option, get it and remove it - // Must be bool specifically, if not, it might be for a attrib filter below - if (isset($config['regex']) && is_bool($config['regex'])) { - $this->regex = $config['regex']; - unset($config['regex']); - } - - foreach ($config as $attribute => $values) { - if (is_string($values)) - $values = array($values); - if (!is_array($values)) - throw new \Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, TRUE)); - foreach ($values as $value){ - if(!is_string($value)) { - throw new \Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, TRUE) . ' value: ' . var_export($value, TRUE) . ' Config is: ' . var_export($config, TRUE)); - } - } - $this->valid_attribute_values[$attribute] = $values; - } - } - - - /** - * Apply filter to validate attributes. - * - * @param array &$request The current request - */ - public function process(&$request) { - $authorize = $this->deny; - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - foreach ($this->valid_attribute_values as $name => $patterns) { - if(array_key_exists($name, $attributes)) { - foreach ($patterns as $pattern){ - $values = $attributes[$name]; - if (!is_array($values)) - $values = array($values); - foreach ($values as $value){ - if ($this->regex) { - $matched = preg_match($pattern, $value); - } else { - $matched = ($value == $pattern); - } - if ($matched) { - $authorize = ($this->deny ? FALSE : TRUE); - break 3; - } - } - } - } - } - if (!$authorize){ - $this->unauthorized($request); - } - } - - - /** - * When the process logic determines that the user is not - * authorized for this service, then forward the user to - * an 403 unauthorized page. - * - * Separated this code into its own method so that child - * classes can override it and change the action. Forward - * thinking in case a "chained" ACL is needed, more complex - * permission logic. - * - * @param array $request - */ - protected function unauthorized(&$request) { - // Save state and redirect to 403 page - $id = \SimpleSAML\Auth\State::saveState($request, - 'authorize:Authorize'); - $url = \SimpleSAML\Module::getModuleURL( - 'authorize/authorize_403.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } + /** + * Flag to deny/unauthorize the user a attribute filter IS found + * + * @var bool + */ + protected $deny = false; + + /** + * Flag to turn the REGEX pattern matching on or off + * + * @var bool + */ + protected $regex = true; + + /** + * Array of valid users. Each element is a regular expression. You should + * user \ to escape special chars, like '.' etc. + * + */ + protected $valid_attribute_values = array(); + + /** + * Initialize this filter. + * Validate configuration parameters. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + // Check for the deny option, get it and remove it + // Must be bool specifically, if not, it might be for a attrib filter below + if (isset($config['deny']) && is_bool($config['deny'])) { + $this->deny = $config['deny']; + unset($config['deny']); + } + + // Check for the regex option, get it and remove it + // Must be bool specifically, if not, it might be for a attrib filter below + if (isset($config['regex']) && is_bool($config['regex'])) { + $this->regex = $config['regex']; + unset($config['regex']); + } + + foreach ($config as $attribute => $values) { + if (is_string($values)) { + $values = array($values); + } + if (!is_array($values)) { + throw new \Exception('Filter Authorize: Attribute values is neither string nor array: '.var_export($attribute, true)); + } + foreach ($values as $value) { + if (!is_string($value)) { + throw new \Exception('Filter Authorize: Each value should be a string for attribute: '.var_export($attribute, true).' value: '.var_export($value, true).' Config is: '.var_export($config, true)); + } + } + $this->valid_attribute_values[$attribute] = $values; + } + } + + /** + * Apply filter to validate attributes. + * + * @param array &$request The current request + */ + public function process(&$request) + { + $authorize = $this->deny; + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $attributes = &$request['Attributes']; + + foreach ($this->valid_attribute_values as $name => $patterns) { + if (array_key_exists($name, $attributes)) { + foreach ($patterns as $pattern) { + $values = $attributes[$name]; + if (!is_array($values)) { + $values = array($values); + } + foreach ($values as $value) { + if ($this->regex) { + $matched = preg_match($pattern, $value); + } else { + $matched = ($value == $pattern); + } + if ($matched) { + $authorize = ($this->deny ? false : true); + break 3; + } + } + } + } + } + if (!$authorize) { + $this->unauthorized($request); + } + } + + /** + * When the process logic determines that the user is not + * authorized for this service, then forward the user to + * an 403 unauthorized page. + * + * Separated this code into its own method so that child + * classes can override it and change the action. Forward + * thinking in case a "chained" ACL is needed, more complex + * permission logic. + * + * @param array $request + */ + protected function unauthorized(&$request) + { + // Save state and redirect to 403 page + $id = \SimpleSAML\Auth\State::saveState($request, + 'authorize:Authorize'); + $url = \SimpleSAML\Module::getModuleURL( + 'authorize/authorize_403.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } } diff --git a/modules/authtwitter/lib/Auth/Source/Twitter.php b/modules/authtwitter/lib/Auth/Source/Twitter.php index 3bf984f9c8718534206afc17c95c9880c8e521c1..3079d20ebcafea024a375dd6e44cfa4944aaba94 100644 --- a/modules/authtwitter/lib/Auth/Source/Twitter.php +++ b/modules/authtwitter/lib/Auth/Source/Twitter.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\authtwitter\Auth\Source; -require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/libextinc/OAuth.php'); +require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/oauth/libextinc/OAuth.php'); /** * Authenticate using Twitter. @@ -13,20 +13,20 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib class Twitter extends \SimpleSAML\Auth\Source { - /** - * The string used to identify our states. - */ - const STAGE_INIT = 'twitter:init'; + /** + * The string used to identify our states. + */ + const STAGE_INIT = 'twitter:init'; - /** - * The key of the AuthId field in the state. - */ - const AUTHID = 'twitter:AuthId'; + /** + * The key of the AuthId field in the state. + */ + const AUTHID = 'twitter:AuthId'; /** * @var string */ - private $key; + private $key; /** * @var string @@ -36,117 +36,115 @@ class Twitter extends \SimpleSAML\Auth\Source /** * @var bool */ - private $force_login; + private $force_login; /** * @var bool */ private $include_email; - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct($info, $config) + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) { - assert(is_array($info)); - assert(is_array($config)); + assert(is_array($info)); + assert(is_array($config)); - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); - $configObject = \SimpleSAML\Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, true) . ']'); + $configObject = \SimpleSAML\Configuration::loadFromArray($config, 'authsources['.var_export($this->authId, true).']'); - $this->key = $configObject->getString('key'); - $this->secret = $configObject->getString('secret'); - $this->force_login = $configObject->getBoolean('force_login', false); - $this->include_email = $configObject->getBoolean('include_email', false); - } + $this->key = $configObject->getString('key'); + $this->secret = $configObject->getString('secret'); + $this->force_login = $configObject->getBoolean('force_login', false); + $this->include_email = $configObject->getBoolean('include_email', false); + } - - /** - * Log-in using Twitter platform - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(&$state) + /** + * Log-in using Twitter platform + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) { - assert(is_array($state)); - - // We are going to need the authId in order to retrieve this authentication source later - $state[self::AUTHID] = $this->authId; - - $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); - - $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); - // Get the request token - $linkback = \SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID)); - $requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback)); - \SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); - - $state['authtwitter:authdata:requestToken'] = $requestToken; - \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); - - // Authorize the request token - $url = 'https://api.twitter.com/oauth/authenticate'; - if ($this->force_login) { - $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array('force_login' => 'true')); - } - $consumer->getAuthorizeRequest($url, $requestToken); - } - - - public function finalStep(&$state) + assert(is_array($state)); + + // We are going to need the authId in order to retrieve this authentication source later + $state[self::AUTHID] = $this->authId; + + $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); + + $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); + // Get the request token + $linkback = \SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID)); + $requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback)); + \SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [". + $requestToken->key."] with the secret [".$requestToken->secret."]"); + + $state['authtwitter:authdata:requestToken'] = $requestToken; + \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); + + // Authorize the request token + $url = 'https://api.twitter.com/oauth/authenticate'; + if ($this->force_login) { + $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array('force_login' => 'true')); + } + $consumer->getAuthorizeRequest($url, $requestToken); + } + + public function finalStep(&$state) { - $requestToken = $state['authtwitter:authdata:requestToken']; - $parameters = array(); - - if (!isset($_REQUEST['oauth_token'])) { - throw new \SimpleSAML\Error\BadRequest("Missing oauth_token parameter."); - } - if ($requestToken->key !== (string)$_REQUEST['oauth_token']) { - throw new \SimpleSAML\Error\BadRequest("Invalid oauth_token parameter."); - } - - if (!isset($_REQUEST['oauth_verifier'])) { - throw new \SimpleSAML\Error\BadRequest("Missing oauth_verifier parameter."); - } - $parameters['oauth_verifier'] = (string)$_REQUEST['oauth_verifier']; - - $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); - - \SimpleSAML\Logger::debug("oauth: Using this request token [" . - $requestToken->key . "] with the secret [" . $requestToken->secret . "]"); - - // Replace the request token with an access token - $accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters); - \SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [" . - $accessToken->key . "] with the secret [" . $accessToken->secret . "]"); - - $verify_credentials_url = 'https://api.twitter.com/1.1/account/verify_credentials.json'; - if ($this->include_email) { - $verify_credentials_url = $verify_credentials_url . '?include_email=true'; - } - $userdata = $consumer->getUserInfo($verify_credentials_url, $accessToken); - - if (!isset($userdata['id_str']) || !isset($userdata['screen_name'])) { - throw new \SimpleSAML\Error\AuthSource($this->authId, 'Authentication error: id_str and screen_name not set.'); - } - - $attributes = array(); - foreach ($userdata as $key => $value) { - if (is_string($value)) { - $attributes['twitter.' . $key] = array((string)$value); - } - } - - $attributes['twitter_at_screen_name'] = array('@' . $userdata['screen_name']); - $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'] . '@twitter.com'); - $attributes['twitter_targetedID'] = array('http://twitter.com!' . $userdata['id_str']); - - $state['Attributes'] = $attributes; - } + $requestToken = $state['authtwitter:authdata:requestToken']; + $parameters = array(); + + if (!isset($_REQUEST['oauth_token'])) { + throw new \SimpleSAML\Error\BadRequest("Missing oauth_token parameter."); + } + if ($requestToken->key !== (string) $_REQUEST['oauth_token']) { + throw new \SimpleSAML\Error\BadRequest("Invalid oauth_token parameter."); + } + + if (!isset($_REQUEST['oauth_verifier'])) { + throw new \SimpleSAML\Error\BadRequest("Missing oauth_verifier parameter."); + } + $parameters['oauth_verifier'] = (string) $_REQUEST['oauth_verifier']; + + $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret); + + \SimpleSAML\Logger::debug("oauth: Using this request token [". + $requestToken->key."] with the secret [".$requestToken->secret."]"); + + // Replace the request token with an access token + $accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters); + \SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [". + $accessToken->key."] with the secret [".$accessToken->secret."]"); + + $verify_credentials_url = 'https://api.twitter.com/1.1/account/verify_credentials.json'; + if ($this->include_email) { + $verify_credentials_url = $verify_credentials_url.'?include_email=true'; + } + $userdata = $consumer->getUserInfo($verify_credentials_url, $accessToken); + + if (!isset($userdata['id_str']) || !isset($userdata['screen_name'])) { + throw new \SimpleSAML\Error\AuthSource($this->authId, 'Authentication error: id_str and screen_name not set.'); + } + + $attributes = array(); + foreach ($userdata as $key => $value) { + if (is_string($value)) { + $attributes['twitter.'.$key] = array((string) $value); + } + } + + $attributes['twitter_at_screen_name'] = array('@'.$userdata['screen_name']); + $attributes['twitter_screen_n_realm'] = array($userdata['screen_name'].'@twitter.com'); + $attributes['twitter_targetedID'] = array('http://twitter.com!'.$userdata['id_str']); + + $state['Attributes'] = $attributes; + } } diff --git a/modules/authtwitter/www/linkback.php b/modules/authtwitter/www/linkback.php index fc0184059e40859c949c2e046575a76f5c976878..ebba693a4ac5d60d71a2c95e44802e8afbb60618 100644 --- a/modules/authtwitter/www/linkback.php +++ b/modules/authtwitter/www/linkback.php @@ -11,20 +11,19 @@ $state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], \SimpleSAML\M // Find authentication source if (!array_key_exists(\SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID, $state)) { - throw new \SimpleSAML\Error\BadRequest('No data in state for ' . \SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID); + throw new \SimpleSAML\Error\BadRequest('No data in state for '.\SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID); } $sourceId = $state[\SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID]; $source = \SimpleSAML\Auth\Source::getById($sourceId); if ($source === null) { - throw new \SimpleSAML\Error\BadRequest('Could not find authentication source with id ' . var_export($sourceId, TRUE)); + throw new \SimpleSAML\Error\BadRequest('Could not find authentication source with id '.var_export($sourceId, true)); } try { if (array_key_exists('denied', $_REQUEST)) { throw new \SimpleSAML\Error\UserAborted(); } - $source->finalStep($state); } catch (\SimpleSAML\Error\Exception $e) { \SimpleSAML\Auth\State::throwException($state, $e); diff --git a/modules/authwindowslive/lib/Auth/Source/LiveID.php b/modules/authwindowslive/lib/Auth/Source/LiveID.php index 474d6d800fbb45914972284e1da0a1422c428542..45488abe294b68836e8095d9239df47c8e7d1c95 100644 --- a/modules/authwindowslive/lib/Auth/Source/LiveID.php +++ b/modules/authwindowslive/lib/Auth/Source/LiveID.php @@ -24,7 +24,6 @@ class LiveID extends \SimpleSAML\Auth\Source private $key; private $secret; - /** * Constructor for this authentication source. * @@ -54,7 +53,6 @@ class LiveID extends \SimpleSAML\Auth\Source $this->secret = $config['secret']; } - /** * Log-in using LiveID platform * @@ -69,24 +67,23 @@ class LiveID extends \SimpleSAML\Auth\Source $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); - \SimpleSAML\Logger::debug('authwindowslive auth state id = ' . $stateID); + \SimpleSAML\Logger::debug('authwindowslive auth state id = '.$stateID); // authenticate the user // documentation at: // https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/ - $authorizeURL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' - . '?client_id=' . $this->key - . '&response_type=code' - . '&response_mode=query' - . '&redirect_uri=' . urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php') - . '&state=' . urlencode($stateID) - . '&scope=' . urlencode('openid https://graph.microsoft.com/user.read') + $authorizeURL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'. + '?client_id='.$this->key. + '&response_type=code'. + '&response_mode=query'. + '&redirect_uri='.urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive').'/linkback.php'). + '&state='.urlencode($stateID). + '&scope='.urlencode('openid https://graph.microsoft.com/user.read') ; \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL); } - /** * @param $state * @@ -101,17 +98,17 @@ class LiveID extends \SimpleSAML\Auth\Source // retrieve Access Token // documentation at: // https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/#request-an-access-token - $postData = 'client_id=' . urlencode($this->key) - . '&client_secret=' . urlencode($this->secret) - . '&scope=' . urlencode('https://graph.microsoft.com/user.read') - . '&grant_type=authorization_code' - . '&redirect_uri=' . urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php') - . '&code=' . urlencode($state['authwindowslive:verification_code']); + $postData = 'client_id='.urlencode($this->key). + '&client_secret='.urlencode($this->secret). + '&scope='.urlencode('https://graph.microsoft.com/user.read'). + '&grant_type=authorization_code'. + '&redirect_uri='.urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive').'/linkback.php'). + '&code='.urlencode($state['authwindowslive:verification_code']); $context = array( 'http' => array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postData, ), ); @@ -124,7 +121,7 @@ class LiveID extends \SimpleSAML\Auth\Source if (!array_key_exists('access_token', $response)) { throw new \Exception( '['.$response['error'].'] '.$response['error_description']. - "\r\nNo access_token returned - cannot proceed\r\n" . implode(', ', $response['error_codes']) + "\r\nNo access_token returned - cannot proceed\r\n".implode(', ', $response['error_codes']) ); } @@ -133,8 +130,10 @@ class LiveID extends \SimpleSAML\Auth\Source ); // documentation at: http://graph.microsoft.io/en-us/docs/overview/call_api - $opts = array('http' => array('header' => "Accept: application/json\r\nAuthorization: Bearer ". - $response['access_token']."\r\n")); + $opts = array( + 'http' => array('header' => "Accept: application/json\r\nAuthorization: Bearer ". + $response['access_token']."\r\n") + ); $data = \SimpleSAML\Utils\HTTP::fetch('https://graph.microsoft.com/v1.0/me', $opts); $userdata = json_decode($data, true); @@ -151,12 +150,12 @@ class LiveID extends \SimpleSAML\Auth\Source ); foreach ($userdata as $key => $value) { if (is_string($value)) { - $attributes['windowslive.' . $key] = array((string)$value); + $attributes['windowslive.'.$key] = array((string) $value); } } - \SimpleSAML\Logger::debug('LiveID Returned Attributes: '. implode(", ", array_keys($attributes))); + \SimpleSAML\Logger::debug('LiveID Returned Attributes: '.implode(", ", array_keys($attributes))); $state['Attributes'] = $attributes; } diff --git a/modules/cas/lib/Auth/Source/CAS.php b/modules/cas/lib/Auth/Source/CAS.php index 7b7f9a3d1966b84f45376846c996a80c22bdb3e0..9ae671a76bfd3bf9ab562c92c0c18b5d154314e6 100644 --- a/modules/cas/lib/Auth/Source/CAS.php +++ b/modules/cas/lib/Auth/Source/CAS.php @@ -70,14 +70,14 @@ class CAS extends \SimpleSAML\Auth\Source if (isset($this->_casConfig['serviceValidate'])) { $this->_validationMethod = 'serviceValidate'; - } elseif(isset($this->_casConfig['validate'])) { + } elseif (isset($this->_casConfig['validate'])) { $this->_validationMethod = 'validate'; } else { throw new \Exception("validate or serviceValidate not specified"); } if (isset($this->_casConfig['login'])) { - $this->_loginMethod = $this->_casConfig['login']; + $this->_loginMethod = $this->_casConfig['login']; } else { throw new \Exception("cas login URL not specified"); } @@ -99,7 +99,7 @@ class CAS extends \SimpleSAML\Auth\Source 'service' => $service, )); $result = \SimpleSAML\Utils\HTTP::fetch($url); - $res = preg_split("/\r?\n/",$result); + $res = preg_split("/\r?\n/", $result); if (strcmp($res[0], "yes") == 0) { return array($res[1], array()); @@ -134,10 +134,11 @@ class CAS extends \SimpleSAML\Auth\Source $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user"); if ($success->length == 0) { $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure"); - throw new \Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent); + throw new \Exception("Error when validating CAS service ticket: ".$failure->item(0)->textContent); } else { $attributes = array(); - if ($casattributes = $this->_casConfig['attributes']) { # some has attributes in the xml - attributes is a list of XPath expressions to get them + if ($casattributes = $this->_casConfig['attributes']) { + // Some has attributes in the xml - attributes is a list of XPath expressions to get them foreach ($casattributes as $name => $query) { $attrs = $xPath->query($query); foreach ($attrs as $attrvalue) { @@ -162,8 +163,7 @@ class CAS extends \SimpleSAML\Auth\Source */ protected function casValidation($ticket, $service) { - switch ($this->_validationMethod) - { + switch ($this->_validationMethod) { case 'validate': return $this->casValidate($ticket, $service); case 'serviceValidate': @@ -183,12 +183,12 @@ class CAS extends \SimpleSAML\Auth\Source { $ticket = $state['cas:ticket']; $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT); - $service = \SimpleSAML\Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID)); + $service = \SimpleSAML\Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID)); list($username, $casattributes) = $this->casValidation($ticket, $service); $ldapattributes = array(); $config = \SimpleSAML\Configuration::loadFromArray($this->_ldapConfig, - 'Authentication source ' . var_export($this->authId, true)); + 'Authentication source '.var_export($this->authId, true)); if ($this->_ldapConfig['servers']) { $ldap = new \SimpleSAML\Auth\LDAP( $config->getString('servers'), diff --git a/modules/cas/www/linkback.php b/modules/cas/www/linkback.php index a429b9c8e7fed6111212fe6466f126c6c278ce76..e547a9afeb0ff18cdba5fce89b282f96e891089c 100644 --- a/modules/cas/www/linkback.php +++ b/modules/cas/www/linkback.php @@ -12,7 +12,7 @@ $state = \SimpleSAML\Auth\State::loadState($_GET['stateID'], \SimpleSAML\Module\ if (!isset($_GET['ticket'])) { throw new \SimpleSAML\Error\BadRequest('Missing ticket parameter.'); } -$state['cas:ticket'] = (string)$_GET['ticket']; +$state['cas:ticket'] = (string) $_GET['ticket']; // Find authentication source assert(array_key_exists(\SimpleSAML\Module\cas\Auth\Source\CAS::AUTHID, $state)); @@ -20,7 +20,7 @@ $sourceId = $state[\SimpleSAML\Module\cas\Auth\Source\CAS::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); } $source->finalStep($state); diff --git a/modules/cdc/lib/Auth/Process/CDC.php b/modules/cdc/lib/Auth/Process/CDC.php index c616e7aeae0881b09b0bf0fd4f940cfe8a42e513..d16569ef80765634b9cc6650d4c2357ee1db09b0 100644 --- a/modules/cdc/lib/Auth/Process/CDC.php +++ b/modules/cdc/lib/Auth/Process/CDC.php @@ -40,7 +40,7 @@ class CDC extends \SimpleSAML\Auth\ProcessingFilter if (!isset($config['domain'])) { throw new \SimpleSAML\Error\Exception('Missing domain option in cdc:CDC filter.'); } - $this->domain = (string)$config['domain']; + $this->domain = (string) $config['domain']; $this->client = new \SimpleSAML\Module\cdc\Client($this->domain); } diff --git a/modules/cdc/lib/Server.php b/modules/cdc/lib/Server.php index 1c4be9aa49b93bde70311700224422ec90e32310..4292ce53fee306a0a306f8c18e3a6e661be6144d 100644 --- a/modules/cdc/lib/Server.php +++ b/modules/cdc/lib/Server.php @@ -136,14 +136,14 @@ class Server if (!isset($request['op'])) { throw new \SimpleSAML\Error\BadRequest('Missing "op" in CDC request.'); } - $op = (string)$request['op']; + $op = (string) $request['op']; \SimpleSAML\Logger::info('Received CDC request with "op": '.var_export($op, true)); if (!isset($request['return'])) { throw new \SimpleSAML\Error\BadRequest('Missing "return" in CDC request.'); } - $return = (string)$request['return']; + $return = (string) $request['return']; switch ($op) { case 'append': @@ -167,7 +167,7 @@ class Server $response['op'] = $op; if (isset($request['id'])) { - $response['id'] = (string)$request['id']; + $response['id'] = (string) $request['id']; } $response['domain'] = $this->domain; @@ -186,7 +186,7 @@ class Server if (!isset($request['entityID'])) { throw new \SimpleSAML\Error\BadRequest('Missing entityID in append request.'); } - $entityID = (string)$request['entityID']; + $entityID = (string) $request['entityID']; $list = $this->getCDC(); @@ -252,7 +252,7 @@ class Server if (!isset($_REQUEST[$parameter])) { return null; } - $message = (string)$_REQUEST[$parameter]; + $message = (string) $_REQUEST[$parameter]; $message = @base64_decode($message); if ($message === false) { @@ -267,7 +267,7 @@ class Server if (!isset($message['timestamp'])) { throw new \SimpleSAML\Error\BadRequest('Missing timestamp in CDC message.'); } - $timestamp = (int)$message['timestamp']; + $timestamp = (int) $message['timestamp']; if ($timestamp + 60 < time()) { throw new \SimpleSAML\Error\BadRequest('CDC signature has expired.'); @@ -296,12 +296,12 @@ class Server assert(is_string($parameter)); assert(isset($_REQUEST[$parameter])); - $message = (string)$_REQUEST[$parameter]; + $message = (string) $_REQUEST[$parameter]; if (!isset($_REQUEST['Signature'])) { throw new \SimpleSAML\Error\BadRequest('Missing Signature on CDC message.'); } - $signature = (string)$_REQUEST['Signature']; + $signature = (string) $_REQUEST['Signature']; $cSignature = $this->calcSignature($message); if ($signature !== $cSignature) { @@ -352,7 +352,7 @@ class Server { assert(is_string($rawMessage)); - return sha1($this->key . $rawMessage . $this->key); + return sha1($this->key.$rawMessage.$this->key); } @@ -367,7 +367,7 @@ class Server return array(); } - $ret = (string)$_COOKIE['_saml_idp']; + $ret = (string) $_COOKIE['_saml_idp']; $ret = explode(' ', $ret); foreach ($ret as &$idp) { $idp = base64_decode($idp); diff --git a/modules/cdc/www/resume.php b/modules/cdc/www/resume.php index 1e6f7910368478115c541e5f1c8ad3871e642c70..ebe6b1cc9f246b94dca7ab01d3b208f8f15bd281 100644 --- a/modules/cdc/www/resume.php +++ b/modules/cdc/www/resume.php @@ -1,11 +1,10 @@ <?php - if (!array_key_exists('domain', $_REQUEST)) { throw new \SimpleSAML\Error\BadRequest('Missing domain to CDC resume handler.'); } -$domain = (string)$_REQUEST['domain']; +$domain = (string) $_REQUEST['domain']; $client = new \SimpleSAML\Module\cdc\Client($domain); $response = $client->getResponse(); diff --git a/modules/consent/dictionaries/consent.php b/modules/consent/dictionaries/consent.php index dfb70c73e6d676845982aa58100d0b3a75b7b398..509d069ad10b3a85403b6af36b8e20c86943f834 100644 --- a/modules/consent/dictionaries/consent.php +++ b/modules/consent/dictionaries/consent.php @@ -1,7 +1,7 @@ <?php $lang = array( - 'yes' => array ( + 'yes' => array( 'no' => 'Ja, fortsett', 'nn' => 'Ja, fortsett', 'da' => 'Ja, jeg accepterer', @@ -21,7 +21,7 @@ $lang = array( 'pt-br' => 'Sim, Aceito', 'tr' => 'Evet, devam et', ), - 'no' => array ( + 'no' => array( 'no' => 'Nei, avbryt', 'nn' => 'Nei, avbryt', 'da' => 'Nej, jeg accepterer ikke', @@ -41,7 +41,7 @@ $lang = array( 'pt-br' => 'NĂŁo, nĂŁo aceito', 'tr' => 'Hayır, iptal et', ), - 'remember' => array ( + 'remember' => array( 'no' => 'Godta ogsĂĄ for fremtiden', 'nn' => 'Godta ogsĂĄ for framtida', 'da' => 'Husk samtykke', @@ -61,7 +61,7 @@ $lang = array( 'pt-br' => 'Lembrar Consentimento', 'tr' => 'Hatırla', ), - 'consent_header' => array ( + 'consent_header' => array( 'no' => 'Samtykke om overføring av personinformasjon', 'nn' => 'Samtykke til overføring av personinformasjon', 'da' => 'Samtykke til at frigive personlige oplysninger', @@ -78,7 +78,7 @@ $lang = array( 'pt' => 'Consentimento do envio de informação pessoal', 'tr' => 'KiĹźisel bilgilerin verilmesi hakkında onay', ), - 'consent_accept' => array ( + 'consent_accept' => array( 'no' => 'For ĂĄ fullføre innloggingen mĂĄ du godta at opplysningene nedenfor sendes til SPNAME.', 'nn' => 'For ĂĄ fullføra innlogginga mĂĄ du godta at opplysningane under blir sende til SPNAME', 'da' => 'SPNAME kræver at nedenstĂĄende oplysninger overføres fra IDPNAME. Vil du acceptere dette?', @@ -98,7 +98,7 @@ $lang = array( 'pt-br' => 'VocĂŞ está prestes a acessar o serviço SPNAME. O serviço exige que as informações a seguir sejam transferidas do IDPNAME. VocĂŞ aceita isso?', 'tr' => 'SPNAME aĹźağıdaki bilgilerin gönderilmesine ihtiyaç duyuyor.', ), - 'consent_purpose' => array ( + 'consent_purpose' => array( 'no' => 'FormĂĄlet med SPNAME er SPDESC', 'nn' => 'Hensikta med SPNAME er SPDESC', 'da' => 'SPNAME har til formĂĄl at SPDESC', @@ -115,7 +115,7 @@ $lang = array( 'pt' => 'O propĂłsito de SPNAME Ă© SPDESC', 'tr' => 'SPNAME\'in amacı SPDESC\'tir', ), - 'consent_privacypolicy' => array ( + 'consent_privacypolicy' => array( 'no' => 'Personvern for tjenesten', 'nn' => 'Personvern for tenesta', 'da' => 'Tjenestens politik vedrørende personoplysninger', @@ -133,7 +133,7 @@ $lang = array( 'pt-br' => 'PolĂtica de Privacidade deste serviço', 'tr' => 'Servis için gizlilik politikası', ), - 'consent_attributes_header' => array ( + 'consent_attributes_header' => array( 'no' => 'Opplysninger som vil bli sendt til SPNAME', 'nn' => 'Opplysningar som blir sende til SPNAME', 'da' => 'Attributter som bliver sendt til SPNAME', @@ -150,7 +150,7 @@ $lang = array( 'pt' => 'Informação que irá ser enviada para SPNAME', 'tr' => 'SPNAME\'e gönderilecek bilgiler', ), - 'show_attributes' => array ( + 'show_attributes' => array( 'no' => 'Vis opplysninger', 'nn' => 'Vis opplysingar', 'da' => 'Vis attributter', @@ -167,7 +167,7 @@ $lang = array( 'pt' => 'Mostrar atributos', 'tr' => 'Ă–zellikleri göster', ), - 'show_attribute' => array ( + 'show_attribute' => array( 'no' => 'Vis innhold', 'nn' => 'Vis innhald', 'da' => 'Vis indhold', @@ -177,7 +177,7 @@ $lang = array( 'nl' => 'Toon inhoud', 'sl' => 'PrikaĹľi vsebino', ), - 'login' => array ( + 'login' => array( 'no' => 'innlogging', 'nn' => 'Logg inn', 'da' => 'login', @@ -197,7 +197,7 @@ $lang = array( 'pt-br' => 'login', 'tr' => 'GiriĹź', ), - 'service_providers_for' => array ( + 'service_providers_for' => array( 'no' => 'Tjenesteleverandør for', 'nn' => 'Tenesteleverandørar for', 'da' => 'Tjenesteudbyder for', @@ -217,7 +217,7 @@ $lang = array( 'pt-br' => 'Provedor de serviços para', 'tr' => 'için Servis SaÄźlayıcılar', ), - 'service_provider_header' => array ( + 'service_provider_header' => array( 'no' => 'Tjenesteleverandør', 'nn' => 'Tenesteleverandør', 'da' => 'Tjenesteudbyder', @@ -237,7 +237,7 @@ $lang = array( 'pt-br' => 'Provedor de Serviços', 'tr' => 'Servis SaÄźlayıcı', ), - 'status_header' => array ( + 'status_header' => array( 'no' => 'Samtykke-status', 'nn' => 'Samtykkestatus', 'da' => 'Samtykke status', @@ -257,7 +257,7 @@ $lang = array( 'pt-br' => 'Status do Consentimento', 'tr' => 'Onay durumu', ), - 'show_hide_attributes' => array ( + 'show_hide_attributes' => array( 'no' => 'Vis/skjul opplysninger', 'nn' => 'Vis/skjul opplysningar', 'da' => 'vis/skjul attributter', @@ -277,7 +277,7 @@ $lang = array( 'pt-br' => 'mostra/esconder Atributos', 'tr' => 'bilgileri göster/gizle ', ), - 'noconsent_title' => array ( + 'noconsent_title' => array( 'no' => 'Ikke akseptert overføring av informasjon', 'nn' => 'Ikkje akseptert overføring av informasjon', 'da' => 'Manglende samtykke', @@ -295,7 +295,7 @@ $lang = array( 'pt-br' => 'Nenhum consentimento dado', 'tr' => 'Onay verilmemiĹź', ), - 'noconsent_text' => array ( + 'noconsent_text' => array( 'no' => 'Du har ikke akseptert ĂĄ overlevere opplysninger til tjenesteleverandøren.', 'nn' => 'Du har ikkje akseptert til at dine opplysningar kan sendast til tenesteleverandøren', 'da' => 'Du har ikke givet samtykke til overleveringen af oplysninger til tjenesten', @@ -313,7 +313,7 @@ $lang = array( 'pt-br' => 'VocĂŞ nĂŁo deu o consentimento para a transferĂŞncia de seus atributos para o provedor de serviços.', 'tr' => 'Bilgilerinizin servis saÄźlayıcıya gönderilmesi için onay vermediniz.', ), - 'noconsent_return' => array ( + 'noconsent_return' => array( 'no' => 'GĂĄ tilbake til aksept-siden med opplysninger', 'nn' => 'GĂĄ tilbake til aksept-sida for overføring av opplysningar', 'da' => 'GĂĄ tilbage', @@ -331,7 +331,7 @@ $lang = array( 'pt-br' => 'Retornar a página de consentimento', 'tr' => 'Onay sayfasına geri dön', ), - 'noconsent_goto_about' => array ( + 'noconsent_goto_about' => array( 'no' => 'GĂĄ til informasjonsside om tjenesten', 'nn' => 'GĂĄ til informasjonssida for tenesta', 'da' => 'GĂĄ til side med information om tjenesten', @@ -348,7 +348,7 @@ $lang = array( 'pt' => 'Ir para página de informação do serviço', 'tr' => 'Servis için bilgi sayfasına git', ), - 'table_caption' => array ( + 'table_caption' => array( 'no' => 'Bruker innformasjon', 'da' => 'Bruger information', 'en' => 'User information', @@ -362,7 +362,7 @@ $lang = array( 'pt' => 'Informação do utilizador', 'tr' => 'Kullanıcı bilgisi', ), - 'table_summary' => array ( + 'table_summary' => array( 'no' => 'Her listes den innformasjonen om deg som blir send til den tjenesten du er i ferd med ĂĄ logge pĂĄ', 'da' => 'Informationer som vil blive sendt til den service du er ved at logge in pĂĄ', 'en' => 'List the information about you that is about to be transmitted to the service you are going to login to', @@ -375,5 +375,4 @@ $lang = array( 'pt' => 'Listar a informação acerca de si que será enviada para o serviço no qual se está autenticar', 'tr' => 'Girmek istediÄźiniz servise gönderilecek bilginizi listeleyin', ), - ); diff --git a/modules/consent/lib/Consent/Store/Database.php b/modules/consent/lib/Consent/Store/Database.php index 739edcff375dfbe327c42ca38bc1d28926fca79c..35f438f16716c41004cd4d2f69620638262ec498 100644 --- a/modules/consent/lib/Consent/Store/Database.php +++ b/modules/consent/lib/Consent/Store/Database.php @@ -171,8 +171,8 @@ class Database extends \SimpleSAML\Module\consent\Store assert(is_string($attributeSet)); $st = $this->_execute( - 'UPDATE ' . $this->_table . ' ' . - 'SET usage_date = ' . $this->_dateTime . ' ' . + 'UPDATE '.$this->_table.' '. + 'SET usage_date = '.$this->_dateTime.' '. 'WHERE hashed_user_id = ? AND service_id = ? AND attribute = ?', array($userId, $destinationId, $attributeSet) ); @@ -212,8 +212,8 @@ class Database extends \SimpleSAML\Module\consent\Store // Check for old consent (with different attribute set) $st = $this->_execute( - 'UPDATE ' . $this->_table . ' ' . - 'SET consent_date = ' . $this->_dateTime . ', usage_date = ' . $this->_dateTime . ', attribute = ? ' . + 'UPDATE '.$this->_table.' '. + 'SET consent_date = '.$this->_dateTime.', usage_date = '.$this->_dateTime.', attribute = ? '. 'WHERE hashed_user_id = ? AND service_id = ?', array($attributeSet, $userId, $destinationId) ); @@ -230,8 +230,8 @@ class Database extends \SimpleSAML\Module\consent\Store // Add new consent $st = $this->_execute( - 'INSERT INTO ' . $this->_table . ' (' . 'consent_date, usage_date, hashed_user_id, service_id, attribute' . - ') ' . 'VALUES (' . $this->_dateTime . ', ' . $this->_dateTime . ', ?, ?, ?)', + 'INSERT INTO '.$this->_table.' ('.'consent_date, usage_date, hashed_user_id, service_id, attribute'. + ') '.'VALUES ('.$this->_dateTime.', '.$this->_dateTime.', ?, ?, ?)', array($userId, $destinationId, $attributeSet) ); @@ -258,7 +258,7 @@ class Database extends \SimpleSAML\Module\consent\Store assert(is_string($destinationId)); $st = $this->_execute( - 'DELETE FROM ' . $this->_table . ' WHERE hashed_user_id = ? AND service_id = ?;', + 'DELETE FROM '.$this->_table.' WHERE hashed_user_id = ? AND service_id = ?;', array($userId, $destinationId) ); @@ -289,7 +289,7 @@ class Database extends \SimpleSAML\Module\consent\Store assert(is_string($userId)); $st = $this->_execute( - 'DELETE FROM ' . $this->_table . ' WHERE hashed_user_id = ?', + 'DELETE FROM '.$this->_table.' WHERE hashed_user_id = ?', array($userId) ); @@ -298,7 +298,7 @@ class Database extends \SimpleSAML\Module\consent\Store } if ($st->rowCount() > 0) { - \SimpleSAML\Logger::debug('consent:Database - Deleted (' . $st->rowCount() . ') consent(s).'); + \SimpleSAML\Logger::debug('consent:Database - Deleted ('.$st->rowCount().') consent(s).'); return $st->rowCount(); } else { \SimpleSAML\Logger::warning('consent:Database - Attempted to delete nonexistent consent'); @@ -322,7 +322,7 @@ class Database extends \SimpleSAML\Module\consent\Store $ret = array(); $st = $this->_execute( - 'SELECT service_id, attribute, consent_date, usage_date FROM ' . $this->_table . + 'SELECT service_id, attribute, consent_date, usage_date FROM '.$this->_table. ' WHERE hashed_user_id = ?', array($userId) ); @@ -363,16 +363,16 @@ class Database extends \SimpleSAML\Module\consent\Store $st = $db->prepare($statement); if ($st === false) { \SimpleSAML\Logger::error( - 'consent:Database - Error preparing statement \'' . - $statement . '\': ' . self::_formatError($db->errorInfo()) + 'consent:Database - Error preparing statement \''. + $statement.'\': '.self::_formatError($db->errorInfo()) ); return false; } if ($st->execute($parameters) !== true) { \SimpleSAML\Logger::error( - 'consent:Database - Error executing statement \'' . - $statement . '\': ' . self::_formatError($st->errorInfo()) + 'consent:Database - Error executing statement \''. + $statement.'\': '.self::_formatError($st->errorInfo()) ); return false; } @@ -408,7 +408,7 @@ class Database extends \SimpleSAML\Module\consent\Store // Get total number of users that has given consent $st = $this->_execute( - 'SELECT COUNT(*) AS no ' . + 'SELECT COUNT(*) AS no '. 'FROM (SELECT DISTINCT hashed_user_id FROM '.$this->_table.' ) AS foo', array() ); @@ -480,7 +480,7 @@ class Database extends \SimpleSAML\Module\consent\Store assert(is_array($error)); assert(count($error) >= 3); - return $error[0] . ' - ' . $error[2] . ' (' . $error[1] . ')'; + return $error[0].' - '.$error[2].' ('.$error[1].')'; } @@ -492,7 +492,7 @@ class Database extends \SimpleSAML\Module\consent\Store public function selftest() { $st = $this->_execute( - 'SELECT * FROM ' . $this->_table . ' WHERE hashed_user_id = ? AND service_id = ? AND attribute = ?', + 'SELECT * FROM '.$this->_table.' WHERE hashed_user_id = ? AND service_id = ? AND attribute = ?', array('test', 'test', 'test') ); diff --git a/modules/consent/templates/logout_completed.php b/modules/consent/templates/logout_completed.php index 978931c2bdf3aa8231a27cd824d2fec3b7ce9662..d488d490dd0f380cd8531fee0f3cd83c0dca1f31 100644 --- a/modules/consent/templates/logout_completed.php +++ b/modules/consent/templates/logout_completed.php @@ -3,7 +3,7 @@ $this->data['header'] = $this->t('{logout:title}'); $this->includeAtTemplateBase('includes/header.php'); -echo('<h2>' . $this->data['header'] . '</h2>'); -echo('<p>' . $this->t('{logout:logged_out_text}') . '</p>'); +echo '<h2>'.$this->data['header'].'</h2>'; +echo '<p>'.$this->t('{logout:logged_out_text}').'</p>'; $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/consentAdmin/hooks/hook_frontpage.php b/modules/consentAdmin/hooks/hook_frontpage.php index 2567f2be69a41a1a16e8d81b4004c224f8b762ab..792e2ff45cc9f9dbffd8dc8c44c9b15a344def71 100644 --- a/modules/consentAdmin/hooks/hook_frontpage.php +++ b/modules/consentAdmin/hooks/hook_frontpage.php @@ -4,7 +4,9 @@ * * @param array &$links The links on the frontpage, split into sections. */ -function consentAdmin_hook_frontpage(&$links) { + +function consentAdmin_hook_frontpage(&$links) +{ assert(is_array($links)); assert(array_key_exists('links', $links)); diff --git a/modules/consentAdmin/www/consentAdmin.php b/modules/consentAdmin/www/consentAdmin.php index 26ef3198b16dea02f1b423a271d374f706e45340..5477786c3951eba333d4cdf95f487259257f895a 100644 --- a/modules/consentAdmin/www/consentAdmin.php +++ b/modules/consentAdmin/www/consentAdmin.php @@ -24,8 +24,8 @@ function driveProcessingChain( $userid, $hashAttributes = false, $excludeAttributes = array() -) { - +) +{ /* * Create a new processing chain */ diff --git a/modules/core/hooks/hook_frontpage.php b/modules/core/hooks/hook_frontpage.php index caf392928acf6bb285524b9b963d3ce23cc8a91c..ea7aefd570013d0c1dce3a464a2a990424dabe07 100644 --- a/modules/core/hooks/hook_frontpage.php +++ b/modules/core/hooks/hook_frontpage.php @@ -4,29 +4,30 @@ * * @param array &$links The links on the frontpage, split into sections. */ -function core_hook_frontpage(&$links) { - assert(is_array($links)); - assert(array_key_exists('links', $links)); - $links['links']['frontpage_welcome'] = array( - 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_welcome.php'), - 'text' => '{core:frontpage:welcome}', - 'shorttext' => '{core:frontpage:welcome}', - ); - $links['links']['frontpage_config'] = array( - 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_config.php'), - 'text' => '{core:frontpage:configuration}', - 'shorttext' => '{core:frontpage:configuration}', - ); - $links['links']['frontpage_auth'] = array( - 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_auth.php'), - 'text' => '{core:frontpage:auth}', - 'shorttext' => '{core:frontpage:auth}', - ); - $links['links']['frontpage_federation'] = array( - 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_federation.php'), - 'text' => '{core:frontpage:federation}', - 'shorttext' => '{core:frontpage:federation}', - ); +function core_hook_frontpage(&$links) +{ + assert(is_array($links)); + assert(array_key_exists('links', $links)); + $links['links']['frontpage_welcome'] = array( + 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_welcome.php'), + 'text' => '{core:frontpage:welcome}', + 'shorttext' => '{core:frontpage:welcome}', + ); + $links['links']['frontpage_config'] = array( + 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_config.php'), + 'text' => '{core:frontpage:configuration}', + 'shorttext' => '{core:frontpage:configuration}', + ); + $links['links']['frontpage_auth'] = array( + 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_auth.php'), + 'text' => '{core:frontpage:auth}', + 'shorttext' => '{core:frontpage:auth}', + ); + $links['links']['frontpage_federation'] = array( + 'href' => SimpleSAML\Module::getModuleURL('core/frontpage_federation.php'), + 'text' => '{core:frontpage:federation}', + 'shorttext' => '{core:frontpage:federation}', + ); } diff --git a/modules/core/hooks/hook_sanitycheck.php b/modules/core/hooks/hook_sanitycheck.php index d3683a3698dd77402841767edeef9b122b205ebf..2f40c8cfe3a3b43e31feec5c5a6ef2bdc8f14bf6 100644 --- a/modules/core/hooks/hook_sanitycheck.php +++ b/modules/core/hooks/hook_sanitycheck.php @@ -4,45 +4,46 @@ * * @param array &$hookinfo hookinfo */ -function core_hook_sanitycheck(&$hookinfo) { - assert(is_array($hookinfo)); - assert(array_key_exists('errors', $hookinfo)); - assert(array_key_exists('info', $hookinfo)); - $config = \SimpleSAML\Configuration::getInstance(); - - if($config->getString('auth.adminpassword', '123') === '123') { - $hookinfo['errors'][] = '[core] Password in config.php is not set properly'; - } else { - $hookinfo['info'][] = '[core] Password in config.php is set properly'; - } +function core_hook_sanitycheck(&$hookinfo) +{ + assert(is_array($hookinfo)); + assert(array_key_exists('errors', $hookinfo)); + assert(array_key_exists('info', $hookinfo)); - if($config->getString('technicalcontact_email', 'na@example.org') === 'na@example.org') { - $hookinfo['errors'][] = '[core] In config.php technicalcontact_email is not set properly'; - } else { - $hookinfo['info'][] = '[core] In config.php technicalcontact_email is set properly'; - } - - if (version_compare(phpversion(), '5.4', '>=')) { - $hookinfo['info'][] = '[core] You are running a PHP version suitable for SimpleSAMLphp.'; - } else { - $hookinfo['errors'][] = '[core] You are running an old PHP installation. Please check the requirements for your SimpleSAMLphp version and upgrade.'; - } - - $info = array(); - $mihookinfo = array( - 'info' => &$info, - ); - $availmodules = SimpleSAML\Module::getModules(); - SimpleSAML\Module::callHooks('moduleinfo', $mihookinfo); - foreach($info AS $mi => $i) { - 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; - } - } - } - } - + $config = \SimpleSAML\Configuration::getInstance(); + + if ($config->getString('auth.adminpassword', '123') === '123') { + $hookinfo['errors'][] = '[core] Password in config.php is not set properly'; + } else { + $hookinfo['info'][] = '[core] Password in config.php is set properly'; + } + + if ($config->getString('technicalcontact_email', 'na@example.org') === 'na@example.org') { + $hookinfo['errors'][] = '[core] In config.php technicalcontact_email is not set properly'; + } else { + $hookinfo['info'][] = '[core] In config.php technicalcontact_email is set properly'; + } + + if (version_compare(phpversion(), '5.4', '>=')) { + $hookinfo['info'][] = '[core] You are running a PHP version suitable for SimpleSAMLphp.'; + } else { + $hookinfo['errors'][] = '[core] You are running an old PHP installation. Please check the requirements for your SimpleSAMLphp version and upgrade.'; + } + + $info = array(); + $mihookinfo = array( + 'info' => &$info, + ); + $availmodules = SimpleSAML\Module::getModules(); + SimpleSAML\Module::callHooks('moduleinfo', $mihookinfo); + foreach ($info as $mi => $i) { + 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; + } + } + } + } } diff --git a/modules/core/lib/ACL.php b/modules/core/lib/ACL.php index b99483b745a0f30b43284d7bad9dbce7116a1a5a..aa67c31c5bdf4880e098a5f5f2274455ff09477e 100644 --- a/modules/core/lib/ACL.php +++ b/modules/core/lib/ACL.php @@ -8,302 +8,291 @@ namespace SimpleSAML\Module\core; * @package SimpleSAMLphp */ -class ACL { - - /** - * The access control list, as an array. - * - * @var array - */ - private $acl; - - - /** - * Initializer for this access control list. - * - * @param array|string $acl The access control list. - */ - public function __construct($acl) { - assert(is_string($acl) || is_array($acl)); - - if (is_string($acl)) { - $acl = self::getById($acl); - } - - foreach ($acl as $rule) { - if (!is_array($rule)) { - throw new \SimpleSAML\Error\Exception('Invalid rule in access control list: ' . var_export($rule, TRUE)); - } - if (count($rule) === 0) { - throw new \SimpleSAML\Error\Exception('Empty rule in access control list.'); - } - - $action = array_shift($rule); - if ($action !== 'allow' && $action !== 'deny') { - throw new \SimpleSAML\Error\Exception('Invalid action in rule in access control list: ' . var_export($action, TRUE)); - } - - } - - $this->acl = $acl; - } - - - /** - * Retrieve an access control list with the given id. - * - * @param string $id The id of the access control list. - * @return array The access control list array. - */ - private static function getById($id) { - assert(is_string($id)); - - $config = \SimpleSAML\Configuration::getOptionalConfig('acl.php'); - if (!$config->hasValue($id)) { - throw new \SimpleSAML\Error\Exception('No ACL with id ' . var_export($id, TRUE) . ' in config/acl.php.'); - } - - return $config->getArray($id); - } - - - /** - * Match the attributes against the access control list. - * - * @param array $attributes The attributes of an user. - * @return boolean TRUE if the user is allowed to access the resource, FALSE if not. - */ - public function allows(array $attributes) { - - foreach ($this->acl as $rule) { - $action = array_shift($rule); - - if (!self::match($attributes, $rule)) { - continue; - } - - if ($action === 'allow') { - return TRUE; - } else { - return FALSE; - } - } - } - - - /** - * Match the attributes against the given rule. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function match(array $attributes, array $rule) { - - $op = array_shift($rule); - if ($op === NULL) { - // An empty rule always matches - return TRUE; - } - - switch($op) { - case 'and': - return self::opAnd($attributes, $rule); - case 'equals': - return self::opEquals($attributes, $rule); - case 'equals-preg': - return self::opEqualsPreg($attributes, $rule); - case 'has': - return self::opHas($attributes, $rule); - case 'has-preg': - return self::opHasPreg($attributes, $rule); - case 'not': - return !self::match($attributes, $rule); - case 'or': - return self::opOr($attributes, $rule); - default: - throw new \SimpleSAML\Error\Exception('Invalid ACL operation: ' . var_export($op, TRUE)); - } - } - - - /** - * 'and' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opAnd($attributes, $rule) { - - foreach ($rule as $subRule) { - if (!self::match($attributes, $subRule)) { - return FALSE; - } - } - - // All matches - return TRUE; - } - - - /** - * 'equals' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opEquals($attributes, $rule) { - - $attributeName = array_shift($rule); - - if (!array_key_exists($attributeName, $attributes)) { - $attributeValues = array(); - } else { - $attributeValues = $attributes[$attributeName]; - } - - foreach ($rule as $value) { - $found = FALSE; - foreach ($attributeValues as $i => $v) { - if ($value !== $v) { - continue; - } - unset($attributeValues[$i]); - $found = TRUE; - break; - } - if (!$found) { - return FALSE; - } - } - if (!empty($attributeValues)) { - /* One of the attribute values didn't match. */ - return FALSE; - } - - /* All the values in the attribute matched one in the rule. */ - return TRUE; - } - - - /** - * 'equals-preg' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opEqualsPreg($attributes, $rule) { - - $attributeName = array_shift($rule); - - if (!array_key_exists($attributeName, $attributes)) { - $attributeValues = array(); - } else { - $attributeValues = $attributes[$attributeName]; - } - - foreach ($rule as $pattern) { - $found = FALSE; - foreach ($attributeValues as $i => $v) { - if (!preg_match($pattern, $v)) { - continue; - } - unset($attributeValues[$i]); - $found = TRUE; - break; - } - if (!$found) { - return FALSE; - } - } - - if (!empty($attributeValues)) { - /* One of the attribute values didn't match. */ - return FALSE; - } - - /* All the values in the attribute matched one in the rule. */ - return TRUE; - } - - - /** - * 'has' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opHas($attributes, $rule) { - - $attributeName = array_shift($rule); - - if (!array_key_exists($attributeName, $attributes)) { - $attributeValues = array(); - } else { - $attributeValues = $attributes[$attributeName]; - } - - foreach ($rule as $value) { - if (!in_array($value, $attributeValues, TRUE)) { - return FALSE; - } - } - - /* Found all values in the rule in the attribute. */ - return TRUE; - } - - - /** - * 'has-preg' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opHasPreg($attributes, $rule) { - - $attributeName = array_shift($rule); - - if (!array_key_exists($attributeName, $attributes)) { - $attributeValues = array(); - } else { - $attributeValues = $attributes[$attributeName]; - } - - foreach ($rule as $pattern) { - $matches = preg_grep($pattern, $attributeValues); - if (count($matches) === 0) { - return FALSE; - } - } - - /* Found all values in the rule in the attribute. */ - return TRUE; - } - - - /** - * 'or' match operator. - * - * @param array $attributes The attributes of an user. - * @param array $rule The rule we should check. - * @return boolean TRUE if the rule matches, FALSE if not. - */ - private static function opOr($attributes, $rule) { - - foreach ($rule as $subRule) { - if (self::match($attributes, $subRule)) { - return TRUE; - } - } - - /* None matches. */ - return FALSE; - } - +class ACL +{ + /** + * The access control list, as an array. + * + * @var array + */ + private $acl; + + /** + * Initializer for this access control list. + * + * @param array|string $acl The access control list. + */ + public function __construct($acl) + { + assert(is_string($acl) || is_array($acl)); + + if (is_string($acl)) { + $acl = self::getById($acl); + } + + foreach ($acl as $rule) { + if (!is_array($rule)) { + throw new \SimpleSAML\Error\Exception('Invalid rule in access control list: '.var_export($rule, true)); + } + if (count($rule) === 0) { + throw new \SimpleSAML\Error\Exception('Empty rule in access control list.'); + } + + $action = array_shift($rule); + if ($action !== 'allow' && $action !== 'deny') { + throw new \SimpleSAML\Error\Exception('Invalid action in rule in access control list: '.var_export($action, true)); + } + } + $this->acl = $acl; + } + + /** + * Retrieve an access control list with the given id. + * + * @param string $id The id of the access control list. + * @return array The access control list array. + */ + private static function getById($id) + { + assert(is_string($id)); + + $config = \SimpleSAML\Configuration::getOptionalConfig('acl.php'); + if (!$config->hasValue($id)) { + throw new \SimpleSAML\Error\Exception('No ACL with id '.var_export($id, true).' in config/acl.php.'); + } + + return $config->getArray($id); + } + + /** + * Match the attributes against the access control list. + * + * @param array $attributes The attributes of an user. + * @return boolean TRUE if the user is allowed to access the resource, FALSE if not. + */ + public function allows(array $attributes) + { + foreach ($this->acl as $rule) { + $action = array_shift($rule); + + if (!self::match($attributes, $rule)) { + continue; + } + + if ($action === 'allow') { + return true; + } else { + return false; + } + } + } + + /** + * Match the attributes against the given rule. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function match(array $attributes, array $rule) + { + $op = array_shift($rule); + if ($op === null) { + // An empty rule always matches + return true; + } + + switch ($op) { + case 'and': + return self::opAnd($attributes, $rule); + case 'equals': + return self::opEquals($attributes, $rule); + case 'equals-preg': + return self::opEqualsPreg($attributes, $rule); + case 'has': + return self::opHas($attributes, $rule); + case 'has-preg': + return self::opHasPreg($attributes, $rule); + case 'not': + return !self::match($attributes, $rule); + case 'or': + return self::opOr($attributes, $rule); + default: + throw new \SimpleSAML\Error\Exception('Invalid ACL operation: '.var_export($op, true)); + } + } + + /** + * 'and' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opAnd($attributes, $rule) + { + foreach ($rule as $subRule) { + if (!self::match($attributes, $subRule)) { + return false; + } + } + + // All matches + return true; + } + + /** + * 'equals' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opEquals($attributes, $rule) + { + $attributeName = array_shift($rule); + + if (!array_key_exists($attributeName, $attributes)) { + $attributeValues = array(); + } else { + $attributeValues = $attributes[$attributeName]; + } + + foreach ($rule as $value) { + $found = false; + foreach ($attributeValues as $i => $v) { + if ($value !== $v) { + continue; + } + unset($attributeValues[$i]); + $found = true; + break; + } + if (!$found) { + return false; + } + } + if (!empty($attributeValues)) { + // One of the attribute values didn't match + return false; + } + + // All the values in the attribute matched one in the rule + return true; + } + + /** + * 'equals-preg' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opEqualsPreg($attributes, $rule) + { + $attributeName = array_shift($rule); + + if (!array_key_exists($attributeName, $attributes)) { + $attributeValues = array(); + } else { + $attributeValues = $attributes[$attributeName]; + } + + foreach ($rule as $pattern) { + $found = false; + foreach ($attributeValues as $i => $v) { + if (!preg_match($pattern, $v)) { + continue; + } + unset($attributeValues[$i]); + $found = true; + break; + } + if (!$found) { + return false; + } + } + + if (!empty($attributeValues)) { + // One of the attribute values didn't match + return false; + } + + // All the values in the attribute matched one in the rule + return true; + } + + /** + * 'has' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opHas($attributes, $rule) + { + $attributeName = array_shift($rule); + + if (!array_key_exists($attributeName, $attributes)) { + $attributeValues = array(); + } else { + $attributeValues = $attributes[$attributeName]; + } + + foreach ($rule as $value) { + if (!in_array($value, $attributeValues, true)) { + return false; + } + } + + // Found all values in the rule in the attribute + return true; + } + + /** + * 'has-preg' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opHasPreg($attributes, $rule) + { + $attributeName = array_shift($rule); + + if (!array_key_exists($attributeName, $attributes)) { + $attributeValues = array(); + } else { + $attributeValues = $attributes[$attributeName]; + } + + foreach ($rule as $pattern) { + $matches = preg_grep($pattern, $attributeValues); + if (count($matches) === 0) { + return false; + } + } + + // Found all values in the rule in the attribute + return true; + } + + /** + * 'or' match operator. + * + * @param array $attributes The attributes of an user. + * @param array $rule The rule we should check. + * @return boolean TRUE if the rule matches, FALSE if not. + */ + private static function opOr($attributes, $rule) + { + foreach ($rule as $subRule) { + if (self::match($attributes, $subRule)) { + return true; + } + } + + // None matches + return false; + } } diff --git a/modules/core/lib/Auth/Process/AttributeAdd.php b/modules/core/lib/Auth/Process/AttributeAdd.php index e83a54f05573171c638f0b5540d343e524d04a5b..076287f9f98b4946e026b44d9f7dca07ae9ab8e4 100644 --- a/modules/core/lib/Auth/Process/AttributeAdd.php +++ b/modules/core/lib/Auth/Process/AttributeAdd.php @@ -13,75 +13,73 @@ namespace SimpleSAML\Module\core\Auth\Process; class AttributeAdd extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Flag which indicates wheter this filter should append new values or replace old values. - */ - private $replace = FALSE; + /** + * Flag which indicates wheter this filter should append new values or replace old values. + */ + private $replace = false; + /** + * Attributes which should be added/appended. + * + * Assiciative array of arrays. + */ + private $attributes = array(); - /** - * Attributes which should be added/appended. - * - * Assiciative array of arrays. - */ - private $attributes = array(); + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + assert(is_array($config)); - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); + foreach ($config as $name => $values) { + if (is_int($name)) { + if ($values === '%replace') { + $this->replace = true; + } else { + throw new \Exception('Unknown flag: '.var_export($values, true)); + } + continue; + } - assert(is_array($config)); + if (!is_array($values)) { + $values = array($values); + } + foreach ($values as $value) { + if (!is_string($value)) { + throw new \Exception('Invalid value for attribute '.$name.': '.var_export($values, true)); + } + } - foreach($config as $name => $values) { - if(is_int($name)) { - if($values === '%replace') { - $this->replace = TRUE; - } else { - throw new \Exception('Unknown flag: ' . var_export($values, TRUE)); - } - continue; - } + $this->attributes[$name] = $values; + } + } - if(!is_array($values)) { - $values = array($values); - } - foreach($values as $value) { - if(!is_string($value)) { - throw new \Exception('Invalid value for attribute ' . $name . ': ' . - var_export($values, TRUE)); - } - } + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - $this->attributes[$name] = $values; - } - } + $attributes = &$request['Attributes']; - - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - foreach($this->attributes as $name => $values) { - if($this->replace === TRUE || !array_key_exists($name, $attributes)) { - $attributes[$name] = $values; - } else { - $attributes[$name] = array_merge($attributes[$name], $values); - } - } - } + foreach ($this->attributes as $name => $values) { + if ($this->replace === true || !array_key_exists($name, $attributes)) { + $attributes[$name] = $values; + } else { + $attributes[$name] = array_merge($attributes[$name], $values); + } + } + } } diff --git a/modules/core/lib/Auth/Process/AttributeAlter.php b/modules/core/lib/Auth/Process/AttributeAlter.php index da0546e9b640d91d5ca5a9c2fe28c93f75f21ce9..5672947c694497e26701c61b88df3489380e9ad1 100644 --- a/modules/core/lib/Auth/Process/AttributeAlter.php +++ b/modules/core/lib/Auth/Process/AttributeAlter.php @@ -65,7 +65,7 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter } elseif ($value === '%remove') { $this->remove = true; } else { - throw new \SimpleSAML\Error\Exception('Unknown flag : ' . var_export($value, true)); + throw new \SimpleSAML\Error\Exception('Unknown flag : '.var_export($value, true)); } continue; } elseif ($name === 'pattern') { @@ -92,12 +92,13 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter * @param array &$request The current request. * @throws \SimpleSAML\Error\Exception In case of invalid configuration. */ - public function process(&$request) { + public function process(&$request) + { assert(is_array($request)); assert(array_key_exists('Attributes', $request)); // get attributes from request - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; // check that all required params are set in config if (empty($this->pattern) || empty($this->subject)) { @@ -131,13 +132,14 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter return; } - if ($this->replace) { // replace the whole value + if ($this->replace) { + // replace the whole value foreach ($attributes[$this->subject] as &$value) { $matches = array(); if (preg_match($this->pattern, $value, $matches) > 0) { $new_value = $matches[0]; - if ($this->replacement !== FALSE) { + if ($this->replacement !== false) { $new_value = $this->replacement; } @@ -148,7 +150,8 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter } } } - } elseif ($this->remove) { // remove the whole value + } elseif ($this->remove) { + // remove the whole value $removedAttrs = array(); foreach ($attributes[$this->subject] as $value) { $matches = array(); @@ -161,7 +164,8 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter if (empty($attributes[$this->target])) { unset($attributes[$this->target]); } - } else { // replace only the part that matches + } else { + // replace only the part that matches if ($this->subject === $this->target) { $attributes[$this->target] = preg_replace( $this->pattern, $this->replacement, diff --git a/modules/core/lib/Auth/Process/AttributeCopy.php b/modules/core/lib/Auth/Process/AttributeCopy.php index 0e156d956fb40b42d055453316b7bd23e1e3b22c..44d3b71f00548e75fa1e460eab75985b3f274a55 100644 --- a/modules/core/lib/Auth/Process/AttributeCopy.php +++ b/modules/core/lib/Auth/Process/AttributeCopy.php @@ -20,60 +20,59 @@ namespace SimpleSAML\Module\core\Auth\Process; class AttributeCopy extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Assosiative array with the mappings of attribute names. - */ - private $map = array(); + /** + * Assosiative array with the mappings of attribute names. + */ + private $map = array(); + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); + assert(is_array($config)); - assert(is_array($config)); + foreach ($config as $source => $destination) { - foreach($config as $source => $destination) { + if (!is_string($source)) { + throw new \Exception('Invalid source attribute name: '.var_export($source, true)); + } - if(!is_string($source)) { - 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)); + } - if(!is_string($destination) && !is_array($destination)) { - throw new \Exception('Invalid destination attribute name: ' . var_export($destination, TRUE)); - } + $this->map[$source] = $destination; + } + } - $this->map[$source] = $destination; - } - } + /** + * Apply filter to rename attributes. + * + * @param array &$request The current request + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + $attributes = &$request['Attributes']; - /** - * Apply filter to rename attributes. - * - * @param array &$request The current request - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - foreach($attributes as $name => $values) { - if (array_key_exists($name,$this->map)){ - if (!is_array($this->map[$name])) { - $attributes[$this->map[$name]] = $values; - } else { - foreach ($this->map[$name] as $to_map) { - $attributes[$to_map] = $values; - } - } - } - } - - } + foreach ($attributes as $name => $values) { + if (array_key_exists($name, $this->map)) { + if (!is_array($this->map[$name])) { + $attributes[$this->map[$name]] = $values; + } else { + foreach ($this->map[$name] as $to_map) { + $attributes[$to_map] = $values; + } + } + } + } + } } diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php index 70e991590b4899847ac0468c3968050820d1d176..f5ba3aaca3b28c9a36e4396a9d1180449bedf2b4 100644 --- a/modules/core/lib/Auth/Process/AttributeLimit.php +++ b/modules/core/lib/Auth/Process/AttributeLimit.php @@ -11,110 +11,109 @@ namespace SimpleSAML\Module\core\Auth\Process; class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter { - /** - * List of attributes which this filter will allow through. - */ - private $allowedAttributes = array(); - - - /** - * Whether the 'attributes' option in the metadata takes precedence. - * - * @var bool - */ - private $isDefault = false; + /** + * List of attributes which this filter will allow through. + */ + private $allowedAttributes = array(); + /** + * Whether the 'attributes' option in the metadata takes precedence. + * + * @var bool + */ + private $isDefault = false; - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use - * @throws \SimpleSAML\Error\Exception If invalid configuration is found. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use + * @throws \SimpleSAML\Error\Exception If invalid configuration is found. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); - assert(is_array($config)); + assert(is_array($config)); - foreach ($config as $index => $value) { - if ($index === 'default') { - $this->isDefault = (bool)$value; - } elseif (is_int($index)) { - if (!is_string($value)) { - throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid attribute name: ' . - var_export($value, TRUE)); - } - $this->allowedAttributes[] = $value; + foreach ($config as $index => $value) { + if ($index === 'default') { + $this->isDefault = (bool) $value; + } elseif (is_int($index)) { + if (!is_string($value)) { + throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid attribute name: '. + var_export($value, true)); + } + $this->allowedAttributes[] = $value; } elseif (is_string($index)) { if (!is_array($value)) { - throw new \SimpleSAML\Error\Exception('AttributeLimit: Values for ' . var_export($index, TRUE) . - ' must be specified in an array.'); + throw new \SimpleSAML\Error\Exception('AttributeLimit: Values for '. + var_export($index, true).' must be specified in an array.'); } $this->allowedAttributes[$index] = $value; - } else { - throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid option: ' . var_export($index, TRUE)); - } - } - } - - - /** - * Get list of allowed from the SP/IdP config. - * - * @param array &$request The current request. - * @return array|NULL Array with attribute names, or NULL if no limit is placed. - */ - private static function getSPIdPAllowed(array &$request) { - - if (array_key_exists('attributes', $request['Destination'])) { - // SP Config - return $request['Destination']['attributes']; - } - if (array_key_exists('attributes', $request['Source'])) { - // IdP Config - return $request['Source']['attributes']; - } - return NULL; - } + } else { + throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid option: '.var_export($index, true)); + } + } + } + /** + * Get list of allowed from the SP/IdP config. + * + * @param array &$request The current request. + * @return array|NULL Array with attribute names, or NULL if no limit is placed. + */ + private static function getSPIdPAllowed(array &$request) + { + if (array_key_exists('attributes', $request['Destination'])) { + // SP Config + return $request['Destination']['attributes']; + } + if (array_key_exists('attributes', $request['Source'])) { + // IdP Config + return $request['Source']['attributes']; + } + return null; + } - /** - * Apply filter to remove attributes. - * - * Removes all attributes which aren't one of the allowed attributes. - * - * @param array &$request The current request - * @throws \SimpleSAML\Error\Exception If invalid configuration is found. - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); + /** + * Apply filter to remove attributes. + * + * Removes all attributes which aren't one of the allowed attributes. + * + * @param array &$request The current request + * @throws \SimpleSAML\Error\Exception If invalid configuration is found. + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - if ($this->isDefault) { - $allowedAttributes = self::getSPIdPAllowed($request); - if ($allowedAttributes === NULL) { - $allowedAttributes = $this->allowedAttributes; - } - } elseif (!empty($this->allowedAttributes)) { - $allowedAttributes = $this->allowedAttributes; - } else { - $allowedAttributes = self::getSPIdPAllowed($request); - if ($allowedAttributes === NULL) { - return; /* No limit on attributes. */ - } - } + if ($this->isDefault) { + $allowedAttributes = self::getSPIdPAllowed($request); + if ($allowedAttributes === null) { + $allowedAttributes = $this->allowedAttributes; + } + } elseif (!empty($this->allowedAttributes)) { + $allowedAttributes = $this->allowedAttributes; + } else { + $allowedAttributes = self::getSPIdPAllowed($request); + if ($allowedAttributes === null) { + // No limit on attributes + return; + } + } - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; - foreach ($attributes as $name => $values) { - if (!in_array($name, $allowedAttributes, TRUE)) { + foreach ($attributes as $name => $values) { + if (!in_array($name, $allowedAttributes, true)) { // the attribute name is not in the array of allowed attributes if (array_key_exists($name, $allowedAttributes)) { // but it is an index of the array if (!is_array($allowedAttributes[$name])) { - throw new \SimpleSAML\Error\Exception('AttributeLimit: Values for ' . var_export($name, TRUE) . - ' must be specified in an array.'); + throw new \SimpleSAML\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])) { @@ -122,10 +121,9 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter } } unset($attributes[$name]); - } - } - - } + } + } + } /** * Perform the filtering of attributes @@ -144,8 +142,8 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter } foreach ($values as $index => $attributeValue) { /* Suppress errors in preg_match since phpunit is set to fail on warnings, which - prevents us from testing with invalid regex. - */ + * prevents us from testing with invalid regex. + */ $regexResult = @preg_match($pattern, $attributeValue); if ($regexResult === false) { \SimpleSAML\Logger::warning("Error processing regex '$pattern' on value '$attributeValue'"); diff --git a/modules/core/lib/Auth/Process/AttributeMap.php b/modules/core/lib/Auth/Process/AttributeMap.php index 6eb229cd40b9819fa42a643bfb38fc835ceb5efa..42ab192631b2b3fed5e3ec4ce40b3e6aac82135e 100644 --- a/modules/core/lib/Auth/Process/AttributeMap.php +++ b/modules/core/lib/Auth/Process/AttributeMap.php @@ -79,7 +79,8 @@ class AttributeMap extends \SimpleSAML\Auth\ProcessingFilter $config = \SimpleSAML\Configuration::getInstance(); $m = explode(':', $fileName); - if (count($m) === 2) { // we are asked for a file in a module + if (count($m) === 2) { + // we are asked for a file in a module if (!\SimpleSAML\Module::isModuleEnabled($m[0])) { throw new \Exception("Module '$m[0]' is not enabled."); } diff --git a/modules/core/lib/Auth/Process/AttributeRealm.php b/modules/core/lib/Auth/Process/AttributeRealm.php index 9b16dcd0d0a89b7742c9ba2964062049b0927013..866dbb0dcfd70cd91530f0c3d6f241aeb3c2ed2e 100644 --- a/modules/core/lib/Auth/Process/AttributeRealm.php +++ b/modules/core/lib/Auth/Process/AttributeRealm.php @@ -21,13 +21,14 @@ class AttributeRealm extends \SimpleSAML\Auth\ProcessingFilter * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. */ - public function __construct($config, $reserved) { + public function __construct($config, $reserved) + { parent::__construct($config, $reserved); assert(is_array($config)); - if (array_key_exists('attributename', $config)) + if (array_key_exists('attributename', $config)) { $this->attributename = $config['attributename']; - + } } /** @@ -37,18 +38,21 @@ class AttributeRealm extends \SimpleSAML\Auth\ProcessingFilter * * @param array &$request The current request */ - public function process(&$request) { + public function process(&$request) + { assert(is_array($request)); 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']; $decomposed = explode('@', $userID); - if (count($decomposed) !== 2) return; + if (count($decomposed) !== 2) { + return; + } $request['Attributes'][$this->attributename] = array($decomposed[1]); } } diff --git a/modules/core/lib/Auth/Process/AttributeValueMap.php b/modules/core/lib/Auth/Process/AttributeValueMap.php index 293bc9b13fbbf232206e8350b5197ff5472debd9..15dce8e16da93f3f09110e2a6c9e54969b578ac6 100644 --- a/modules/core/lib/Auth/Process/AttributeValueMap.php +++ b/modules/core/lib/Auth/Process/AttributeValueMap.php @@ -12,28 +12,28 @@ namespace SimpleSAML\Module\core\Auth\Process; class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter { /** - * The name of the attribute we should assign values to (ie: the target attribute). - */ + * The name of the attribute we should assign values to (ie: the target attribute). + */ private $targetattribute; /** - * The name of the attribute we should create values from. - */ + * The name of the attribute we should create values from. + */ private $sourceattribute; /** - * The required $sourceattribute values and target affiliations. - */ + * The required $sourceattribute values and target affiliations. + */ private $values = array(); /** - * Whether $sourceattribute should be kept or not. - */ + * Whether $sourceattribute should be kept or not. + */ private $keep = false; /** - * Whether $target attribute values should be replaced by new values or not. - */ + * Whether $target attribute values should be replaced by new values or not. + */ private $replace = false; /** @@ -42,7 +42,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter * @param array $config Configuration information about this filter. * @param mixed $reserved For future use. * @throws \SimpleSAML\Error\Exception If the configuration is not valid. - */ + */ public function __construct($config, $reserved) { parent::__construct($config, $reserved); @@ -106,7 +106,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter assert(is_array($request)); assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; if (!array_key_exists($this->sourceattribute, $attributes)) { // the source attribute does not exist, nothing to do here diff --git a/modules/core/lib/Auth/Process/Cardinality.php b/modules/core/lib/Auth/Process/Cardinality.php index 983431fce775c88a20b4c1ed2720d1c94245e80f..6f85b8b393d4adc02c4278fc8f804c2f834695a3 100644 --- a/modules/core/lib/Auth/Process/Cardinality.php +++ b/modules/core/lib/Auth/Process/Cardinality.php @@ -35,7 +35,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter parent::__construct($config, $reserved); assert(is_array($config)); - $this->http = $http ?: new HTTPAdapter(); + $this->http = $http ? : new HTTPAdapter(); foreach ($config as $attribute => $rules) { if ($attribute === '%ignoreEntities') { diff --git a/modules/core/lib/Auth/Process/CardinalitySingle.php b/modules/core/lib/Auth/Process/CardinalitySingle.php index 0d4b180f378881c08c6607d69e64c6a02c05a3dd..be7707e597f9898e2e72523ede3b795c95eb8095 100644 --- a/modules/core/lib/Auth/Process/CardinalitySingle.php +++ b/modules/core/lib/Auth/Process/CardinalitySingle.php @@ -46,7 +46,7 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter parent::__construct($config, $reserved); assert(is_array($config)); - $this->http = $http ?: new HTTPAdapter(); + $this->http = $http ? : new HTTPAdapter(); if (array_key_exists('singleValued', $config)) { $this->singleValued = $config['singleValued']; diff --git a/modules/core/lib/Auth/Process/ExtendIdPSession.php b/modules/core/lib/Auth/Process/ExtendIdPSession.php index 4a4bd5ae51b777415fbc7ad2e5c4b28c7f2746bf..4d28c5cf7f2ed7efddf68d05effa137f90bc9c23 100644 --- a/modules/core/lib/Auth/Process/ExtendIdPSession.php +++ b/modules/core/lib/Auth/Process/ExtendIdPSession.php @@ -4,47 +4,47 @@ namespace SimpleSAML\Module\core\Auth\Process; /** * Extend IdP session and cookies. -*/ + */ class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter { - public function process(&$state) { - assert(is_array($state)); - - if (empty($state['Expire']) || empty($state['Authority'])) { - return; - } - - $now = time(); - $delta = $state['Expire'] - $now; - - $globalConfig = \SimpleSAML\Configuration::getInstance(); - $sessionDuration = $globalConfig->getInteger('session.duration', 8*60*60); - - // Extend only if half of session duration already passed - if ($delta >= ($sessionDuration * 0.5)) { - return; - } - - // Update authority expire time - $session = \SimpleSAML\Session::getSessionFromRequest(); - $session->setAuthorityExpire($state['Authority']); - - /* Update session cookies duration */ - - /* If remember me is active */ - $rememberMeExpire = $session->getRememberMeExpire(); - if (!empty($state['RememberMe']) && $rememberMeExpire !== NULL && $globalConfig->getBoolean('session.rememberme.enable', FALSE)) { - $session->setRememberMeExpire(); - return; - } - - /* Or if session lifetime is more than zero */ - $sessionHandler = \SimpleSAML\SessionHandler::getSessionHandler(); - $cookieParams = $sessionHandler->getCookieParams(); - if ($cookieParams['lifetime'] > 0) { - $session->updateSessionCookies(); - } - } - + public function process(&$state) + { + assert(is_array($state)); + + if (empty($state['Expire']) || empty($state['Authority'])) { + return; + } + + $now = time(); + $delta = $state['Expire'] - $now; + + $globalConfig = \SimpleSAML\Configuration::getInstance(); + $sessionDuration = $globalConfig->getInteger('session.duration', 28800); // 8*60*60 + + // Extend only if half of session duration already passed + if ($delta >= ($sessionDuration * 0.5)) { + return; + } + + // Update authority expire time + $session = \SimpleSAML\Session::getSessionFromRequest(); + $session->setAuthorityExpire($state['Authority']); + + // Update session cookies duration + + // If remember me is active + $rememberMeExpire = $session->getRememberMeExpire(); + if (!empty($state['RememberMe']) && $rememberMeExpire !== null && $globalConfig->getBoolean('session.rememberme.enable', false)) { + $session->setRememberMeExpire(); + return; + } + + // Or if session lifetime is more than zero + $sessionHandler = \SimpleSAML\SessionHandler::getSessionHandler(); + $cookieParams = $sessionHandler->getCookieParams(); + if ($cookieParams['lifetime'] > 0) { + $session->updateSessionCookies(); + } + } } diff --git a/modules/core/lib/Auth/Process/GenerateGroups.php b/modules/core/lib/Auth/Process/GenerateGroups.php index f2bdf41b82b5c091fd51cec05f52b30f27b99997..12af86f803370ea8af16ff46b09269b5cf62f89c 100644 --- a/modules/core/lib/Auth/Process/GenerateGroups.php +++ b/modules/core/lib/Auth/Process/GenerateGroups.php @@ -11,134 +11,134 @@ namespace SimpleSAML\Module\core\Auth\Process; class GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter { - /** - * The attributes we should generate groups from. - */ - private $generateGroupsFrom; - - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - - assert(is_array($config)); - - if (count($config) === 0) { - // Use default groups - $this->generateGroupsFrom = array( - 'eduPersonAffiliation', - 'eduPersonOrgUnitDN', - 'eduPersonEntitlement', - ); - - } else { - // Validate configuration - foreach ($config as $attributeName) { - if (!is_string($attributeName)) { - throw new \Exception('Invalid attribute name for core:GenerateGroups filter: ' . - var_export($attributeName, TRUE)); - } - } - - $this->generateGroupsFrom = $config; - } - } - - - /** - * Apply filter to add groups attribute. - * - * @param array &$request The current request - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); - - $groups = array(); - $attributes =& $request['Attributes']; - - $realm = self::getRealm($attributes); - if ($realm !== NULL) { - $groups[] = 'realm-' . $realm; - } - - - foreach ($this->generateGroupsFrom as $name) { - if (!array_key_exists($name, $attributes)) { - \SimpleSAML\Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.'); - /* Attribute not present. */ - continue; - } - - foreach ($attributes[$name] as $value) { - $value = self::escapeIllegalChars($value); - $groups[] = $name . '-' . $value; - if ($realm !== NULL) { - $groups[] = $name . '-' . $realm . '-' . $value; - } - } - } - - if (count($groups) > 0) { - $attributes['groups'] = $groups; - } - } - - - /** - * Determine which realm the user belongs to. - * - * This function will attempt to determine the realm a user belongs to based on the - * eduPersonPrincipalName attribute if it is present. If it isn't, or if it doesn't contain - * a realm, NULL will be returned. - * - * @param array $attributes The attributes of the user. - * @return string|NULL The realm of the user, or NULL if we are unable to determine the realm. - */ - private static function getRealm($attributes) { - assert(is_array($attributes)); - - if (!array_key_exists('eduPersonPrincipalName', $attributes)) { - return NULL; - } - $eppn = $attributes['eduPersonPrincipalName']; - - if (count($eppn) < 1) { - return NULL; - } - $eppn = $eppn[0]; - - $realm = explode('@', $eppn, 2); - if (count($realm) < 2) { - return NULL; - } - $realm = $realm[1]; - - return self::escapeIllegalChars($realm); - } - - - /** - * Escape special characters in a string. - * - * This function is similar to urlencode, but encodes many more characters. - * This function takes any characters not in [a-zA-Z0-9_@=.] and encodes them with as - * %<hex version>. For example, it will encode '+' as '%2b' and '%' as '%25'. - * - * @param string $string The string which should be escaped. - * @return string The escaped string. - */ - private static function escapeIllegalChars($string) { - assert(is_string($string)); - - return preg_replace_callback('/([^a-zA-Z0-9_@=.])/', - function ($m) { return sprintf("%%%02x", ord($m[1])); }, - $string); - } - + /** + * The attributes we should generate groups from. + */ + private $generateGroupsFrom; + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (count($config) === 0) { + // Use default groups + $this->generateGroupsFrom = array( + 'eduPersonAffiliation', + 'eduPersonOrgUnitDN', + 'eduPersonEntitlement', + ); + } else { + // Validate configuration + foreach ($config as $attributeName) { + if (!is_string($attributeName)) { + throw new \Exception('Invalid attribute name for core:GenerateGroups filter: '. + var_export($attributeName, true)); + } + } + $this->generateGroupsFrom = $config; + } + } + + /** + * Apply filter to add groups attribute. + * + * @param array &$request The current request + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $groups = array(); + $attributes = &$request['Attributes']; + + $realm = self::getRealm($attributes); + if ($realm !== null) { + $groups[] = 'realm-'.$realm; + } + + foreach ($this->generateGroupsFrom as $name) { + if (!array_key_exists($name, $attributes)) { + \SimpleSAML\Logger::debug('GenerateGroups - attribute \''.$name.'\' not found.'); + // Attribute not present + continue; + } + + foreach ($attributes[$name] as $value) { + $value = self::escapeIllegalChars($value); + $groups[] = $name.'-'.$value; + if ($realm !== null) { + $groups[] = $name.'-'.$realm.'-'.$value; + } + } + } + + if (count($groups) > 0) { + $attributes['groups'] = $groups; + } + } + + /** + * Determine which realm the user belongs to. + * + * This function will attempt to determine the realm a user belongs to based on the + * eduPersonPrincipalName attribute if it is present. If it isn't, or if it doesn't contain + * a realm, NULL will be returned. + * + * @param array $attributes The attributes of the user. + * @return string|NULL The realm of the user, or NULL if we are unable to determine the realm. + */ + private static function getRealm($attributes) + { + assert(is_array($attributes)); + + if (!array_key_exists('eduPersonPrincipalName', $attributes)) { + return null; + } + $eppn = $attributes['eduPersonPrincipalName']; + + if (count($eppn) < 1) { + return null; + } + $eppn = $eppn[0]; + + $realm = explode('@', $eppn, 2); + if (count($realm) < 2) { + return null; + } + $realm = $realm[1]; + + return self::escapeIllegalChars($realm); + } + + /** + * Escape special characters in a string. + * + * This function is similar to urlencode, but encodes many more characters. + * This function takes any characters not in [a-zA-Z0-9_@=.] and encodes them with as + * %<hex version>. For example, it will encode '+' as '%2b' and '%' as '%25'. + * + * @param string $string The string which should be escaped. + * @return string The escaped string. + */ + private static function escapeIllegalChars($string) + { + assert(is_string($string)); + + return preg_replace_callback( + '/([^a-zA-Z0-9_@=.])/', + function($m) { + return sprintf("%%%02x", ord($m[1])); + }, + $string + ); + } } diff --git a/modules/core/lib/Auth/Process/LanguageAdaptor.php b/modules/core/lib/Auth/Process/LanguageAdaptor.php index eb120e29af782af277531cf947fb2c5e0c34408c..bcd4210fb5a99bcfbba2bd74ac69c305b8344a1a 100644 --- a/modules/core/lib/Auth/Process/LanguageAdaptor.php +++ b/modules/core/lib/Auth/Process/LanguageAdaptor.php @@ -11,59 +11,58 @@ namespace SimpleSAML\Module\core\Auth\Process; class LanguageAdaptor extends \SimpleSAML\Auth\ProcessingFilter { - private $langattr = 'preferredLanguage'; - - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - assert(is_array($config)); - - if (array_key_exists('attributename', $config)) { - $this->langattr = $config['attributename']; - } - } - - - /** - * Apply filter to add or replace attributes. - * - * Add or replace existing attributes with the configured values. - * - * @param array &$request The current request - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); - - $attributes =& $request['Attributes']; - - $attrlang = NULL; - if (array_key_exists($this->langattr, $attributes)) - $attrlang = $attributes[$this->langattr][0]; - - $lang = \SimpleSAML\Locale\Language::getLanguageCookie(); - - - if (isset($attrlang)) - \SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']'); - if (isset($lang)) - \SimpleSAML\Logger::debug('LanguageAdaptor: Language in session was set [' . $lang . ']'); - - - if (isset($attrlang) && !isset($lang)) { - // Language set in attribute but not in cookie - update cookie - \SimpleSAML\Locale\Language::setLanguageCookie($attrlang); - } elseif (!isset($attrlang) && isset($lang)) { - // Language set in cookie, but not in attribute. Update attribute - $request['Attributes'][$this->langattr] = array($lang); - } - - } - + private $langattr = 'preferredLanguage'; + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + assert(is_array($config)); + + if (array_key_exists('attributename', $config)) { + $this->langattr = $config['attributename']; + } + } + + /** + * Apply filter to add or replace attributes. + * + * Add or replace existing attributes with the configured values. + * + * @param array &$request The current request + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); + + $attributes = &$request['Attributes']; + + $attrlang = null; + if (array_key_exists($this->langattr, $attributes)) { + $attrlang = $attributes[$this->langattr][0]; + } + + $lang = \SimpleSAML\Locale\Language::getLanguageCookie(); + + if (isset($attrlang)) { + \SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set ['.$attrlang.']'); + } + if (isset($lang)) { + \SimpleSAML\Logger::debug('LanguageAdaptor: Language in session was set ['.$lang.']'); + } + + if (isset($attrlang) && !isset($lang)) { + // Language set in attribute but not in cookie - update cookie + \SimpleSAML\Locale\Language::setLanguageCookie($attrlang); + } elseif (!isset($attrlang) && isset($lang)) { + // Language set in cookie, but not in attribute. Update attribute + $request['Attributes'][$this->langattr] = array($lang); + } + } } diff --git a/modules/core/lib/Auth/Process/ScopeAttribute.php b/modules/core/lib/Auth/Process/ScopeAttribute.php index ee7eb0409ceff20ba275ad0f33b1e33888be70b5..46605783afcfdb66745c556635e2ea426e8a195a 100644 --- a/modules/core/lib/Auth/Process/ScopeAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeAttribute.php @@ -10,101 +10,97 @@ namespace SimpleSAML\Module\core\Auth\Process; class ScopeAttribute extends \SimpleSAML\Auth\ProcessingFilter { - /** - * The attribute we extract the scope from. - * - * @var string - */ - private $scopeAttribute; - - - /** - * The attribute we want to add scope to. - * - * @var string - */ - private $sourceAttribute; - - - /** - * The attribute we want to add the scoped attributes to. - * - * @var string - */ - private $targetAttribute; - - /** - * Only modify targetAttribute if it doesn't already exist. - * - * @var bool - */ - private $onlyIfEmpty = false; - - - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) + /** + * The attribute we extract the scope from. + * + * @var string + */ + private $scopeAttribute; + + /** + * The attribute we want to add scope to. + * + * @var string + */ + private $sourceAttribute; + + /** + * The attribute we want to add the scoped attributes to. + * + * @var string + */ + private $targetAttribute; + + /** + * Only modify targetAttribute if it doesn't already exist. + * + * @var bool + */ + private $onlyIfEmpty = false; + + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - assert(is_array($config)); - - $config = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeAttribute'); - - $this->scopeAttribute = $config->getString('scopeAttribute'); - $this->sourceAttribute = $config->getString('sourceAttribute'); - $this->targetAttribute = $config->getString('targetAttribute'); - $this->onlyIfEmpty = $config->getBoolean('onlyIfEmpty', false); - } - - - /** - * Apply this filter to the request. - * - * @param array &$request The current request - */ - public function process(&$request) + parent::__construct($config, $reserved); + assert(is_array($config)); + + $config = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeAttribute'); + + $this->scopeAttribute = $config->getString('scopeAttribute'); + $this->sourceAttribute = $config->getString('sourceAttribute'); + $this->targetAttribute = $config->getString('targetAttribute'); + $this->onlyIfEmpty = $config->getBoolean('onlyIfEmpty', false); + } + + /** + * Apply this filter to the request. + * + * @param array &$request The current request + */ + public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; - if (!isset($attributes[$this->scopeAttribute])) { - return; - } + if (!isset($attributes[$this->scopeAttribute])) { + return; + } - if (!isset($attributes[$this->sourceAttribute])) { - return; - } + if (!isset($attributes[$this->sourceAttribute])) { + return; + } - if (!isset($attributes[$this->targetAttribute])) { - $attributes[$this->targetAttribute] = array(); - } + if (!isset($attributes[$this->targetAttribute])) { + $attributes[$this->targetAttribute] = array(); + } - if ($this->onlyIfEmpty && count($attributes[$this->targetAttribute]) > 0) { - return; - } + if ($this->onlyIfEmpty && count($attributes[$this->targetAttribute]) > 0) { + return; + } - foreach ($attributes[$this->scopeAttribute] as $scope) { - if (strpos($scope, '@') !== false) { - $scope = explode('@', $scope, 2); - $scope = $scope[1]; - } + foreach ($attributes[$this->scopeAttribute] as $scope) { + if (strpos($scope, '@') !== false) { + $scope = explode('@', $scope, 2); + $scope = $scope[1]; + } - foreach ($attributes[$this->sourceAttribute] as $value) { - $value = $value . '@' . $scope; + foreach ($attributes[$this->sourceAttribute] as $value) { + $value = $value.'@'.$scope; - if (in_array($value, $attributes[$this->targetAttribute], true)) { - // Already present - continue; - } + if (in_array($value, $attributes[$this->targetAttribute], true)) { + // Already present + continue; + } - $attributes[$this->targetAttribute][] = $value; - } - } - } + $attributes[$this->targetAttribute][] = $value; + } + } + } } diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php index da41e9ab022d8baaeb21d31249588a801a741bfe..8497fbb058c42eb9c469155c8409ff4ba877181c 100644 --- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php @@ -21,73 +21,74 @@ namespace SimpleSAML\Module\core\Auth\Process; class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter { - /** - * The attribute where the scope is taken from - * - * @var string - */ - private $sourceAttribute; - /** - * The name of the attribute which includes the scope - * - * @var string - */ - private $targetAttribute; + /** + * The attribute where the scope is taken from + * + * @var string + */ + private $sourceAttribute; - /** - * Initialize this filter, parse configuration - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - assert(is_array($config)); + /** + * The name of the attribute which includes the scope + * + * @var string + */ + private $targetAttribute; - $config = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeFromAttribute'); - $this->targetAttribute = $config->getString('targetAttribute'); - $this->sourceAttribute = $config->getString('sourceAttribute'); - } // end constructor + /** + * Initialize this filter, parse configuration + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + assert(is_array($config)); + $config = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeFromAttribute'); + $this->targetAttribute = $config->getString('targetAttribute'); + $this->sourceAttribute = $config->getString('sourceAttribute'); + } // end constructor - /** - * Apply this filter. - * - * @param array &$request The current request - */ - public function process(&$request) { - assert(is_array($request)); - assert(array_key_exists('Attributes', $request)); + /** + * Apply this filter. + * + * @param array &$request The current request + */ + public function process(&$request) + { + assert(is_array($request)); + assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; - if (!isset($attributes[$this->sourceAttribute])) { - return; - } + if (!isset($attributes[$this->sourceAttribute])) { + return; + } - // will not overwrite existing attribute - if (isset($attributes[$this->targetAttribute])) { - return; - } + // will not overwrite existing attribute + if (isset($attributes[$this->targetAttribute])) { + return; + } - $sourceAttrVal = $attributes[$this->sourceAttribute][0]; + $sourceAttrVal = $attributes[$this->sourceAttribute][0]; - /* the last position of an @ is usually the beginning of the scope - * string */ - $scopeIndex = strrpos($sourceAttrVal, '@'); + /* the last position of an @ is usually the beginning of the + * scope string + */ + $scopeIndex = strrpos($sourceAttrVal, '@'); - if ($scopeIndex !== FALSE) { - $attributes[$this->targetAttribute] = array(); - $scope = substr($sourceAttrVal, $scopeIndex+1); - $attributes[$this->targetAttribute][] = $scope; - \SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute ' . - $this->targetAttribute . ', with scope ' . - $scope); - } else { - \SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute ' . - $this->sourceAttribute . - ' does not have a scope. Did not add attribute ' . - $this->targetAttribute . '.'); - } - } /* end process */ + if ($scopeIndex !== false) { + $attributes[$this->targetAttribute] = array(); + $scope = substr($sourceAttrVal, $scopeIndex + 1); + $attributes[$this->targetAttribute][] = $scope; + \SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute '. + $this->targetAttribute.', with scope '.$scope); + } else { + \SimpleSAML\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 35848be87d9ecdfd73689ca9bd7de80895f47b1d..86db3063c575396706a4373d8ba5f8db9bc3b3d6 100644 --- a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php +++ b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php @@ -90,11 +90,11 @@ class StatisticsWithAttribute extends \SimpleSAML\Auth\ProcessingFilter if (!array_key_exists('PreviousSSOTimestamp', $state)) { // The user hasn't authenticated with this SP earlier in this session - \SimpleSAML\Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '. $logAttribute); + \SimpleSAML\Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '.$logAttribute); } \SimpleSAML\Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute); - } + } /** * @param string &$direction Either 'Source' or 'Destination'. diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php index 538d8138f7827345294545250e97b84887867edc..99ebdc04e36d16cb5d892bdfe387a2ca5e3af399 100644 --- a/modules/core/lib/Auth/Process/TargetedID.php +++ b/modules/core/lib/Auth/Process/TargetedID.php @@ -33,142 +33,140 @@ namespace SimpleSAML\Module\core\Auth\Process; class TargetedID extends \SimpleSAML\Auth\ProcessingFilter { - /** - * The attribute we should generate the targeted id from, or NULL if we should use the - * UserID. - */ - private $attribute = NULL; - - - /** - * Whether the attribute should be generated as a NameID value, or as a simple string. - * - * @var boolean - */ - private $generateNameId = FALSE; - - - /** - * Initialize this filter. - * - * @param array $config Configuration information about this filter. - * @param mixed $reserved For future use. - */ - public function __construct($config, $reserved) { - parent::__construct($config, $reserved); - - assert(is_array($config)); - - if (array_key_exists('attributename', $config)) { - $this->attribute = $config['attributename']; - if (!is_string($this->attribute)) { - throw new \Exception('Invalid attribute name given to core:TargetedID filter.'); - } - } - - if (array_key_exists('nameId', $config)) { - $this->generateNameId = $config['nameId']; - if (!is_bool($this->generateNameId)) { - throw new \Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.'); - } - } - } - - - /** - * Apply filter to add the targeted ID. - * - * @param array &$state The current state. - */ - public function process(&$state) { - assert(is_array($state)); - assert(array_key_exists('Attributes', $state)); - - 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' . - ' 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 . - '\', which is needed to generate the targeted ID.'); - } - - $userID = $state['Attributes'][$this->attribute][0]; - } - - - $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt(); - - if (array_key_exists('Source', $state)) { - $srcID = self::getEntityId($state['Source']); - } else { - $srcID = ''; - } - - if (array_key_exists('Destination', $state)) { - $dstID = self::getEntityId($state['Destination']); - } else { - $dstID = ''; - } - - $uidData = 'uidhashbase' . $secretSalt; - $uidData .= strlen($srcID) . ':' . $srcID; - $uidData .= strlen($dstID) . ':' . $dstID; - $uidData .= strlen($userID) . ':' . $userID; - $uidData .= $secretSalt; - - $uid = hash('sha1', $uidData); - - if ($this->generateNameId) { - // Convert the targeted ID to a SAML 2.0 name identifier element - $nameId = new \SAML2\XML\saml\NameID(); - $nameId->value = $uid; - $nameId->Format = \SAML2\Constants::NAMEID_PERSISTENT; - - if (isset($state['Source']['entityid'])) { - $nameId->NameQualifier = $state['Source']['entityid']; - } - if (isset($state['Destination']['entityid'])) { - $nameId->SPNameQualifier = $state['Destination']['entityid']; - } - } else { - $nameId = $uid; - } - - $state['Attributes']['eduPersonTargetedID'] = array($nameId); - } - - - /** - * Generate ID from entity metadata. - * - * This function takes in the metadata of an entity, and attempts to generate - * an unique identifier based on that. - * - * @param array $metadata The metadata of the entity. - * @return string The unique identifier for the entity. - */ - private static function getEntityId($metadata) { - assert(is_array($metadata)); - - $id = ''; - - if (array_key_exists('metadata-set', $metadata)) { - $set = $metadata['metadata-set']; - $id .= 'set' . strlen($set) . ':' . $set; - } - - if (array_key_exists('entityid', $metadata)) { - $entityid = $metadata['entityid']; - $id .= 'set' . strlen($entityid) . ':' . $entityid; - } - - return $id; - } - + /** + * The attribute we should generate the targeted id from, or NULL if we should use the + * UserID. + */ + private $attribute = null; + + /** + * Whether the attribute should be generated as a NameID value, or as a simple string. + * + * @var boolean + */ + private $generateNameId = false; + + /** + * Initialize this filter. + * + * @param array $config Configuration information about this filter. + * @param mixed $reserved For future use. + */ + public function __construct($config, $reserved) + { + parent::__construct($config, $reserved); + + assert(is_array($config)); + + if (array_key_exists('attributename', $config)) { + $this->attribute = $config['attributename']; + if (!is_string($this->attribute)) { + throw new \Exception('Invalid attribute name given to core:TargetedID filter.'); + } + } + + if (array_key_exists('nameId', $config)) { + $this->generateNameId = $config['nameId']; + if (!is_bool($this->generateNameId)) { + throw new \Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.'); + } + } + } + + /** + * Apply filter to add the targeted ID. + * + * @param array &$state The current state. + */ + public function process(&$state) + { + assert(is_array($state)); + assert(array_key_exists('Attributes', $state)); + + 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'. + ' 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. + '\', which is needed to generate the targeted ID.'); + } + + $userID = $state['Attributes'][$this->attribute][0]; + } + + + $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt(); + + if (array_key_exists('Source', $state)) { + $srcID = self::getEntityId($state['Source']); + } else { + $srcID = ''; + } + + if (array_key_exists('Destination', $state)) { + $dstID = self::getEntityId($state['Destination']); + } else { + $dstID = ''; + } + + $uidData = 'uidhashbase'.$secretSalt; + $uidData .= strlen($srcID).':'.$srcID; + $uidData .= strlen($dstID).':'.$dstID; + $uidData .= strlen($userID).':'.$userID; + $uidData .= $secretSalt; + + $uid = hash('sha1', $uidData); + + if ($this->generateNameId) { + // Convert the targeted ID to a SAML 2.0 name identifier element + $nameId = new \SAML2\XML\saml\NameID(); + $nameId->value = $uid; + $nameId->Format = \SAML2\Constants::NAMEID_PERSISTENT; + + if (isset($state['Source']['entityid'])) { + $nameId->NameQualifier = $state['Source']['entityid']; + } + if (isset($state['Destination']['entityid'])) { + $nameId->SPNameQualifier = $state['Destination']['entityid']; + } + } else { + $nameId = $uid; + } + + $state['Attributes']['eduPersonTargetedID'] = array($nameId); + } + + /** + * Generate ID from entity metadata. + * + * This function takes in the metadata of an entity, and attempts to generate + * an unique identifier based on that. + * + * @param array $metadata The metadata of the entity. + * @return string The unique identifier for the entity. + */ + private static function getEntityId($metadata) + { + assert(is_array($metadata)); + + $id = ''; + + if (array_key_exists('metadata-set', $metadata)) { + $set = $metadata['metadata-set']; + $id .= 'set'.strlen($set).':'.$set; + } + + if (array_key_exists('entityid', $metadata)) { + $entityid = $metadata['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 b51180f5c335b845716bac28740bac28e570198f..6e6d392b9cc998292fc20e577392abad72a4c8fe 100644 --- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php +++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php @@ -10,46 +10,44 @@ namespace SimpleSAML\Module\core\Auth\Process; class WarnShortSSOInterval extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Process a authentication response. - * - * This function checks how long it is since the last time the user was authenticated. - * If it is to short a while since, we will show a warning to the user. - * - * @param array $state The state of the response. - */ - public function process(&$state) { - assert(is_array($state)); - - if (!array_key_exists('PreviousSSOTimestamp', $state)) { - /* - * No timestamp from the previous SSO to this SP. This is the first - * time during this session. - */ - return; - } - - $timeDelta = time() - $state['PreviousSSOTimestamp']; - if ($timeDelta >= 10) { - // At least 10 seconds since last attempt - return; - } - - if (array_key_exists('Destination', $state) - && array_key_exists('entityid', $state['Destination'])) { - $entityId = $state['Destination']['entityid']; - } else { - $entityId = 'UNKNOWN'; - } - - \SimpleSAML\Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta . - ' seconds since last SSO for this user from the SP ' . - var_export($entityId, TRUE)); - - // Save state and redirect - $id = \SimpleSAML\Auth\State::saveState($state, 'core:short_sso_interval'); - $url = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } - + /** + * Process a authentication response. + * + * This function checks how long it is since the last time the user was authenticated. + * If it is to short a while since, we will show a warning to the user. + * + * @param array $state The state of the response. + */ + public function process(&$state) + { + assert(is_array($state)); + + if (!array_key_exists('PreviousSSOTimestamp', $state)) { + /* + * No timestamp from the previous SSO to this SP. This is the first + * time during this session. + */ + return; + } + + $timeDelta = time() - $state['PreviousSSOTimestamp']; + if ($timeDelta >= 10) { + // At least 10 seconds since last attempt + return; + } + + if (array_key_exists('Destination', $state) && array_key_exists('entityid', $state['Destination'])) { + $entityId = $state['Destination']['entityid']; + } else { + $entityId = 'UNKNOWN'; + } + + \SimpleSAML\Logger::warning('WarnShortSSOInterval: Only '.$timeDelta. + ' seconds since last SSO for this user from the SP '.var_export($entityId, true)); + + // Save state and redirect + $id = \SimpleSAML\Auth\State::saveState($state, 'core:short_sso_interval'); + $url = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } } diff --git a/modules/core/lib/Auth/Source/AdminPassword.php b/modules/core/lib/Auth/Source/AdminPassword.php index 13afe27f0fecb4242eafc899020e5e7fbe14c8f9..e7e11874643880646d18dd2877932d6aa77841ef 100644 --- a/modules/core/lib/Auth/Source/AdminPassword.php +++ b/modules/core/lib/Auth/Source/AdminPassword.php @@ -11,55 +11,55 @@ namespace SimpleSAML\Module\core\Auth\Source; class AdminPassword extends \SimpleSAML\Module\core\Auth\UserPassBase { - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct($info, $config) { - assert(is_array($info)); - assert(is_array($config)); + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) + { + assert(is_array($info)); + assert(is_array($config)); - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); - $this->setForcedUsername("admin"); - } + $this->setForcedUsername("admin"); + } + /** + * Attempt to log in using the given username and password. + * + * On a successful login, this function should return the users attributes. On failure, + * it should throw an exception. If the error was caused by the user entering the wrong + * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. + * + * Note that both the username and the password are UTF-8 encoded. + * + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + * @return array Associative array with the users attributes. + */ + protected function login($username, $password) + { + assert(is_string($username)); + assert(is_string($password)); - /** - * Attempt to log in using the given username and password. - * - * On a successful login, this function should return the users attributes. On failure, - * it should throw an exception. If the error was caused by the user entering the wrong - * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. - * - * Note that both the username and the password are UTF-8 encoded. - * - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - * @return array Associative array with the users attributes. - */ - protected function login($username, $password) { - assert(is_string($username)); - assert(is_string($password)); + $config = \SimpleSAML\Configuration::getInstance(); + $adminPassword = $config->getString('auth.adminpassword', '123'); + if ($adminPassword === '123') { + // We require that the user changes the password + throw new \SimpleSAML\Error\Error('NOTSET'); + } - $config = \SimpleSAML\Configuration::getInstance(); - $adminPassword = $config->getString('auth.adminpassword', '123'); - if ($adminPassword === '123') { - // We require that the user changes the password - throw new \SimpleSAML\Error\Error('NOTSET'); - } + if ($username !== "admin") { + throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); + } - if ($username !== "admin") { - throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); - } - - if (!\SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) { - throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); - } - - return array('user' => array('admin')); - } + if (!\SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) { + throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); + } + return array('user' => array('admin')); + } } diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php index 324a5fc2ca6c944ad16b79a6c7761192cd15ca7d..eb426d19d2af8841b46f57dd62fa3ed2aefd8f12 100644 --- a/modules/core/lib/Auth/UserPassBase.php +++ b/modules/core/lib/Auth/UserPassBase.php @@ -14,47 +14,45 @@ namespace SimpleSAML\Module\core\Auth; abstract class UserPassBase extends \SimpleSAML\Auth\Source { - /** - * The string used to identify our states. - */ - const STAGEID = '\SimpleSAML\Module\core\Auth\UserPassBase.state'; - - - /** - * The key of the AuthId field in the state. - */ - const AUTHID = '\SimpleSAML\Module\core\Auth\UserPassBase.AuthId'; - - - /** - * Username we should force. - * - * A forced username cannot be changed by the user. - * If this is NULL, we won't force any username. - */ - private $forcedUsername; - - /** - * Links to pages from login page. - * From configuration - */ - protected $loginLinks; - - /** - * Storage for authsource config option remember.username.enabled - * loginuserpass.php and loginuserpassorg.php pages/templates use this option to - * present users with a checkbox to save their username for the next login request. - * @var bool - */ - protected $rememberUsernameEnabled = FALSE; - - /** - * Storage for authsource config option remember.username.checked - * loginuserpass.php and loginuserpassorg.php pages/templates use this option - * to default the remember username checkbox to checked or not. - * @var bool - */ - protected $rememberUsernameChecked = FALSE; + /** + * The string used to identify our states. + */ + const STAGEID = '\SimpleSAML\Module\core\Auth\UserPassBase.state'; + + /** + * The key of the AuthId field in the state. + */ + const AUTHID = '\SimpleSAML\Module\core\Auth\UserPassBase.AuthId'; + + /** + * Username we should force. + * + * A forced username cannot be changed by the user. + * If this is NULL, we won't force any username. + */ + private $forcedUsername; + + /** + * Links to pages from login page. + * From configuration + */ + protected $loginLinks; + + /** + * Storage for authsource config option remember.username.enabled + * loginuserpass.php and loginuserpassorg.php pages/templates use this option to + * present users with a checkbox to save their username for the next login request. + * @var bool + */ + protected $rememberUsernameEnabled = false; + + /** + * Storage for authsource config option remember.username.checked + * loginuserpass.php and loginuserpassorg.php pages/templates use this option + * to default the remember username checkbox to checked or not. + * @var bool + */ + protected $rememberUsernameChecked = false; /** * Storage for general config option session.rememberme.enable. @@ -64,7 +62,7 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source * browser again). * @var bool */ - protected $rememberMeEnabled = FALSE; + protected $rememberMeEnabled = false; /** * Storage for general config option session.rememberme.checked. @@ -72,83 +70,88 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source * the "remember me" checkbox to checked or not. * @var bool */ - protected $rememberMeChecked = FALSE; - - /** - * Constructor for this authentication source. - * - * All subclasses who implement their own constructor must call this constructor before - * using $config for anything. - * - * @param array $info Information about this authentication source. - * @param array &$config Configuration for this authentication source. - */ - public function __construct($info, &$config) { - assert(is_array($info)); - assert(is_array($config)); - - if (isset($config['core:loginpage_links'])) { - $this->loginLinks = $config['core:loginpage_links']; - } - - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - // Get the remember username config options - if (isset($config['remember.username.enabled'])) { - $this->rememberUsernameEnabled = (bool) $config['remember.username.enabled']; - unset($config['remember.username.enabled']); - } - if (isset($config['remember.username.checked'])) { - $this->rememberUsernameChecked = (bool) $config['remember.username.checked']; - unset($config['remember.username.checked']); - } + protected $rememberMeChecked = false; + + /** + * Constructor for this authentication source. + * + * All subclasses who implement their own constructor must call this constructor before + * using $config for anything. + * + * @param array $info Information about this authentication source. + * @param array &$config Configuration for this authentication source. + */ + public function __construct($info, &$config) + { + assert(is_array($info)); + assert(is_array($config)); + + if (isset($config['core:loginpage_links'])) { + $this->loginLinks = $config['core:loginpage_links']; + } + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + // Get the remember username config options + if (isset($config['remember.username.enabled'])) { + $this->rememberUsernameEnabled = (bool) $config['remember.username.enabled']; + unset($config['remember.username.enabled']); + } + if (isset($config['remember.username.checked'])) { + $this->rememberUsernameChecked = (bool) $config['remember.username.checked']; + unset($config['remember.username.checked']); + } // get the "remember me" config options $sspcnf = \SimpleSAML\Configuration::getInstance(); - $this->rememberMeEnabled = $sspcnf->getBoolean('session.rememberme.enable', FALSE); - $this->rememberMeChecked = $sspcnf->getBoolean('session.rememberme.checked', FALSE); - } - - - /** - * Set forced username. - * - * @param string|NULL $forcedUsername The forced username. - */ - public function setForcedUsername($forcedUsername) { - assert(is_string($forcedUsername) || $forcedUsername === null); - $this->forcedUsername = $forcedUsername; - } - - /** - * Return login links from configuration - */ - public function getLoginLinks() { - return $this->loginLinks; - } - - /** - * Getter for the authsource config option remember.username.enabled - * @return bool - */ - public function getRememberUsernameEnabled() { - return $this->rememberUsernameEnabled; - } - - /** - * Getter for the authsource config option remember.username.checked - * @return bool - */ - public function getRememberUsernameChecked() { - return $this->rememberUsernameChecked; - } + $this->rememberMeEnabled = $sspcnf->getBoolean('session.rememberme.enable', false); + $this->rememberMeChecked = $sspcnf->getBoolean('session.rememberme.checked', false); + } + + /** + * Set forced username. + * + * @param string|NULL $forcedUsername The forced username. + */ + public function setForcedUsername($forcedUsername) + { + assert(is_string($forcedUsername) || $forcedUsername === null); + $this->forcedUsername = $forcedUsername; + } + + /** + * Return login links from configuration + */ + public function getLoginLinks() + { + return $this->loginLinks; + } + + /** + * Getter for the authsource config option remember.username.enabled + * @return bool + */ + public function getRememberUsernameEnabled() + { + return $this->rememberUsernameEnabled; + } + + /** + * Getter for the authsource config option remember.username.checked + * @return bool + */ + public function getRememberUsernameChecked() + { + return $this->rememberUsernameChecked; + } /** * Check if the "remember me" feature is enabled. * @return bool TRUE if enabled, FALSE otherwise. */ - public function isRememberMeEnabled() { + public function isRememberMeEnabled() + { return $this->rememberMeEnabled; } @@ -156,133 +159,133 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source * Check if the "remember me" checkbox should be checked. * @return bool TRUE if enabled, FALSE otherwise. */ - public function isRememberMeChecked() { + public function isRememberMeChecked() + { return $this->rememberMeChecked; } - /** - * Initialize login. - * - * This function saves the information about the login, and redirects to a - * login page. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(&$state) { - assert(is_array($state)); - - /* - * Save the identifier of this authentication source, so that we can - * retrieve it later. This allows us to call the login()-function on - * the current object. - */ - $state[self::AUTHID] = $this->authId; - - // What username we should force, if any - if ($this->forcedUsername !== NULL) { - /* - * This is accessed by the login form, to determine if the user - * is allowed to change the username. - */ - $state['forcedUsername'] = $this->forcedUsername; - } - - // ECP requests supply authentication credentials with the AUthnRequest - // so we validate them now rather than redirecting - if (isset($state['core:auth:username']) && isset($state['core:auth:password'])) { - $username = $state['core:auth:username']; - $password = $state['core:auth:password']; - - if (isset($state['forcedUsername'])) { - $username = $state['forcedUsername']; - } - - $attributes = $this->login($username, $password); - assert(is_array($attributes)); - $state['Attributes'] = $attributes; - - return; - } - - /* Save the $state-array, so that we can restore it after a redirect. */ - $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID); - - /* - * Redirect to the login form. We include the identifier of the saved - * state array as a parameter to the login form. - */ - $url = \SimpleSAML\Module::getModuleURL('core/loginuserpass.php'); - $params = array('AuthState' => $id); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); - - /* The previous function never returns, so this code is never executed. */ - assert(false); - } - - - /** - * Attempt to log in using the given username and password. - * - * On a successful login, this function should return the users attributes. On failure, - * it should throw an exception/error. If the error was caused by the user entering the wrong - * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. - * - * Note that both the username and the password are UTF-8 encoded. - * - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - * @return array Associative array with the user's attributes. - */ - abstract protected function login($username, $password); - - - /** - * Handle login request. - * - * This function is used by the login form (core/www/loginuserpass.php) when the user - * enters a username and password. On success, it will not return. On wrong - * username/password failure, and other errors, it will throw an exception. - * - * @param string $authStateId The identifier of the authentication state. - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - */ - public static function handleLogin($authStateId, $username, $password) { - assert(is_string($authStateId)); - assert(is_string($username)); - assert(is_string($password)); - - /* Here we retrieve the state array we saved in the authenticate-function. */ - $state = \SimpleSAML\Auth\State::loadState($authStateId, self::STAGEID); - - /* Retrieve the authentication source we are executing. */ - assert(array_key_exists(self::AUTHID, $state)); - $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]); - if ($source === NULL) { - throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]); - } - - /* - * $source now contains the authentication source on which authenticate() - * was called. We should call login() on the same authentication source. - */ - - /* Attempt to log in. */ - try { - $attributes = $source->login($username, $password); - } catch (\Exception $e) { - \SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.'); - throw $e; - } - - \SimpleSAML\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)); - $state['Attributes'] = $attributes; - - /* Return control to SimpleSAMLphp after successful authentication. */ - \SimpleSAML\Auth\Source::completeAuth($state); - } + /** + * Initialize login. + * + * This function saves the information about the login, and redirects to a + * login page. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) + { + assert(is_array($state)); + + /* + * Save the identifier of this authentication source, so that we can + * retrieve it later. This allows us to call the login()-function on + * the current object. + */ + $state[self::AUTHID] = $this->authId; + + // What username we should force, if any + if ($this->forcedUsername !== null) { + /* + * This is accessed by the login form, to determine if the user + * is allowed to change the username. + */ + $state['forcedUsername'] = $this->forcedUsername; + } + + // ECP requests supply authentication credentials with the AUthnRequest + // so we validate them now rather than redirecting + if (isset($state['core:auth:username']) && isset($state['core:auth:password'])) { + $username = $state['core:auth:username']; + $password = $state['core:auth:password']; + + if (isset($state['forcedUsername'])) { + $username = $state['forcedUsername']; + } + + $attributes = $this->login($username, $password); + assert(is_array($attributes)); + $state['Attributes'] = $attributes; + + return; + } + + // Save the $state-array, so that we can restore it after a redirect + $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID); + + /* + * Redirect to the login form. We include the identifier of the saved + * state array as a parameter to the login form. + */ + $url = \SimpleSAML\Module::getModuleURL('core/loginuserpass.php'); + $params = array('AuthState' => $id); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); + + // The previous function never returns, so this code is never executed. + assert(false); + } + + /** + * Attempt to log in using the given username and password. + * + * On a successful login, this function should return the users attributes. On failure, + * it should throw an exception/error. If the error was caused by the user entering the wrong + * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. + * + * Note that both the username and the password are UTF-8 encoded. + * + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + * @return array Associative array with the user's attributes. + */ + abstract protected function login($username, $password); + /** + * Handle login request. + * + * This function is used by the login form (core/www/loginuserpass.php) when the user + * enters a username and password. On success, it will not return. On wrong + * username/password failure, and other errors, it will throw an exception. + * + * @param string $authStateId The identifier of the authentication state. + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + */ + public static function handleLogin($authStateId, $username, $password) + { + assert(is_string($authStateId)); + assert(is_string($username)); + assert(is_string($password)); + + // Here we retrieve the state array we saved in the authenticate-function. + $state = \SimpleSAML\Auth\State::loadState($authStateId, self::STAGEID); + + // Retrieve the authentication source we are executing. + assert(array_key_exists(self::AUTHID, $state)); + $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]); + if ($source === null) { + throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]); + } + + /* + * $source now contains the authentication source on which authenticate() + * was called. We should call login() on the same authentication source. + */ + + // Attempt to log in + try { + $attributes = $source->login($username, $password); + } catch (\Exception $e) { + \SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.'); + throw $e; + } + + \SimpleSAML\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)); + $state['Attributes'] = $attributes; + + // Return control to SimpleSAMLphp after successful authentication. + \SimpleSAML\Auth\Source::completeAuth($state); + } } diff --git a/modules/core/lib/Stats/Output/File.php b/modules/core/lib/Stats/Output/File.php index fe0dc3fddd67a8ec63392e8697f5ebc22048cb77..1e6941c214f05b6809b74fe65a8f0c59bf6a7c18 100644 --- a/modules/core/lib/Stats/Output/File.php +++ b/modules/core/lib/Stats/Output/File.php @@ -10,91 +10,87 @@ namespace SimpleSAML\Module\core\Stats\Output; class File extends \SimpleSAML\Stats\Output { - /** - * The log directory. - * @var string - */ - private $logDir; - - - /** - * The file handle for the current file. - * @var resource - */ - private $file = NULL; - - /** - * The current file date. - * @var string - */ - private $fileDate = NULL; - - - /** - * Initialize the output. - * - * @param \SimpleSAML\Configuration $config The configuration for this output. - */ - public function __construct(\SimpleSAML\Configuration $config) { - - $this->logDir = $config->getPathValue('directory'); - if ($this->logDir === NULL) { - throw new \Exception('Missing "directory" option for core:File'); - } - if (!is_dir($this->logDir)) { - throw new \Exception('Could not find log directory: ' . var_export($this->logDir, TRUE)); - } - - } - - - /** - * Open a log file. - * - * @param string $date The date for the log file. - */ - private function openLog($date) { - assert(is_string($date)); - - if ($this->file !== NULL && $this->file !== FALSE) { - fclose($this->file); - $this->file = NULL; - } - - $fileName = $this->logDir . '/' . $date . '.log'; - $this->file = @fopen($fileName, 'a'); - if ($this->file === FALSE) { - throw new \SimpleSAML\Error\Exception('Error opening log file: ' . var_export($fileName, TRUE)); - } - - // Disable output buffering - stream_set_write_buffer($this->file, 0); - - $this->fileDate = $date; - } - - - /** - * Write a stats event. - * - * @param array $data The event. - */ - public function emit(array $data) { - assert(isset($data['time'])); - - $time = $data['time']; - $milliseconds = (int)(($time - (int)$time) * 1000); - - $timestamp = gmdate('Y-m-d\TH:i:s', $time) . sprintf('.%03dZ', $milliseconds); - - $outDate = substr($timestamp, 0, 10); // The date-part of the timstamp - - if ($outDate !== $this->fileDate) { - $this->openLog($outDate); - } - - $line = $timestamp . ' ' . json_encode($data) . "\n"; - fwrite($this->file, $line); - } - + /** + * The log directory. + * @var string + */ + private $logDir; + + /** + * The file handle for the current file. + * @var resource + */ + private $file = null; + + /** + * The current file date. + * @var string + */ + private $fileDate = null; + + /** + * Initialize the output. + * + * @param \SimpleSAML\Configuration $config The configuration for this output. + */ + public function __construct(\SimpleSAML\Configuration $config) + { + $this->logDir = $config->getPathValue('directory'); + if ($this->logDir === null) { + throw new \Exception('Missing "directory" option for core:File'); + } + if (!is_dir($this->logDir)) { + throw new \Exception('Could not find log directory: '.var_export($this->logDir, true)); + } + } + + /** + * Open a log file. + * + * @param string $date The date for the log file. + */ + private function openLog($date) + { + assert(is_string($date)); + + if ($this->file !== null && $this->file !== false) { + fclose($this->file); + $this->file = null; + } + + $fileName = $this->logDir.'/'.$date.'.log'; + $this->file = @fopen($fileName, 'a'); + if ($this->file === false) { + throw new \SimpleSAML\Error\Exception('Error opening log file: '.var_export($fileName, true)); + } + + // Disable output buffering + stream_set_write_buffer($this->file, 0); + + $this->fileDate = $date; + } + + /** + * Write a stats event. + * + * @param array $data The event. + */ + public function emit(array $data) + { + assert(isset($data['time'])); + + $time = $data['time']; + $milliseconds = (int) (($time - (int) $time) * 1000); + + $timestamp = gmdate('Y-m-d\TH:i:s', $time).sprintf('.%03dZ', $milliseconds); + + $outDate = substr($timestamp, 0, 10); // The date-part of the timstamp + + if ($outDate !== $this->fileDate) { + $this->openLog($outDate); + } + + $line = $timestamp.' '.json_encode($data)."\n"; + fwrite($this->file, $line); + } } diff --git a/modules/core/lib/Stats/Output/Log.php b/modules/core/lib/Stats/Output/Log.php index b4872bd5bead6089b51f2ae872586af128a6e478..41d04ddf7fc90ec0fec5011839d3deb33e138f8c 100644 --- a/modules/core/lib/Stats/Output/Log.php +++ b/modules/core/lib/Stats/Output/Log.php @@ -10,34 +10,34 @@ namespace SimpleSAML\Module\core\Stats\Output; class Log extends \SimpleSAML\Stats\Output { - /** - * The logging function we should call. - * @var callback - */ - private $logger; + /** + * The logging function we should call. + * @var callback + */ + private $logger; + /** + * Initialize the output. + * + * @param \SimpleSAML\Configuration $config The configuration for this output. + */ + public function __construct(\SimpleSAML\Configuration $config) + { + $logLevel = $config->getString('level', 'notice'); + $this->logger = array('\SimpleSAML\Logger', $logLevel); + if (!is_callable($this->logger)) { + throw new \Exception('Invalid log level: '.var_export($logLevel, true)); + } + } - /** - * Initialize the output. - * - * @param \SimpleSAML\Configuration $config The configuration for this output. - */ - public function __construct(\SimpleSAML\Configuration $config) { - $logLevel = $config->getString('level', 'notice'); - $this->logger = array('\SimpleSAML\Logger', $logLevel); - if (!is_callable($this->logger)) { - throw new \Exception('Invalid log level: ' . var_export($logLevel, TRUE)); - } - } - - - /** - * Write a stats event. - * - * @param string $data The event (as a JSON string). - */ - public function emit(array $data) { - $str_data = json_encode($data); - call_user_func($this->logger, 'EVENT ' . $str_data); - } + /** + * Write a stats event. + * + * @param string $data The event (as a JSON string). + */ + public function emit(array $data) + { + $str_data = json_encode($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 516044fc134a117dc37eb05a55fbc60968e75af8..8b73c77a8e1e2d1c5ab95d2e4a9feac0a1279d2a 100644 --- a/modules/core/lib/Storage/SQLPermanentStorage.php +++ b/modules/core/lib/Storage/SQLPermanentStorage.php @@ -213,7 +213,7 @@ class SQLPermanentStorage } $conditions[] = "(expire IS NULL OR expire >= ".time().")"; - return join(' AND ', $conditions); + return join(' AND ', $conditions); } } diff --git a/modules/core/templates/logout-iframe-wrapper.php b/modules/core/templates/logout-iframe-wrapper.php index 5f56009fe1041f47de50f7ee2c2183ad19b8c35f..3392e4cb4f0dd202417ba8def2047a38bba938a2 100644 --- a/modules/core/templates/logout-iframe-wrapper.php +++ b/modules/core/templates/logout-iframe-wrapper.php @@ -10,8 +10,8 @@ $iframeHeight = 25 + count($SPs) * 4; $this->data['header'] = $this->t('{logout:progress}'); $this->includeAtTemplateBase('includes/header.php'); -echo '<iframe style="width:100%; height:'.$iframeHeight.'em; border:0;" src="'.htmlspecialchars($iframeURL). - '"></iframe>'; +echo '<iframe style="width:100%; height:'.$iframeHeight.'em; border:0;" src="'. + htmlspecialchars($iframeURL).'"></iframe>'; foreach ($SPs as $assocId => $sp) { $spId = sha1($assocId); @@ -23,7 +23,7 @@ foreach ($SPs as $assocId => $sp) { $url = $sp["core:Logout-IFrame:URL"]; - echo('<iframe style="width:0; height:0; border:0;" src="'.htmlspecialchars($url).'"></iframe>'); + echo '<iframe style="width:0; height:0; border:0;" src="'.htmlspecialchars($url).'"></iframe>'; } $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/core/templates/logout-iframe.php b/modules/core/templates/logout-iframe.php index 6ada50bdab75ec66dc2b846030e5d7897b487ec2..634ed122da80247efe7fd85625758848c3338e7c 100644 --- a/modules/core/templates/logout-iframe.php +++ b/modules/core/templates/logout-iframe.php @@ -76,7 +76,7 @@ if ($type === 'embed') { <?php if ($from !== null) { echo '<div><img style="float: left; margin-right: 12px" src="/'.$this->data['baseurlpath']. - 'resources/icons/checkmark.48x48.png" alt="Successful logout" />'; + 'resources/icons/checkmark.48x48.png" alt="Successful logout" />'; echo '<p style="padding-top: 16px; ">'. $this->t('{logout:loggedoutfrom}', array('%SP%' => '<strong>'.htmlspecialchars($from).'</strong>')).'</p>'; echo '<p style="height: 0px; clear: left;"></p></div>'; @@ -110,7 +110,7 @@ foreach ($SPs as $assocId => $sp) { echo '<td style="width: 3em;"></td>'; echo '<td>'; echo '<img class="logoutstatusimage" id="statusimage-'.$spId.'" src="'.htmlspecialchars($stateImage[$spState]). - '" alt="'.htmlspecialchars($stateText[$spState]).'"/>'; + '" alt="'.htmlspecialchars($stateText[$spState]).'"/>'; echo '</td>'; echo '<td>'.htmlspecialchars($spName).'</td>'; echo '</tr>'; @@ -149,9 +149,9 @@ if ($type === 'init') { $displayStyle = 'display: none;'; } echo '<div id="logout-failed-message" style="margin-top: 1em; border: 1px solid #ccc; padding: 1em; '. - 'background: #eaeaea;'.$displayStyle.'">'; + 'background: #eaeaea;'.$displayStyle.'">'; echo '<img src="/'.$this->data['baseurlpath'].'resources/icons/experience/gtk-dialog-warning.48x48.png" alt="" '. - 'style="float: left; margin-right: 5px;" />'; + 'style="float: left; margin-right: 5px;" />'; echo '<p>'.$this->t('{logout:failedsps}').'</p>'; echo '<form method="post" action="logout-iframe-done.php" id="failed-form" target="_top">'; echo '<input type="hidden" name="id" value="'.$id.'" />'; @@ -180,7 +180,7 @@ if ($type === 'init') { } assert(isset($sp['core:Logout-IFrame:URL'])); echo '<iframe style="width:0; height:0; border:0;" src="'. - htmlspecialchars($sp['core:Logout-IFrame:URL']).'"></iframe>'; + htmlspecialchars($sp['core:Logout-IFrame:URL']).'"></iframe>'; } } } diff --git a/modules/core/templates/short_sso_interval.php b/modules/core/templates/short_sso_interval.php index a50b3b82b7b6ab9047b6e348479d5a122ece51f0..ac334a6c0d8ca6f47f9f5b9c37a8bd28dd16840d 100644 --- a/modules/core/templates/short_sso_interval.php +++ b/modules/core/templates/short_sso_interval.php @@ -18,23 +18,22 @@ $this->includeAtTemplateBase('includes/header.php'); <h1><?php echo $this->data['header']; ?></h1> <form style="display: inline; margin: 0px; padding: 0px" action="<?php echo htmlspecialchars($this->data['target']); ?>"> - <?php - // Embed hidden fields... - foreach ($this->data['params'] as $name => $value) { - echo('<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'); - } - ?> - <p><?php echo $this->t('{core:short_sso_interval:warning}'); ?></p> +<?php + // Embed hidden fields... + foreach ($this->data['params'] as $name => $value) { + echo '<input type="hidden" name="'.htmlspecialchars($name).'" value="'.htmlspecialchars($value).'" />'; + } +?> + <p><?php echo $this->t('{core:short_sso_interval:warning}'); ?></p> <div class="trackidtext"><p> <?php echo $this->t('{errors:report_trackid}'); ?> <span class="trackid"><?php echo $this->data['trackId']; ?></span> </p> </div> - <input type="submit" name="continue" id="contbutton" value="<?php echo htmlspecialchars($this->t('{core:short_sso_interval:retry}')) ?>" /> + <input type="submit" name="continue" id="contbutton" value="<?php echo htmlspecialchars($this->t('{core:short_sso_interval:retry}')) ?>" /> </form> - <?php $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/core/www/cleardiscochoices.php b/modules/core/www/cleardiscochoices.php index 96c19d8418c883c2fa4b4fdc28d99c5a9b357ee4..8d134f7d758d1af750f14d844dbdf6f36b598cfb 100644 --- a/modules/core/www/cleardiscochoices.php +++ b/modules/core/www/cleardiscochoices.php @@ -11,26 +11,26 @@ $config = \SimpleSAML\Configuration::getInstance(); $cookiePath = $config->getBasePath(); // We delete all cookies which starts with 'idpdisco_' -foreach($_COOKIE as $cookieName => $value) { - if (substr($cookieName, 0, 9) !== 'idpdisco_') { - /* Not a idpdisco cookie. */ - continue; - } - - /* Delete the cookie. We delete it once without the secure flag and once with the secure flag. This - * ensures that the cookie will be deleted in any case. - */ - \SimpleSAML\Utils\HTTP::setCookie($cookieName, NULL, array('path' => $cookiePath, 'httponly' => FALSE), FALSE); +foreach ($_COOKIE as $cookieName => $value) { + if (substr($cookieName, 0, 9) !== 'idpdisco_') { + // Not a idpdisco cookie. + continue; + } + + /* Delete the cookie. We delete it once without the secure flag and once with the secure flag. This + * ensures that the cookie will be deleted in any case. + */ + \SimpleSAML\Utils\HTTP::setCookie($cookieName, null, array('path' => $cookiePath, 'httponly' => false), false); } -/* Find where we should go now. */ -if(array_key_exists('ReturnTo', $_REQUEST)) { - $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); +// Find where we should go now. +if (array_key_exists('ReturnTo', $_REQUEST)) { + $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); } else { - /* Return to the front page if no other destination is given. This is the same as the base cookie path. */ - $returnTo = $cookiePath; + // Return to the front page if no other destination is given. This is the same as the base cookie path. + $returnTo = $cookiePath; } -/* Redirect to destination. */ +// Redirect to destination. \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo); diff --git a/modules/core/www/frontpage_auth.php b/modules/core/www/frontpage_auth.php index fd61b0b8c0fd2fd0605b309f19ceffbcf7d2256c..0c9fb078777bb0e2b2c8645147e3f3eb755cec3e 100644 --- a/modules/core/www/frontpage_auth.php +++ b/modules/core/www/frontpage_auth.php @@ -18,16 +18,16 @@ $links_auth = array(); $links_federation = array(); $links_auth[] = array( - 'href' => 'login.php', - 'text' => '{core:frontpage:authtest}', + 'href' => 'login.php', + 'text' => '{core:frontpage:authtest}', ); $allLinks = array( - 'links' => &$links, - 'welcome' => &$links_welcome, - 'config' => &$links_config, - 'auth' => &$links_auth, - 'federation' => &$links_federation, + 'links' => &$links, + 'welcome' => &$links_welcome, + 'config' => &$links_config, + 'auth' => &$links_auth, + 'federation' => &$links_federation, ); \SimpleSAML\Module::callHooks('frontpage', $allLinks); diff --git a/modules/core/www/frontpage_config.php b/modules/core/www/frontpage_config.php index 5a621107cf495e1ad186173deedfc72a664a00cb..26d388b8bda8d8409021c0d53b0474aa235c7b5e 100644 --- a/modules/core/www/frontpage_config.php +++ b/modules/core/www/frontpage_config.php @@ -24,7 +24,7 @@ if ($config->getValue('secretsalt') === 'defaultsecretsalt') { if (extension_loaded('suhosin')) { $suhosinLength = ini_get('suhosin.get.max_value_length'); - if (empty($suhosinLength) || (int)$suhosinLength < 2048) { + if (empty($suhosinLength) || (int) $suhosinLength < 2048) { $warnings[] = '{core:frontpage:warnings_suhosin_url_length}'; } } @@ -36,12 +36,12 @@ $links_auth = array(); $links_federation = array(); $links_config[] = array( - 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/hostnames.php', + 'href' => \SimpleSAML\Utils\HTTP::getBaseURL().'admin/hostnames.php', 'text' => '{core:frontpage:link_diagnostics}' ); $links_config[] = array( - 'href' => \SimpleSAML\Utils\HTTP::getBaseURL() . 'admin/phpinfo.php', + 'href' => \SimpleSAML\Utils\HTTP::getBaseURL().'admin/phpinfo.php', 'text' => '{core:frontpage:link_phpinfo}' ); @@ -116,7 +116,7 @@ if (\SimpleSAML\Module::isModuleEnabled('radius')) { $funcmatrix = array(); $funcmatrix[] = array( 'required' => 'required', - 'descr' => 'PHP Version >= 5.4. You run: ' . phpversion(), + 'descr' => 'PHP Version >= 5.4. You run: '.phpversion(), 'enabled' => version_compare(phpversion(), '5.4', '>=') ); foreach ($functionchecks as $func => $descr) { diff --git a/modules/core/www/frontpage_welcome.php b/modules/core/www/frontpage_welcome.php index 60b9ef9565cc0b24061718a604e201f8d62e2337..46a3c0bc5c923336af3df32b4e84d185ec823984 100644 --- a/modules/core/www/frontpage_welcome.php +++ b/modules/core/www/frontpage_welcome.php @@ -18,16 +18,16 @@ $links_auth = array(); $links_federation = array(); $allLinks = array( - 'links' => &$links, - 'welcome' => &$links_welcome, - 'config' => &$links_config, - 'auth' => &$links_auth, - 'federation' => &$links_federation, + 'links' => &$links, + 'welcome' => &$links_welcome, + 'config' => &$links_config, + 'auth' => &$links_auth, + 'federation' => &$links_federation, ); $links_welcome[] = array( - 'href' => 'https://simplesamlphp.org/docs/stable/', - 'text' => '{core:frontpage:doc_header}', + 'href' => 'https://simplesamlphp.org/docs/stable/', + 'text' => '{core:frontpage:doc_header}', ); \SimpleSAML\Module::callHooks('frontpage', $allLinks); @@ -44,8 +44,4 @@ $t->data['links_auth'] = $links_auth; $t->data['links_federation'] = $links_federation; $t->data['header'] = $t->getTranslator()->t('{core:frontpage:page_title}'); - - $t->show(); - - diff --git a/modules/core/www/idp/logout-iframe.php b/modules/core/www/idp/logout-iframe.php index 547d86a1048c2a91dd5fbbfd008cbe11f44bf57a..4af3da1cdbd711fe79d12efeae787ae779903fb0 100644 --- a/modules/core/www/idp/logout-iframe.php +++ b/modules/core/www/idp/logout-iframe.php @@ -22,7 +22,8 @@ $state = \SimpleSAML\Auth\State::loadState($_REQUEST['id'], 'core:Logout-IFrame' $idp = \SimpleSAML\IdP::getByState($state); $mdh = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler(); -if ($type !== 'init') { // update association state +if ($type !== 'init') { + // update association state foreach ($state['core:Logout-IFrame:Associations'] as $assocId => &$sp) { $spId = sha1($assocId); diff --git a/modules/core/www/login-admin.php b/modules/core/www/login-admin.php index 2fc0c6623944c783c63b974caba1f38ecc96d597..01ea86c93d41978b6503bafb5e8651602f9ebbe1 100644 --- a/modules/core/www/login-admin.php +++ b/modules/core/www/login-admin.php @@ -5,10 +5,9 @@ */ if (!array_key_exists('ReturnTo', $_REQUEST)) { - throw new \SimpleSAML\Error\BadRequest('Missing ReturnTo parameter.'); + throw new \SimpleSAML\Error\BadRequest('Missing ReturnTo parameter.'); } \SimpleSAML\Utils\Auth::requireAdmin(); - \SimpleSAML\Utils\HTTP::redirectUntrustedURL($_REQUEST['ReturnTo']); diff --git a/modules/core/www/loginuserpass.php b/modules/core/www/loginuserpass.php index 0b97e55cbd14077e511e121365083ed7919eac62..f5211bb7fb808255bd6d66dd698af46efe65a62f 100644 --- a/modules/core/www/loginuserpass.php +++ b/modules/core/www/loginuserpass.php @@ -73,18 +73,18 @@ if (!empty($_REQUEST['username']) || !empty($password)) { try { \SimpleSAML\Module\core\Auth\UserPassBase::handleLogin($authStateId, $username, $password); } catch (\SimpleSAML\Error\Error $e) { - /* Login failed. Extract error code and parameters, to display the error. */ + // Login failed. Extract error code and parameters, to display the error $errorCode = $e->getErrorCode(); $errorParams = $e->getParameters(); - $state['error']= array( + $state['error'] = array( 'code' => $errorCode, 'params' => $errorParams ); $authStateId = \SimpleSAML\Auth\State::saveState($state, \SimpleSAML\Module\core\Auth\UserPassBase::STAGEID); $queryParams = array('AuthState' => $authStateId); - } - if (isset($state['error'])){ - unset($state['error']); + } + if (isset($state['error'])) { + unset($state['error']); } } diff --git a/modules/core/www/loginuserpassorg.php b/modules/core/www/loginuserpassorg.php index acbad36735b11c8e327a19b32e362824f6bf262e..4b293e2dc09fd40a82e6de39edcc113bc8109893 100644 --- a/modules/core/www/loginuserpassorg.php +++ b/modules/core/www/loginuserpassorg.php @@ -84,14 +84,14 @@ if ($organizations === null || !empty($organization)) { // Login failed. Extract error code and parameters, to display the error $errorCode = $e->getErrorCode(); $errorParams = $e->getParameters(); - $state['error']= array( + $state['error'] = array( 'code' => $errorCode, 'params' => $errorParams ); $authStateId = \SimpleSAML\Auth\State::saveState($state, \SimpleSAML\Module\core\Auth\UserPassOrgBase::STAGEID); $queryParams = array('AuthState' => $authStateId); } - if (isset($state['error'])){ + if (isset($state['error'])) { unset($state['error']); } } diff --git a/modules/core/www/postredirect.php b/modules/core/www/postredirect.php index 40441f1980e2c451a8e93505b815bcd48f51b9ee..a748eea8272995f9056235fcf906d565bdfbadd7 100644 --- a/modules/core/www/postredirect.php +++ b/modules/core/www/postredirect.php @@ -7,35 +7,35 @@ */ if (array_key_exists('RedirId', $_REQUEST)) { - $postId = $_REQUEST['RedirId']; - $session = \SimpleSAML\Session::getSessionFromRequest(); + $postId = $_REQUEST['RedirId']; + $session = \SimpleSAML\Session::getSessionFromRequest(); } elseif (array_key_exists('RedirInfo', $_REQUEST)) { - $encData = base64_decode($_REQUEST['RedirInfo']); + $encData = base64_decode($_REQUEST['RedirInfo']); - if (empty($encData)) { - throw new \SimpleSAML\Error\BadRequest('Invalid RedirInfo data.'); - } + if (empty($encData)) { + throw new \SimpleSAML\Error\BadRequest('Invalid RedirInfo data.'); + } - list($sessionId, $postId) = explode(':', \SimpleSAML\Utils\Crypto::aesDecrypt($encData)); + list($sessionId, $postId) = explode(':', \SimpleSAML\Utils\Crypto::aesDecrypt($encData)); - if (empty($sessionId) || empty($postId)) { - throw new \SimpleSAML\Error\BadRequest('Invalid session info data.'); - } + if (empty($sessionId) || empty($postId)) { + throw new \SimpleSAML\Error\BadRequest('Invalid session info data.'); + } - $session = \SimpleSAML\Session::getSession($sessionId); + $session = \SimpleSAML\Session::getSession($sessionId); } else { - throw new \SimpleSAML\Error\BadRequest('Missing redirection info parameter.'); + throw new \SimpleSAML\Error\BadRequest('Missing redirection info parameter.'); } -if ($session === NULL) { - throw new Exception('Unable to load session.'); +if ($session === null) { + throw new Exception('Unable to load session.'); } $postData = $session->getData('core_postdatalink', $postId); -if ($postData === NULL) { - // The post data is missing, probably because it timed out - throw new Exception('The POST data we should restore was lost.'); +if ($postData === null) { + // The post data is missing, probably because it timed out + throw new Exception('The POST data we should restore was lost.'); } $session->deleteData('core_postdatalink', $postId); diff --git a/modules/core/www/short_sso_interval.php b/modules/core/www/short_sso_interval.php index d1f5ae32dd5dfec1fa3b38d08f83163411c98c81..9844e9c5f3c8b4e0aa29beaf73b4ca4deb515c0d 100644 --- a/modules/core/www/short_sso_interval.php +++ b/modules/core/www/short_sso_interval.php @@ -8,15 +8,15 @@ */ if (!array_key_exists('StateId', $_REQUEST)) { - throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.'); + throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.'); } $id = $_REQUEST['StateId']; $state = \SimpleSAML\Auth\State::loadState($id, 'core:short_sso_interval'); $session = \SimpleSAML\Session::getSessionFromRequest(); if (array_key_exists('continue', $_REQUEST)) { - // The user has pressed the continue/retry-button - \SimpleSAML\Auth\ProcessingChain::resumeProcessing($state); + // The user has pressed the continue/retry-button + \SimpleSAML\Auth\ProcessingChain::resumeProcessing($state); } $globalConfig = \SimpleSAML\Configuration::getInstance(); diff --git a/modules/cron/bin/cron.php b/modules/cron/bin/cron.php index 073c278cbea20179f238d99e5477a11acf568ce8..61e690e0fd05f42be515dd2f5ff4cc208e6829ed 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 "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"; exit(1); } diff --git a/modules/cron/config-templates/module_cron.php b/modules/cron/config-templates/module_cron.php index 32d5c28e7b6339f5b7b2f7f5c0647c5a64187d61..abee18711383baa95d93f6c712f857b0d1ee8783 100644 --- a/modules/cron/config-templates/module_cron.php +++ b/modules/cron/config-templates/module_cron.php @@ -3,11 +3,9 @@ * Configuration for the Cron module. */ -$config = array ( - - 'key' => 'secret', - 'allowed_tags' => array('daily', 'hourly', 'frequent'), - 'debug_message' => TRUE, - 'sendemail' => TRUE, - +$config = array( + 'key' => 'secret', + 'allowed_tags' => array('daily', 'hourly', 'frequent'), + 'debug_message' => true, + 'sendemail' => true, ); diff --git a/modules/cron/hooks/hook_cron.php b/modules/cron/hooks/hook_cron.php index 6d2cd290ca96092420a91afd7b5c0d2c038cea94..61812906a2e8fee62ba13e042314d827ca36f39d 100644 --- a/modules/cron/hooks/hook_cron.php +++ b/modules/cron/hooks/hook_cron.php @@ -4,16 +4,16 @@ * * @param array &$croninfo Output */ -function cron_hook_cron(&$croninfo) { - assert(is_array($croninfo)); - assert(array_key_exists('summary', $croninfo)); - assert(array_key_exists('tag', $croninfo)); - $cronconfig = \SimpleSAML\Configuration::getConfig('module_cron.php'); - - if ($cronconfig->getValue('debug_message', TRUE)) { +function cron_hook_cron(&$croninfo) +{ + assert(is_array($croninfo)); + assert(array_key_exists('summary', $croninfo)); + assert(array_key_exists('tag', $croninfo)); - $croninfo['summary'][] = 'Cron did run tag [' . $croninfo['tag'] . '] at ' . date(DATE_RFC822); - } + $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); + } } diff --git a/modules/cron/hooks/hook_frontpage.php b/modules/cron/hooks/hook_frontpage.php index b0e6696349429011d289fdff1db40449c3683aa1..46a7ab954d1c1bac4e9a4100923848b67ee38836 100644 --- a/modules/cron/hooks/hook_frontpage.php +++ b/modules/cron/hooks/hook_frontpage.php @@ -4,7 +4,9 @@ * * @param array &$links The links on the frontpage, split into sections. */ -function cron_hook_frontpage(&$links) { + +function cron_hook_frontpage(&$links) +{ assert(is_array($links)); assert(array_key_exists('links', $links)); diff --git a/modules/cron/lib/Cron.php b/modules/cron/lib/Cron.php index 0df16e375f4ab725b1db4ac37a1a341f05063e8b..169d248beee8718a5bbbde2a1f945106af2ba0dd 100644 --- a/modules/cron/lib/Cron.php +++ b/modules/cron/lib/Cron.php @@ -47,7 +47,7 @@ class Cron \SimpleSAML\Module::callHooks('cron', $croninfo); foreach ($summary as $s) { - \SimpleSAML\Logger::debug('Cron - Summary: ' . $s); + \SimpleSAML\Logger::debug('Cron - Summary: '.$s); } return $croninfo; diff --git a/modules/cron/templates/croninfo-result.php b/modules/cron/templates/croninfo-result.php index 489cd5d51f383eb93401d88e2e8b9d9240bfa20f..fecd11cdb19d6f183fd3236bee5e43cb73a8323a 100644 --- a/modules/cron/templates/croninfo-result.php +++ b/modules/cron/templates/croninfo-result.php @@ -3,14 +3,15 @@ $this->data['header'] = $this->t('cron_header'); $this->includeAtTemplateBase('includes/header.php'); ?> - <p><?php echo $this->t('cron_result_title') ?></p> - <pre style="color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code> - <?php - echo '<h1>' .$this->t('cron_report_title'). '</h1><p>' .$this->t('ran_text'). ' ' .$this->data['time'] . '</p>' . - '<p>URL: <tt>' . $this->data['url'] . '</tt></p>' . - '<p>Tag: ' . $this->data['tag'] . "</p>\n\n" . - '<ul><li>' . join('</li><li>', $this->data['summary']) . '</li></ul>'; - ?> + <p><?php echo $this->t('cron_result_title') ?></p> + <pre style="color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code> +<?php + +echo ' <h1>'.$this->t('cron_report_title').'</h1><p>'.$this->t('ran_text'). + ' '.$this->data['time'].'</p>'.'<p>URL: <tt>'.$this->data['url'].'</tt></p>'. + '<p>Tag: '.$this->data['tag']."</p>\n\n". + '<ul><li>'.join('</li><li>', $this->data['summary']).'</li></ul>'; +?> </code> </pre> </div> diff --git a/modules/cron/templates/croninfo.tpl.php b/modules/cron/templates/croninfo.tpl.php index 49aa3131e0f90b77260b96f85eb9a73f9e74fc31..f6181f6cf3a4eb6dcaeec18e2ae4e928b4a3f16f 100644 --- a/modules/cron/templates/croninfo.tpl.php +++ b/modules/cron/templates/croninfo.tpl.php @@ -6,31 +6,27 @@ $this->includeAtTemplateBase('includes/header.php'); $run_text = $this->t('run_text'); ?> - <p><?php echo $this->t('cron_info') ?></p> + <p><?php echo $this->t('cron_info') ?></p> - <p><?php echo $this->t('cron_suggestion') ?></p> - <pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code><?php - - foreach ($this->data['urls'] AS $url ) { - echo "# " . $run_text. ' [' .$url['tag']. ']' . "\n"; - echo "" . $url['int'] . " curl --silent \"" . $url['href'] . "\" > /dev/null 2>&1\n"; - } - - ?> - </code></pre> - - <br><p><?php echo $this->t('cron_execution') ?></p> - <ul> - <?php - - foreach ($this->data['urls'] AS $url ) { - echo '<li><a href="' . $url['href'] . '&output=xhtml">' . $run_text. ' [' .$url['tag']. ']' . '</a></li>'; - } - - ?> - - </ul> + <p><?php echo $this->t('cron_suggestion') ?></p> + <pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code> +<?php +foreach ($this->data['urls'] as $url ) { + echo "# ".$run_text. ' ['.$url['tag'].']'."\n"; + echo $url['int']." curl --silent \"".$url['href']."\" > /dev/null 2>&1\n"; +} +?> + </code></pre> + <br /> + <p><?php echo $this->t('cron_execution') ?></p> + <ul> +<?php +foreach ($this->data['urls'] as $url ) { + echo ' <li><a href="'.$url['href'].'&output=xhtml">'.$run_text.' ['.$url['tag'].']'.'</a></li>'; +} +?> + </ul> </div> <?php diff --git a/modules/cron/www/cron.php b/modules/cron/www/cron.php index 69329b977a6018af9b73fec1b2e57e169b43b0e9..4a2ec9ab9ad38faa42d01f986366b35ee1287960 100644 --- a/modules/cron/www/cron.php +++ b/modules/cron/www/cron.php @@ -4,15 +4,15 @@ $config = \SimpleSAML\Configuration::getInstance(); $cronconfig = \SimpleSAML\Configuration::getConfig('module_cron.php'); if (!is_null($cronconfig->getValue('key'))) { - if ($_REQUEST['key'] !== $cronconfig->getValue('key')) { - \SimpleSAML\Logger::error('Cron - Wrong key provided. Cron will not run.'); - exit; - } + if ($_REQUEST['key'] !== $cronconfig->getValue('key')) { + \SimpleSAML\Logger::error('Cron - Wrong key provided. Cron will not run.'); + exit; + } } $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; } @@ -22,28 +22,28 @@ $time = date(DATE_RFC822); $croninfo = $cron->runTag($_REQUEST['tag']); $summary = $croninfo['summary']; -if ($cronconfig->getValue('sendemail', TRUE) && count($summary) > 0) { - $message = '<h1>Cron report</h1><p>Cron ran at ' . $time . '</p>' . - '<p>URL: <tt>' . $url . '</tt></p>' . - '<p>Tag: ' . $croninfo['tag'] . "</p>\n\n" . - '<ul><li>' . join('</li><li>', $summary) . '</li></ul>'; - - $toaddress = $config->getString('technicalcontact_email', 'na@example.org'); - if($toaddress == 'na@example.org') { - \SimpleSAML\Logger::error('Cron - Could not send email. [technicalcontact_email] not set in config.'); - } else { - // Use $toaddress for both TO and FROM - $email = new \SimpleSAML\XHTML\EMail($toaddress, 'SimpleSAMLphp cron report', $toaddress); - $email->setBody($message); - $email->send(); - } +if ($cronconfig->getValue('sendemail', true) && count($summary) > 0) { + $message = '<h1>Cron report</h1><p>Cron ran at '.$time.'</p>'. + '<p>URL: <tt>'.$url.'</tt></p>'. + '<p>Tag: '.$croninfo['tag']."</p>\n\n". + '<ul><li>'.join('</li><li>', $summary).'</li></ul>'; + + $toaddress = $config->getString('technicalcontact_email', 'na@example.org'); + if ($toaddress == 'na@example.org') { + \SimpleSAML\Logger::error('Cron - Could not send email. [technicalcontact_email] not set in config.'); + } else { + // Use $toaddress for both TO and FROM + $email = new \SimpleSAML\XHTML\EMail($toaddress, 'SimpleSAMLphp cron report', $toaddress); + $email->setBody($message); + $email->send(); + } } if (isset($_REQUEST['output']) && $_REQUEST['output'] == "xhtml") { - $t = new \SimpleSAML\XHTML\Template($config, 'cron:croninfo-result.php','cron:cron'); - $t->data['tag'] = $croninfo['tag']; - $t->data['time'] = $time; - $t->data['url'] = $url; - $t->data['summary'] = $summary; - $t->show(); + $t = new \SimpleSAML\XHTML\Template($config, 'cron:croninfo-result.php', 'cron:cron'); + $t->data['tag'] = $croninfo['tag']; + $t->data['time'] = $time; + $t->data['url'] = $url; + $t->data['summary'] = $summary; + $t->show(); } diff --git a/modules/cron/www/croninfo.php b/modules/cron/www/croninfo.php index 3e646cc6ccca52d6b14e545aa2c624c9685aa20e..8479de13f62472946fea76e52243c93ca012406c 100644 --- a/modules/cron/www/croninfo.php +++ b/modules/cron/www/croninfo.php @@ -19,19 +19,19 @@ $key = $cronconfig->getValue('key', ''); $tags = $cronconfig->getValue('allowed_tags'); $def = array( - 'weekly' => "22 0 * * 0", - 'daily' => "02 0 * * *", - 'hourly' => "01 * * * *", - 'default' => "XXXXXXXXXX", + 'weekly' => "22 0 * * 0", + 'daily' => "02 0 * * *", + 'hourly' => "01 * * * *", + 'default' => "XXXXXXXXXX", ); $urls = array(); -foreach ($tags AS $tag) { - $urls[] = array( - 'href' => \SimpleSAML\Module::getModuleURL('cron/cron.php', array('key' => $key, 'tag' => $tag)), - 'tag' => $tag, - 'int' => (array_key_exists($tag, $def) ? $def[$tag] : $def['default']), - ); +foreach ($tags as $tag) { + $urls[] = array( + 'href' => \SimpleSAML\Module::getModuleURL('cron/cron.php', array('key' => $key, 'tag' => $tag)), + 'tag' => $tag, + 'int' => (array_key_exists($tag, $def) ? $def[$tag] : $def['default']), + ); } $t = new \SimpleSAML\XHTML\Template($config, 'cron:croninfo.tpl.php', 'cron:cron'); diff --git a/modules/discopower/config-templates/module_discopower.php b/modules/discopower/config-templates/module_discopower.php index 5f5507f764e2e522e58b767b68a301dacae476b1..4579f9d101fa2c2ceace1cd34582f7c98015c917 100644 --- a/modules/discopower/config-templates/module_discopower.php +++ b/modules/discopower/config-templates/module_discopower.php @@ -3,44 +3,43 @@ * Configuration for the DiscoPower module. */ -$config = array ( +$config = array( + // Which tab should be set as default. 0 is the first tab + 'defaulttab' => 0, - // Which tab should be set as default. 0 is the first tab - 'defaulttab' => 0, - - /* - * List a set of tags (Tabs) that should be listed in a specific order. - * All other available tabs will be listed after the ones specified below. - */ - 'taborder' => array('norway'), - /* - * the 'tab' parameter allows you to limit the tabs to a specific list. (excluding unlisted tags) - * - * 'tabs' => array('norway', 'finland'), - */ - - /** - * If you want to change the scoring algorithm to a more google suggest like one - * (filters by start of words) uncomment this ... - * - * 'score' => 'suggest', - */ + /* + * List a set of tags (Tabs) that should be listed in a specific order. + * All other available tabs will be listed after the ones specified below. + */ + 'taborder' => array('norway'), - /* - * The domain to use for common domain cookie support. - * This must be a parent domain of the domain hosting the discovery service. - * - * If this is NULL (the default), common domain cookie support will be disabled. - */ - 'cdc.domain' => NULL, + /* + * the 'tab' parameter allows you to limit the tabs to a specific list. (excluding unlisted tags) + * + * 'tabs' => array('norway', 'finland'), + */ - /* - * The lifetime of the common domain cookie, in seconds. - * - * If this is NULL (the default), the common domain cookie will be deleted when the browser closes. - * - * Example: 'cdc.lifetime' => 180*24*60*60, // 180 days - */ - 'cdc.lifetime' => NULL, + /* + * If you want to change the scoring algorithm to a more google suggest like one + * (filters by start of words) uncomment this ... + * + * 'score' => 'suggest', + */ + /* + * The domain to use for common domain cookie support. + * This must be a parent domain of the domain hosting the discovery service. + * + * If this is NULL (the default), common domain cookie support will be disabled. + */ + 'cdc.domain' => null, + + /* + * The lifetime of the common domain cookie, in seconds. + * + * If this is NULL (the default), the common domain cookie will be deleted when the browser closes. + * + * Example: 'cdc.lifetime' => 180*24*60*60, // 180 days + */ + 'cdc.lifetime' => null, ); diff --git a/modules/discopower/lib/PowerIdPDisco.php b/modules/discopower/lib/PowerIdPDisco.php index 0a448d2de400032e34bdc07260dcaa95f24cd3ee..52ded4331b991bff8d2f2260ede635f53f79c730 100644 --- a/modules/discopower/lib/PowerIdPDisco.php +++ b/modules/discopower/lib/PowerIdPDisco.php @@ -288,7 +288,7 @@ class PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco $("#tabdiv").tabs({ selected: '.$t->data['defaulttab'].' });'; $i = 0; foreach ($idpList as $tab => $slist) { - $search .= "\n".'$("#query_'.$tab.'").liveUpdate("#list_'.$tab.'")' . + $search .= "\n".'$("#query_'.$tab.'").liveUpdate("#list_'.$tab.'")'. (($i++ == 0) && (empty($this->data['faventry'])) ? '.focus()' : '').';'; } $search .= "});\n</script>"; @@ -306,7 +306,7 @@ class PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco private function processMetadata($t, $metadata, $favourite) { - $basequerystring = '?' . + $basequerystring = '?'. 'entityID='.urlencode($t->data['entityID']).'&'. 'return='.urlencode($t->data['return']).'&'. 'returnIDParam='.urlencode($t->data['returnIDParam']).'&idpentityid='; diff --git a/modules/exampleattributeserver/www/attributeserver.php b/modules/exampleattributeserver/www/attributeserver.php index 9978b0bbc274ae41d6e80a8fc5ce9a7e15002e83..1de9e54b06186977707846db08eea286222365ce 100644 --- a/modules/exampleattributeserver/www/attributeserver.php +++ b/modules/exampleattributeserver/www/attributeserver.php @@ -5,15 +5,15 @@ $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler(); $binding = \SAML2\Binding::getCurrentBinding(); $query = $binding->receive(); if (!($query instanceof \SAML2\AttributeQuery)) { - throw new \SimpleSAML\Error\BadRequest('Invalid message received to AttributeQuery endpoint.'); + throw new \SimpleSAML\Error\BadRequest('Invalid message received to AttributeQuery endpoint.'); } $idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); $spEntityId = $query->getIssuer(); -if ($spEntityId === NULL) { - throw new \SimpleSAML\Error\BadRequest('Missing <saml:Issuer> in <samlp:AttributeQuery>.'); +if ($spEntityId === null) { + throw new \SimpleSAML\Error\BadRequest('Missing <saml:Issuer> in <samlp:AttributeQuery>.'); } $idpMetadata = $metadata->getMetadataConfig($idpEntityId, 'saml20-idp-hosted'); @@ -24,49 +24,45 @@ $endpoint = $spMetadata->getString('testAttributeEndpoint'); // The attributes we will return $attributes = array( - 'name' => array('value1', 'value2', 'value3'), - 'test' => array('test'), + 'name' => array('value1', 'value2', 'value3'), + 'test' => array('test'), ); -/* The name format of the attributes. */ +// The name format of the attributes $attributeNameFormat = \SAML2\Constants::NAMEFORMAT_UNSPECIFIED; - -/* Determine which attributes we will return. */ +// Determine which attributes we will return $returnAttributes = array_keys($query->getAttributes()); if (count($returnAttributes) === 0) { - SimpleSAML\Logger::debug('No attributes requested - return all attributes.'); - $returnAttributes = $attributes; - + SimpleSAML\Logger::debug('No attributes requested - return all attributes.'); + $returnAttributes = $attributes; } elseif ($query->getAttributeNameFormat() !== $attributeNameFormat) { - SimpleSAML\Logger::debug('Requested attributes with wrong NameFormat - no attributes returned.'); - $returnAttributes = array(); + SimpleSAML\Logger::debug('Requested attributes with wrong NameFormat - no attributes returned.'); + $returnAttributes = array(); } else { - foreach ($returnAttributes as $name => $values) { - if (!array_key_exists($name, $attributes)) { - /* We don't have this attribute. */ - unset($returnAttributes[$name]); - continue; - } - - if (count($values) === 0) { - /* Return all attributes. */ - $returnAttributes[$name] = $attributes[$name]; - continue; - } - - /* Filter which attribute values we should return. */ - $returnAttributes[$name] = array_intersect($values, $attributes[$name]); - } + foreach ($returnAttributes as $name => $values) { + if (!array_key_exists($name, $attributes)) { + // We don't have this attribute + unset($returnAttributes[$name]); + continue; + } + if (count($values) === 0) { + // Return all attributes + $returnAttributes[$name] = $attributes[$name]; + continue; + } + + // Filter which attribute values we should return + $returnAttributes[$name] = array_intersect($values, $attributes[$name]); + } } - -/* $returnAttributes contains the attributes we should return. Send them. */ +// $returnAttributes contains the attributes we should return. Send them $assertion = new \SAML2\Assertion(); $assertion->setIssuer($idpEntityId); $assertion->setNameId($query->getNameId()); $assertion->setNotBefore(time()); -$assertion->setNotOnOrAfter(time() + 5*60); +$assertion->setNotOnOrAfter(time() + 300); // 60*5 = 5min $assertion->setValidAudiences(array($spEntityId)); $assertion->setAttributes($returnAttributes); $assertion->setAttributeNameFormat($attributeNameFormat); @@ -74,7 +70,7 @@ $assertion->setAttributeNameFormat($attributeNameFormat); $sc = new \SAML2\XML\saml\SubjectConfirmation(); $sc->Method = \SAML2\Constants::CM_BEARER; $sc->SubjectConfirmationData = new \SAML2\XML\saml\SubjectConfirmationData(); -$sc->SubjectConfirmationData->NotOnOrAfter = time() + 5*60; +$sc->SubjectConfirmationData->NotOnOrAfter = time() + 300; // 60*5 = 5min $sc->SubjectConfirmationData->Recipient = $endpoint; $sc->SubjectConfirmationData->InResponseTo = $query->getId(); $assertion->setSubjectConfirmation(array($sc)); diff --git a/modules/exampleauth/lib/Auth/Process/RedirectTest.php b/modules/exampleauth/lib/Auth/Process/RedirectTest.php index 1499769594f123c5f50673e945d55b00963f64f8..4e8d3b7781dc0d87e762ca5e653ed11164878cb6 100644 --- a/modules/exampleauth/lib/Auth/Process/RedirectTest.php +++ b/modules/exampleauth/lib/Auth/Process/RedirectTest.php @@ -9,21 +9,22 @@ namespace SimpleSAML\Module\exampleautth\Auth\Process; class RedirectTest extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Initialize processing of the redirect test. - * - * @param array &$state The state we should update. - */ - public function process(&$state) { - assert(is_array($state)); - assert(array_key_exists('Attributes', $state)); + /** + * Initialize processing of the redirect test. + * + * @param array &$state The state we should update. + */ + public function process(&$state) + { + assert(is_array($state)); + assert(array_key_exists('Attributes', $state)); - // To check whether the state is saved correctly - $state['Attributes']['RedirectTest1'] = array('OK'); + // To check whether the state is saved correctly + $state['Attributes']['RedirectTest1'] = array('OK'); - // Save state and redirect - $id = \SimpleSAML\Auth\State::saveState($state, 'exampleauth:redirectfilter-test'); - $url = \SimpleSAML\Module::getModuleURL('exampleauth/redirecttest.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } + // Save state and redirect + $id = \SimpleSAML\Auth\State::saveState($state, 'exampleauth:redirectfilter-test'); + $url = \SimpleSAML\Module::getModuleURL('exampleauth/redirecttest.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } } diff --git a/modules/exampleauth/lib/Auth/Source/StaticSource.php b/modules/exampleauth/lib/Auth/Source/StaticSource.php index ca17a378cc36f1fb41b2d25b556d1491a626480b..d81dd325638fe2c2e1f3e64d45ca329310115c54 100644 --- a/modules/exampleauth/lib/Auth/Source/StaticSource.php +++ b/modules/exampleauth/lib/Auth/Source/StaticSource.php @@ -14,46 +14,42 @@ namespace SimpleSAML\Module\exampleauth\Auth\Source; class StaticSource extends \SimpleSAML\Auth\Source { - /** - * The attributes we return. - */ - private $attributes; - - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct($info, $config) { - assert(is_array($info)); - assert(is_array($config)); - - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - - // Parse attributes - try { - $this->attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($config); - } catch (\Exception $e) { - throw new \Exception('Invalid attributes for authentication source ' . - $this->authId . ': ' . $e->getMessage()); - } - - } - - - /** - * Log in using static attributes. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(&$state) { - assert(is_array($state)); - - $state['Attributes'] = $this->attributes; - } - + /** + * The attributes we return. + */ + private $attributes; + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) + { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + // Parse attributes + try { + $this->attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($config); + } catch (\Exception $e) { + throw new \Exception('Invalid attributes for authentication source '. + $this->authId.': '.$e->getMessage()); + } + } + + /** + * Log in using static attributes. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) + { + assert(is_array($state)); + $state['Attributes'] = $this->attributes; + } } diff --git a/modules/exampleauth/lib/Auth/Source/UserPass.php b/modules/exampleauth/lib/Auth/Source/UserPass.php index 8a5ef6215bbcffc97edd20405cb7f59b37874e93..f1d6fcb042e6e9b1967b8c1aee0622c76ac877ca 100644 --- a/modules/exampleauth/lib/Auth/Source/UserPass.php +++ b/modules/exampleauth/lib/Auth/Source/UserPass.php @@ -14,78 +14,74 @@ namespace SimpleSAML\Module\exampleauth\Auth\Source; class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase { - /** - * Our users, stored in an associative array. The key of the array is "<username>:<password>", - * while the value of each element is a new array with the attributes for each user. - */ - private $users; + /** + * Our users, stored in an associative array. The key of the array is "<username>:<password>", + * while the value of each element is a new array with the attributes for each user. + */ + private $users; + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) + { + assert(is_array($info)); + assert(is_array($config)); - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct($info, $config) { - assert(is_array($info)); - assert(is_array($config)); + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); + $this->users = array(); - $this->users = array(); + // Validate and parse our configuration + foreach ($config as $userpass => $attributes) { + if (!is_string($userpass)) { + throw new \Exception('Invalid <username>:<password> for authentication source '.$this->authId.': '.$userpass); + } - // Validate and parse our configuration - foreach ($config as $userpass => $attributes) { - if (!is_string($userpass)) { - throw new \Exception('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]); + } + $username = $userpass[0]; + $password = $userpass[1]; - $userpass = explode(':', $userpass, 2); - if (count($userpass) !== 2) { - throw new \Exception('Invalid <username>:<password> for authentication source ' . - $this->authId . ': ' . $userpass[0]); - } - $username = $userpass[0]; - $password = $userpass[1]; + try { + $attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes); + } catch (\Exception $e) { + throw new \Exception('Invalid attributes for user '.$username. + ' in authentication source '.$this->authId.': '.$e->getMessage()); + } + $this->users[$username.':'.$password] = $attributes; + } + } - try { - $attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes); - } catch(\Exception $e) { - throw new \Exception('Invalid attributes for user ' . $username . - ' in authentication source ' . $this->authId . ': ' . - $e->getMessage()); - } + /** + * Attempt to log in using the given username and password. + * + * On a successful login, this function should return the users attributes. On failure, + * it should throw an exception. If the error was caused by the user entering the wrong + * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. + * + * Note that both the username and the password are UTF-8 encoded. + * + * @param string $username The username the user wrote. + * @param string $password The password the user wrote. + * @return array Associative array with the users attributes. + */ + protected function login($username, $password) + { + assert(is_string($username)); + assert(is_string($password)); - $this->users[$username . ':' . $password] = $attributes; - } - } + $userpass = $username.':'.$password; + if (!array_key_exists($userpass, $this->users)) { + throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); + } - - /** - * Attempt to log in using the given username and password. - * - * On a successful login, this function should return the users attributes. On failure, - * it should throw an exception. If the error was caused by the user entering the wrong - * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown. - * - * Note that both the username and the password are UTF-8 encoded. - * - * @param string $username The username the user wrote. - * @param string $password The password the user wrote. - * @return array Associative array with the users attributes. - */ - protected function login($username, $password) { - assert(is_string($username)); - assert(is_string($password)); - - $userpass = $username . ':' . $password; - if (!array_key_exists($userpass, $this->users)) { - throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); - } - - return $this->users[$userpass]; - } + return $this->users[$userpass]; + } } diff --git a/modules/exampleauth/www/authpage.php b/modules/exampleauth/www/authpage.php index 5f176ec4ff8d6283271651907a51b32a1b40efbe..f4fc5339d45e0dd253d04d508eb493d2c146bcab 100644 --- a/modules/exampleauth/www/authpage.php +++ b/modules/exampleauth/www/authpage.php @@ -10,12 +10,11 @@ */ if (!isset($_REQUEST['ReturnTo'])) { - die('Missing ReturnTo parameter.'); + die('Missing ReturnTo parameter.'); } $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); - /* * The following piece of code would never be found in a real authentication page. Its * purpose in this example is to make this example safer in the case where the @@ -27,7 +26,7 @@ $returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']); */ if (!preg_match('@State=(.*)@', $returnTo, $matches)) { - die('Invalid ReturnTo URL for this example.'); + die('Invalid ReturnTo URL for this example.'); } \SimpleSAML\Auth\State::loadState(urldecode($matches[1]), 'exampleauth:External'); @@ -37,59 +36,55 @@ if (!preg_match('@State=(.*)@', $returnTo, $matches)) { * through the exampleauth:External authentication page. */ - /* * Our list of users. */ $users = array( - 'student' => array( - 'password' => 'student', - 'uid' => 'student', - 'name' => 'Student Name', - 'mail' => 'somestudent@example.org', - 'type' => 'student', - ), - 'admin' => array( - 'password' => 'admin', - 'uid' => 'admin', - 'name' => 'Admin Name', - 'mail' => 'someadmin@example.org', - 'type' => 'employee', - ), + 'student' => array( + 'password' => 'student', + 'uid' => 'student', + 'name' => 'Student Name', + 'mail' => 'somestudent@example.org', + 'type' => 'student', + ), + 'admin' => array( + 'password' => 'admin', + 'uid' => 'admin', + 'name' => 'Admin Name', + 'mail' => 'someadmin@example.org', + 'type' => 'employee', + ), ); - /* * Time to handle login responses. * Since this is a dummy example, we accept any data. */ -$badUserPass = FALSE; +$badUserPass = false; if ($_SERVER['REQUEST_METHOD'] === 'POST') { - $username = (string)$_REQUEST['username']; - $password = (string)$_REQUEST['password']; - - if (!isset($users[$username]) || $users[$username]['password'] !== $password) { - $badUserPass = TRUE; - } else { - - $user = $users[$username]; - - if (!session_id()) { - // session_start not called before. Do it here. - session_start(); - } - - $_SESSION['uid'] = $user['uid']; - $_SESSION['name'] = $user['name']; - $_SESSION['mail'] = $user['mail']; - $_SESSION['type'] = $user['type']; - - \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo); - } + $username = (string) $_REQUEST['username']; + $password = (string) $_REQUEST['password']; + + if (!isset($users[$username]) || $users[$username]['password'] !== $password) { + $badUserPass = true; + } else { + $user = $users[$username]; + + if (!session_id()) { + // session_start not called before. Do it here. + session_start(); + } + + $_SESSION['uid'] = $user['uid']; + $_SESSION['name'] = $user['name']; + $_SESSION['mail'] = $user['mail']; + $_SESSION['type'] = $user['type']; + + \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo); + } } - /* * If we get this far, we need to show the login page to the user. */ diff --git a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php index 44c472ce38cf31259967847b0a018ff104ca15c8..c41178c84023a3c8f31475260d66675fd23b3a1b 100644 --- a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php +++ b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php @@ -84,7 +84,7 @@ class ExpiryDate extends \SimpleSAML\Auth\ProcessingFilter $end = $expireOnDate; if ($expireOnDate >= $now) { - $days = (int)(($end - $now) / (24*60*60)); + $days = (int) (($end - $now) / 86400); //24*60*60=86400 if ($days <= $warndaysbefore) { $state['daysleft'] = $days; return true; diff --git a/modules/expirycheck/templates/expired.php b/modules/expirycheck/templates/expired.php index 2095d809926fd1347c80ccb340fc9eb8a0bd72e3..dc4f54718acc90a3adef7e94d4fccf369db3acc0 100644 --- a/modules/expirycheck/templates/expired.php +++ b/modules/expirycheck/templates/expired.php @@ -2,10 +2,9 @@ $this->data['header'] = $this->t('{expirycheck:expwarning:access_denied}'); $this->includeAtTemplateBase('includes/header.php'); ?> - - <h2><?php echo $this->t('{expirycheck:expwarning:access_denied}');?></h2> - <p><?php echo $this->t('{expirycheck:expwarning:no_access_to}', array('%NETID%' => htmlspecialchars($this->data['netId'])));?></p> - <p><?php echo $this->t('{expirycheck:expwarning:expiry_date_text}');?> <b><?php echo htmlspecialchars($this->data['expireOnDate']);?></b></p> - <p><?php echo $this->t('{expirycheck:expwarning:contact_home}');?></p> + <h2><?php echo $this->t('{expirycheck:expwarning:access_denied}'); ?></h2> + <p><?php echo $this->t('{expirycheck:expwarning:no_access_to}', array('%NETID%' => htmlspecialchars($this->data['netId']))); ?></p> + <p><?php echo $this->t('{expirycheck:expwarning:expiry_date_text}'); ?> <b><?php echo htmlspecialchars($this->data['expireOnDate']); ?></b></p> + <p><?php echo $this->t('{expirycheck:expwarning:contact_home}'); ?></p> <?php $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php index 3aced463831844ef14e375869619a4ed07146ec1..b8d1a1eb792bc19462e683eb283e5ec8d002965e 100644 --- a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php +++ b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php @@ -142,7 +142,7 @@ class AttributeAddFromLDAP extends BaseFilter assert(is_array($request)); assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; // perform a merge on the ldap_search_filter // loop over the attributes and build the search and replace arrays @@ -163,13 +163,13 @@ class AttributeAddFromLDAP extends BaseFilter if (strpos($filter, '%') !== false) { \SimpleSAML\Logger::info('AttributeAddFromLDAP: There are non-existing attributes in the search filter. ('. - $this->search_filter.')'); + $this->search_filter.')'); return; } if (!in_array($this->attr_policy, array('merge', 'replace', 'add'), true)) { \SimpleSAML\Logger::warning("AttributeAddFromLDAP: 'attribute.policy' must be one of 'merge',". - "'replace' or 'add'."); + "'replace' or 'add'."); return; } @@ -178,7 +178,7 @@ class AttributeAddFromLDAP extends BaseFilter $ldap = $this->getLdap(); } catch (\Exception $e) { // Added this warning in case $this->getLdap() fails - \SimpleSAML\Logger::warning("AttributeAddFromLDAP: exception = " . $e); + \SimpleSAML\Logger::warning("AttributeAddFromLDAP: exception = ".$e); return; } // search for matching entries diff --git a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php index c9b0a17dc37995c754cbc1ee5d085987fcb38bef..20ebfd33029a4fb0aab837b9500b4eade2a732ed 100644 --- a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php +++ b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php @@ -29,12 +29,12 @@ class AttributeAddUsersGroups extends BaseFilter // Log the process \SimpleSAML\Logger::debug( - $this->title . 'Attempting to get the users groups...' + $this->title.'Attempting to get the users groups...' ); // Reference the attributes, just to make the names shorter - $attributes =& $request['Attributes']; - $map =& $this->attribute_map; + $attributes = &$request['Attributes']; + $map = &$this->attribute_map; // Get the users groups from LDAP $groups = $this->getGroups($attributes); @@ -47,20 +47,20 @@ class AttributeAddUsersGroups extends BaseFilter // Must be an array, else cannot merge groups if (!is_array($attributes[$map['groups']])) { throw new \SimpleSAML\Error\Exception( - $this->title . 'The group attribute [' . $map['groups'] . - '] is not an array of group DNs. ' . $this->var_export($attributes[$map['groups']]) + $this->title.'The group attribute ['.$map['groups']. + '] is not an array of group DNs. '.$this->var_export($attributes[$map['groups']]) ); } // Add the users group(s) - $group_attribute =& $attributes[$map['groups']]; + $group_attribute = &$attributes[$map['groups']]; $group_attribute = array_merge($group_attribute, $groups); $group_attribute = array_unique($group_attribute); // All done \SimpleSAML\Logger::debug( - $this->title . 'Added users groups to the group attribute [' . - $map['groups'] . ']: ' . implode('; ', $groups) + $this->title.'Added users groups to the group attribute ['. + $map['groups'].']: '.implode('; ', $groups) ); } @@ -80,7 +80,7 @@ class AttributeAddUsersGroups extends BaseFilter { // Log the request \SimpleSAML\Logger::debug( - $this->title . 'Checking for groups based on the best method for the LDAP product.' + $this->title.'Checking for groups based on the best method for the LDAP product.' ); // Based on the directory service, search LDAP for groups @@ -94,25 +94,25 @@ class AttributeAddUsersGroups extends BaseFilter break; default: // Reference the map, just to make the name shorter - $map =& $this->attribute_map; + $map = &$this->attribute_map; // Log the general search \SimpleSAML\Logger::debug( - $this->title . 'Searching LDAP using the default search method.' + $this->title.'Searching LDAP using the default search method.' ); // Make sure the defined memberOf attribute exists if (!isset($attributes[$map['memberof']])) { throw new \SimpleSAML\Error\Exception( - $this->title . 'The memberof attribute [' . $map['memberof'] . - '] is not defined in the user\'s Attributes: ' . implode(', ', array_keys($attributes))); + $this->title.'The memberof attribute ['.$map['memberof']. + '] is not defined in the user\'s Attributes: '.implode(', ', array_keys($attributes))); } // MemberOf must be an array of group DN's if (!is_array($attributes[$map['memberof']])) { throw new \SimpleSAML\Error\Exception( - $this->title . 'The memberof attribute [' . $map['memberof'] . - '] is not an array of group DNs. ' . $this->var_export($attributes[$map['memberof']]) + $this->title.'The memberof attribute ['.$map['memberof']. + '] is not an array of group DNs. '.$this->var_export($attributes[$map['memberof']]) ); } @@ -122,7 +122,7 @@ class AttributeAddUsersGroups extends BaseFilter // All done \SimpleSAML\Logger::debug( - $this->title . 'User found to be a member of the groups:' . implode('; ', $groups) + $this->title.'User found to be a member of the groups:'.implode('; ', $groups) ); return $groups; } @@ -141,22 +141,23 @@ class AttributeAddUsersGroups extends BaseFilter { // Log the OpenLDAP specific search \SimpleSAML\Logger::debug( - $this->title . 'Searching LDAP using OpenLDAP specific method.' + $this->title.'Searching LDAP using OpenLDAP specific method.' ); // Reference the map, just to make the name shorter - $map =& $this->attribute_map; + $map = &$this->attribute_map; // Print group search string and search for all group names - $openldap_base = $this->config->getString('ldap.basedn','ou=groups,dc=example,dc=com'); + $openldap_base = $this->config->getString('ldap.basedn', 'ou=groups,dc=example,dc=com'); \SimpleSAML\Logger::debug( - $this->title . "Searching for groups in ldap.basedn ".$openldap_base." with filter (".$map['memberof']."=".$attributes[$map['username']][0].") and attributes ".$map['member'] + $this->title."Searching for groups in ldap.basedn ".$openldap_base." with filter (".$map['memberof']. + "=".$attributes[$map['username']][0].") and attributes ".$map['member'] ); $groups = array(); try { // Intention is to filter in 'ou=groups,dc=example,dc=com' for '(memberUid = <value of attribute.username>)' and take only the attributes 'cn' (=name of the group) - $all_groups = $this->getLdap()->searchformultiple($openldap_base, array($map['memberof'] => $attributes[$map['username']][0]) , array($map['member'])); + $all_groups = $this->getLdap()->searchformultiple($openldap_base, array($map['memberof'] => $attributes[$map['username']][0]), array($map['member'])); } catch (\SimpleSAML\Error\UserNotFound $e) { return $groups; // if no groups found return with empty (still just initialized) groups array } @@ -183,24 +184,24 @@ class AttributeAddUsersGroups extends BaseFilter { // Log the AD specific search \SimpleSAML\Logger::debug( - $this->title . 'Searching LDAP using ActiveDirectory specific method.' + $this->title.'Searching LDAP using ActiveDirectory specific method.' ); // Reference the map, just to make the name shorter - $map =& $this->attribute_map; + $map = &$this->attribute_map; // Make sure the defined dn attribute exists if (!isset($attributes[$map['dn']])) { throw new \SimpleSAML\Error\Exception( - $this->title . 'The DN attribute [' . $map['dn'] . - '] is not defined in the user\'s Attributes: ' . implode(', ', array_keys($attributes))); + $this->title.'The DN attribute ['.$map['dn']. + '] is not defined in the user\'s Attributes: '.implode(', ', array_keys($attributes))); } // DN attribute must have a value if (!isset($attributes[$map['dn']][0]) || !$attributes[$map['dn']][0]) { throw new \SimpleSAML\Error\Exception( - $this->title . 'The DN attribute [' . $map['dn'] . - '] does not have a [0] value defined. ' . $this->var_export($attributes[$map['dn']]) + $this->title.'The DN attribute ['.$map['dn']. + '] does not have a [0] value defined. '.$this->var_export($attributes[$map['dn']]) ); } @@ -228,22 +229,22 @@ class AttributeAddUsersGroups extends BaseFilter $groups = array(); // Shorten the variable name - $map =& $this->attribute_map; + $map = &$this->attribute_map; // Log the search \SimpleSAML\Logger::debug( - $this->title . 'Checking DNs for groups.' . - ' DNs: '. implode('; ', $memberof) . - ' Attributes: ' . $map['memberof'] . ', ' . $map['type'] . - ' Group Type: ' . $this->type_map['group'] + $this->title.'Checking DNs for groups.'. + ' DNs: '.implode('; ', $memberof). + ' Attributes: '.$map['memberof'].', '.$map['type']. + ' Group Type: '.$this->type_map['group'] ); // Work out what attributes to get for a group - $use_group_name = FALSE; + $use_group_name = false; $get_attributes = array($map['memberof'], $map['type']); if (isset($map['name']) && $map['name']) { $get_attributes[] = $map['name']; - $use_group_name = TRUE; + $use_group_name = false; } // Check each DN of the passed memberOf @@ -301,17 +302,17 @@ class AttributeAddUsersGroups extends BaseFilter assert(is_string($dn) && $dn != ''); // Shorten the variable name - $map =& $this->attribute_map; + $map = &$this->attribute_map; // Log the search \SimpleSAML\Logger::debug( - $this->title . 'Searching ActiveDirectory group membership.' . - ' DN: ' . $dn . - ' DN Attribute: ' . $map['dn'] . - ' Member Attribute: ' . $map['member'] . - ' Type Attribute: ' . $map['type'] . - ' Type Value: ' . $this->type_map['group'] . - ' Base: ' . implode('; ', $this->base_dn) + $this->title.'Searching ActiveDirectory group membership.'. + ' DN: '.$dn. + ' DN Attribute: '.$map['dn']. + ' Member Attribute: '.$map['member']. + ' Type Attribute: '.$map['type']. + ' Type Value: '.$this->type_map['group']. + ' Base: '.implode('; ', $this->base_dn) ); // AD connections should have this set @@ -321,7 +322,7 @@ class AttributeAddUsersGroups extends BaseFilter try { $entries = $this->getLdap()->searchformultiple( $this->base_dn, - array($map['type'] => $this->type_map['group'], $map['member'] . ':1.2.840.113556.1.4.1941:' => $dn), + array($map['type'] => $this->type_map['group'], $map['member'].':1.2.840.113556.1.4.1941:' => $dn), array($map['dn']) ); @@ -356,9 +357,9 @@ class AttributeAddUsersGroups extends BaseFilter // Could not find DN, log and continue \SimpleSAML\Logger::notice( - $this->title . 'The DN attribute [' . - implode(', ', array($map['dn'], strtolower($map['dn']), 'dn')) . - '] could not be found in the entry. ' . $this->var_export($entry) + $this->title.'The DN attribute ['. + implode(', ', array($map['dn'], strtolower($map['dn']), 'dn')). + '] could not be found in the entry. '.$this->var_export($entry) ); } diff --git a/modules/ldap/lib/Auth/Source/LDAP.php b/modules/ldap/lib/Auth/Source/LDAP.php index 38101cce72eb184674c7bba02960bae922583b3f..e3cbd9d52c1fe20d910e56fceebcf9c8970911c5 100644 --- a/modules/ldap/lib/Auth/Source/LDAP.php +++ b/modules/ldap/lib/Auth/Source/LDAP.php @@ -36,7 +36,7 @@ class LDAP extends \SimpleSAML\Module\core\Auth\UserPassBase parent::__construct($info, $config); $this->ldapConfig = new \SimpleSAML\Module\ldap\ConfigHelper($config, - 'Authentication source ' . var_export($this->authId, true)); + 'Authentication source '.var_export($this->authId, true)); } diff --git a/modules/memcacheMonitor/hooks/hook_frontpage.php b/modules/memcacheMonitor/hooks/hook_frontpage.php index 10a5cead6dc22ab5ce737feb6e4dd8a57e97766d..c7f59bc6ce06f0117c370a10de78206abe882fea 100644 --- a/modules/memcacheMonitor/hooks/hook_frontpage.php +++ b/modules/memcacheMonitor/hooks/hook_frontpage.php @@ -4,7 +4,9 @@ * * @param array &$links The links on the frontpage, split into sections. */ -function memcacheMonitor_hook_frontpage(&$links) { + +function memcacheMonitor_hook_frontpage(&$links) +{ assert(is_array($links)); assert(array_key_exists('links', $links)); diff --git a/modules/memcacheMonitor/hooks/hook_sanitycheck.php b/modules/memcacheMonitor/hooks/hook_sanitycheck.php index da802f3117c6df8b9d8e2e330c8e7112698ae60c..a7a36c415dbdbbe7d1fec858040d650cdd5db5cd 100644 --- a/modules/memcacheMonitor/hooks/hook_sanitycheck.php +++ b/modules/memcacheMonitor/hooks/hook_sanitycheck.php @@ -8,7 +8,8 @@ * @param array &$hookinfo hookinfo */ -function memcacheMonitor_hook_sanitycheck(&$hookinfo) { +function memcacheMonitor_hook_sanitycheck(&$hookinfo) +{ assert(is_array($hookinfo)); assert(array_key_exists('errors', $hookinfo)); assert(array_key_exists('info', $hookinfo)); @@ -16,7 +17,7 @@ function memcacheMonitor_hook_sanitycheck(&$hookinfo) { try { $servers = \SimpleSAML\Memcache::getRawStats(); } catch (\Exception $e) { - $hookinfo['errors'][] = '[memcacheMonitor] Error parsing memcache configuration: ' . $e->getMessage(); + $hookinfo['errors'][] = '[memcacheMonitor] Error parsing memcache configuration: '.$e->getMessage(); return; } @@ -24,7 +25,7 @@ function memcacheMonitor_hook_sanitycheck(&$hookinfo) { foreach ($servers as $group) { foreach ($group as $server => $status) { if ($status === false) { - $hookinfo['errors'][] = '[memcacheMonitor] No response from server: ' . $server; + $hookinfo['errors'][] = '[memcacheMonitor] No response from server: '.$server; $allOK = false; } } diff --git a/modules/memcacheMonitor/www/memcachestat.php b/modules/memcacheMonitor/www/memcachestat.php index 30eb76cbeff8c3b72c8f30c4ddbcc94663c39237..3025afce4679b47f64263c84cb86869f5e312116 100644 --- a/modules/memcacheMonitor/www/memcachestat.php +++ b/modules/memcacheMonitor/www/memcachestat.php @@ -161,9 +161,9 @@ if (array_key_exists('bytes', $statsraw) && array_key_exists('limit_maxbytes', $ $maxpix = 400; foreach ($statsraw['bytes'] as $key => $row_data) { $pix = floor($statsraw['bytes'][$key] * $maxpix / $statsraw['limit_maxbytes'][$key]); - $usage[$key] = $pix . 'px'; + $usage[$key] = $pix.'px'; } - $t->data['maxpix'] = $maxpix . 'px'; + $t->data['maxpix'] = $maxpix.'px'; $t->data['usage'] = $usage; } diff --git a/modules/metarefresh/bin/metarefresh.php b/modules/metarefresh/bin/metarefresh.php index aa18eb65d540e6d240410e1636a8df61800bdd25..08a08a0bfd37750bf1d25d421f660fbaf87b7d6f 100755 --- a/modules/metarefresh/bin/metarefresh.php +++ b/modules/metarefresh/bin/metarefresh.php @@ -11,167 +11,168 @@ $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('metarefresh')) { - echo("You need to enable the metarefresh module before this script can be used.\n"); - echo("You can enable it by running the following command:\n"); - echo(' echo >"' . $baseDir . '/modules/metarefresh/enable' . "\"\n"); - exit(1); +if (!\SimpleSAML\Module::isModuleEnabled('metarefresh')) { + echo "You need to enable the metarefresh module before this script can be used.\n"; + echo "You can enable it by running the following command:\n"; + echo ' echo >"'.$baseDir.'/modules/metarefresh/enable'."\"\n"; + exit(1); } -/* Initialize the configuration. */ +// Initialize the configuration $configdir = \SimpleSAML\Utils\Config::getConfigDir(); \SimpleSAML\Configuration::setConfigDir($configdir); -/* $outputDir contains the directory we will store the generated metadata in. */ -$outputDir = $baseDir . '/metadata-generated'; +// $outputDir contains the directory we will store the generated metadata in +$outputDir = $baseDir.'/metadata-generated'; /* $toStdOut is a boolean telling us wheter we will print the output to stdout instead * of writing it to files in $outputDir. */ -$toStdOut = FALSE; +$toStdOut = false; /* $certificates contains the certificates which should be used to check the signature of the signed * EntityDescriptor in the metadata, or NULL if signature verification shouldn't be done. */ -$certificates = NULL; +$certificates = null; /* $validateFingerprint contains the fingerprint of the certificate which should have been used * to sign the EntityDescriptor in the metadata, or NULL if fingerprint validation shouldn't be * done. */ -$validateFingerprint = NULL; +$validateFingerprint = null; - -/* This variable contains the files we will parse. */ +// This variable contains the files we will parse $files = array(); -/* Parse arguments. */ +// Parse arguments $progName = array_shift($argv); -foreach($argv as $a) { - if(strlen($a) === 0) { - continue; - } - - if($a[0] !== '-') { - /* Not an option. Assume that it is a file we should parse. */ - $files[] = $a; - continue; - } - - if(strpos($a, '=') !== FALSE) { - $p = strpos($a, '='); - $v = substr($a, $p + 1); - $a = substr($a, 0, $p); - } else { - $v = NULL; - } - - /* Map short options to long options. */ - $shortOptMap = array( - '-h' => '--help', - '-o' => '--out-dir', - '-s' => '--stdout', - ); - if(array_key_exists($a, $shortOptMap)) { - $a = $shortOptMap[$a]; - } - - switch($a) { - case '--certificate': - if($v === NULL || strlen($v) === 0) { - echo('The --certficate option requires an parameter.' . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); - exit(1); - } - $certificates[] = $v; - break; - case '--validate-fingerprint': - if($v === NULL || strlen($v) === 0) { - echo('The --validate-fingerprint option requires an parameter.' . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); - exit(1); - } - $validateFingerprint = $v; - break; - case '--help': - printHelp(); - exit(0); - case '--out-dir': - if($v === NULL || strlen($v) === 0) { - echo('The --out-dir option requires an parameter.' . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); - exit(1); - } - $outputDir = $baseDir . ($v[0] == '/' ? $v : '/' . $v); - break; - case '--stdout': - $toStdOut = TRUE; - break; - default: - echo('Unknown option: ' . $a . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); - exit(1); - } +foreach ($argv as $a) { + if (strlen($a) === 0) { + continue; + } + + if ($a[0] !== '-') { + // Not an option. Assume that it is a file we should parse + $files[] = $a; + continue; + } + + if (strpos($a, '=') !== false) { + $p = strpos($a, '='); + $v = substr($a, $p + 1); + $a = substr($a, 0, $p); + } else { + $v = null; + } + + // Map short options to long options + $shortOptMap = array( + '-h' => '--help', + '-o' => '--out-dir', + '-s' => '--stdout', + ); + if (array_key_exists($a, $shortOptMap)) { + $a = $shortOptMap[$a]; + } + + switch ($a) { + case '--certificate': + if ($v === null || strlen($v) === 0) { + echo 'The --certficate option requires an parameter.'."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; + exit(1); + } + $certificates[] = $v; + break; + case '--validate-fingerprint': + if ($v === null || strlen($v) === 0) { + echo 'The --validate-fingerprint option requires an parameter.'."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; + exit(1); + } + $validateFingerprint = $v; + break; + case '--help': + printHelp(); + exit(0); + case '--out-dir': + if ($v === null || strlen($v) === 0) { + echo 'The --out-dir option requires an parameter.'."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; + exit(1); + } + $outputDir = $baseDir.($v[0] == '/' ? $v : '/'.$v); + break; + case '--stdout': + $toStdOut = true; + break; + default: + echo 'Unknown option: '.$a."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; + exit(1); + } } -if(count($files) === 0) { - echo($progName . ': Missing input files. Please run `' . $progName . ' --help` for usage information.' . "\n"); - exit(1); +if (count($files) === 0) { + echo $progName.': Missing input files. Please run `'.$progName.' --help` for usage information.'."\n"; + exit(1); } - - - -/* The metadata global variable will be filled with the metadata we extract. */ +// The metadata global variable will be filled with the metadata we extract $metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader(); -foreach($files as $f) { - $source = array('src' => $f); - if (isset($certificates)) $source['certificates'] = $certificates; - if (isset($validateFingerprint)) $source['validateFingerprint'] = $validateFingerprint; - $metaloader->loadSource($source); +foreach ($files as $f) { + $source = array('src' => $f); + if (isset($certificates)) { + $source['certificates'] = $certificates; + } + if (isset($validateFingerprint)) { + $source['validateFingerprint'] = $validateFingerprint; + } + $metaloader->loadSource($source); } -if($toStdOut) { - $metaloader->dumpMetadataStdOut(); +if ($toStdOut) { + $metaloader->dumpMetadataStdOut(); } else { - $metaloader->writeMetadataFiles($outputDir); + $metaloader->writeMetadataFiles($outputDir); } /** * This function prints the help output. */ -function printHelp() { - global $progName; - - /* '======================================================================' */ - echo('Usage: ' . $progName . ' [options] [files]' . "\n"); - echo("\n"); - echo('This program parses a SAML metadata files and output pieces that can' . "\n"); - echo('be added to the metadata files in metadata/.' . "\n"); - echo("\n"); - echo('Options:' . "\n"); - echo(' --certificate=<FILE> The certificate which should be used' . "\n"); - echo(' to check the signature of the metadata.' . "\n"); - echo(' The file are stored in the cert dir.' . "\n"); - echo(' It is possibility to add multiple' . "\n"); - echo(' --certificate options to handle' . "\n"); - echo(' key rollover.' . "\n"); - echo(' --validate-fingerprint=<FINGERPRINT>' . "\n"); - echo(' Check the signature of the metadata,' . "\n"); - echo(' and check the fingerprint of the' . "\n"); - echo(' certificate against <FINGERPRINT>.' . "\n"); - echo(' -h, --help Print this help.' . "\n"); - echo(' -o=<DIR>, --out-dir=<DIR> Write the output to this directory. The' . "\n"); - echo(' default directory is metadata-generated/.' . "\n"); - echo(' Path will be relative to the SimpleSAMLphp' . "\n"); - echo(' base directory.' . "\n"); - echo(' -s, --stdout Write the output to stdout instead of' . "\n"); - echo(' seperate files in the output directory.' . "\n"); - echo("\n"); +function printHelp() +{ + global $progName; + + /* '======================================================================' */ + echo 'Usage: '.$progName.' [options] [files]'."\n"; + echo "\n"; + echo 'This program parses a SAML metadata files and output pieces that can'."\n"; + echo 'be added to the metadata files in metadata/.'."\n"; + echo "\n"; + echo 'Options:'."\n"; + echo ' --certificate=<FILE> The certificate which should be used'."\n"; + echo ' to check the signature of the metadata.'."\n"; + echo ' The file are stored in the cert dir.'."\n"; + echo ' It is possibility to add multiple'."\n"; + echo ' --certificate options to handle'."\n"; + echo ' key rollover.'."\n"; + echo ' --validate-fingerprint=<FINGERPRINT>'."\n"; + echo ' Check the signature of the metadata,'."\n"; + echo ' and check the fingerprint of the'."\n"; + echo ' certificate against <FINGERPRINT>.'."\n"; + echo ' -h, --help Print this help.'."\n"; + echo ' -o=<DIR>, --out-dir=<DIR> Write the output to this directory. The'."\n"; + echo ' default directory is metadata-generated/.'."\n"; + echo ' Path will be relative to the SimpleSAMLphp'."\n"; + echo ' base directory.'."\n"; + echo ' -s, --stdout Write the output to stdout instead of'."\n"; + echo ' seperate files in the output directory.'."\n"; + echo "\n"; } diff --git a/modules/metarefresh/config-templates/config-metarefresh.php b/modules/metarefresh/config-templates/config-metarefresh.php index 0147b1850763e5d258728bbf3191ded5340de1d2..978170178fd3388b63687fde928be04688e37944 100644 --- a/modules/metarefresh/config-templates/config-metarefresh.php +++ b/modules/metarefresh/config-templates/config-metarefresh.php @@ -1,96 +1,92 @@ <?php $config = array( + /* + * Global blacklist: entityIDs that should be excluded from ALL sets. + */ + #'blacklist' = array( + # 'http://my.own.uni/idp' + #), - /* - * Global blacklist: entityIDs that should be excluded from ALL sets. - */ - #'blacklist' = array( - # 'http://my.own.uni/idp' - #), - - /* - * Conditional GET requests - * Efficient downloading so polling can be done more frequently. - * Works for sources that send 'Last-Modified' or 'Etag' headers. - * Note that the 'data' directory needs to be writable for this to work. - */ - #'conditionalGET' => TRUE, + /* + * Conditional GET requests + * Efficient downloading so polling can be done more frequently. + * Works for sources that send 'Last-Modified' or 'Etag' headers. + * Note that the 'data' directory needs to be writable for this to work. + */ + #'conditionalGET' => true, - 'sets' => array( + 'sets' => array( - 'kalmar' => array( - 'cron' => array('hourly'), - 'sources' => array( - array( - /* - * entityIDs that should be excluded from this src. - */ - #'blacklist' => array( - # 'http://some.other.uni/idp', - #), + 'kalmar' => array( + 'cron' => array('hourly'), + 'sources' => array( + array( + /* + * entityIDs that should be excluded from this src. + */ + #'blacklist' => array( + # 'http://some.other.uni/idp', + #), - /* - * Whitelist: only keep these EntityIDs. - */ - #'whitelist' => array( - # 'http://some.uni/idp', - # 'http://some.other.uni/idp', - #), + /* + * Whitelist: only keep these EntityIDs. + */ + #'whitelist' => array( + # 'http://some.uni/idp', + # 'http://some.other.uni/idp', + #), - #'conditionalGET' => TRUE, - 'src' => 'https://kalmar2.org/simplesaml/module.php/aggregator/?id=kalmarcentral&set=saml2&exclude=norway', - 'certificates' => array( - 'current.crt', - 'rollover.crt', - ), - 'validateFingerprint' => '59:1D:4B:46:70:46:3E:ED:A9:1F:CC:81:6D:C0:AF:2A:09:2A:A8:01', - 'template' => array( - 'tags' => array('kalmar'), - 'authproc' => array( - 51 => array('class' => 'core:AttributeMap', 'oid2name'), - ), - ), + #'conditionalGET' => true, + 'src' => 'https://kalmar2.org/simplesaml/module.php/aggregator/?id=kalmarcentral&set=saml2&exclude=norway', + 'certificates' => array( + 'current.crt', + 'rollover.crt', + ), + 'validateFingerprint' => '59:1D:4B:46:70:46:3E:ED:A9:1F:CC:81:6D:C0:AF:2A:09:2A:A8:01', + 'template' => array( + 'tags' => array('kalmar'), + 'authproc' => array( + 51 => array('class' => 'core:AttributeMap', 'oid2name'), + ), + ), - /* - * The sets of entities to load, any combination of: - * - 'saml20-idp-remote' - * - 'saml20-sp-remote' - * - 'shib13-idp-remote' - * - 'shib13-sp-remote' - * - 'attributeauthority-remote' - * - * All of them will be used by default. - * - * This option takes precedence over the same option per metadata set. - */ - //'types' => array(), - ), - ), - 'expireAfter' => 60*60*24*4, // Maximum 4 days cache time - 'outputDir' => 'metadata/metadata-kalmar-consuming/', + /* + * The sets of entities to load, any combination of: + * - 'saml20-idp-remote' + * - 'saml20-sp-remote' + * - 'shib13-idp-remote' + * - 'shib13-sp-remote' + * - 'attributeauthority-remote' + * + * All of them will be used by default. + * + * This option takes precedence over the same option per metadata set. + */ + //'types' => array(), + ), + ), - /* - * Which output format the metadata should be saved as. - * Can be 'flatfile' or 'serialize'. 'flatfile' is the default. - */ - 'outputFormat' => 'flatfile', + 'expireAfter' => 34560060, // Maximum 4 days cache time (3600*24*4) + 'outputDir' => 'metadata/metadata-kalmar-consuming/', + /* + * Which output format the metadata should be saved as. + * Can be 'flatfile' or 'serialize'. 'flatfile' is the default. + */ + 'outputFormat' => 'flatfile', - /* - * The sets of entities to load, any combination of: - * - 'saml20-idp-remote' - * - 'saml20-sp-remote' - * - 'shib13-idp-remote' - * - 'shib13-sp-remote' - * - 'attributeauthority-remote' - * - * All of them will be used by default. - */ - //'types' => array(), - ), - ), + /* + * The sets of entities to load, any combination of: + * - 'saml20-idp-remote' + * - 'saml20-sp-remote' + * - 'shib13-idp-remote' + * - 'shib13-sp-remote' + * - 'attributeauthority-remote' + * + * All of them will be used by default. + */ + //'types' => array(), + ), + ), ); - - - diff --git a/modules/metarefresh/hooks/hook_cron.php b/modules/metarefresh/hooks/hook_cron.php index 8b627292d358b19ae06ba0f81803266f6694fdbf..8feee46ee642405a78d8c1dbf8237c39d97f146a 100644 --- a/modules/metarefresh/hooks/hook_cron.php +++ b/modules/metarefresh/hooks/hook_cron.php @@ -4,111 +4,113 @@ * * @param array &$croninfo Output */ -function metarefresh_hook_cron(&$croninfo) { - assert(is_array($croninfo)); - assert(array_key_exists('summary', $croninfo)); - assert(array_key_exists('tag', $croninfo)); - - SimpleSAML\Logger::info('cron [metarefresh]: Running cron in cron tag [' . $croninfo['tag'] . '] '); - - try { - $config = \SimpleSAML\Configuration::getInstance(); - $mconfig = \SimpleSAML\Configuration::getOptionalConfig('config-metarefresh.php'); - - $sets = $mconfig->getConfigList('sets', array()); - $stateFile = $config->getPathValue('datadir', 'data/') . 'metarefresh-state.php'; - - foreach ($sets AS $setkey => $set) { - // Only process sets where cron matches the current cron tag - $cronTags = $set->getArray('cron'); - if (!in_array($croninfo['tag'], $cronTags, true)) continue; - - \SimpleSAML\Logger::info('cron [metarefresh]: Executing set [' . $setkey . ']'); - - $expireAfter = $set->getInteger('expireAfter', NULL); - if ($expireAfter !== NULL) { - $expire = time() + $expireAfter; - } else { - $expire = NULL; - } - - $outputDir = $set->getString('outputDir'); - $outputDir = $config->resolvePath($outputDir); - $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile'); - - $oldMetadataSrc = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(array( - 'type' => $outputFormat, - 'directory' => $outputDir, - )); - - $metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire, $stateFile, $oldMetadataSrc); - - # Get global blacklist, whitelist and caching info - $blacklist = $mconfig->getArray('blacklist', array()); - $whitelist = $mconfig->getArray('whitelist', array()); - $conditionalGET = $mconfig->getBoolean('conditionalGET', FALSE); - - // get global type filters - $available_types = array( - 'saml20-idp-remote', - 'saml20-sp-remote', - 'shib13-idp-remote', - 'shib13-sp-remote', - 'attributeauthority-remote' - ); - $set_types = $set->getArrayize('types', $available_types); - - foreach($set->getArray('sources') AS $source) { - - // filter metadata by type of entity - if (isset($source['types'])) { - $metaloader->setTypes($source['types']); - } else { - $metaloader->setTypes($set_types); - } - - # Merge global and src specific blacklists - if(isset($source['blacklist'])) { - $source['blacklist'] = array_unique(array_merge($source['blacklist'], $blacklist)); - } else { - $source['blacklist'] = $blacklist; - } - - # Merge global and src specific whitelists - if(isset($source['whitelist'])) { - $source['whitelist'] = array_unique(array_merge($source['whitelist'], $whitelist)); - } else { - $source['whitelist'] = $whitelist; - } - - # Let src specific conditionalGET override global one - if(!isset($source['conditionalGET'])) { - $source['conditionalGET'] = $conditionalGET; - } - - \SimpleSAML\Logger::debug('cron [metarefresh]: In set [' . $setkey . '] loading source [' . $source['src'] . ']'); - $metaloader->loadSource($source); - } - - // Write state information back to disk - $metaloader->writeState(); - - switch ($outputFormat) { - case 'flatfile': - $metaloader->writeMetadataFiles($outputDir); - break; - case 'serialize': - $metaloader->writeMetadataSerialize($outputDir); - break; - } - - if ($set->hasValue('arp')) { - $arpconfig = \SimpleSAML\Configuration::loadFromArray($set->getValue('arp')); - $metaloader->writeARPfile($arpconfig); - } - } - - } catch (\Exception $e) { - $croninfo['summary'][] = 'Error during metarefresh: ' . $e->getMessage(); - } +function metarefresh_hook_cron(&$croninfo) +{ + assert(is_array($croninfo)); + assert(array_key_exists('summary', $croninfo)); + assert(array_key_exists('tag', $croninfo)); + + SimpleSAML\Logger::info('cron [metarefresh]: Running cron in cron tag ['.$croninfo['tag'].'] '); + + try { + $config = \SimpleSAML\Configuration::getInstance(); + $mconfig = \SimpleSAML\Configuration::getOptionalConfig('config-metarefresh.php'); + + $sets = $mconfig->getConfigList('sets', array()); + $stateFile = $config->getPathValue('datadir', 'data/').'metarefresh-state.php'; + + foreach ($sets as $setkey => $set) { + // Only process sets where cron matches the current cron tag + $cronTags = $set->getArray('cron'); + if (!in_array($croninfo['tag'], $cronTags, true)) { + continue; + } + + \SimpleSAML\Logger::info('cron [metarefresh]: Executing set ['.$setkey.']'); + + $expireAfter = $set->getInteger('expireAfter', null); + if ($expireAfter !== null) { + $expire = time() + $expireAfter; + } else { + $expire = null; + } + + $outputDir = $set->getString('outputDir'); + $outputDir = $config->resolvePath($outputDir); + $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile'); + + $oldMetadataSrc = \SimpleSAML\Metadata\MetaDataStorageSource::getSource(array( + 'type' => $outputFormat, + 'directory' => $outputDir, + )); + + $metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire, $stateFile, $oldMetadataSrc); + + // Get global blacklist, whitelist and caching info + $blacklist = $mconfig->getArray('blacklist', array()); + $whitelist = $mconfig->getArray('whitelist', array()); + $conditionalGET = $mconfig->getBoolean('conditionalGET', false); + + // get global type filters + $available_types = array( + 'saml20-idp-remote', + 'saml20-sp-remote', + 'shib13-idp-remote', + 'shib13-sp-remote', + 'attributeauthority-remote' + ); + $set_types = $set->getArrayize('types', $available_types); + + foreach ($set->getArray('sources') as $source) { + + // filter metadata by type of entity + if (isset($source['types'])) { + $metaloader->setTypes($source['types']); + } else { + $metaloader->setTypes($set_types); + } + + // Merge global and src specific blacklists + if (isset($source['blacklist'])) { + $source['blacklist'] = array_unique(array_merge($source['blacklist'], $blacklist)); + } else { + $source['blacklist'] = $blacklist; + } + + // Merge global and src specific whitelists + if (isset($source['whitelist'])) { + $source['whitelist'] = array_unique(array_merge($source['whitelist'], $whitelist)); + } else { + $source['whitelist'] = $whitelist; + } + + // Let src specific conditionalGET override global one + if (!isset($source['conditionalGET'])) { + $source['conditionalGET'] = $conditionalGET; + } + + \SimpleSAML\Logger::debug('cron [metarefresh]: In set ['.$setkey.'] loading source ['.$source['src'].']'); + $metaloader->loadSource($source); + } + + // Write state information back to disk + $metaloader->writeState(); + + switch ($outputFormat) { + case 'flatfile': + $metaloader->writeMetadataFiles($outputDir); + break; + case 'serialize': + $metaloader->writeMetadataSerialize($outputDir); + break; + } + + if ($set->hasValue('arp')) { + $arpconfig = \SimpleSAML\Configuration::loadFromArray($set->getValue('arp')); + $metaloader->writeARPfile($arpconfig); + } + } + } catch (\Exception $e) { + $croninfo['summary'][] = 'Error during metarefresh: '.$e->getMessage(); + } } diff --git a/modules/metarefresh/hooks/hook_frontpage.php b/modules/metarefresh/hooks/hook_frontpage.php index 0c5c2b17529f9e5a10e9e85d9035003f49a2d52f..9179368393a066a5c12693485d4e741dfe6214b3 100644 --- a/modules/metarefresh/hooks/hook_frontpage.php +++ b/modules/metarefresh/hooks/hook_frontpage.php @@ -4,13 +4,14 @@ * * @param array &$links The links on the frontpage, split into sections. */ -function metarefresh_hook_frontpage(&$links) { - assert(is_array($links)); - assert(array_key_exists('links', $links)); - $links['federation'][] = array( - 'href' => SimpleSAML\Module::getModuleURL('metarefresh/fetch.php'), - 'text' => '{metarefresh:metarefresh:frontpage_link}', - ); +function metarefresh_hook_frontpage(&$links) +{ + assert(is_array($links)); + assert(array_key_exists('links', $links)); + $links['federation'][] = array( + 'href' => SimpleSAML\Module::getModuleURL('metarefresh/fetch.php'), + 'text' => '{metarefresh:metarefresh:frontpage_link}', + ); } diff --git a/modules/metarefresh/lib/ARP.php b/modules/metarefresh/lib/ARP.php index 52c61d4687550e235c8db187b91a8a8aa2aba762..00ce469725b061ab9b8b91ae0210d4584b977cfe 100644 --- a/modules/metarefresh/lib/ARP.php +++ b/modules/metarefresh/lib/ARP.php @@ -36,7 +36,7 @@ class ARP * @param string $attributemap_filename * @param string $prefix * @param string $suffix - */ + */ public function __construct($metadata, $attributemap_filename, $prefix, $suffix) { $this->metadata = $metadata; @@ -56,7 +56,7 @@ class ARP private function loadAttributeMap($attributemap_filename) { $config = \SimpleSAML\Configuration::getInstance(); - include($config->getPathValue('attributemap', 'attributemap/') . $attributemap_filename . '.php'); + include($config->getPathValue('attributemap', 'attributemap/').$attributemap_filename.'.php'); // Note that $attributemap is defined in the included attributemap-file! $this->attributes = $attributemap; } @@ -126,9 +126,9 @@ MSG; private function getEntryXML($entry) { $entityid = $entry['entityid']; - return ' <AttributeFilterPolicy id="' . $entityid . - '"><PolicyRequirementRule xsi:type="basic:AttributeRequesterString" value="' . $entityid . - '" />' . $this->getEntryXMLcontent($entry) . '</AttributeFilterPolicy>'; + return ' <AttributeFilterPolicy id="'.$entityid. + '"><PolicyRequirementRule xsi:type="basic:AttributeRequesterString" value="'.$entityid. + '" />'.$this->getEntryXMLcontent($entry).'</AttributeFilterPolicy>'; } /** @@ -144,7 +144,7 @@ MSG; $ret = ''; foreach ($entry['attributes'] as $a) { - $ret .= ' <AttributeRule attributeID="' . $this->getAttributeID($a) . + $ret .= ' <AttributeRule attributeID="'.$this->getAttributeID($a). '"><PermitValueRule xsi:type="basic:ANY" /></AttributeRule>'; } return $ret; diff --git a/modules/metarefresh/lib/MetaLoader.php b/modules/metarefresh/lib/MetaLoader.php index 87afecf209edc3f41821b35ee8841c0b790930a0..0c53c472e02fccc120f9eb6cf84a9a19faa7a20e 100644 --- a/modules/metarefresh/lib/MetaLoader.php +++ b/modules/metarefresh/lib/MetaLoader.php @@ -23,7 +23,6 @@ class MetaLoader 'attributeauthority-remote' ); - /** * Constructor * @@ -47,7 +46,6 @@ class MetaLoader $this->state = array(); } - /** * Get the types of entities that will be loaded. * @@ -58,7 +56,6 @@ class MetaLoader return $this->types; } - /** * Set the types of entities that will be loaded. * @@ -73,7 +70,6 @@ class MetaLoader $this->types = $types; } - /** * This function processes a SAML metadata file. * @@ -88,14 +84,14 @@ class MetaLoader // GET! try { list($data, $responseHeaders) = \SimpleSAML\Utils\HTTP::fetch($source['src'], $context, true); - } catch(\Exception $e) { - \SimpleSAML\Logger::warning('metarefresh: ' . $e->getMessage()); + } catch (\Exception $e) { + \SimpleSAML\Logger::warning('metarefresh: '.$e->getMessage()); } // We have response headers, so the request succeeded if (!isset($responseHeaders)) { // No response headers, this means the request failed in some way, so re-use old data - \SimpleSAML\Logger::debug('No response from ' . $source['src'] . ' - attempting to re-use cached metadata'); + \SimpleSAML\Logger::debug('No response from '.$source['src'].' - attempting to re-use cached metadata'); $this->addCachedMetadata($source); return; } elseif (preg_match('@^HTTP/1\.[01]\s304\s@', $responseHeaders[0])) { @@ -105,7 +101,7 @@ class MetaLoader return; } elseif (!preg_match('@^HTTP/1\.[01]\s200\s@', $responseHeaders[0])) { // Other error - \SimpleSAML\Logger::debug('Error from ' . $source['src'] . ' - attempting to re-use cached metadata'); + \SimpleSAML\Logger::debug('Error from '.$source['src'].' - attempting to re-use cached metadata'); $this->addCachedMetadata($source); return; } @@ -123,9 +119,9 @@ class MetaLoader try { $entities = $this->loadXML($data, $source); - } catch(\Exception $e) { - \SimpleSAML\Logger::debug('XML parser error when parsing ' . $source['src'] . ' - attempting to re-use cached metadata'); - \SimpleSAML\Logger::debug('XML parser returned: ' . $e->getMessage()); + } catch (\Exception $e) { + \SimpleSAML\Logger::debug('XML parser error when parsing '.$source['src'].' - attempting to re-use cached metadata'); + \SimpleSAML\Logger::debug('XML parser returned: '.$e->getMessage()); $this->addCachedMetadata($source); return; } @@ -134,21 +130,21 @@ class MetaLoader if (isset($source['blacklist'])) { if (!empty($source['blacklist']) && in_array($entity->getEntityID(), $source['blacklist'], true)) { - \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityID() . '" - blacklisted.' . "\n"); + \SimpleSAML\Logger::info('Skipping "'.$entity->getEntityID().'" - blacklisted.'."\n"); continue; } } if (isset($source['whitelist'])) { if (!empty($source['whitelist']) && !in_array($entity->getEntityID(), $source['whitelist'], true)) { - \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityID() . '" - not in the whitelist.' . "\n"); + \SimpleSAML\Logger::info('Skipping "'.$entity->getEntityID().'" - not in the whitelist.'."\n"); continue; } } if (array_key_exists('certificates', $source) && $source['certificates'] !== null) { if (!$entity->validateSignature($source['certificates'])) { - \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using certificate.' . "\n"); + \SimpleSAML\Logger::info('Skipping "'.$entity->getEntityId().'" - could not verify signature using certificate.'."\n"); continue; } } @@ -156,11 +152,11 @@ class MetaLoader if (array_key_exists('validateFingerprint', $source) && $source['validateFingerprint'] !== null) { if (!array_key_exists('certificates', $source) || $source['certificates'] == null) { if (!$entity->validateFingerprint($source['validateFingerprint'])) { - \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using fingerprint.' . "\n"); + \SimpleSAML\Logger::info('Skipping "'.$entity->getEntityId().'" - could not verify signature using fingerprint.'."\n"); continue; } } else { - \SimpleSAML\Logger::info('Skipping validation with fingerprint since option certificate is set.' . "\n"); + \SimpleSAML\Logger::info('Skipping validation with fingerprint since option certificate is set.'."\n"); } } @@ -208,11 +204,11 @@ class MetaLoader $sourceState = $this->state[$source['src']]; if (isset($sourceState['last-modified'])) { - $rawheader .= 'If-Modified-Since: ' . $sourceState['last-modified'] . "\r\n"; + $rawheader .= 'If-Modified-Since: '.$sourceState['last-modified']."\r\n"; } if (isset($sourceState['etag'])) { - $rawheader .= 'If-None-Match: ' . $sourceState['etag'] . "\r\n"; + $rawheader .= 'If-None-Match: '.$sourceState['etag']."\r\n"; } } } @@ -270,10 +266,10 @@ class MetaLoader try { $doc = \SAML2\DOMDocumentFactory::fromString($data); } catch (\Exception $e) { - throw new \Exception('Failed to read XML from ' . $source['src']); + throw new \Exception('Failed to read XML from '.$source['src']); } if ($doc->documentElement === null) { - throw new \Exception('Opened file is not an XML document: ' . $source['src']); + throw new \Exception('Opened file is not an XML document: '.$source['src']); } return \SimpleSAML\Metadata\SAMLParser::parseDescriptorsElement($doc->documentElement); } @@ -285,12 +281,12 @@ class MetaLoader public function writeState() { if ($this->changed) { - \SimpleSAML\Logger::debug('Writing: ' . $this->stateFile); + \SimpleSAML\Logger::debug('Writing: '.$this->stateFile); \SimpleSAML\Utils\System::writeFile( $this->stateFile, - "<?php\n/* This file was generated by the metarefresh module at ".$this->getTime() . ".\n". + "<?php\n/* This file was generated by the metarefresh module at ".$this->getTime().".\n". " Do not update it manually as it will get overwritten. */\n". - '$state = ' . var_export($this->state, true) . ";\n?>\n", + '$state = '.var_export($this->state, true).";\n?>\n", 0644 ); } @@ -304,19 +300,19 @@ class MetaLoader { foreach ($this->metadata as $category => $elements) { - echo '/* The following data should be added to metadata/' . $category . '.php. */' . "\n"; + echo '/* The following data should be added to metadata/'.$category.'.php. */'."\n"; foreach ($elements as $m) { $filename = $m['filename']; $entityID = $m['metadata']['entityid']; echo "\n"; - echo '/* The following metadata was generated from ' . $filename . ' on ' . $this->getTime() . '. */' . "\n"; - echo '$metadata[\'' . addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n"; + echo '/* The following metadata was generated from '.$filename.' on '.$this->getTime().'. */'."\n"; + echo '$metadata[\''.addslashes($entityID).'\'] = '.var_export($m['metadata'], true).';'."\n"; } echo "\n"; - echo '/* End of data which should be added to metadata/' . $category . '.php. */' . "\n"; + echo '/* End of data which should be added to metadata/'.$category.'.php. */'."\n"; echo "\n"; } } @@ -349,7 +345,7 @@ class MetaLoader if (!empty($this->expire)) { // If expire is already in metadata if (array_key_exists('expire', $metadata)) { - // Override metadata expire with more restrictive global config- + // Override metadata expire with more restrictive global config if ($this->expire < $metadata['expire']) { $metadata['expire'] = $this->expire; } @@ -391,7 +387,7 @@ class MetaLoader $arpxml = $arp->getXML(); - \SimpleSAML\Logger::info('Writing ARP file: ' . $arpfile . "\n"); + \SimpleSAML\Logger::info('Writing ARP file: '.$arpfile."\n"); file_put_contents($arpfile, $arpxml); } @@ -406,37 +402,37 @@ class MetaLoader } if (!file_exists($outputDir)) { - \SimpleSAML\Logger::info('Creating directory: ' . $outputDir . "\n"); + \SimpleSAML\Logger::info('Creating directory: '.$outputDir."\n"); $res = @mkdir($outputDir, 0777, true); if ($res === false) { - throw new \Exception('Error creating directory: ' . $outputDir); + throw new \Exception('Error creating directory: '.$outputDir); } } foreach ($this->types as $type) { - $filename = $outputDir . '/' . $type . '.php'; + $filename = $outputDir.'/'.$type.'.php'; if (array_key_exists($type, $this->metadata)) { $elements = $this->metadata[$type]; - \SimpleSAML\Logger::debug('Writing: ' . $filename); + \SimpleSAML\Logger::debug('Writing: '.$filename); - $content = '<?php' . "\n" . '/* This file was generated by the metarefresh module at '. $this->getTime() . "\n"; - $content .= ' Do not update it manually as it will get overwritten' . "\n" . '*/' . "\n"; + $content = '<?php'."\n".'/* This file was generated by the metarefresh module at '.$this->getTime()."\n"; + $content .= ' Do not update it manually as it will get overwritten'."\n".'*/'."\n"; foreach ($elements as $m) { $entityID = $m['metadata']['entityid']; $content .= "\n"; - $content .= '$metadata[\'' . addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n"; + $content .= '$metadata[\''.addslashes($entityID).'\'] = '.var_export($m['metadata'], true).';'."\n"; } - $content .= "\n" . '?>'; + $content .= "\n".'?>'; \SimpleSAML\Utils\System::writeFile($filename, $content, 0644); } elseif (is_file($filename)) { if (unlink($filename)) { - \SimpleSAML\Logger::debug('Deleting stale metadata file: ' . $filename); + \SimpleSAML\Logger::debug('Deleting stale metadata file: '.$filename); } else { - \SimpleSAML\Logger::warning('Could not delete stale metadata file: ' . $filename); + \SimpleSAML\Logger::warning('Could not delete stale metadata file: '.$filename); } } } @@ -454,37 +450,37 @@ class MetaLoader $metaHandler = new \SimpleSAML\Metadata\MetaDataStorageHandlerSerialize(array('directory' => $outputDir)); - /* First we add all the metadata entries to the metadata handler. */ + // First we add all the metadata entries to the metadata handler foreach ($this->metadata as $set => $elements) { foreach ($elements as $m) { $entityId = $m['metadata']['entityid']; \SimpleSAML\Logger::debug( - 'metarefresh: Add metadata entry ' . - var_export($entityId, true) . ' in set ' . var_export($set, true) . '.' + 'metarefresh: Add metadata entry '. + var_export($entityId, true).' in set '.var_export($set, true).'.' ); $metaHandler->saveMetadata($entityId, $set, $m['metadata']); } } - /* Then we delete old entries which should no longer exist. */ + // Then we delete old entries which should no longer exist $ct = time(); foreach ($metaHandler->getMetadataSets() as $set) { foreach ($metaHandler->getMetadataSet($set) as $entityId => $metadata) { if (!array_key_exists('expire', $metadata)) { \SimpleSAML\Logger::warning( - 'metarefresh: Metadata entry without expire timestamp: ' . var_export($entityId, true) . - ' in set ' . var_export($set, true) . '.' + 'metarefresh: Metadata entry without expire timestamp: '.var_export($entityId, true). + ' in set '.var_export($set, true).'.' ); continue; } if ($metadata['expire'] > $ct) { continue; } - \SimpleSAML\Logger::debug('metarefresh: ' . $entityId . ' expired ' . date('l jS \of F Y h:i:s A', $metadata['expire'])); + \SimpleSAML\Logger::debug('metarefresh: '.$entityId.' expired '.date('l jS \of F Y h:i:s A', $metadata['expire'])); \SimpleSAML\Logger::debug( - 'metarefresh: Delete expired metadata entry ' . - var_export($entityId, true) . ' in set ' . var_export($set, true) . '. (' . ($ct - $metadata['expire']) . ' sec)' + 'metarefresh: Delete expired metadata entry '. + var_export($entityId, true).' in set '.var_export($set, true).'. ('.($ct - $metadata['expire']).' sec)' ); $metaHandler->deleteMetadata($entityId, $set); } @@ -494,7 +490,7 @@ class MetaLoader private function getTime() { - /* The current date, as a string. */ + // The current date, as a string date_default_timezone_set('UTC'); return date('Y-m-d\\TH:i:s\\Z'); } diff --git a/modules/metarefresh/www/fetch.php b/modules/metarefresh/www/fetch.php index 8c3120b2d4f1b6645b233c00acb37938f9ec56ee..2a1bbc01fe715c83f4cfb1b1c63f1d57f00a3a99 100644 --- a/modules/metarefresh/www/fetch.php +++ b/modules/metarefresh/www/fetch.php @@ -5,82 +5,79 @@ $mconfig = \SimpleSAML\Configuration::getOptionalConfig('config-metarefresh.php' \SimpleSAML\Utils\Auth::requireAdmin(); -\SimpleSAML\Logger::setCaptureLog(TRUE); - +\SimpleSAML\Logger::setCaptureLog(true); $sets = $mconfig->getConfigList('sets', array()); -foreach ($sets AS $setkey => $set) { - - \SimpleSAML\Logger::info('[metarefresh]: Executing set [' . $setkey . ']'); - - try { - $expireAfter = $set->getInteger('expireAfter', NULL); - if ($expireAfter !== NULL) { - $expire = time() + $expireAfter; - } else { - $expire = NULL; - } - - $metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire); - - # Get global black/whitelists - $blacklist = $mconfig->getArray('blacklist', array()); - $whitelist = $mconfig->getArray('whitelist', array()); - - // get global type filters - $available_types = array( - 'saml20-idp-remote', - 'saml20-sp-remote', - 'shib13-idp-remote', - 'shib13-sp-remote', - 'attributeauthority-remote' - ); - $set_types = $set->getArrayize('types', $available_types); - - foreach($set->getArray('sources') AS $source) { - - // filter metadata by type of entity - if (isset($source['types'])) { - $metaloader->setTypes($source['types']); - } else { - $metaloader->setTypes($set_types); - } - - # Merge global and src specific blacklists - if(isset($source['blacklist'])) { - $source['blacklist'] = array_unique(array_merge($source['blacklist'], $blacklist)); - } else { - $source['blacklist'] = $blacklist; - } - - # Merge global and src specific whitelists - if(isset($source['whitelist'])) { - $source['whitelist'] = array_unique(array_merge($source['whitelist'], $whitelist)); - } else { - $source['whitelist'] = $whitelist; - } - - \SimpleSAML\Logger::debug('[metarefresh]: In set [' . $setkey . '] loading source [' . $source['src'] . ']'); - $metaloader->loadSource($source); - } - - $outputDir = $set->getString('outputDir'); - $outputDir = $config->resolvePath($outputDir); - - $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile'); - switch ($outputFormat) { - case 'flatfile': - $metaloader->writeMetadataFiles($outputDir); - break; - case 'serialize': - $metaloader->writeMetadataSerialize($outputDir); - break; - } - } catch (\Exception $e) { - $e = \SimpleSAML\Error\Exception::fromException($e); - $e->logWarning(); - } +foreach ($sets as $setkey => $set) { + \SimpleSAML\Logger::info('[metarefresh]: Executing set ['.$setkey.']'); + + try { + $expireAfter = $set->getInteger('expireAfter', null); + if ($expireAfter !== null) { + $expire = time() + $expireAfter; + } else { + $expire = null; + } + $metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire); + + # Get global black/whitelists + $blacklist = $mconfig->getArray('blacklist', array()); + $whitelist = $mconfig->getArray('whitelist', array()); + + // get global type filters + $available_types = array( + 'saml20-idp-remote', + 'saml20-sp-remote', + 'shib13-idp-remote', + 'shib13-sp-remote', + 'attributeauthority-remote' + ); + $set_types = $set->getArrayize('types', $available_types); + + foreach ($set->getArray('sources') as $source) { + + // filter metadata by type of entity + if (isset($source['types'])) { + $metaloader->setTypes($source['types']); + } else { + $metaloader->setTypes($set_types); + } + + # Merge global and src specific blacklists + if (isset($source['blacklist'])) { + $source['blacklist'] = array_unique(array_merge($source['blacklist'], $blacklist)); + } else { + $source['blacklist'] = $blacklist; + } + + # Merge global and src specific whitelists + if (isset($source['whitelist'])) { + $source['whitelist'] = array_unique(array_merge($source['whitelist'], $whitelist)); + } else { + $source['whitelist'] = $whitelist; + } + + \SimpleSAML\Logger::debug('[metarefresh]: In set ['.$setkey.'] loading source ['.$source['src'].']'); + $metaloader->loadSource($source); + } + + $outputDir = $set->getString('outputDir'); + $outputDir = $config->resolvePath($outputDir); + + $outputFormat = $set->getValueValidate('outputFormat', array('flatfile', 'serialize'), 'flatfile'); + switch ($outputFormat) { + case 'flatfile': + $metaloader->writeMetadataFiles($outputDir); + break; + case 'serialize': + $metaloader->writeMetadataSerialize($outputDir); + break; + } + } catch (\Exception $e) { + $e = \SimpleSAML\Error\Exception::fromException($e); + $e->logWarning(); + } } $logentries = \SimpleSAML\Logger::getCapturedLog(); diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php index 6714560e281eeff71158900e27e2f6d0b52215f6..ae3682f697b90dd6601047db89792d2fe18ff869 100644 --- a/modules/multiauth/lib/Auth/Source/MultiAuth.php +++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php @@ -12,229 +12,234 @@ namespace SimpleSAML\Module\multiauth\Auth\Source; class MultiAuth extends \SimpleSAML\Auth\Source { - /** - * The key of the AuthId field in the state. - */ - const AUTHID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.AuthId'; - - /** - * The string used to identify our states. - */ - const STAGEID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.StageId'; - - /** - * The key where the sources is saved in the state. - */ - const SOURCESID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.SourceId'; - - /** - * The key where the selected source is saved in the session. - */ - const SESSION_SOURCE = 'multiauth:selectedSource'; - - /** - * Array of sources we let the user chooses among. - */ - private $sources; - - /** - * Constructor for this authentication source. - * - * @param array $info Information about this authentication source. - * @param array $config Configuration. - */ - public function __construct($info, $config) { - assert(is_array($info)); - assert(is_array($config)); - - // Call the parent constructor first, as required by the interface - parent::__construct($info, $config); - - if (!array_key_exists('sources', $config)) { - throw new \Exception('The required "sources" config option was not found'); - } - - $globalConfiguration = \SimpleSAML\Configuration::getInstance(); - $defaultLanguage = $globalConfiguration->getString('language.default', 'en'); - $authsources = \SimpleSAML\Configuration::getConfig('authsources.php'); - $this->sources = array(); - foreach($config['sources'] as $source => $info) { - - if (is_int($source)) { // Backwards compatibility - $source = $info; - $info = array(); - } - - if (array_key_exists('text', $info)) { - $text = $info['text']; - } else { - $text = array($defaultLanguage => $source); - } - - if (array_key_exists('help', $info)) { - $help = $info['help']; - } - if (array_key_exists('css-class', $info)) { - $css_class = $info['css-class']; - } else { - // Use the authtype as the css class - $authconfig = $authsources->getArray($source, NULL); - if (!array_key_exists(0, $authconfig) || !is_string($authconfig[0])) { - $css_class = ""; - } else { - $css_class = str_replace(":", "-", $authconfig[0]); - } - } - - $this->sources[] = array( - 'source' => $source, - 'text' => $text, - 'help' => $help, - 'css_class' => $css_class, - ); - } - } - - /** - * Prompt the user with a list of authentication sources. - * - * This method saves the information about the configured sources, - * and redirects to a page where the user must select one of these - * authentication sources. - * - * This method never return. The authentication process is finished - * in the delegateAuthentication method. - * - * @param array &$state Information about the current authentication. - */ - public function authenticate(&$state) { - assert(is_array($state)); - - $state[self::AUTHID] = $this->authId; - $state[self::SOURCESID] = $this->sources; - - /* Save the $state array, so that we can restore if after a redirect */ - $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID); - - /* Redirect to the select source page. We include the identifier of the - saved state array as a parameter to the login form */ - $url = \SimpleSAML\Module::getModuleURL('multiauth/selectsource.php'); - $params = array('AuthState' => $id); - - // Allowes the user to specify the auth souce to be used - if(isset($_GET['source'])) { - $params['source'] = $_GET['source']; - } - - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); - - /* The previous function never returns, so this code is never - executed */ - assert(false); - } - - /** - * Delegate authentication. - * - * This method is called once the user has choosen one authentication - * source. It saves the selected authentication source in the session - * to be able to logout properly. Then it calls the authenticate method - * on such selected authentication source. - * - * @param string $authId Selected authentication source - * @param array $state Information about the current authentication. - */ - public static function delegateAuthentication($authId, $state) { - assert(is_string($authId)); - assert(is_array($state)); - - $as = \SimpleSAML\Auth\Source::getById($authId); - $valid_sources = array_map( - function($src) { - return $src['source']; - }, - $state[self::SOURCESID] + /** + * The key of the AuthId field in the state. + */ + const AUTHID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.AuthId'; + + /** + * The string used to identify our states. + */ + const STAGEID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.StageId'; + + /** + * The key where the sources is saved in the state. + */ + const SOURCESID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.SourceId'; + + /** + * The key where the selected source is saved in the session. + */ + const SESSION_SOURCE = 'multiauth:selectedSource'; + + /** + * Array of sources we let the user chooses among. + */ + private $sources; + + /** + * Constructor for this authentication source. + * + * @param array $info Information about this authentication source. + * @param array $config Configuration. + */ + public function __construct($info, $config) + { + assert(is_array($info)); + assert(is_array($config)); + + // Call the parent constructor first, as required by the interface + parent::__construct($info, $config); + + if (!array_key_exists('sources', $config)) { + throw new \Exception('The required "sources" config option was not found'); + } + + $globalConfiguration = \SimpleSAML\Configuration::getInstance(); + $defaultLanguage = $globalConfiguration->getString('language.default', 'en'); + $authsources = \SimpleSAML\Configuration::getConfig('authsources.php'); + $this->sources = array(); + foreach ($config['sources'] as $source => $info) { + if (is_int($source)) { + // Backwards compatibility + $source = $info; + $info = array(); + } + + if (array_key_exists('text', $info)) { + $text = $info['text']; + } else { + $text = array($defaultLanguage => $source); + } + + if (array_key_exists('help', $info)) { + $help = $info['help']; + } + if (array_key_exists('css-class', $info)) { + $css_class = $info['css-class']; + } else { + // Use the authtype as the css class + $authconfig = $authsources->getArray($source, null); + if (!array_key_exists(0, $authconfig) || !is_string($authconfig[0])) { + $css_class = ""; + } else { + $css_class = str_replace(":", "-", $authconfig[0]); + } + } + + $this->sources[] = array( + 'source' => $source, + 'text' => $text, + 'help' => $help, + 'css_class' => $css_class, + ); + } + } + + /** + * Prompt the user with a list of authentication sources. + * + * This method saves the information about the configured sources, + * and redirects to a page where the user must select one of these + * authentication sources. + * + * This method never return. The authentication process is finished + * in the delegateAuthentication method. + * + * @param array &$state Information about the current authentication. + */ + public function authenticate(&$state) + { + assert(is_array($state)); + + $state[self::AUTHID] = $this->authId; + $state[self::SOURCESID] = $this->sources; + + // Save the $state array, so that we can restore if after a redirect + $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID); + + /* Redirect to the select source page. We include the identifier of the + * saved state array as a parameter to the login form + */ + $url = \SimpleSAML\Module::getModuleURL('multiauth/selectsource.php'); + $params = array('AuthState' => $id); + + // Allowes the user to specify the auth souce to be used + if (isset($_GET['source'])) { + $params['source'] = $_GET['source']; + } + + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params); + + // The previous function never returns, so this code is never executed + assert(false); + } + + /** + * Delegate authentication. + * + * This method is called once the user has choosen one authentication + * source. It saves the selected authentication source in the session + * to be able to logout properly. Then it calls the authenticate method + * on such selected authentication source. + * + * @param string $authId Selected authentication source + * @param array $state Information about the current authentication. + */ + public static function delegateAuthentication($authId, $state) + { + assert(is_string($authId)); + assert(is_array($state)); + + $as = \SimpleSAML\Auth\Source::getById($authId); + $valid_sources = array_map( + function($src) { + return $src['source']; + }, + $state[self::SOURCESID] ); - if ($as === NULL || !in_array($authId, $valid_sources, true)) { - throw new \Exception('Invalid authentication source: ' . $authId); - } - - /* Save the selected authentication source for the logout process. */ - $session = \SimpleSAML\Session::getSessionFromRequest(); - $session->setData(self::SESSION_SOURCE, $state[self::AUTHID], $authId, \SimpleSAML\Session::DATA_TIMEOUT_SESSION_END); - - try { - $as->authenticate($state); - } catch (\SimpleSAML\Error\Exception $e) { - \SimpleSAML\Auth\State::throwException($state, $e); - } catch (\Exception $e) { - $e = new \SimpleSAML\Error\UnserializableException($e); - \SimpleSAML\Auth\State::throwException($state, $e); - } - \SimpleSAML\Auth\Source::completeAuth($state); - } - - /** - * Log out from this authentication source. - * - * This method retrieves the authentication source used for this - * session and then call the logout method on it. - * - * @param array &$state Information about the current logout operation. - */ - public function logout(&$state) { - assert(is_array($state)); - - /* Get the source that was used to authenticate */ - $session = \SimpleSAML\Session::getSessionFromRequest(); - $authId = $session->getData(self::SESSION_SOURCE, $this->authId); - - $source = \SimpleSAML\Auth\Source::getById($authId); - if ($source === NULL) { - throw new \Exception('Invalid authentication source during logout: ' . $source); - } - /* Then, do the logout on it */ - $source->logout($state); - } - - /** - * Set the previous authentication source. - * - * This method remembers the authentication source that the user selected - * by storing its name in a cookie. - * - * @param string $source Name of the authentication source the user selected. - */ - public function setPreviousSource($source) { - assert(is_string($source)); - - $cookieName = 'multiauth_source_' . $this->authId; - - $config = \SimpleSAML\Configuration::getInstance(); - $params = array( - /* We save the cookies for 90 days. */ - 'lifetime' => (60*60*24*90), - /* The base path for cookies. - This should be the installation directory for SimpleSAMLphp. */ - 'path' => $config->getBasePath(), - 'httponly' => FALSE, - ); - - \SimpleSAML\Utils\HTTP::setCookie($cookieName, $source, $params, FALSE); - } - - /** - * Get the previous authentication source. - * - * This method retrieves the authentication source that the user selected - * last time or NULL if this is the first time or remembering is disabled. - */ - public function getPreviousSource() { - $cookieName = 'multiauth_source_' . $this->authId; - if(array_key_exists($cookieName, $_COOKIE)) { - return $_COOKIE[$cookieName]; - } else { - return NULL; - } - } + if ($as === null || !in_array($authId, $valid_sources, true)) { + throw new \Exception('Invalid authentication source: '.$authId); + } + + // Save the selected authentication source for the logout process. + $session = \SimpleSAML\Session::getSessionFromRequest(); + $session->setData(self::SESSION_SOURCE, $state[self::AUTHID], $authId, \SimpleSAML\Session::DATA_TIMEOUT_SESSION_END); + + try { + $as->authenticate($state); + } catch (\SimpleSAML\Error\Exception $e) { + \SimpleSAML\Auth\State::throwException($state, $e); + } catch (\Exception $e) { + $e = new \SimpleSAML\Error\UnserializableException($e); + \SimpleSAML\Auth\State::throwException($state, $e); + } + \SimpleSAML\Auth\Source::completeAuth($state); + } + + /** + * Log out from this authentication source. + * + * This method retrieves the authentication source used for this + * session and then call the logout method on it. + * + * @param array &$state Information about the current logout operation. + */ + public function logout(&$state) + { + assert(is_array($state)); + + // Get the source that was used to authenticate + $session = \SimpleSAML\Session::getSessionFromRequest(); + $authId = $session->getData(self::SESSION_SOURCE, $this->authId); + + $source = \SimpleSAML\Auth\Source::getById($authId); + if ($source === null) { + throw new \Exception('Invalid authentication source during logout: '.$source); + } + // Then, do the logout on it + $source->logout($state); + } + + /** + * Set the previous authentication source. + * + * This method remembers the authentication source that the user selected + * by storing its name in a cookie. + * + * @param string $source Name of the authentication source the user selected. + */ + public function setPreviousSource($source) + { + assert(is_string($source)); + + $cookieName = 'multiauth_source_'.$this->authId; + + $config = \SimpleSAML\Configuration::getInstance(); + $params = array( + // We save the cookies for 90 days + 'lifetime' => 7776000, //60*60*24*90 + // The base path for cookies. This should be the installation directory for SimpleSAMLphp. + 'path' => $config->getBasePath(), + 'httponly' => false, + ); + + \SimpleSAML\Utils\HTTP::setCookie($cookieName, $source, $params, false); + } + + /** + * Get the previous authentication source. + * + * This method retrieves the authentication source that the user selected + * last time or NULL if this is the first time or remembering is disabled. + */ + public function getPreviousSource() + { + $cookieName = 'multiauth_source_'.$this->authId; + if (array_key_exists($cookieName, $_COOKIE)) { + return $_COOKIE[$cookieName]; + } else { + return null; + } + } } diff --git a/modules/multiauth/templates/selectsource.php b/modules/multiauth/templates/selectsource.php index f5eaba07e742a959fa8ddcba53196eb45185a7cf..294fcbc0c53c703862a870624327a82bba812f3d 100644 --- a/modules/multiauth/templates/selectsource.php +++ b/modules/multiauth/templates/selectsource.php @@ -1,6 +1,5 @@ <?php $this->data['header'] = $this->t('{multiauth:multiauth:select_source_header}'); - $this->includeAtTemplateBase('includes/header.php'); ?> @@ -9,23 +8,23 @@ $this->includeAtTemplateBase('includes/header.php'); <p><?php echo $this->t('{multiauth:multiauth:select_source_text}'); ?></p> <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get"> -<input type="hidden" name="AuthState" value="<?php echo htmlspecialchars($this->data['authstate']); ?>" /> -<ul> + <input type="hidden" name="AuthState" value="<?php echo htmlspecialchars($this->data['authstate']); ?>" /> + <ul> <?php -foreach($this->data['sources'] as $source) { - echo '<li class="' . htmlspecialchars($source['css_class']) . ' authsource">'; - if ($source['source'] === $this->data['preferred']) { - $autofocus = ' autofocus="autofocus"'; - } else { - $autofocus = ''; - } - $name = 'src-' . base64_encode($source['source']); - echo '<input type="submit" name="' . htmlspecialchars($name) . '"' . $autofocus . ' ' . - 'id="button-' . htmlspecialchars($source['source']) . '" ' . - 'value="' . htmlspecialchars($this->t($source['text'])) . '" />'; - echo '</li>'; +foreach ($this->data['sources'] as $source) { + echo '<li class="'.htmlspecialchars($source['css_class']).' authsource">'; + if ($source['source'] === $this->data['preferred']) { + $autofocus = ' autofocus="autofocus"'; + } else { + $autofocus = ''; + } + $name = 'src-'.base64_encode($source['source']); + echo '<input type="submit" name="'.htmlspecialchars($name).'"'.$autofocus.' '. + 'id="button-'.htmlspecialchars($source['source']).'" '. + 'value="'.htmlspecialchars($this->t($source['text'])).'" />'; + echo '</li>'; } ?> -</ul> + </ul> </form> <?php $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/multiauth/www/selectsource.php b/modules/multiauth/www/selectsource.php index 1a8d141f94ca4f3824375c9795501f69bcf3740e..70c889d8a5646912ea17c0e2ebfcc647bb347167 100644 --- a/modules/multiauth/www/selectsource.php +++ b/modules/multiauth/www/selectsource.php @@ -54,10 +54,10 @@ $defaultLanguage = $globalConfig->getString('language.default', 'en'); $language = $t->getTranslator()->getLanguage()->getLanguage(); $sources = $state[\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth::SOURCESID]; -foreach ($sources as $key => $source){ +foreach ($sources as $key => $source) { $sources[$key]['source64'] = base64_encode($sources[$key]['source']); - $sources[$key]['text'] = (isSet($sources[$key]['text'][$language]) ? $sources[$key]['text'][$language] : $sources[$key]['text'][$defaultLanguage]); - $sources[$key]['help'] = (isSet($sources[$key]['help'][$language]) ? $sources[$key]['help'][$language] : $sources[$key]['help'][$defaultLanguage]); + $sources[$key]['text'] = (isset($sources[$key]['text'][$language]) ? $sources[$key]['text'][$language] : $sources[$key]['text'][$defaultLanguage]); + $sources[$key]['help'] = (isset($sources[$key]['help'][$language]) ? $sources[$key]['help'][$language] : $sources[$key]['help'][$defaultLanguage]); } $t->data['authstate'] = $authStateId; diff --git a/modules/negotiate/www/disable.php b/modules/negotiate/www/disable.php index fafe79a067aebf3aa2797adb4f60f6b3c348b74d..1832f4a3238e307687eff4215b5aca4b8224d651 100644 --- a/modules/negotiate/www/disable.php +++ b/modules/negotiate/www/disable.php @@ -1,23 +1,20 @@ <?php - /** - * - * * @author Mathias Meisfjordskar, University of Oslo. * <mathias.meisfjordskar@usit.uio.no> * @package SimpleSAMLphp */ $params = array( - 'expire' => (mktime(0,0,0,1,1,2038)), - 'secure' => FALSE, - 'httponly' => TRUE, + 'expire' => (mktime(0, 0, 0, 1, 1, 2038)), + 'secure' => false, + 'httponly' => true, ); -\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', 'True', $params, FALSE); +\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', 'True', $params, false); $globalConfig = \SimpleSAML\Configuration::getInstance(); $session = \SimpleSAML\Session::getSessionFromRequest(); -$session->setData('negotiate:disable', 'session', FALSE, 24*60*60); +$session->setData('negotiate:disable', 'session', false, 86400); //24*60*60=86400 $t = new \SimpleSAML\XHTML\Template($globalConfig, 'negotiate:disable.php'); $t->data['url'] = \SimpleSAML\Module::getModuleURL('negotiate/enable.php'); $t->show(); diff --git a/modules/negotiate/www/enable.php b/modules/negotiate/www/enable.php index 293b7b97c19882dfcac12258dc2f4fa03ea0bec9..891eac6d738a3a365411368e389274a267c2b40b 100644 --- a/modules/negotiate/www/enable.php +++ b/modules/negotiate/www/enable.php @@ -1,22 +1,19 @@ <?php - /** - * - * * @author Mathias Meisfjordskar, University of Oslo. * <mathias.meisfjordskar@usit.uio.no> * @package SimpleSAMLphp */ $params = array( - 'secure' => FALSE, - 'httponly' => TRUE, + 'secure' => false, + 'httponly' => true, ); -\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', NULL, $params, FALSE); +\SimpleSAML\Utils\HTTP::setCookie('NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT', null, $params, false); $globalConfig = \SimpleSAML\Configuration::getInstance(); $session = \SimpleSAML\Session::getSessionFromRequest(); -$session->setData('negotiate:disable', 'session', FALSE, 24*60*60); +$session->setData('negotiate:disable', 'session', false, 86400); // 24*60*60=86400 $t = new \SimpleSAML\XHTML\Template($globalConfig, 'negotiate:enable.php'); $t->data['url'] = \SimpleSAML\Module::getModuleURL('negotiate/disable.php'); $t->show(); diff --git a/modules/negotiate/www/retry.php b/modules/negotiate/www/retry.php index 8378714f71d86a964da8c64d92a9322987ba88ec..390e712e42b339774fe719f29c5c658e2833522b 100644 --- a/modules/negotiate/www/retry.php +++ b/modules/negotiate/www/retry.php @@ -17,11 +17,11 @@ $idpmeta = $metadata->getMetaData($idpid, 'saml20-idp-hosted'); if (isset($idpmeta['auth'])) { $source = \SimpleSAML\Auth\Source::getById($idpmeta['auth']); if ($source === null) { - throw new \SimpleSAML\Error\BadRequest('Invalid AuthId "' . $idpmeta['auth'] . '" - not found.'); + throw new \SimpleSAML\Error\BadRequest('Invalid AuthId "'.$idpmeta['auth'].'" - not found.'); } $session = \SimpleSAML\Session::getSessionFromRequest(); - $session->setData('negotiate:disable', 'session', FALSE, 24*60*60); + $session->setData('negotiate:disable', 'session', false, 86400); //24*60*60=86400 \SimpleSAML\Logger::debug('Negotiate(retry) - session enabled, retrying.'); $source->authenticate($state); assert(false); diff --git a/modules/oauth/lib/Consumer.php b/modules/oauth/lib/Consumer.php index f655368ff6f4c368356856753c7b4162e4b5acd7..43642f49ffef0b41d4634b82341054a74bd599ac 100644 --- a/modules/oauth/lib/Consumer.php +++ b/modules/oauth/lib/Consumer.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\oauth; -require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php'); +require_once(dirname(dirname(__FILE__)).'/libextinc/OAuth.php'); /** * OAuth Consumer @@ -23,7 +23,9 @@ class Consumer } // Used only to load the libextinc library early - public static function dummy() {} + public static function dummy() + { + } public static function getOAuthError($hrh) { @@ -64,14 +66,14 @@ class Consumer $statuscode = $matches[1]; } - $error = $context . ' [statuscode: ' . $statuscode . ']: '; + $error = $context.' [statuscode: '.$statuscode.']: '; $oautherror = self::getOAuthError($http_response_header); if (!empty($oautherror)) { $error .= $oautherror; } - throw new \Exception($error . ':' . $url); + throw new \Exception($error.':'.$url); } // Fall back to return response, if could not reckognize HTTP header. Should not happen. return $response; @@ -90,7 +92,7 @@ class Consumer parse_str($response_req, $responseParsed); if (array_key_exists('error', $responseParsed)) { - throw new \Exception('Error getting request token: ' . $responseParsed['error']); + throw new \Exception('Error getting request token: '.$responseParsed['error']); } $requestToken = $responseParsed['oauth_token']; @@ -124,12 +126,12 @@ class Consumer throw new \Exception('Error contacting request_token endpoint on the OAuth Provider'); } - \SimpleSAML\Logger::debug('oauth: Reponse to get access token: '. $response_acc); + \SimpleSAML\Logger::debug('oauth: Reponse to get access token: '.$response_acc); parse_str($response_acc, $accessResponseParsed); if (array_key_exists('error', $accessResponseParsed)) { - throw new \Exception('Error getting request token: ' . $accessResponseParsed['error']); + throw new \Exception('Error getting request token: '.$accessResponseParsed['error']); } $accessToken = $accessResponseParsed['oauth_token']; @@ -160,7 +162,7 @@ class Consumer try { $response = \SimpleSAML\Utils\HTTP::fetch($url, $opts); } catch (\SimpleSAML\Error\Exception $e) { - throw new \SimpleSAML\Error\Exception('Failed to push definition file to ' . $url); + throw new \SimpleSAML\Error\Exception('Failed to push definition file to '.$url); } return $response; } diff --git a/modules/oauth/lib/OAuthServer.php b/modules/oauth/lib/OAuthServer.php index 30087c6da5fb3e6be1dedd6d9bcee197905ca0c5..5114fff1ff0ddca40b849e6cde55a75a8377c471 100644 --- a/modules/oauth/lib/OAuthServer.php +++ b/modules/oauth/lib/OAuthServer.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\oauth; -require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php'); +require_once(dirname(dirname(__FILE__)).'/libextinc/OAuth.php'); /** * OAuth Provider implementation.. diff --git a/modules/oauth/lib/OAuthStore.php b/modules/oauth/lib/OAuthStore.php index 4b7bd9a7c0906f362280b7a66254f3c582c319af..5469dab2d3bfa0d114fceddf926ee49ad4666bf2 100644 --- a/modules/oauth/lib/OAuthStore.php +++ b/modules/oauth/lib/OAuthStore.php @@ -2,7 +2,7 @@ namespace SimpleSAML\Module\oauth; -require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php'); +require_once(dirname(dirname(__FILE__)).'/libextinc/OAuth.php'); /** * OAuth Store @@ -68,7 +68,7 @@ class OAuthStore extends \OAuthDataStore $verifier = \SimpleSAML\Utils\Random::generateID(); $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array("oauth_verifier"=>$verifier)); - $this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 60*30)); + $this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 1800)); //60*30=1800 return array($url, $verifier); } @@ -83,20 +83,20 @@ class OAuthStore extends \OAuthDataStore */ public function isAuthorized($requestToken, $verifier = '') { - \SimpleSAML\Logger::info('OAuth isAuthorized(' . $requestToken . ')'); + \SimpleSAML\Logger::info('OAuth isAuthorized('.$requestToken.')'); return $this->store->exists('authorized', $requestToken, $verifier); } public function getAuthorizedData($token, $verifier = '') { - \SimpleSAML\Logger::info('OAuth getAuthorizedData(' . $token . ')'); + \SimpleSAML\Logger::info('OAuth getAuthorizedData('.$token.')'); $data = $this->store->get('authorized', $token, $verifier); return $data['value']; } public function moveAuthorizedData($requestToken, $verifier, $accessTokenKey) { - \SimpleSAML\Logger::info('OAuth moveAuthorizedData(' . $requestToken . ', ' . $accessTokenKey . ')'); + \SimpleSAML\Logger::info('OAuth moveAuthorizedData('.$requestToken.', '.$accessTokenKey.')'); // Retrieve authorizedData from authorized.requestToken (with provider verifier) $authorizedData = $this->getAuthorizedData($requestToken, $verifier); @@ -106,12 +106,12 @@ class OAuthStore extends \OAuthDataStore // Add accesstoken with authorizedData to authorized store (with empty verifier) // accessTokenKey+consumer => accessToken is already registered in 'access'-table - $this->store->set('authorized', $accessTokenKey, '', $authorizedData, $this->config->getValue('accessTokenDuration', 60*60*24)); + $this->store->set('authorized', $accessTokenKey, '', $authorizedData, $this->config->getValue('accessTokenDuration', 86400)); //60*60*24=86400 } public function lookup_consumer($consumer_key) { - \SimpleSAML\Logger::info('OAuth lookup_consumer(' . $consumer_key . ')'); + \SimpleSAML\Logger::info('OAuth lookup_consumer('.$consumer_key.')'); if (!$this->store->exists('consumers', $consumer_key, '')) { return null; } @@ -131,7 +131,7 @@ class OAuthStore extends \OAuthDataStore public function lookup_token($consumer, $tokenType = 'default', $token) { - \SimpleSAML\Logger::info('OAuth lookup_token(' . $consumer->key . ', ' . $tokenType. ',' . $token . ')'); + \SimpleSAML\Logger::info('OAuth lookup_token('.$consumer->key.', '.$tokenType.','.$token.')'); $data = $this->store->get($tokenType, $token, $consumer->key); if ($data == null) { throw new \Exception('Could not find token'); @@ -141,28 +141,28 @@ class OAuthStore extends \OAuthDataStore public function lookup_nonce($consumer, $token, $nonce, $timestamp) { - \SimpleSAML\Logger::info('OAuth lookup_nonce(' . $consumer . ', ' . $token. ',' . $nonce . ')'); + \SimpleSAML\Logger::info('OAuth lookup_nonce('.$consumer.', '.$token.','.$nonce.')'); if ($this->store->exists('nonce', $nonce, $consumer->key)) { return true; } - $this->store->set('nonce', $nonce, $consumer->key, true, $this->config->getValue('nonceCache', 60*60*24*14)); + $this->store->set('nonce', $nonce, $consumer->key, true, $this->config->getValue('nonceCache', 1209600)); //60*60*24*14=1209600 return false; } public function new_request_token($consumer, $callback = null, $version = null) { - \SimpleSAML\Logger::info('OAuth new_request_token(' . $consumer . ')'); + \SimpleSAML\Logger::info('OAuth new_request_token('.$consumer.')'); - $lifetime = $this->config->getValue('requestTokenDuration', 60*30); + $lifetime = $this->config->getValue('requestTokenDuration', 1800); //60*30 $token = new \OAuthToken(\SimpleSAML\Utils\Random::generateID(), \SimpleSAML\Utils\Random::generateID()); - $token->callback = $callback; // OAuth1.0-RevA + $token->callback = $callback; // OAuth1.0-RevA $this->store->set('request', $token->key, $consumer->key, $token, $lifetime); // also store in requestToken->key => array('callback'=>CallbackURL, 'version'=>oauth_version $request_attributes = array( 'callback' => $callback, - 'version' => ($version?$version:$this->defaultversion), + 'version' => ($version ? $version : $this->defaultversion), 'consumerKey' => $consumer->key, ); $this->store->set('requesttorequest', $token->key, '', $request_attributes, $lifetime); @@ -175,9 +175,9 @@ class OAuthStore extends \OAuthDataStore public function new_access_token($requestToken, $consumer, $verifier = null) { - \SimpleSAML\Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')'); + \SimpleSAML\Logger::info('OAuth new_access_token('.$requestToken.','.$consumer.')'); $accesstoken = new \OAuthToken(\SimpleSAML\Utils\Random::generateID(), \SimpleSAML\Utils\Random::generateID()); - $this->store->set('access', $accesstoken->key, $consumer->key, $accesstoken, $this->config->getValue('accessTokenDuration', 60*60*24) ); + $this->store->set('access', $accesstoken->key, $consumer->key, $accesstoken, $this->config->getValue('accessTokenDuration', 86400)); //60*60*24=86400 return $accesstoken; } @@ -188,7 +188,7 @@ class OAuthStore extends \OAuthDataStore */ public function lookup_consumer_by_requestToken($requestTokenKey) { - \SimpleSAML\Logger::info('OAuth lookup_consumer_by_requestToken(' . $requestTokenKey . ')'); + \SimpleSAML\Logger::info('OAuth lookup_consumer_by_requestToken('.$requestTokenKey.')'); if (!$this->store->exists('requesttorequest', $requestTokenKey, '')) { return null; } diff --git a/modules/oauth/templates/registry.list.php b/modules/oauth/templates/registry.list.php index 28d64e38ee539f028a385b8a94136db4d92e1f86..e17329e52467e6c5da9271872b6ef5164b7dcab4 100644 --- a/modules/oauth/templates/registry.list.php +++ b/modules/oauth/templates/registry.list.php @@ -1,7 +1,7 @@ <?php +$this->data['jquery'] = array('core' => true, 'ui' => true, 'css' => true); +$this->data['head'] = '<link rel="stylesheet" type="text/css" href="/'.$this->data['baseurlpath'].'module.php/oauth/resources/style.css" />'."\n"; -$this->data['jquery'] = array('core' => TRUE, 'ui' => TRUE, 'css' => TRUE); -$this->data['head'] = '<link rel="stylesheet" type="text/css" href="/' . $this->data['baseurlpath'] . 'module.php/oauth/resources/style.css" />' . "\n"; $this->includeAtTemplateBase('includes/header.php'); diff --git a/modules/oauth/www/getUserInfo.php b/modules/oauth/www/getUserInfo.php index e68808add1ecd8158d2be9726a3f8046b1bd2e55..d793ed97345b2131f77f69495fe027c536630d35 100644 --- a/modules/oauth/www/getUserInfo.php +++ b/modules/oauth/www/getUserInfo.php @@ -1,6 +1,6 @@ <?php -require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php'); +require_once(dirname(dirname(__FILE__)).'/libextinc/OAuth.php'); $oauthconfig = \SimpleSAML\Configuration::getConfig('module_oauth.php'); diff --git a/modules/oauth/www/registry.edit.php b/modules/oauth/www/registry.edit.php index 45d21cf685fa63385a223df147a1f435f268e402..053f7737f5096a972c4c2cc8fecd5f08aedb6431 100644 --- a/modules/oauth/www/registry.edit.php +++ b/modules/oauth/www/registry.edit.php @@ -7,7 +7,7 @@ $oauthconfig = \SimpleSAML\Configuration::getOptionalConfig('module_oauth.php'); $store = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('oauth'); -$authsource = "admin"; // force admin to authenticate as registry maintainer +$authsource = "admin"; // force admin to authenticate as registry maintainer $useridattr = $oauthconfig->getValue('useridattr', 'user'); if ($session->isValid($authsource)) { diff --git a/modules/portal/config-templates/module_portal.php b/modules/portal/config-templates/module_portal.php index 8bba3c350178a57550db8e0f1329542d8b0d18b5..e390ce25052b7934265427d374f532bc93b8d612 100644 --- a/modules/portal/config-templates/module_portal.php +++ b/modules/portal/config-templates/module_portal.php @@ -3,11 +3,9 @@ * Configuration for the module portal. */ -$config = array ( - - 'pagesets' => array( - array('frontpage_welcome', 'frontpage_config', 'frontpage_auth', 'frontpage_federation'), - array('sanitycheck', 'statistics'), - ), - +$config = array( + 'pagesets' => array( + array('frontpage_welcome', 'frontpage_config', 'frontpage_auth', 'frontpage_federation'), + array('sanitycheck', 'statistics'), + ), ); diff --git a/modules/portal/hooks/hook_htmlinject.php b/modules/portal/hooks/hook_htmlinject.php index c4c060cbdde752bd230a230411d0712f7ff6a6ad..699837c0551a77df3b56b810f610d6b63436c454 100644 --- a/modules/portal/hooks/hook_htmlinject.php +++ b/modules/portal/hooks/hook_htmlinject.php @@ -5,39 +5,41 @@ * * @param array &$hookinfo hookinfo */ -function portal_hook_htmlinject(&$hookinfo) { - assert(is_array($hookinfo)); - assert(array_key_exists('pre', $hookinfo)); - assert(array_key_exists('post', $hookinfo)); - assert(array_key_exists('page', $hookinfo)); - - $links = array('links' => array()); - \SimpleSAML\Module::callHooks('frontpage', $links); - - $portalConfig = \SimpleSAML\Configuration::getOptionalConfig('module_portal.php'); - - $allLinks = array(); - foreach($links AS $ls) { - $allLinks = array_merge($allLinks, $ls); - } - - $pagesets = $portalConfig->getValue('pagesets', array( - array('frontpage_welcome', 'frontpage_config', 'frontpage_auth', 'frontpage_federation'), - )); - \SimpleSAML\Module::callHooks('portalextras', $pagesets); - $portal = new \SimpleSAML\Module\portal\Portal($allLinks, $pagesets); - - if (!$portal->isPortalized($hookinfo['page'])) return; - - // Include jquery UI CSS files in header - $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']) . - '<div id="portalcontent" class="ui-tabs-panel ui-widget-content ui-corner-bottom">'; - - // Footer - $hookinfo['post'][] = '</div></div>'; - +function portal_hook_htmlinject(&$hookinfo) +{ + assert(is_array($hookinfo)); + assert(array_key_exists('pre', $hookinfo)); + assert(array_key_exists('post', $hookinfo)); + assert(array_key_exists('page', $hookinfo)); + + $links = array('links' => array()); + \SimpleSAML\Module::callHooks('frontpage', $links); + + $portalConfig = \SimpleSAML\Configuration::getOptionalConfig('module_portal.php'); + + $allLinks = array(); + foreach ($links as $ls) { + $allLinks = array_merge($allLinks, $ls); + } + + $pagesets = $portalConfig->getValue('pagesets', array( + array('frontpage_welcome', 'frontpage_config', 'frontpage_auth', 'frontpage_federation'), + )); + \SimpleSAML\Module::callHooks('portalextras', $pagesets); + $portal = new \SimpleSAML\Module\portal\Portal($allLinks, $pagesets); + + if (!$portal->isPortalized($hookinfo['page'])) { + return; + } + + // Include jquery UI CSS files in header + $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']). + '<div id="portalcontent" class="ui-tabs-panel ui-widget-content ui-corner-bottom">'; + + // Footer + $hookinfo['post'][] = '</div></div>'; } diff --git a/modules/portal/lib/Portal.php b/modules/portal/lib/Portal.php index fd4e909cbad64253b20975c308de48a6b5f98a57..52d722c112f7f76929b34bf87a903d8e39283b9b 100644 --- a/modules/portal/lib/Portal.php +++ b/modules/portal/lib/Portal.php @@ -4,78 +4,79 @@ namespace SimpleSAML\Module\portal; class Portal { - private $pages; - private $config; - - public function __construct($pages, $config = null) + private $pages; + private $config; + + public function __construct($pages, $config = null) { - $this->pages = $pages; - $this->config = $config; - } - - public function getTabset($thispage) + $this->pages = $pages; + $this->config = $config; + } + + public function getTabset($thispage) { - if (!isset($this->config)) { + if (!isset($this->config)) { return null; } - foreach($this->config as $set) { - if (in_array($thispage, $set, true)) { - return $set; - } - } - return null; - } - - public function isPortalized($thispage) + foreach ($this->config as $set) { + if (in_array($thispage, $set, true)) { + return $set; + } + } + return null; + } + + public function isPortalized($thispage) { - foreach($this->config as $set) { - if (in_array($thispage, $set, true)) { - return true; - } - } - return false; - } - - public function getLoginInfo($translator, $thispage) + foreach ($this->config as $set) { + if (in_array($thispage, $set, true)) { + return true; + } + } + return false; + } + + public function getLoginInfo($translator, $thispage) { - $info = array('info' => '', 'translator' => $translator, 'thispage' => $thispage); - \SimpleSAML\Module::callHooks('portalLoginInfo', $info); - return $info['info']; - } - - public function getMenu($thispage) + $info = array('info' => '', 'translator' => $translator, 'thispage' => $thispage); + \SimpleSAML\Module::callHooks('portalLoginInfo', $info); + return $info['info']; + } + + public function getMenu($thispage) { - $config = \SimpleSAML\Configuration::getInstance(); - $t = new \SimpleSAML\Locale\Translate($config); - $tabset = $this->getTabset($thispage); - $logininfo = $this->getLoginInfo($t, $thispage); - $text = ''; - $text .= '<ul class="tabset_tabs ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">'; - foreach ($this->pages as $pageid => $page) { - if (isset($tabset) && !in_array($pageid, $tabset, true)) { + $config = \SimpleSAML\Configuration::getInstance(); + $t = new \SimpleSAML\Locale\Translate($config); + $tabset = $this->getTabset($thispage); + $logininfo = $this->getLoginInfo($t, $thispage); + $text = ''; + $text .= '<ul class="tabset_tabs ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">'; + foreach ($this->pages as $pageid => $page) { + if (isset($tabset) && !in_array($pageid, $tabset, true)) { continue; } - $name = 'uknown'; - if (isset($page['text'])) { + $name = 'uknown'; + if (isset($page['text'])) { $name = $page['text']; } - if (isset($page['shorttext'])) { + if (isset($page['shorttext'])) { $name = $page['shorttext']; } - if (!isset($page['href'])) { - $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">' . $t->t($name) . '</a></li>'; - } else if($pageid === $thispage ) { - $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">' . $t->t($name) . '</a></li>'; - } else { - $text .= '<li class="ui-state-default ui-corner-top"><a href="' . $page['href'] . '">' . $t->t($name) . '</a></li>'; - } - - } - $text .= '</ul>'; - if (!empty($logininfo)) { - $text .= '<p class="logininfo" style="text-align: right; margin: 0px">' . $logininfo . '</p>'; - } - - return $text; - } + if (!isset($page['href'])) { + $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">'. + $t->t($name).'</a></li>'; + } else if ($pageid === $thispage) { + $text .= '<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">'. + $t->t($name).'</a></li>'; + } else { + $text .= '<li class="ui-state-default ui-corner-top"><a href="'.$page['href'].'">'. + $t->t($name).'</a></li>'; + } + } + $text .= '</ul>'; + if (!empty($logininfo)) { + $text .= '<p class="logininfo" style="text-align: right; margin: 0px">'.$logininfo.'</p>'; + } + return $text; + } } diff --git a/modules/preprodwarning/lib/Auth/Process/Warning.php b/modules/preprodwarning/lib/Auth/Process/Warning.php index 5ea5b400d212e2a7c1613585a13d43eb717f2d93..1a235a83aa20d1210fe8d3e4f4404940aec8138d 100644 --- a/modules/preprodwarning/lib/Auth/Process/Warning.php +++ b/modules/preprodwarning/lib/Auth/Process/Warning.php @@ -10,25 +10,26 @@ namespace SimpleSAML\Module\preprodwarning\Auth\Process; class Warning extends \SimpleSAML\Auth\ProcessingFilter { - /** - * Process a authentication response. - * - * This function saves the state, and redirects the user to the page where the user - * can authorize the release of the attributes. - * - * @param array $state The state of the response. - */ - public function process(&$state) { - assert(is_array($state)); + /** + * Process a authentication response. + * + * This function saves the state, and redirects the user to the page where the user + * can authorize the release of the attributes. + * + * @param array $state The state of the response. + */ + public function process(&$state) + { + assert(is_array($state)); - if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { - // We have a passive request. Skip the warning - return; - } + if (isset($state['isPassive']) && $state['isPassive'] === true) { + // We have a passive request. Skip the warning + return; + } - // Save state and redirect. - $id = \SimpleSAML\Auth\State::saveState($state, 'warning:request'); - $url = \SimpleSAML\Module::getModuleURL('preprodwarning/showwarning.php'); - \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); - } + // Save state and redirect. + $id = \SimpleSAML\Auth\State::saveState($state, 'warning:request'); + $url = \SimpleSAML\Module::getModuleURL('preprodwarning/showwarning.php'); + \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id)); + } } diff --git a/modules/preprodwarning/templates/warning.php b/modules/preprodwarning/templates/warning.php index 981e2ffe3247849b75ae08ddb633b5a9b3879b52..41f2912d875219502a63b366ae7a1ecdfc886ef3 100644 --- a/modules/preprodwarning/templates/warning.php +++ b/modules/preprodwarning/templates/warning.php @@ -16,7 +16,6 @@ * @package SimpleSAMLphp */ - $this->data['header'] = $this->t('{preprodwarning:warning:warning_header}'); $this->data['autofocus'] = 'yesbutton'; @@ -26,19 +25,17 @@ $this->includeAtTemplateBase('includes/header.php'); <form style="display: inline; margin: 0px; padding: 0px" action="<?php echo htmlspecialchars($this->data['yesTarget']); ?>"> - <?php - // Embed hidden fields... - foreach ($this->data['yesData'] as $name => $value) { - echo('<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'); - } - ?> - <p><?php echo $this->t('{preprodwarning:warning:warning}'); ?></p> - - <input type="submit" name="yes" id="yesbutton" value="<?php echo htmlspecialchars($this->t('{preprodwarning:warning:yes}')) ?>" /> +<?php + // Embed hidden fields... + foreach ($this->data['yesData'] as $name => $value) { + echo '<input type="hidden" name="'.htmlspecialchars($name).'" value="'.htmlspecialchars($value).'" />'; + } +?> + <p><?php echo $this->t('{preprodwarning:warning:warning}'); ?></p> + <input type="submit" name="yes" id="yesbutton" value="<?php echo htmlspecialchars($this->t('{preprodwarning:warning:yes}')) ?>" /> </form> - <?php $this->includeAtTemplateBase('includes/footer.php'); diff --git a/modules/radius/lib/Auth/Source/Radius.php b/modules/radius/lib/Auth/Source/Radius.php index 1688d85ef2180409e2415afb4a1c57759cdb4443..c37238e826973f2be3e0c1e674b33730832bb743 100644 --- a/modules/radius/lib/Auth/Source/Radius.php +++ b/modules/radius/lib/Auth/Source/Radius.php @@ -84,24 +84,27 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase // Parse configuration. $config = \SimpleSAML\Configuration::loadFromArray($config, - 'Authentication source ' . var_export($this->authId, true)); + 'Authentication source '.var_export($this->authId, true)); $this->servers = $config->getArray('servers', array()); - /* For backwards compatibility. */ + // For backwards compatibility if (empty($this->servers)) { $this->hostname = $config->getString('hostname'); $this->port = $config->getIntegerRange('port', 1, 65535, 1812); $this->secret = $config->getString('secret'); - $this->servers[] = array('hostname' => $this->hostname, - 'port' => $this->port, - 'secret' => $this->secret); + $this->servers[] = array( + 'hostname' => $this->hostname, + 'port' => $this->port, + 'secret' => $this->secret + ); } $this->timeout = $config->getInteger('timeout', 5); $this->retries = $config->getInteger('retries', 3); $this->realm = $config->getString('realm', null); $this->usernameAttribute = $config->getString('username_attribute', null); $this->nasIdentifier = $config->getString('nas_identifier', - \SimpleSAML\Utils\HTTP::getSelfHost()); + \SimpleSAML\Utils\HTTP::getSelfHost() + ); $this->vendor = $config->getInteger('attribute_vendor', null); if ($this->vendor !== null) { @@ -130,11 +133,13 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase if (!isset($server['port'])) { $server['port'] = 1812; } - if (!radius_add_server($radius, + if (!radius_add_server( + $radius, $server['hostname'], $server['port'], $server['secret'], $this->timeout, $this->retries)) { - \SimpleSAML\Logger::info("Could not add radius server: " . - radius_strerror($radius)); + \SimpleSAML\Logger::info("Could not add radius server: ". + radius_strerror($radius) + ); continue; } $success = true; @@ -144,14 +149,15 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase } if (!radius_create_request($radius, \RADIUS_ACCESS_REQUEST)) { - throw new \Exception('Error creating radius request: ' . - radius_strerror($radius)); + throw new \Exception('Error creating radius request: '. + radius_strerror($radius) + ); } if ($this->realm === null) { radius_put_attr($radius, \RADIUS_USER_NAME, $username); } else { - radius_put_attr($radius, \RADIUS_USER_NAME, $username . '@' . $this->realm); + radius_put_attr($radius, \RADIUS_USER_NAME, $username.'@'.$this->realm); } radius_put_attr($radius, \RADIUS_USER_PASSWORD, $password); @@ -162,18 +168,19 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase $res = radius_send_request($radius); if ($res != \RADIUS_ACCESS_ACCEPT) { switch ($res) { - case \RADIUS_ACCESS_REJECT: - /* Invalid username or password. */ - throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); - case \RADIUS_ACCESS_CHALLENGE: - throw new \Exception('Radius authentication error: Challenge requested, but not supported.'); - default: - throw new \Exception('Error during radius authentication: ' . - radius_strerror($radius)); + case \RADIUS_ACCESS_REJECT: + // Invalid username or password + throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); + case \RADIUS_ACCESS_CHALLENGE: + throw new \Exception('Radius authentication error: Challenge requested, but not supported.'); + default: + throw new \Exception('Error during radius authentication: '. + radius_strerror($radius) + ); } } - /* If we get this far, we have a valid login. */ + // If we get this far, we have a valid login $attributes = array(); @@ -189,15 +196,16 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase return $attributes; } - /* get AAI attribute sets. Contributed by Stefan Winter, (c) RESTENA */ + // get AAI attribute sets. Contributed by Stefan Winter, (c) RESTENA while ($resa = radius_get_attr($radius)) { if (!is_array($resa)) { - throw new \Exception('Error getting radius attributes: ' . - radius_strerror($radius)); + throw new \Exception('Error getting radius attributes: '. + radius_strerror($radius) + ); } - /* Use the received user name */ + // Use the received user name if ($resa['attr'] == \RADIUS_USER_NAME) { $attributes[$this->usernameAttribute] = array($resa['data']); continue; @@ -209,8 +217,9 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase $resv = radius_get_vendor_attr($resa['data']); if (!is_array($resv)) { - throw new \Exception('Error getting vendor specific attribute: ' . - radius_strerror($radius)); + throw new \Exception('Error getting vendor specific attribute: '. + radius_strerror($radius) + ); } $vendor = $resv['vendor']; @@ -221,18 +230,17 @@ class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase continue; } - $attrib_name = strtok($datav,'='); + $attrib_name = strtok($datav, '='); $attrib_value = strtok('='); - /* if the attribute name is already in result set, - add another value */ + // if the attribute name is already in result set, add another value if (array_key_exists($attrib_name, $attributes)) { $attributes[$attrib_name][] = $attrib_value; } else { $attributes[$attrib_name] = array($attrib_value); } } - /* end of contribution */ + // end of contribution return $attributes; } diff --git a/modules/riak/config-templates/module_riak.php b/modules/riak/config-templates/module_riak.php index 33be27efedcb85e4edcadbb92cad3e37cc9cd469..4d3043195f2b07b4323dce5b4cbac33bc3b0ca5e 100644 --- a/modules/riak/config-templates/module_riak.php +++ b/modules/riak/config-templates/module_riak.php @@ -4,13 +4,13 @@ * */ -$config = array ( - /* - * This module has the following config options and defaults. - * - * 'path' => 'riak-php-client/riak.php', - * 'host' => 'localhost', - * 'port' => 8098, - * 'bucket' => 'SimpleSAMLphp', - */ +$config = array( + /* + * This module has the following config options and defaults. + * + * 'path' => 'riak-php-client/riak.php', + * 'host' => 'localhost', + * 'port' => 8098, + * 'bucket' => 'SimpleSAMLphp', + */ ); diff --git a/modules/riak/hooks/hook_cron.php b/modules/riak/hooks/hook_cron.php index cce9cec0ecfcde9aa428ca25b70005a2718d11ea..c7bc7e6f17d632af01b5f4c39f17d6508a6035c2 100644 --- a/modules/riak/hooks/hook_cron.php +++ b/modules/riak/hooks/hook_cron.php @@ -24,32 +24,34 @@ namespace SimpleSAML\Module\riak; * and Information Technology. */ - /** * Hook to run a cron job. * * @param array &$croninfo Output */ -function riak_hook_cron(&$croninfo) { - assert(is_array($croninfo)); - assert(array_key_exists('summary', $croninfo)); - assert(array_key_exists('tag', $croninfo)); - - if ($croninfo['tag'] !== 'hourly') return; - - try { - $store = new \SimpleSAML\Module\riak\Store\Store(); - $result = $store->bucket->indexSearch('expires', 'int', - 1, time() - 30); - foreach ($result as $link) { - $link->getBinary()->delete(); - } - - \SimpleSAML\Logger::info(sprintf("deleted %s riak key%s", - sizeof($result), sizeof($result) == 1 ? '' : 's')); - } catch (\Exception $e) { - $message = 'riak threw exception: ' . $e->getMessage(); - \SimpleSAML\Logger::warning($message); - $croninfo['summary'][] = $message; - } +function riak_hook_cron(&$croninfo) +{ + assert(is_array($croninfo)); + assert(array_key_exists('summary', $croninfo)); + assert(array_key_exists('tag', $croninfo)); + + if ($croninfo['tag'] !== 'hourly') { + return; + } + + try { + $store = new \SimpleSAML\Module\riak\Store\Store(); + $result = $store->bucket->indexSearch('expires', 'int', + 1, time() - 30); + foreach ($result as $link) { + $link->getBinary()->delete(); + } + + \SimpleSAML\Logger::info(sprintf("deleted %s riak key%s", + sizeof($result), sizeof($result) == 1 ? '' : 's')); + } catch (\Exception $e) { + $message = 'riak threw exception: '.$e->getMessage(); + \SimpleSAML\Logger::warning($message); + $croninfo['summary'][] = $message; + } } diff --git a/modules/riak/lib/Store/Store.php b/modules/riak/lib/Store/Store.php index 89b62d60cc2aea7d0cbe70f12fd06337f94e217b..c44f599502e9bea7073e5ce84d164ebd4f782ee8 100644 --- a/modules/riak/lib/Store/Store.php +++ b/modules/riak/lib/Store/Store.php @@ -29,85 +29,83 @@ class Store extends \SimpleSAML\Store public $client; public $bucket; - protected function __construct() + protected function __construct() { - $config = \SimpleSAML\Configuration::getConfig('module_riak.php'); - - $path = $config->getString('path', 'riak-php-client/riak.php'); - $host = $config->getString('host', 'localhost'); - $port = $config->getString('port', 8098); - $bucket = $config->getString('bucket', 'simpleSAMLphp'); - - require_once($path); - $this->client = new \RiakClient($host, $port); - $this->bucket = $this->client->bucket($bucket); - } - - /** - * Retrieve a value from the datastore. - * - * @param string $type The datatype. - * @param string $key The key. - * @return mixed|NULL The value. - */ - public function get($type, $key) + $config = \SimpleSAML\Configuration::getConfig('module_riak.php'); + + $path = $config->getString('path', 'riak-php-client/riak.php'); + $host = $config->getString('host', 'localhost'); + $port = $config->getString('port', 8098); + $bucket = $config->getString('bucket', 'simpleSAMLphp'); + + require_once($path); + $this->client = new \RiakClient($host, $port); + $this->bucket = $this->client->bucket($bucket); + } + + /** + * Retrieve a value from the datastore. + * + * @param string $type The datatype. + * @param string $key The key. + * @return mixed|NULL The value. + */ + public function get($type, $key) { - assert(is_string($type)); - assert(is_string($key)); - - $v = $this->bucket->getBinary("$type.$key"); - if (!$v->exists()) { - return null; - } - - $expires = $v->getIndex('Expires', 'int'); - if (sizeof($expires) && (int)array_shift($expires) <= time()) { - $v->delete(); - return null; - } - - return (unserialize($v->getData())); - } - - - /** - * Save a value to the datastore. - * - * @param string $type The datatype. - * @param string $key The key. - * @param mixed $value The value. - * @param int|NULL $expire The expiration time (unix timestamp), or NULL if it never expires. - */ - public function set($type, $key, $value, $expire = null) + assert(is_string($type)); + assert(is_string($key)); + + $v = $this->bucket->getBinary("$type.$key"); + if (!$v->exists()) { + return null; + } + + $expires = $v->getIndex('Expires', 'int'); + if (sizeof($expires) && (int) array_shift($expires) <= time()) { + $v->delete(); + return null; + } + + return (unserialize($v->getData())); + } + + /** + * Save a value to the datastore. + * + * @param string $type The datatype. + * @param string $key The key. + * @param mixed $value The value. + * @param int|NULL $expire The expiration time (unix timestamp), or NULL if it never expires. + */ + public function set($type, $key, $value, $expire = null) { - assert(is_string($type)); - assert(is_string($key)); - assert($expire === null || (is_int($expire) && $expire > 2592000)); - - $v = $this->bucket->newBinary("$type.$key", serialize($value), 'application/php'); - if (!is_null($expire)) { - $v->addIndex("Expires", "int", $expire); - } - - $v->store(); - } - - /** - * Delete a value from the datastore. - * - * @param string $type The datatype. - * @param string $key The key. - */ - public function delete($type, $key) + assert(is_string($type)); + assert(is_string($key)); + assert($expire === null || (is_int($expire) && $expire > 2592000)); + + $v = $this->bucket->newBinary("$type.$key", serialize($value), 'application/php'); + if (!is_null($expire)) { + $v->addIndex("Expires", "int", $expire); + } + + $v->store(); + } + + /** + * Delete a value from the datastore. + * + * @param string $type The datatype. + * @param string $key The key. + */ + public function delete($type, $key) { - assert(is_string($type)); - assert(is_string($key)); - - $v = $this->bucket->getBinary("$type.$key"); - if (!$v->exists()) { - return; - } - - $v->delete(); - } + assert(is_string($type)); + assert(is_string($key)); + + $v = $this->bucket->getBinary("$type.$key"); + if (!$v->exists()) { + return; + } + $v->delete(); + } } diff --git a/modules/saml/hooks/hook_metadata_hosted.php b/modules/saml/hooks/hook_metadata_hosted.php index d27f5246d619e48f054b9b53b44229f747946f5d..9090edd9c62c66bfd0dd0d1aada5243d45b827ea 100644 --- a/modules/saml/hooks/hook_metadata_hosted.php +++ b/modules/saml/hooks/hook_metadata_hosted.php @@ -27,7 +27,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/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php index e410a7eca80c3b185ba7c1125d87b92d5ddbe16b..25a70078156e207d741039d470fa2e483470ae6c 100644 --- a/modules/saml/lib/Auth/Source/SP.php +++ b/modules/saml/lib/Auth/Source/SP.php @@ -57,8 +57,10 @@ class SP extends Source * gives the entity id. */ $config['entityid'] = $config['entityID']; - $this->metadata = \SimpleSAML\Configuration::loadFromArray($config, - 'authsources[' . var_export($this->authId, true) . ']'); + $this->metadata = \SimpleSAML\Configuration::loadFromArray( + $config, + 'authsources['.var_export($this->authId, true).']' + ); $this->entityId = $this->metadata->getString('entityID'); $this->idp = $this->metadata->getString('idp', null); $this->discoURL = $this->metadata->getString('discoURL', null); @@ -75,7 +77,7 @@ class SP extends Source */ public function getMetadataURL() { - return \SimpleSAML\Module::getModuleURL('saml/sp/metadata.php/' . urlencode($this->authId)); + return \SimpleSAML\Module::getModuleURL('saml/sp/metadata.php/'.urlencode($this->authId)); } /** @@ -109,9 +111,8 @@ class SP extends Source assert(is_string($entityId)); if ($this->idp !== null && $this->idp !== $entityId) { - throw new \SimpleSAML\Error\Exception('Cannot retrieve metadata for IdP ' . - var_export($entityId, true) . - ' because it isn\'t a valid IdP for this SP.'); + throw new \SimpleSAML\Error\Exception('Cannot retrieve metadata for IdP '. + var_export($entityId, true).' because it isn\'t a valid IdP for this SP.'); } $metadataHandler = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler(); @@ -120,20 +121,20 @@ class SP extends Source try { return $metadataHandler->getMetaDataConfig($entityId, 'saml20-idp-remote'); } catch (\Exception $e) { - /* Metadata wasn't found. */ - \SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage()); + // Metadata wasn't found + \SimpleSAML\Logger::debug('getIdpMetadata: '.$e->getMessage()); } - /* Not found in saml20-idp-remote, look in shib13-idp-remote. */ + // Not found in saml20-idp-remote, look in shib13-idp-remote try { return $metadataHandler->getMetaDataConfig($entityId, 'shib13-idp-remote'); } catch (\Exception $e) { - /* Metadata wasn't found. */ - \SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage()); + // Metadata wasn't found + \SimpleSAML\Logger::debug('getIdpMetadata: '.$e->getMessage()); } - /* Not found. */ - throw new \SimpleSAML\Error\Exception('Could not find the metadata of an IdP with entity ID ' . + // Not found + throw new \SimpleSAML\Error\Exception('Could not find the metadata of an IdP with entity ID '. var_export($entityId, true)); } @@ -161,20 +162,20 @@ class SP extends Source } if ($useArtifact) { - $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId . '/artifact'); + $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/'.$this->authId.'/artifact'); } else { - $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId); + $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/'.$this->authId); } $url = $ar->createRedirect($idpEntityId, $shire); - \SimpleSAML\Logger::debug('Starting SAML 1 SSO to ' . var_export($idpEntityId, true) . - ' from ' . var_export($this->entityId, true) . '.'); + \SimpleSAML\Logger::debug('Starting SAML 1 SSO to '.var_export($idpEntityId, true). + ' from '.var_export($this->entityId, true).'.'); \SimpleSAML\Utils\HTTP::redirectTrustedURL($url); } /** - * Send a SAML2 SSO request to an IdP. + * Send a SAML2 SSO request to an IdP * * @param \SimpleSAML\Configuration $idpMetadata The metadata of the IdP. * @param array $state The state array for the current authentication. @@ -190,7 +191,7 @@ class SP extends Source $ar = \SimpleSAML\Module\saml\Message::buildAuthnRequest($this->metadata, $idpMetadata); - $ar->setAssertionConsumerServiceURL(\SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->authId)); + $ar->setAssertionConsumerServiceURL(\SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/'.$this->authId)); if (isset($state['\SimpleSAML\Auth\Source.ReturnURL'])) { $ar->setRelayState($state['\SimpleSAML\Auth\Source.ReturnURL']); @@ -199,23 +200,24 @@ class SP extends Source if (isset($state['saml:AuthnContextClassRef'])) { $accr = \SimpleSAML\Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']); $comp = \SAML2\Constants::COMPARISON_EXACT; - if (isset($state['saml:AuthnContextComparison']) && in_array($state['AuthnContextComparison'], array( - \SAML2\Constants::COMPARISON_EXACT, - \SAML2\Constants::COMPARISON_MINIMUM, - \SAML2\Constants::COMPARISON_MAXIMUM, - \SAML2\Constants::COMPARISON_BETTER, - ), true)) { + if (isset($state['saml:AuthnContextComparison']) + && in_array($state['AuthnContextComparison'], array( + \SAML2\Constants::COMPARISON_EXACT, + \SAML2\Constants::COMPARISON_MINIMUM, + \SAML2\Constants::COMPARISON_MAXIMUM, + \SAML2\Constants::COMPARISON_BETTER, + ), true)) { $comp = $state['saml:AuthnContextComparison']; } $ar->setRequestedAuthnContext(array('AuthnContextClassRef' => $accr, 'Comparison' => $comp)); } if (isset($state['ForceAuthn'])) { - $ar->setForceAuthn((bool)$state['ForceAuthn']); + $ar->setForceAuthn((bool) $state['ForceAuthn']); } if (isset($state['isPassive'])) { - $ar->setIsPassive((bool)$state['isPassive']); + $ar->setIsPassive((bool) $state['isPassive']); } if (isset($state['saml:NameID'])) { @@ -228,7 +230,7 @@ class SP extends Source if (isset($state['saml:NameIDPolicy'])) { if (is_string($state['saml:NameIDPolicy'])) { $policy = array( - 'Format' => (string)$state['saml:NameIDPolicy'], + 'Format' => (string) $state['saml:NameIDPolicy'], 'AllowCreate' => true, ); } elseif (is_array($state['saml:NameIDPolicy'])) { @@ -245,9 +247,13 @@ class SP extends Source $IDPList = array(); } - $ar->setIDPList(array_unique(array_merge($this->metadata->getArray('IDPList', array()), - $idpMetadata->getArray('IDPList', array()), - (array) $IDPList))); + $ar->setIDPList(array_unique( + array_merge( + $this->metadata->getArray('IDPList', array()), + $idpMetadata->getArray('IDPList', array() + ), + (array) $IDPList) + )); if (isset($state['saml:ProxyCount']) && $state['saml:ProxyCount'] !== null) { $ar->setProxyCount($state['saml:ProxyCount']); @@ -278,10 +284,10 @@ class SP extends Source $id = State::saveState($state, 'saml:sp:sso', true); $ar->setId($id); - \SimpleSAML\Logger::debug('Sending SAML 2 AuthnRequest to ' . + \SimpleSAML\Logger::debug('Sending SAML 2 AuthnRequest to '. var_export($idpMetadata->getString('entityid'), true)); - /* Select appropriate SSO endpoint */ + // Select appropriate SSO endpoint if ($ar->getProtocolBinding() === \SAML2\Constants::BINDING_HOK_SSO) { $dst = $idpMetadata->getDefaultEndpoint('SingleSignOnService', array( \SAML2\Constants::BINDING_HOK_SSO) @@ -330,15 +336,15 @@ class SP extends Source $type = $idpMetadata->getString('metadata-set'); switch ($type) { - case 'shib13-idp-remote': - $this->startSSO1($idpMetadata, $state); - assert(false); /* Should not return. */ - case 'saml20-idp-remote': - $this->startSSO2($idpMetadata, $state); - assert(false); /* Should not return. */ - default: - /* Should only be one of the known types. */ - assert(false); + case 'shib13-idp-remote': + $this->startSSO1($idpMetadata, $state); + assert(false); // Should not return + case 'saml20-idp-remote': + $this->startSSO2($idpMetadata, $state); + assert(false); // Should not return + default: + // Should only be one of the known types + assert(false); } } @@ -353,7 +359,7 @@ class SP extends Source $discoURL = $this->discoURL; if ($discoURL === null) { - /* Fallback to internal discovery service. */ + // Fallback to internal discovery service $discoURL = \SimpleSAML\Module::getModuleURL('saml/disco.php'); } @@ -365,7 +371,7 @@ class SP extends Source 'returnIDParam' => 'idpentityid' ); - if(isset($state['saml:IDPList'])) { + if (isset($state['saml:IDPList'])) { $params['IDPList'] = $state['saml:IDPList']; } @@ -387,13 +393,13 @@ class SP extends Source { assert(is_array($state)); - /* We are going to need the authId in order to retrieve this authentication source later. */ + // We are going to need the authId in order to retrieve this authentication source later $state['saml:sp:AuthId'] = $this->authId; $idp = $this->idp; if (isset($state['saml:idp'])) { - $idp = (string)$state['saml:idp']; + $idp = (string) $state['saml:idp']; } if (isset($state['saml:IDPList']) && sizeof($state['saml:IDPList']) > 0) { @@ -453,8 +459,7 @@ class SP extends 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)) - { + !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 @@ -531,7 +536,7 @@ class SP extends Source assert(array_key_exists('core:IdP', $state)); assert(array_key_exists('SPMetadata', $state)); - if (isset($state['isPassive']) && (bool)$state['isPassive']) { + if (isset($state['isPassive']) && (bool) $state['isPassive']) { // passive request, we cannot authenticate the user throw new \SimpleSAML\Module\saml\Error\NoPassive( \SAML2\Constants::STATUS_REQUESTER, @@ -635,7 +640,7 @@ class SP extends Source \SAML2\Constants::BINDING_HTTP_REDIRECT, \SAML2\Constants::BINDING_HTTP_POST), false); if ($endpoint === false) { - \SimpleSAML\Logger::info('No logout endpoint for IdP ' . var_export($idp, true) . '.'); + \SimpleSAML\Logger::info('No logout endpoint for IdP '.var_export($idp, true).'.'); return; } @@ -671,15 +676,15 @@ class SP extends Source $logoutType = $state['saml:logout:Type']; switch ($logoutType) { - case 'saml1': - /* Nothing to do. */ - return; - case 'saml2': - $this->startSLO2($state); - return; - default: - /* Should never happen. */ - assert(false); + case 'saml1': + // Nothing to do + return; + case 'saml2': + $this->startSLO2($state); + return; + default: + // Should never happen + assert(false); } } @@ -783,15 +788,15 @@ class SP extends Source $sourceId = $state['saml:sp:AuthId']; $source = 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. */ + // Register a callback that we can call if we receive a logout request from the IdP $source->addLogoutCallback($idp, $state); $state['Attributes'] = $authProcState['Attributes']; - if (isset($state['saml:sp:isUnsolicited']) && (bool)$state['saml:sp:isUnsolicited']) { + if (isset($state['saml:sp:isUnsolicited']) && (bool) $state['saml:sp:isUnsolicited']) { if (!empty($state['saml:sp:RelayState'])) { $redirectTo = $state['saml:sp:RelayState']; } else { diff --git a/modules/saml/lib/Error.php b/modules/saml/lib/Error.php index ad0349f89e5a5de8f107249ff5b80971e3ad66c5..b288ef107e8d71cf6c6959452522ab3598270ab5 100644 --- a/modules/saml/lib/Error.php +++ b/modules/saml/lib/Error.php @@ -48,10 +48,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); @@ -129,7 +129,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/SAML1.php b/modules/saml/lib/IdP/SAML1.php index 8e5226c472f4bc185df6ee87ec1e9b2c14e8b825..a6d8ce0ed4b075b57fe443ee50d6b4d3e6e188b3 100644 --- a/modules/saml/lib/IdP/SAML1.php +++ b/modules/saml/lib/IdP/SAML1.php @@ -28,9 +28,9 @@ class SAML1 $spMetadata = $state["SPMetadata"]; $spEntityId = $spMetadata['entityid']; $spMetadata = \SimpleSAML\Configuration::loadFromArray($spMetadata, - '$metadata[' . var_export($spEntityId, true) . ']'); + '$metadata['.var_export($spEntityId, true).']'); - \SimpleSAML\Logger::info('Sending SAML 1.1 Response to ' . var_export($spEntityId, true)); + \SimpleSAML\Logger::info('Sending SAML 1.1 Response to '.var_export($spEntityId, true)); $attributes = $state['Attributes']; $shire = $state['saml:shire']; @@ -70,7 +70,7 @@ class SAML1 public static function receiveAuthnRequest(\SimpleSAML\IdP $idp) { if (isset($_REQUEST['cookieTime'])) { - $cookieTime = (int)$_REQUEST['cookieTime']; + $cookieTime = (int) $_REQUEST['cookieTime']; if ($cookieTime + 5 > time()) { /* * Less than five seconds has passed since we were @@ -83,12 +83,12 @@ class SAML1 if (!isset($_REQUEST['providerId'])) { throw new \SimpleSAML\Error\BadRequest('Missing providerId parameter.'); } - $spEntityId = (string)$_REQUEST['providerId']; + $spEntityId = (string) $_REQUEST['providerId']; if (!isset($_REQUEST['shire'])) { throw new \SimpleSAML\Error\BadRequest('Missing shire parameter.'); } - $shire = (string)$_REQUEST['shire']; + $shire = (string) $_REQUEST['shire']; if (isset($_REQUEST['target'])) { $target = $_REQUEST['target']; @@ -96,7 +96,7 @@ class SAML1 $target = null; } - \SimpleSAML\Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from ' . var_export($spEntityId, true) . '.'); + \SimpleSAML\Logger::info('Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from '.var_export($spEntityId, true).'.'); $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler(); $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote'); @@ -113,8 +113,8 @@ class SAML1 break; } if (!$found) { - throw new \Exception('Invalid AssertionConsumerService for SP ' . - var_export($spEntityId, true) . ': ' . var_export($shire, true)); + throw new \Exception('Invalid AssertionConsumerService for SP '. + var_export($spEntityId, true).': '.var_export($shire, true)); } \SimpleSAML\Stats::log('saml:idp:AuthnRequest', array( diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php index 55ced36c452a263f9c74a54c79f863da827e5e53..6dae8c4ca6a3b2de00bcbccb8cbc2d584b2fd2b2 100644 --- a/modules/saml/lib/IdP/SAML2.php +++ b/modules/saml/lib/IdP/SAML2.php @@ -1089,8 +1089,8 @@ class SAML2 $key->loadKey($pemKey); } else { throw new \SimpleSAML\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 3a60939278f072fd541d1597508f77cc4aea46e6..f07ff36e2ff644f25cd969f4138fbe563f72b239 100644 --- a/modules/saml/lib/IdP/SQLNameID.php +++ b/modules/saml/lib/IdP/SQLNameID.php @@ -21,7 +21,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, @@ -30,7 +30,7 @@ class SQLNameID )'; $store->pdo->exec($query); - $query = 'CREATE INDEX ' . $store->prefix . '_saml_PersistentNameID_idp_sp ON ' . $store->prefix . '_saml_PersistentNameID (_idp, _sp)'; + $query = 'CREATE INDEX '.$store->prefix.'_saml_PersistentNameID_idp_sp ON '.$store->prefix.'_saml_PersistentNameID (_idp, _sp)'; $store->pdo->exec($query); $store->setTableVersion('saml_PersistentNameID', 1); @@ -82,7 +82,7 @@ class SQLNameID '_value' => $value, ); - $query = 'INSERT INTO ' . $store->prefix . '_saml_PersistentNameID (_idp, _sp, _user, _value) VALUES(:_idp, :_sp, :_user, :_value)'; + $query = 'INSERT INTO '.$store->prefix.'_saml_PersistentNameID (_idp, _sp, _user, _value) VALUES(:_idp, :_sp, :_user, :_value)'; $query = $store->pdo->prepare($query); $query->execute($params); } @@ -110,7 +110,7 @@ class SQLNameID '_user' => $user, ); - $query = 'SELECT _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; + $query = 'SELECT _value FROM '.$store->prefix.'_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; $query = $store->pdo->prepare($query); $query->execute($params); @@ -145,7 +145,7 @@ class SQLNameID '_user' => $user, ); - $query = 'DELETE FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; + $query = 'DELETE FROM '.$store->prefix.'_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp AND _user = :_user'; $query = $store->pdo->prepare($query); $query->execute($params); } @@ -170,7 +170,7 @@ class SQLNameID '_sp' => $spEntityId, ); - $query = 'SELECT _user, _value FROM ' . $store->prefix . '_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp'; + $query = 'SELECT _user, _value FROM '.$store->prefix.'_saml_PersistentNameID WHERE _idp = :_idp AND _sp = :_sp'; $query = $store->pdo->prepare($query); $query->execute($params); diff --git a/modules/saml/lib/SP/LogoutStore.php b/modules/saml/lib/SP/LogoutStore.php index 3b98fdbeaf40f15a04e9ac93bdc1779e7143645d..b3db87991abdd11fb712c6bcc843c8c91b29f148 100644 --- a/modules/saml/lib/SP/LogoutStore.php +++ b/modules/saml/lib/SP/LogoutStore.php @@ -21,14 +21,14 @@ class LogoutStore if ($tableVer === 2) { return; } elseif ($tableVer === 1) { - /* TableVersion 2 increased the column size to 255 which is the maximum length of a FQDN. */ + // TableVersion 2 increased the column size to 255 which is the maximum length of a FQDN switch ($store->driver) { case 'pgsql': // This does not affect the NOT NULL constraint - $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _authSource TYPE VARCHAR(255)'; + $query = 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore ALTER COLUMN _authSource TYPE VARCHAR(255)'; break; default: - $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL'; + $query = 'ALTER TABLE '.$store->prefix.'_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL'; break; } @@ -42,7 +42,7 @@ class LogoutStore return; } - $query = 'CREATE TABLE ' . $store->prefix . '_saml_LogoutStore ( + $query = 'CREATE TABLE '.$store->prefix.'_saml_LogoutStore ( _authSource VARCHAR(255) NOT NULL, _nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, @@ -52,10 +52,10 @@ class LogoutStore )'; $store->pdo->exec($query); - $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ' . $store->prefix . '_saml_LogoutStore (_expire)'; + $query = 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_expire ON '.$store->prefix.'_saml_LogoutStore (_expire)'; $store->pdo->exec($query); - $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ' . $store->prefix . '_saml_LogoutStore (_authSource, _nameId)'; + $query = 'CREATE INDEX '.$store->prefix.'_saml_LogoutStore_nameId ON '.$store->prefix.'_saml_LogoutStore (_authSource, _nameId)'; $store->pdo->exec($query); $store->setTableVersion('saml_LogoutStore', 2); @@ -71,7 +71,7 @@ class LogoutStore { \SimpleSAML\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 = array('now' => gmdate('Y-m-d H:i:s')); $query = $store->pdo->prepare($query); @@ -108,7 +108,7 @@ class LogoutStore '_expire' => gmdate('Y-m-d H:i:s', $expire), '_sessionId' => $sessionId, ); - $store->insertOrUpdate($store->prefix . '_saml_LogoutStore', array('_authSource', '_nameId', '_sessionIndex'), $data); + $store->insertOrUpdate($store->prefix.'_saml_LogoutStore', array('_authSource', '_nameId', '_sessionIndex'), $data); } @@ -134,13 +134,13 @@ 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 . '_saml_LogoutStore' . + $query = 'SELECT _sessionIndex AS _sessionindex, _sessionId AS _sessionid FROM '.$store->prefix.'_saml_LogoutStore'. ' WHERE _authSource = :_authSource AND _nameId = :_nameId AND _expire >= :now'; $query = $store->pdo->prepare($query); $query->execute($params); $res = array(); - while ( ($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) { + while (($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) { $res[$row['_sessionindex']] = $row['_sessionid']; } @@ -164,7 +164,7 @@ class LogoutStore $res = array(); foreach ($sessionIndexes as $sessionIndex) { - $sessionId = $store->get('saml.LogoutStore', $nameId . ':' . $sessionIndex); + $sessionId = $store->get('saml.LogoutStore', $nameId.':'.$sessionIndex); if ($sessionId === null) { continue; } @@ -218,7 +218,7 @@ class LogoutStore $strNameId = serialize($nameId); $strNameId = sha1($strNameId); - /* Normalize SessionIndex. */ + // Normalize SessionIndex if (strlen($sessionIndex) > 50) { $sessionIndex = sha1($sessionIndex); } @@ -229,7 +229,7 @@ class LogoutStore if ($store instanceof \SimpleSAML\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); } } @@ -248,7 +248,7 @@ class LogoutStore $store = \SimpleSAML\Store::getInstance(); if ($store === false) { - /* We don't have a datastore. */ + // We don't have a datastore return false; } @@ -260,7 +260,7 @@ class LogoutStore $strNameId = serialize($nameId); $strNameId = sha1($strNameId); - /* Normalize SessionIndexes. */ + // Normalize SessionIndexes foreach ($sessionIndexes as &$sessionIndex) { assert(is_string($sessionIndex)); if (strlen($sessionIndex) > 50) { @@ -272,7 +272,7 @@ class LogoutStore if ($store instanceof \SimpleSAML\Store\SQL) { $sessions = self::getSessionsSQL($store, $authId, $strNameId); } elseif (empty($sessionIndexes)) { - /* We cannot fetch all sessions without a SQL store. */ + // We cannot fetch all sessions without a SQL store return false; } else { /** @var \SimpleSAML\Store $sessions At this point the store cannot be false */ @@ -304,7 +304,7 @@ class LogoutStore continue; } - \SimpleSAML\Logger::info('saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackID() . '].'); + \SimpleSAML\Logger::info('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 abcffdc98ce02df80a61e78cd3132ea1cb65ac85..7a2597519abfc06c5aaf63e31dd4718b98bfca5b 100644 --- a/modules/saml/www/idp/certs.php +++ b/modules/saml/www/idp/certs.php @@ -16,7 +16,7 @@ if ($config->getBoolean('admin.protectmetadata', false)) { $idpentityid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted'); $idpmeta = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-hosted'); -switch($_SERVER['PATH_INFO']) { +switch ($_SERVER['PATH_INFO']) { case '/new_idp.crt': $certInfo = SimpleSAML\Utils\Crypto::loadPublicKey($idpmeta, false, 'new_'); break; diff --git a/modules/saml/www/proxy/invalid_session.php b/modules/saml/www/proxy/invalid_session.php index 0be45e11def84c4d79388fd4338c664761496420..1afc151ae11fbc928a374f9d8e5062be007077bf 100644 --- a/modules/saml/www/proxy/invalid_session.php +++ b/modules/saml/www/proxy/invalid_session.php @@ -47,7 +47,7 @@ if (isset($_POST['continue'])) { $cfg = \SimpleSAML\Configuration::getInstance(); $template = new \SimpleSAML\XHTML\Template($cfg, 'saml:proxy/invalid_session.php'); $translator = $template->getTranslator(); -$template->data['AuthState'] = (string)$_REQUEST['AuthState']; +$template->data['AuthState'] = (string) $_REQUEST['AuthState']; // get the name of the IdP $idpmdcfg = $state['saml:sp:IdPMetadata']; diff --git a/modules/saml/www/sp/discoresp.php b/modules/saml/www/sp/discoresp.php index 60c15045a629c255ad6505e800bb64b5a9128472..94ac7c1d77aad0da838d2b0e61142e4cee7063dd 100644 --- a/modules/saml/www/sp/discoresp.php +++ b/modules/saml/www/sp/discoresp.php @@ -19,7 +19,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/saml1-acs.php b/modules/saml/www/sp/saml1-acs.php index 0e607eb53ccbc5e969cb3726ae07b3f0d6e642d4..c6be5c70149998fefed8fd312a71d14ed3d9f21a 100644 --- a/modules/saml/www/sp/saml1-acs.php +++ b/modules/saml/www/sp/saml1-acs.php @@ -25,7 +25,7 @@ $source = \SimpleSAML\Auth\Source::getById($sourceId, '\SimpleSAML\Module\saml\A SimpleSAML\Logger::debug('Received SAML1 response'); -$target = (string)$_REQUEST['TARGET']; +$target = (string) $_REQUEST['TARGET']; if (preg_match('@^https?://@i', $target)) { // Unsolicited response diff --git a/modules/saml/www/sp/saml2-acs.php b/modules/saml/www/sp/saml2-acs.php index d897129807aedbd29b4f94077852bb4159860c1f..859c287832028318b9bd94b090ddd7f4fcb2acc1 100644 --- a/modules/saml/www/sp/saml2-acs.php +++ b/modules/saml/www/sp/saml2-acs.php @@ -14,13 +14,15 @@ $spMetadata = $source->getMetadata(); try { $b = \SAML2\Binding::getCurrentBinding(); -} catch (Exception $e) { // TODO: look for a specific exception +} catch (Exception $e) { + // TODO: look for a specific exception // This is dirty. Instead of checking the message of the exception, \SAML2\Binding::getCurrentBinding() should throw // an specific exception when the binding is unknown, and we should capture that here if ($e->getMessage() === 'Unable to find the current binding.') { throw new \SimpleSAML\Error\Error('ACSPARAMS', $e, 400); } else { - throw $e; // do not ignore other exceptions! + // do not ignore other exceptions! + throw $e; } } diff --git a/modules/saml/www/sp/saml2-logout.php b/modules/saml/www/sp/saml2-logout.php index 1ab456692a18bf47befda330f98dfa21f18c8240..8b9cc250f93412fe13dff9583d1197256eb43a5c 100644 --- a/modules/saml/www/sp/saml2-logout.php +++ b/modules/saml/www/sp/saml2-logout.php @@ -14,7 +14,7 @@ $sourceId = substr($_SERVER['PATH_INFO'], 1); $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?'); @@ -22,7 +22,8 @@ if (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) { try { $binding = \SAML2\Binding::getCurrentBinding(); -} catch (\Exception $e) { // TODO: look for a specific exception +} catch (\Exception $e) { + // TODO: look for a specific exception // This is dirty. Instead of checking the message of the exception, \SAML2\Binding::getCurrentBinding() should throw // an specific exception when the binding is unknown, and we should capture that here if ($e->getMessage() === 'Unable to find the current binding.') { @@ -61,7 +62,7 @@ if ($message instanceof \SAML2\LogoutResponse) { } if (!$message->isSuccess()) { - \SimpleSAML\Logger::warning('Unsuccessful logout. Status was: ' . \SimpleSAML\Module\saml\Message::getResponseError($message)); + \SimpleSAML\Logger::warning('Unsuccessful logout. Status was: '.\SimpleSAML\Module\saml\Message::getResponseError($message)); } $state = \SimpleSAML\Auth\State::loadState($relayState, 'saml:slosent'); @@ -70,14 +71,14 @@ if ($message instanceof \SAML2\LogoutResponse) { } 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); @@ -86,11 +87,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; } } @@ -104,18 +105,18 @@ if ($message instanceof \SAML2\LogoutResponse) { $numLoggedOut = \SimpleSAML\Module\saml\SP\LogoutStore::logoutSessions($sourceId, $nameId, $sessionIndexes); if ($numLoggedOut === false) { - /* This type of logout was unsupported. Use the old method. */ + // This type of logout was unsupported. Use the old method $source->handleLogout($idpEntityId); $numLoggedOut = count($sessionIndexes); } - /* Create and send response. */ + // Create and send response $lr = \SimpleSAML\Module\saml\Message::buildLogoutResponse($spMetadata, $idpMetadata); $lr->setRelayState($message->getRelayState()); $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.'); } $dst = $idpMetadata->getEndpointPrioritizedByBinding('SingleLogoutService', array( @@ -136,5 +137,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/modules/sanitycheck/config-templates/config-sanitycheck.php b/modules/sanitycheck/config-templates/config-sanitycheck.php index ac40a0f48e8a5e1da222ce943bb5fd3deee5fcae..7ba3199e33d86cfbe33551e06ad7713de1b3b053 100644 --- a/modules/sanitycheck/config-templates/config-sanitycheck.php +++ b/modules/sanitycheck/config-templates/config-sanitycheck.php @@ -3,8 +3,7 @@ * The configuration of SimpleSAMLphp sanitycheck package */ -$config = array ( - +$config = array( /* * Do you want to generate statistics using the cron module? If so, specify which cron tag to use. * Examples: daily, weekly @@ -12,5 +11,4 @@ $config = array ( * 'cron_tag' => null, */ 'cron_tag' => 'hourly', - ); diff --git a/modules/sanitycheck/hooks/hook_cron.php b/modules/sanitycheck/hooks/hook_cron.php index 5b6a93869df0329e08e929db7dc077e46f31215e..ae85a1a208d665098b62ce46e6d626649b35cf65 100644 --- a/modules/sanitycheck/hooks/hook_cron.php +++ b/modules/sanitycheck/hooks/hook_cron.php @@ -4,13 +4,14 @@ * * @param array &$croninfo Output */ + function sanitycheck_hook_cron(&$croninfo) { assert(is_array($croninfo)); assert(array_key_exists('summary', $croninfo)); assert(array_key_exists('tag', $croninfo)); - \SimpleSAML\Logger::info('cron [sanitycheck]: Running cron in cron tag [' . $croninfo['tag'] . '] '); + \SimpleSAML\Logger::info('cron [sanitycheck]: Running cron in cron tag ['.$croninfo['tag'].'] '); try { $sconfig = \SimpleSAML\Configuration::getOptionalConfig('config-sanitycheck.php'); @@ -30,12 +31,12 @@ function sanitycheck_hook_cron(&$croninfo) SimpleSAML\Module::callHooks('sanitycheck', $hookinfo); if (count($errors) > 0) { - foreach ($errors AS $err) { - $croninfo['summary'][] = 'Sanitycheck error: ' . $err; + foreach ($errors as $err) { + $croninfo['summary'][] = 'Sanitycheck error: '.$err; } } } catch (Exception $e) { - $croninfo['summary'][] = 'Error executing sanity check: ' . $e->getMessage(); + $croninfo['summary'][] = 'Error executing sanity check: '.$e->getMessage(); } } diff --git a/modules/smartattributes/lib/Auth/Process/SmartName.php b/modules/smartattributes/lib/Auth/Process/SmartName.php index 6d86a229760cf4cfde58891a6c4dc639ae72004f..388ffe5c35e6503c1a1632dad3e1a2798d216e7c 100644 --- a/modules/smartattributes/lib/Auth/Process/SmartName.php +++ b/modules/smartattributes/lib/Auth/Process/SmartName.php @@ -81,7 +81,7 @@ class SmartName extends \SimpleSAML\Auth\ProcessingFilter assert(is_array($request)); assert(array_key_exists('Attributes', $request)); - $attributes =& $request['Attributes']; + $attributes = &$request['Attributes']; $fullname = $this->getFullName($attributes); diff --git a/modules/sqlauth/lib/Auth/Source/SQL.php b/modules/sqlauth/lib/Auth/Source/SQL.php index 713c69c322ed0c7180b509fc43455dd3ec614f10..f968dbc9c695d8be002de780289314e9d8a9e791 100644 --- a/modules/sqlauth/lib/Auth/Source/SQL.php +++ b/modules/sqlauth/lib/Auth/Source/SQL.php @@ -57,14 +57,14 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase // Make sure that all required parameters are present. foreach (array('dsn', 'username', 'password', 'query') as $param) { if (!array_key_exists($param, $config)) { - throw new \Exception('Missing required attribute \'' . $param . - '\' for authentication source ' . $this->authId); + throw new \Exception('Missing required attribute \''.$param. + '\' for authentication source '.$this->authId); } if (!is_string($config[$param])) { - throw new \Exception('Expected parameter \'' . $param . - '\' for authentication source ' . $this->authId . - ' to be a string. Instead it was: ' . + throw new \Exception('Expected parameter \''.$param. + '\' for authentication source '.$this->authId. + ' to be a string. Instead it was: '. var_export($config[$param], true)); } } @@ -89,8 +89,8 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase try { $db = new \PDO($this->dsn, $this->username, $this->password, $this->options); } catch (\PDOException $e) { - throw new \Exception('sqlauth:' . $this->authId . ': - Failed to connect to \'' . - $this->dsn . '\': '. $e->getMessage()); + throw new \Exception('sqlauth:'.$this->authId.': - Failed to connect to \''. + $this->dsn.'\': '.$e->getMessage()); } $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); @@ -98,16 +98,16 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase $driver = explode(':', $this->dsn, 2); $driver = strtolower($driver[0]); - /* Driver specific initialization. */ + // Driver specific initialization switch ($driver) { - case 'mysql': - /* Use UTF-8. */ - $db->exec("SET NAMES 'utf8mb4'"); - break; - case 'pgsql': - /* Use UTF-8. */ - $db->exec("SET NAMES 'UTF8'"); - break; + case 'mysql': + // Use UTF-8 + $db->exec("SET NAMES 'utf8mb4'"); + break; + case 'pgsql': + // Use UTF-8 + $db->exec("SET NAMES 'UTF8'"); + break; } return $db; @@ -137,30 +137,30 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase try { $sth = $db->prepare($this->query); } catch (\PDOException $e) { - throw new \Exception('sqlauth:' . $this->authId . - ': - Failed to prepare query: ' . $e->getMessage()); + throw new \Exception('sqlauth:'.$this->authId. + ': - Failed to prepare query: '.$e->getMessage()); } try { $sth->execute(array('username' => $username, 'password' => $password)); } catch (\PDOException $e) { - throw new \Exception('sqlauth:' . $this->authId . - ': - Failed to execute query: ' . $e->getMessage()); + throw new \Exception('sqlauth:'.$this->authId. + ': - Failed to execute query: '.$e->getMessage()); } try { $data = $sth->fetchAll(\PDO::FETCH_ASSOC); } catch (\PDOException $e) { - throw new \Exception('sqlauth:' . $this->authId . - ': - Failed to fetch result set: ' . $e->getMessage()); + throw new \Exception('sqlauth:'.$this->authId. + ': - Failed to fetch result set: '.$e->getMessage()); } - \SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Got ' . count($data) . + \SimpleSAML\Logger::info('sqlauth:'.$this->authId.': Got '.count($data). ' rows from database'); if (count($data) === 0) { - /* No rows returned - invalid username/password. */ - \SimpleSAML\Logger::error('sqlauth:' . $this->authId . + // No rows returned - invalid username/password + \SimpleSAML\Logger::error('sqlauth:'.$this->authId. ': No rows in result set. Probably wrong username/password.'); throw new \SimpleSAML\Error\Error('WRONGUSERPASS'); } @@ -177,14 +177,14 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase continue; } - $value = (string)$value; + $value = (string) $value; if (!array_key_exists($name, $attributes)) { $attributes[$name] = array(); } if (in_array($value, $attributes[$name], true)) { - /* Value already exists in attribute. */ + // Value already exists in attribute continue; } @@ -192,7 +192,7 @@ class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase } } - \SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Attributes: ' . + \SimpleSAML\Logger::info('sqlauth:'.$this->authId.': Attributes: '. implode(',', array_keys($attributes))); return $attributes; diff --git a/modules/statistics/bin/loganalyzer.php b/modules/statistics/bin/loganalyzer.php index 0186477c6d072fc016eb5b7ce6e1cb3c4b9da554..52f5842ea907791a23fb8be53b27e59209b20613 100755 --- a/modules/statistics/bin/loganalyzer.php +++ b/modules/statistics/bin/loganalyzer.php @@ -5,7 +5,7 @@ $baseDir = dirname(dirname(dirname(dirname(__FILE__)))); // Add library autoloader. -require_once($baseDir . '/lib/_autoload.php'); +require_once($baseDir.'/lib/_autoload.php'); // Initialize the configuration. $configdir = \SimpleSAML\Utils\Config::getConfigDir(); @@ -16,7 +16,7 @@ $progName = array_shift($argv); $debug = false; $dryrun = false; -foreach($argv as $a) { +foreach ($argv as $a) { if (strlen($a) === 0) { continue; } @@ -44,8 +44,8 @@ foreach($argv as $a) { $dryrun = true; break; default: - echo('Unknown option: ' . $a . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); + echo 'Unknown option: '.$a."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; exit(1); } } @@ -60,9 +60,9 @@ if (!$dryrun) { $aggregator->store($results); } -foreach ($results AS $slot => $val) { - foreach ($val AS $sp => $no) { - echo $sp . " " . count($no) . " - "; +foreach ($results as $slot => $val) { + foreach ($val as $sp => $no) { + echo $sp." ".count($no)." - "; } echo "\n"; } @@ -72,7 +72,8 @@ foreach ($results AS $slot => $val) { * This function prints the help output. */ -function printHelp() { +function printHelp() +{ global $progName; echo <<<END diff --git a/modules/statistics/bin/logcleaner.php b/modules/statistics/bin/logcleaner.php index 5a84c2a5e3f1366795193c586c963bedf99bde67..071318124d4b9fc002bbdb5a09445361973d20bb 100755 --- a/modules/statistics/bin/logcleaner.php +++ b/modules/statistics/bin/logcleaner.php @@ -5,7 +5,7 @@ $baseDir = dirname(dirname(dirname(dirname(__FILE__)))); // Add library autoloader. -require_once($baseDir . '/lib/_autoload.php'); +require_once($baseDir.'/lib/_autoload.php'); // Initialize the configuration. $configdir = \SimpleSAML\Utils\Config::getConfigDir(); @@ -52,8 +52,8 @@ foreach ($argv as $a) { $output = $v; break; default: - echo('Unknown option: ' . $a . "\n"); - echo('Please run `' . $progName . ' --help` for usage information.' . "\n"); + echo 'Unknown option: '.$a."\n"; + echo 'Please run `'.$progName.' --help` for usage information.'."\n"; exit(1); } } @@ -62,7 +62,7 @@ $cleaner = new \SimpleSAML\Module\statistics\LogCleaner($infile); $cleaner->dumpConfig(); $todelete = $cleaner->clean($debug); -echo "Cleaning these trackIDs: " . join(', ', $todelete) . "\n"; +echo "Cleaning these trackIDs: ".join(', ', $todelete)."\n"; if (!$dryrun) { $cleaner->store($todelete, $output); @@ -72,7 +72,8 @@ if (!$dryrun) { * This function prints the help output. */ -function printHelp() { +function printHelp() +{ global $progName; echo <<<END diff --git a/modules/statistics/config-templates/module_statistics.php b/modules/statistics/config-templates/module_statistics.php index 89c97c4250ceb7baab34ba5711a4fd336b4a9a78..16a21cdd187033b0c131f6f9edfdfd621a00b884 100644 --- a/modules/statistics/config-templates/module_statistics.php +++ b/modules/statistics/config-templates/module_statistics.php @@ -3,8 +3,7 @@ * The configuration of SimpleSAMLphp statistics package */ -$config = array ( - +$config = array( // Authentication & authorization for statistics // Whether the statistics require authentication before use. @@ -24,7 +23,7 @@ $config = array ( 'statdir' => '/tmp/stats/', 'inputfile' => '/var/log/simplesamlphp.stat', - 'offset' => 60*60*2 + 60*60*24*3, // Two hours offset to match epoch and norwegian winter time. + 'offset' => 60 * 60 * 2 + 60 * 60 * 24 * 3, // Two hours offset to match epoch and norwegian winter time. 'datestart' => 1, 'datelength' => 15, @@ -53,44 +52,44 @@ $config = array ( 'timeres' => array( 'day' => array( 'name' => 'Day', - 'slot' => 60*15, // Slots of 15 minutes - 'fileslot' => 60*60*24, // One day (24 hours) file slots - 'axislabelint' => 6*4, // Number of slots per label. 4 per hour *6 = 6 hours - 'dateformat-period' => 'j. M', // 4. Mars - 'dateformat-intra' => 'j. M H:i', // 4. Mars 12:30 + 'slot' => 60 * 15, // Slots of 15 minutes + 'fileslot' => 60 * 60 * 24, // One day (24 hours) file slots + 'axislabelint' => 6 * 4, // Number of slots per label. 4 per hour *6 = 6 hours + 'dateformat-period' => 'j. M', // 4. Mars + 'dateformat-intra' => 'j. M H:i', // 4. Mars 12:30 ), 'week' => array( 'name' => 'Week', - 'slot' => 60*60, // Slots of one hour - 'fileslot' => 60*60*24*7, // 7 days of data in each file - 'axislabelint' => 24, // Number of slots per label. 24 is one each day - 'dateformat-period' => 'j. M', // 4. Mars - 'dateformat-intra' => 'j. M H:i', // 4. Mars 12:30 + 'slot' => 60 * 60, // Slots of one hour + 'fileslot' => 60 * 60 * 24 * 7, // 7 days of data in each file + 'axislabelint' => 24, // Number of slots per label. 24 is one each day + 'dateformat-period' => 'j. M', // 4. Mars + 'dateformat-intra' => 'j. M H:i', // 4. Mars 12:30 ), 'month' => array( 'name' => 'Month', - 'slot' => 60*60*24, // Slots of one day - 'fileslot' => 60*60*24*30, // 30 days of data in each file - 'axislabelint' => 7, // Number of slots per label. 7 days => 1 week - 'dateformat-period' => 'j. M Y H:i', // 4. Mars 12:30 - 'dateformat-intra' => 'j. M', // 4. Mars + 'slot' => 60 * 60 * 24, // Slots of one day + 'fileslot' => 60 * 60 * 24 * 30, // 30 days of data in each file + 'axislabelint' => 7, // Number of slots per label. 7 days => 1 week + 'dateformat-period' => 'j. M Y H:i', // 4. Mars 12:30 + 'dateformat-intra' => 'j. M', // 4. Mars ), 'monthaligned' => array( 'name' => 'AlignedMonth', - 'slot' => 60*60*24, // Slots of one day - 'fileslot' => null, // 30 days of data in each file + 'slot' => 60 * 60 * 24, // Slots of one day + 'fileslot' => null, // 30 days of data in each file 'customDateHandler' => 'month', - 'axislabelint' => 7, // Number of slots per label. 7 days => 1 week - 'dateformat-period' => 'j. M Y H:i', // 4. Mars 12:30 - 'dateformat-intra' => 'j. M', // 4. Mars + 'axislabelint' => 7, // Number of slots per label. 7 days => 1 week + 'dateformat-period' => 'j. M Y H:i', // 4. Mars 12:30 + 'dateformat-intra' => 'j. M', // 4. Mars ), 'days180' => array( 'name' => '180 days', - 'slot' => 60*60*24, // Slots of 1 day (24 hours) - 'fileslot' => 60*60*24*180, // 80 days of data in each file - 'axislabelint' => 30, // Number of slots per label. 7 days => 1 week - 'dateformat-period' => 'j. M', // 4. Mars - 'dateformat-intra' => 'j. M', // 4. Mars + 'slot' => 60 * 60 * 24, // Slots of 1 day (24 hours) + 'fileslot' => 60 * 60 * 24 * 180, // 80 days of data in each file + 'axislabelint' => 30, // Number of slots per label. 7 days => 1 week + 'dateformat-period' => 'j. M', // 4. Mars + 'dateformat-intra' => 'j. M', // 4. Mars ), ), @@ -121,7 +120,7 @@ $config = array ( 'name' => 'SSO to service', 'descr' => 'The number of logins at a Service Provider.', 'action' => 'saml20-idp-SSO', - 'col' => 6, // Service Provider EntityID + 'col' => 6, // Service Provider EntityID 'fieldPresentation' => array( 'class' => 'statistics:Entity', 'config' => 'saml20-sp-remote', @@ -131,7 +130,7 @@ $config = array ( 'name' => 'SSO-first to service', 'descr' => 'The number of logins at a Service Provider.', 'action' => 'saml20-idp-SSO-first', - 'col' => 6, // Service Provider EntityID + 'col' => 6, // Service Provider EntityID 'fieldPresentation' => array( 'class' => 'statistics:Entity', 'config' => 'saml20-sp-remote', @@ -141,7 +140,7 @@ $config = array ( 'name' => 'SLO initiated from service', 'descr' => 'The number of initated Sinlge Logout from each of the service providers.', 'action' => 'saml20-idp-SLO', - 'col' => 7, // Service Provider EntityID that initiated the logout. + 'col' => 7, // Service Provider EntityID that initiated the logout. 'fieldPresentation' => array( 'class' => 'statistics:Entity', 'config' => 'saml20-sp-remote', @@ -171,18 +170,17 @@ $config = array ( 'name' => 'SLO iframe pages', 'descr' => 'The varioust IFrame SLO pages a user visits', 'action' => 'slo-iframe', - 'col' => 6, // Page the user visits. + 'col' => 6, // Page the user visits. ), 'slofail' => array( 'name' => 'Failed iframe IdP-init SLOs', 'descr' => 'The number of logout failures from various SPs', 'action' => 'slo-iframe-fail', - 'col' => 6, // Service Provider EntityID that wasn't logged out. + 'col' => 6, // Service Provider EntityID that wasn't logged out. 'fieldPresentation' => array( 'class' => 'statistics:Entity', 'config' => 'saml20-sp-remote', ), ), ), - ); diff --git a/modules/statistics/hooks/hook_cron.php b/modules/statistics/hooks/hook_cron.php index 7df92b8ddfc5bc8da4bbc3d5fb2f5041beb4451e..b86b480d3121d3c8dd8a6f8b7bda1a86332d0163 100644 --- a/modules/statistics/hooks/hook_cron.php +++ b/modules/statistics/hooks/hook_cron.php @@ -35,7 +35,7 @@ function statistics_hook_cron(&$croninfo) $aggregator->store($results); } } catch (\Exception $e) { - $message = 'Loganalyzer threw exception: ' . $e->getMessage(); + $message = 'Loganalyzer threw exception: '.$e->getMessage(); \SimpleSAML\Logger::warning($message); $croninfo['summary'][] = $message; } diff --git a/modules/statistics/hooks/hook_sanitycheck.php b/modules/statistics/hooks/hook_sanitycheck.php index 82a131394180597af971ef696ee9362000099996..85117477c9bdc3d11014f50899868f44dc50bb85 100644 --- a/modules/statistics/hooks/hook_sanitycheck.php +++ b/modules/statistics/hooks/hook_sanitycheck.php @@ -12,27 +12,27 @@ function statistics_hook_sanitycheck(&$hookinfo) try { $statconfig = \SimpleSAML\Configuration::getConfig('module_statistics.php'); - } catch(Exception $e) { - $hookinfo['errors'][] = '[statistics] Could not get configuration: ' . $e->getMessage(); return; + } catch (Exception $e) { + $hookinfo['errors'][] = '[statistics] Could not get configuration: '.$e->getMessage(); return; } $statdir = $statconfig->getValue('statdir'); $inputfile = $statconfig->getValue('inputfile'); if (file_exists($statdir)) { - $hookinfo['info'][] = '[statistics] Statistics dir [' . $statdir . '] exists'; + $hookinfo['info'][] = '[statistics] Statistics dir ['.$statdir.'] exists'; if (is_writable($statdir)) { - $hookinfo['info'][] = '[statistics] Statistics dir [' . $statdir . '] is writable'; + $hookinfo['info'][] = '[statistics] Statistics dir ['.$statdir.'] is writable'; } else { - $hookinfo['errors'][] = '[statistics] Statistics dir [' . $statdir . '] is not writable'; + $hookinfo['errors'][] = '[statistics] Statistics dir ['.$statdir.'] is not writable'; } } else { - $hookinfo['errors'][] = '[statistics] Statistics dir [' . $statdir . '] does not exists'; + $hookinfo['errors'][] = '[statistics] Statistics dir ['.$statdir.'] does not exists'; } if (file_exists($inputfile)) { - $hookinfo['info'][] = '[statistics] Input file [' . $inputfile . '] exists'; + $hookinfo['info'][] = '[statistics] Input file ['.$inputfile.'] exists'; } else { - $hookinfo['errors'][] = '[statistics] Input file [' . $inputfile . '] does not exists'; + $hookinfo['errors'][] = '[statistics] Input file ['.$inputfile.'] does not exists'; } } diff --git a/modules/statistics/lib/AccessCheck.php b/modules/statistics/lib/AccessCheck.php index 5b7967f1cb2f062a3e52f62c0fdd72484d041bef..a4a003abb90488cda913eb43949dfa8780b50d19 100644 --- a/modules/statistics/lib/AccessCheck.php +++ b/modules/statistics/lib/AccessCheck.php @@ -48,7 +48,7 @@ class AccessCheck $as->requireAuth(); // User logged in with auth source. - \SimpleSAML\Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']'); + \SimpleSAML\Logger::debug('Statistics auth - valid login with auth source ['.$authsource.']'); // Retrieving attributes $attributes = $as->getAttributes(); @@ -61,10 +61,10 @@ class AccessCheck // Check if userid is allowed access.. if (in_array($attributes[$useridattr][0], $allowedusers, true)) { - \SimpleSAML\Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']'); + \SimpleSAML\Logger::debug('Statistics auth - User granted access by user ID ['.$attributes[$useridattr][0].']'); return; } - \SimpleSAML\Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']'); + \SimpleSAML\Logger::debug('Statistics auth - User denied access by user ID ['.$attributes[$useridattr][0].']'); } else { \SimpleSAML\Logger::debug('Statistics auth - no allowedUsers list.'); } diff --git a/modules/statistics/lib/Aggregator.php b/modules/statistics/lib/Aggregator.php index eae6ab5c564d259b51bf853fb326da78a5baf54a..9a022e341194b820382c2e3a941c66a7b61f4b99 100644 --- a/modules/statistics/lib/Aggregator.php +++ b/modules/statistics/lib/Aggregator.php @@ -39,19 +39,19 @@ class Aggregator public function dumpConfig() { - echo 'Statistics directory : ' . $this->statdir . "\n"; - echo 'Input file : ' . $this->inputfile . "\n"; - echo 'Offset : ' . $this->offset . "\n"; + echo 'Statistics directory : '.$this->statdir."\n"; + echo 'Input file : '.$this->inputfile."\n"; + echo 'Offset : '.$this->offset."\n"; } public function debugInfo() { - echo 'Memory usage : ' . number_format(memory_get_usage() / (1024*1024), 2) . " MB\n"; + echo 'Memory usage : '.number_format(memory_get_usage() / 1048576, 2)." MB\n"; // 1024*1024=1048576 } public function loadMetadata() { - $filename = $this->statdir . '/.stat.metadata'; + $filename = $this->statdir.'/.stat.metadata'; $metadata = null; if (file_exists($filename)) { $metadata = unserialize(file_get_contents($filename)); @@ -70,25 +70,26 @@ class Aggregator $this->metadata['memory'] = memory_get_usage(); $this->metadata['lastrun'] = time(); - $filename = $this->statdir . '/.stat.metadata'; + $filename = $this->statdir.'/.stat.metadata'; file_put_contents($filename, serialize($this->metadata), LOCK_EX); } - public function aggregate($debug = false) { + public function aggregate($debug = false) + { $this->loadMetadata(); if (!is_dir($this->statdir)) { - throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']'); + throw new \Exception('Statistics module: output dir do not exists ['.$this->statdir.']'); } if (!file_exists($this->inputfile)) { - throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']'); + throw new \Exception('Statistics module: input file do not exists ['.$this->inputfile.']'); } $file = fopen($this->inputfile, 'r'); if ($file === false) { - throw new \Exception('Statistics module: unable to open file [' . $this->inputfile . ']'); + throw new \Exception('Statistics module: unable to open file ['.$this->inputfile.']'); } $logparser = new LogParser( @@ -131,13 +132,13 @@ class Aggregator $action = trim($content[5]); if ($this->fromcmdline && ($i % 10000) == 0) { - echo("Read line " . $i . "\n"); + echo "Read line ".$i."\n"; } if ($debug) { - echo("----------------------------------------\n"); - echo('Log line: ' . $logline . "\n"); - echo('Date parse [' . substr($logline, 0, $this->statconfig->getValue('datelength', 15)) . '] to [' . date(DATE_RFC822, $epoch) . ']' . "\n"); + echo "----------------------------------------\n"; + echo 'Log line: '.$logline."\n"; + echo 'Date parse ['.substr($logline, 0, $this->statconfig->getValue('datelength', 15)).'] to ['.date(DATE_RFC822, $epoch).']'."\n"; echo htmlentities(print_r($content, true)); if ($i >= 13) { exit; @@ -150,7 +151,7 @@ class Aggregator if ($epoch === $notBefore) { if (!$lastlineflip) { - if (sha1($logline) === $lastlinehash) { + if (sha1($logline) === $lastlinehash) { $lastlineflip = true; } continue; @@ -173,7 +174,7 @@ class Aggregator continue; } - foreach ($this->timeres as $tres => $tresconfig ) { + foreach ($this->timeres as $tres => $tresconfig) { $dh = 'default'; if (isset($tresconfig['customDateHandler'])) { $dh = $tresconfig['customDateHandler']; @@ -268,19 +269,19 @@ class Aggregator $maxslot = $slotlist[count($slotlist) - 1]; // Get start and end slot number within the file, based on the fileslot. - $start = (int)$datehandler['default']->toSlot( + $start = (int) $datehandler['default']->toSlot( $datehandler[$dh]->fromSlot($fileno, $this->timeres[$tres]['fileslot']), $this->timeres[$tres]['slot'] ); - $end = (int)$datehandler['default']->toSlot( - $datehandler[$dh]->fromSlot($fileno+1, $this->timeres[$tres]['fileslot']), + $end = (int) $datehandler['default']->toSlot( + $datehandler[$dh]->fromSlot($fileno + 1, $this->timeres[$tres]['fileslot']), $this->timeres[$tres]['slot'] ); // Fill in missing entries and sort file results $filledresult = array(); for ($slot = $start; $slot < $end; $slot++) { - if (array_key_exists($slot, $fileres)) { + if (array_key_exists($slot, $fileres)) { $filledresult[$slot] = $fileres[$slot]; } else { if ($lastfile == $fileno && $slot > $maxslot) { @@ -291,7 +292,7 @@ class Aggregator } } - $filename = $this->statdir . '/' . $rulename . '-' . $tres . '-' . $fileno . '.stat'; + $filename = $this->statdir.'/'.$rulename.'-'.$tres.'-'.$fileno.'.stat'; if (file_exists($filename)) { $previousData = unserialize(file_get_contents($filename)); $filledresult = $this->cummulateData($previousData, $filledresult); diff --git a/modules/statistics/lib/DateHandler.php b/modules/statistics/lib/DateHandler.php index b35d07ab3f7427a8e7e60cc19e35746d9e59df43..b62cfb62494ab703f3e82b3b2ff866a0f8ce85e1 100644 --- a/modules/statistics/lib/DateHandler.php +++ b/modules/statistics/lib/DateHandler.php @@ -32,14 +32,14 @@ class DateHandler public function toSlot($epoch, $slotsize) { $dst = $this->getDST($epoch); - return floor( ($epoch + $this->offset + $dst) / $slotsize); + return floor(($epoch + $this->offset + $dst) / $slotsize); } public function fromSlot($slot, $slotsize) { - $temp = $slot*$slotsize - $this->offset; + $temp = $slot * $slotsize - $this->offset; $dst = $this->getDST($temp); - return $slot*$slotsize - $this->offset - $dst; + return $slot * $slotsize - $this->offset - $dst; } public function prettyDateEpoch($epoch, $dateformat) diff --git a/modules/statistics/lib/DateHandlerMonth.php b/modules/statistics/lib/DateHandlerMonth.php index 979e1838b99fd888c6649e45dba9fca500366a0b..78209d03e98880ab2a9c0accc076de53b47b397c 100644 --- a/modules/statistics/lib/DateHandlerMonth.php +++ b/modules/statistics/lib/DateHandlerMonth.php @@ -38,6 +38,6 @@ class DateHandlerMonth extends DateHandler { $month = ($from % 12) + 1; $year = 2000 + floor($from / 12); - return $year . '-' . $month; + return $year.'-'.$month; } } diff --git a/modules/statistics/lib/Graph/GoogleCharts.php b/modules/statistics/lib/Graph/GoogleCharts.php index db3df14463ce7585749abc5a4645ecbd7017c76d..072ef33b7d92b867acf0854b9796273141bd10bd 100644 --- a/modules/statistics/lib/Graph/GoogleCharts.php +++ b/modules/statistics/lib/Graph/GoogleCharts.php @@ -48,7 +48,7 @@ class GoogleCharts foreach ($datasets as $dataset) { $setstr[] = self::extEncode($dataset); } - return 'e:' . join(',', $setstr); + return 'e:'.join(',', $setstr); } public static function extEncode($values) // $max = 4095, $min = 0 @@ -63,11 +63,11 @@ class GoogleCharts $first = substr($extended_table, intval(($delta * $v / 100) / $size), 1); $second = substr($extended_table, intval(($delta * $v / 100) % $size), 1); $chardata .= "$first$second"; - } else { + } else { $chardata .= '__'; // Value out of max range; } } - return($chardata); + return $chardata; } /** @@ -82,49 +82,49 @@ class GoogleCharts */ public function show($axis, $axispos, $datasets, $maxes) { - $labeld = '&chxt=x,y' . '&chxr=0,0,1|1,0,' . $maxes[0]; + $labeld = '&chxt=x,y'.'&chxr=0,0,1|1,0,'.$maxes[0]; if (count($datasets) > 1) { if (count($datasets) !== count($maxes)) { throw new \Exception('Incorrect number of max calculations for graph plotting.'); } - $labeld = '&chxt=x,y,r' . '&chxr=0,0,1|1,0,' . $maxes[0] . '|2,0,' . $maxes[1]; + $labeld = '&chxt=x,y,r'.'&chxr=0,0,1|1,0,'.$maxes[0].'|2,0,'.$maxes[1]; } - $url = 'https://chart.apis.google.com/chart?' . + $url = 'https://chart.apis.google.com/chart?'. // Dimension of graph. Default is 800x350 - 'chs=' . $this->x . 'x' . $this->y . + 'chs='.$this->x.'x'.$this->y. // Dateset values - '&chd=' . $this->encodedata($datasets) . + '&chd='.$this->encodedata($datasets). // Fill area... - '&chco=ff5c00,cca600' . - '&chls=1,1,0|1,6,3' . + '&chco=ff5c00,cca600'. + '&chls=1,1,0|1,6,3'. // chart type is linechart - '&cht=lc' . - $labeld . - '&chxl=0:|' . $this->encodeaxis($axis) . # . $'|1:||top' . - '&chxp=0,' . join(',', $axispos) . - '&chg=' . (2400/(count($datasets[0])-1)) . ',-1,3,3'; // lines + '&cht=lc'. + $labeld. + '&chxl=0:|'.$this->encodeaxis($axis).#.$'|1:||top'. + '&chxp=0,'.join(',', $axispos). + '&chg='.(2400 / (count($datasets[0]) - 1)).',-1,3,3'; // lines return $url; } public function showPie($axis, $datasets) { - $url = 'https://chart.apis.google.com/chart?' . + $url = 'https://chart.apis.google.com/chart?'. // Dimension of graph. Default is 800x350 - 'chs=' . $this->x . 'x' . $this->y . + 'chs='.$this->x.'x'.$this->y. // Dateset values. - '&chd=' . $this->encodedata(array($datasets)) . + '&chd='.$this->encodedata(array($datasets)). // chart type is linechart - '&cht=p' . + '&cht=p'. - '&chl=' . $this->encodeaxis($axis); + '&chl='.$this->encodeaxis($axis); return $url; } diff --git a/modules/statistics/lib/LogCleaner.php b/modules/statistics/lib/LogCleaner.php index 77ceeaaa4b9f1e46e2ed2631a813a08f45992838..d04204df951894a9a273d83bb63e8a0eb29e4e70 100644 --- a/modules/statistics/lib/LogCleaner.php +++ b/modules/statistics/lib/LogCleaner.php @@ -37,9 +37,9 @@ class LogCleaner */ public function dumpConfig() { - echo 'Statistics directory : ' . $this->statdir . "\n"; - echo 'Input file : ' . $this->inputfile . "\n"; - echo 'Offset : ' . $this->offset . "\n"; + echo 'Statistics directory : '.$this->statdir."\n"; + echo 'Input file : '.$this->inputfile."\n"; + echo 'Offset : '.$this->offset."\n"; } @@ -50,11 +50,11 @@ class LogCleaner public function clean($debug = false) { if (!is_dir($this->statdir)) { - throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']'); + throw new \Exception('Statistics module: output dir do not exists ['.$this->statdir.']'); } if (!file_exists($this->inputfile)) { - throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']'); + throw new \Exception('Statistics module: input file do not exists ['.$this->inputfile.']'); } $file = fopen($this->inputfile, 'r'); @@ -81,7 +81,7 @@ class LogCleaner $content = $logparser->parseContent($logline); if (($i % 10000) == 0) { - echo("Read line " . $i . "\n"); + echo "Read line ".$i."\n"; } $trackid = $content[4]; @@ -92,9 +92,9 @@ class LogCleaner $sessioncounter[$trackid]++; if ($debug) { - echo("----------------------------------------\n"); - echo('Log line: ' . $logline . "\n"); - echo('Date parse [' . substr($logline, 0, $this->statconfig->getValue('datelength', 15)) . '] to [' . date(DATE_RFC822, $epoch) . ']' . "\n"); + echo "----------------------------------------\n"; + echo 'Log line: '.$logline."\n"; + echo 'Date parse ['.substr($logline, 0, $this->statconfig->getValue('datelength', 15)).'] to ['.date(DATE_RFC822, $epoch).']'."\n"; echo htmlentities(print_r($content, true)); if ($i >= 13) { exit; @@ -129,14 +129,14 @@ class LogCleaner */ public function store($todelete, $outputfile) { - echo "Preparing to delete [" .count($todelete) . "] trackids\n"; + echo "Preparing to delete [".count($todelete)."] trackids\n"; if (!is_dir($this->statdir)) { - throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']'); + throw new \Exception('Statistics module: output dir do not exists ['.$this->statdir.']'); } if (!file_exists($this->inputfile)) { - throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']'); + throw new \Exception('Statistics module: input file do not exists ['.$this->inputfile.']'); } $file = fopen($this->inputfile, 'r'); @@ -146,7 +146,7 @@ class LogCleaner // Delete existing output file. unlink($outputfile); } - $outfile = fopen($outputfile, 'x'); /* Create the output file. */ + $outfile = fopen($outputfile, 'x'); // Create the output file $logparser = new LogParser( $this->statconfig->getValue('datestart', 0), $this->statconfig->getValue('datelength', 15), $this->statconfig->getValue('offsetspan', 44) @@ -166,7 +166,7 @@ class LogCleaner $content = $logparser->parseContent($logline); if (($i % 10000) == 0) { - echo("Read line " . $i . "\n"); + echo "Read line ".$i."\n"; } $trackid = $content[4]; diff --git a/modules/statistics/lib/LogParser.php b/modules/statistics/lib/LogParser.php index e4cf72a15747f4d2dee40dc893d7883678925c44..1fa73aa5e689c094c383a1f3bc1ad70722debe38 100644 --- a/modules/statistics/lib/LogParser.php +++ b/modules/statistics/lib/LogParser.php @@ -47,7 +47,8 @@ class LogParser public function parseEpoch($line) { $epoch = strtotime(substr($line, 0, $this->datelength)); - if ($epoch > time() + 2678400) { // 60 * 60 *24 * 31 = 2678400 + if ($epoch > time() + 2678400) { + // 60 * 60 * 24 * 31 = 2678400 /* * More than a month in the future - probably caused by * the log files missing the year. diff --git a/modules/statistics/lib/RatioDataset.php b/modules/statistics/lib/RatioDataset.php index da9f5d055d5e3b6b379b556931f66f20ea683e7c..fcb7377fd4a0aafdba04dec9d6f855617f8b857a 100644 --- a/modules/statistics/lib/RatioDataset.php +++ b/modules/statistics/lib/RatioDataset.php @@ -17,7 +17,7 @@ class RatioDataset extends StatDataset $this->summary = array(); $noofvalues = array(); foreach ($this->results as $slot => $res) { - foreach ($res AS $key => $value) { + foreach ($res as $key => $value) { if (array_key_exists($key, $this->summary)) { $this->summary[$key] += $value; if ($value > 0) { diff --git a/modules/statistics/lib/Ruleset.php b/modules/statistics/lib/Ruleset.php index 679dd368e928594bcdda080059a9d8384af82800..d94ee7c03ce89f31f769e6f18bed9e22b602dc5f 100644 --- a/modules/statistics/lib/Ruleset.php +++ b/modules/statistics/lib/Ruleset.php @@ -33,20 +33,21 @@ class Ruleset * Walk through file lists, and get available [rule][fileslot]... */ if (!is_dir($statdir)) { - throw new \Exception('Statisics output directory [' . $statdir . '] does not exists.'); + throw new \Exception('Statisics output directory ['.$statdir.'] does not exists.'); } $filelist = scandir($statdir); $this->available = array(); foreach ($filelist as $file) { - if (preg_match('/([a-z0-9_]+)-([a-z0-9_]+)-([0-9]+)\.stat/', $file, $matches)) { - if (array_key_exists($matches[1], $statrules)) { - if (array_key_exists($matches[2], $timeres)) - $this->available[$matches[1]][$matches[2]][] = $matches[3]; + if (preg_match('/([a-z0-9_]+)-([a-z0-9_]+)-([0-9]+)\.stat/', $file, $matches)) { + if (array_key_exists($matches[1], $statrules)) { + if (array_key_exists($matches[2], $timeres)) { + $this->available[$matches[1]][$matches[2]][] = $matches[3]; + } } } } if (empty($this->available)) { - throw new \Exception('No aggregated statistics files found in [' . $statdir . ']'); + throw new \Exception('No aggregated statistics files found in ['.$statdir.']'); } /* diff --git a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php index 6841861ba82c159fa05f7e4b9900100ed5e23ed1..5ceca8590c7a6a7f8f278909ac25a4ddabfcd3e5 100644 --- a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php +++ b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php @@ -36,7 +36,8 @@ class BaseRule return $this->ruleid; } - public function availableTimeRes() { + public function availableTimeRes() + { $timeresConfigs = $this->statconfig->getValue('timeres'); $available_times = array(); foreach ($timeresConfigs as $tres => $tresconfig) {