diff --git a/.gitignore b/.gitignore index 52af6659..8ea128a0 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ utils/dist/ utils/tmp/ utils/starting_HEAD /.settings +.idea/ +vendor/ +.php_cs.cache +composer.lock diff --git a/.php_cs b/.php_cs new file mode 100644 index 00000000..e8c5a2a1 --- /dev/null +++ b/.php_cs @@ -0,0 +1,77 @@ +finder(DefaultFinder::create()->in(__DIR__)) + ->fixers($fixers) + ->level(FixerInterface::NONE_LEVEL) + ->setUsingCache(true); diff --git a/.project b/.project index b3514ecb..6cefd46a 100644 --- a/.project +++ b/.project @@ -1,6 +1,6 @@ - phpcas-devel + phpCAS-devel diff --git a/.travis.yml b/.travis.yml index 3469035c..1218609c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,32 @@ language: php + php: - - "5.4" - - "5.5" - - "5.6" -script: - - cd test - - phpunit TestSuite.php + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - hhvm + +env: + global: + - setup=basic + +matrix: + include: + - php: 5.4 + env: setup=lowest + - php: 5.4 + env: setup=stable + sudo: false + +before_install: + - travis_retry composer self-update + +install: + - if [[ $setup = 'basic' ]]; then travis_retry composer install --no-interaction --prefer-dist; fi + - if [[ $setup = 'stable' ]]; then travis_retry composer update --prefer-dist --no-interaction --prefer-stable; fi + - if [[ $setup = 'lowest' ]]; then travis_retry composer update --prefer-dist --no-interaction --prefer-lowest --prefer-stable; fi + +script: vendor/bin/phpunit + diff --git a/CAS.php b/CAS.php deleted file mode 100644 index 8cd549ea..00000000 --- a/CAS.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ - -require_once dirname(__FILE__).'/source/CAS.php'; \ No newline at end of file diff --git a/composer.json b/composer.json index 825b4c41..47d71ac7 100644 --- a/composer.json +++ b/composer.json @@ -14,12 +14,18 @@ "ext-curl": "*" }, "require-dev": { - "phpunit/phpunit": "~3.7.10" + "fabpot/php-cs-fixer": "~1.11", + "phpunit/phpunit": "~3.7" }, "autoload": { - "classmap": [ - "source/" - ] + "psr-4": { + "phpCAS\\": "source/" + } + }, + "autoload-dev": { + "psr-4": { + "phpCAS\\": "test/" + } }, "extra": { "branch-alias": { diff --git a/docs/Upgrading b/docs/Upgrading index 2176da6f..07461018 100644 --- a/docs/Upgrading +++ b/docs/Upgrading @@ -4,7 +4,7 @@ For security hardening purposes the verbose error messages to the web browsers are now masked. If you want to have the verbose messages you need to use: -phpCAS::setVerbose(true); +CAS::setVerbose(true); This will set the configuration to the old verbose mode that helps during development and debugging. @@ -55,11 +55,11 @@ when validating the proxy tickets. The strings are compared starting from the beginning and must fully match with the proxies in the list. Examples: - phpCAS::allowProxyChain(new CAS_ProxyChain(array( + CAS::allowProxyChain(new CAS_ProxyChain(array( 'https://app.example.com/' ))); or - phpCAS::allowProxyChain(new CAS_ProxyChain(array( + CAS::allowProxyChain(new CAS_ProxyChain(array( '/^https:\/\/app[0-9]\.example\.com\/rest\//', 'http://client.example.com/' ))); @@ -68,7 +68,7 @@ For quick testing or in certain production screnarios you might want to allow allow any other valid service to proxy your service. To do so, add the "Any" chain: - phpcas::allowProxyChain(new CAS_ProxyChain_Any); + CAS::allowProxyChain(new CAS_ProxyChain_Any); THIS SETTING IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER diff --git a/docs/examples/config.example.php b/docs/examples/config.example.php index 2ada01ca..2bc99f79 100644 --- a/docs/examples/config.example.php +++ b/docs/examples/config.example.php @@ -4,20 +4,18 @@ * The purpose of this central config file is configuring all examples * in one place with minimal work for your working environment * Just configure all the items in this config according to your environment - * and rename the file to config.php + * and rename the file to config.php. * * PHP Version 5 * * @file config.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -$phpcas_path = '../../source/'; +$CAS_path = '../../source/'; /////////////////////////////////////// // Basic Config of the phpCAS client // @@ -41,7 +39,7 @@ // The "real" hosts of clustered cas server that send SAML logout messages // Assumes the cas server is load balanced across multiple hosts -$cas_real_hosts = array('cas-real-1.example.com', 'cas-real-2.example.com'); +$cas_real_hosts = ['cas-real-1.example.com', 'cas-real-2.example.com']; // Client config for cookie hardening $client_domain = '127.0.0.1'; @@ -64,41 +62,40 @@ // Generating the URLS for the local cas example services for proxy testing if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { - $curbase = 'https://' . $_SERVER['SERVER_NAME']; + $curbase = 'https://'.$_SERVER['SERVER_NAME']; } else { - $curbase = 'http://' . $_SERVER['SERVER_NAME']; + $curbase = 'http://'.$_SERVER['SERVER_NAME']; } if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) { - $curbase .= ':' . $_SERVER['SERVER_PORT']; + $curbase .= ':'.$_SERVER['SERVER_PORT']; } -$curdir = dirname($_SERVER['REQUEST_URI']) . "/"; +$curdir = dirname($_SERVER['REQUEST_URI']).'/'; // CAS client nodes for rebroadcasting pgtIou/pgtId and logoutRequest $rebroadcast_node_1 = 'http://cas-client-1.example.com'; $rebroadcast_node_2 = 'http://cas-client-2.example.com'; // access to a single service -$serviceUrl = $curbase . $curdir . 'example_service.php'; +$serviceUrl = $curbase.$curdir.'example_service.php'; // access to a second service -$serviceUrl2 = $curbase . $curdir . 'example_service_that_proxies.php'; +$serviceUrl2 = $curbase.$curdir.'example_service_that_proxies.php'; -$pgtBase = preg_quote(preg_replace('/^http:/', 'https:', $curbase . $curdir), '/'); -$pgtUrlRegexp = '/^' . $pgtBase . '.*$/'; +$pgtBase = preg_quote(preg_replace('/^http:/', 'https:', $curbase.$curdir), '/'); +$pgtUrlRegexp = '/^'.$pgtBase.'.*$/'; -$cas_url = 'https://' . $cas_host; +$cas_url = 'https://'.$cas_host; if ($cas_port != '443') { - $cas_url = $cas_url . ':' . $cas_port; + $cas_url = $cas_url.':'.$cas_port; } -$cas_url = $cas_url . $cas_context; +$cas_url = $cas_url.$cas_context; // Set the session-name to be unique to the current script so that the client script // doesn't share its session with a proxied script. // This is just useful when running the example code, but not normally. session_name( 'session_for:' - . preg_replace('/[^a-z0-9-]/i', '_', basename($_SERVER['SCRIPT_NAME'])) + .preg_replace('/[^a-z0-9-]/i', '_', basename($_SERVER['SCRIPT_NAME'])) ); // Set an UTF-8 encoding header for internation characters (User attributes) header('Content-Type: text/html; charset=utf-8'); -?> diff --git a/docs/examples/create_pgt_storage_db_table.php b/docs/examples/create_pgt_storage_db_table.php index 5c424c6b..e680d097 100644 --- a/docs/examples/create_pgt_storage_db_table.php +++ b/docs/examples/create_pgt_storage_db_table.php @@ -8,31 +8,34 @@ * CAS_PGTStorage_Db() options: * $db, $db_user, $db_password, $db_table, $driver_options * have to filled out directly. Option examples can be found in the - * config.example.php + * config.example.php. * * PHP Version 5 * * @file create_pgt_storage_table.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\PGTStorage\Db; // Dummy client because we need a 'client' object -$client = new CAS_Client( - CAS_VERSION_2_0, true, $cas_host, $cas_port, $cas_context, false +$client = new Client( + CAS::CAS_VERSION_2_0, true, $cas_host, $cas_port, $cas_context, false ); -// Set the torage object -$cas_obj = new CAS_PGTStorage_Db( +// Set the storage object +$cas_obj = new Db( $client, $db, $db_user, $db_password, $db_table, $driver_options ); $cas_obj->init(); @@ -46,7 +49,7 @@
' . $db_table . ' successfully created in database ' . $db . ''; +echo 'Table '.$db_table.' successfully created in database '.$db.''; ?>
diff --git a/docs/examples/example_advanced_saml11.php b/docs/examples/example_advanced_saml11.php index 3c495180..86820dca 100644 --- a/docs/examples/example_advanced_saml11.php +++ b/docs/examples/example_advanced_saml11.php @@ -1,53 +1,55 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -phpCAS::setCasServerCACert($cas_server_ca_cert_path); +CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -// phpCAS::setNoCasServerValidation(); +// CAS::setNoCasServerValidation(); // Handle SAML logout requests that emanate from the CAS host exclusively. // Failure to restrict SAML logout requests to authorized hosts could // allow denial of service attacks where at the least the server is // tied up parsing bogus XML messages. -phpCAS::handleLogoutRequests(true, $cas_real_hosts); +CAS::handleLogoutRequests(true, $cas_real_hosts); // Force CAS authentication on any page that includes this file -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // Some small code triggered by the logout button if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } ?> @@ -59,12 +61,12 @@ Authentication succeeded for user -. +.

User Attributes

    $value) { +foreach (CAS::getAttributes() as $key => $value) { if (is_array($value)) { echo '
  • ', $key, ':
      '; foreach ($value as $item) { @@ -72,7 +74,7 @@ } echo '
  • '; } else { - echo '
  • ', $key, ': ', $value, '
  • ' . PHP_EOL; + echo '
  • ', $key, ': ', $value, '
  • '.PHP_EOL; } } ?> diff --git a/docs/examples/example_custom_urls.php b/docs/examples/example_custom_urls.php index 97c155fe..b7ae9d27 100644 --- a/docs/examples/example_custom_urls.php +++ b/docs/examples/example_custom_urls.php @@ -1,70 +1,72 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // Override the validation url for any (ST and PT) CAS 2.0 validation -phpCAS::setServerProxyValidateURL('https://cas.example.org:1443/proxyValidate'); +CAS::setServerProxyValidateURL('https://cas.example.org:1443/proxyValidate'); // Override the validation url for any CAS 1.0 validation -//phpCAS::setServerServiceValidateURL('https://cas.example.org:1443/serviceValidate'); +//CAS::setServerServiceValidateURL('https://cas.example.org:1443/serviceValidate'); //Override the validation url for any SAML11 validation -//phpCAS::setServerSamlValidateURL('https://cas.example.org:1443/samlValidate'); +//CAS::setServerSamlValidateURL('https://cas.example.org:1443/samlValidate'); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // logout if desired if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client -

    Successfull Authentication!

    +

    Successful Authentication!

    -

    the user's login is .

    -

    phpCAS version is .

    +

    the user's login is .

    +

    phpCAS version is .

    Logout

    diff --git a/docs/examples/example_gateway.php b/docs/examples/example_gateway.php index b7715c29..f1a61ba8 100644 --- a/docs/examples/example_gateway.php +++ b/docs/examples/example_gateway.php @@ -1,50 +1,52 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } if (isset($_REQUEST['login'])) { - phpCAS::forceAuthentication(); + CAS::forceAuthentication(); } // check CAS authentication -$auth = phpCAS::checkAuthentication(); +$auth = CAS::checkAuthentication(); ?> @@ -54,18 +56,21 @@ -

    Successfull Authentication!

    +

    Successful Authentication!

    -

    the user's login is .

    +

    the user's login is .

    Logout

    + ?>

    Guest mode

    Login

    -

    phpCAS version is .

    +

    phpCAS version is .

    diff --git a/docs/examples/example_hardening.php b/docs/examples/example_hardening.php index 25aae275..29e181d8 100644 --- a/docs/examples/example_hardening.php +++ b/docs/examples/example_hardening.php @@ -7,50 +7,52 @@ * * @file example_hardening.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(false); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(false); // Harden session cookie to prevent some attacks on the cookie (e.g. XSS) session_set_cookie_params($client_lifetime, $client_path, $client_domain, $client_secure, $client_httpOnly); // Initialize phpCAS -phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -phpCAS::setCasServerCACert($cas_server_ca_cert_path); +CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -// phpCAS::setNoCasServerValidation(); +// CAS::setNoCasServerValidation(); // Handle SAML logout requests that emanate from the CAS host exclusively. // Failure to restrict SAML logout requests to authorized hosts could // allow denial of service attacks where at the least the server is // tied up parsing bogus XML messages. -phpCAS::handleLogoutRequests(true, $cas_real_hosts); +CAS::handleLogoutRequests(true, $cas_real_hosts); // Force CAS authentication on any page that includes this file -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // Some small code triggered by the logout button if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } ?> @@ -62,12 +64,12 @@ Authentication succeeded for user -. +.

    User Attributes

      $value) { +foreach (CAS::getAttributes() as $key => $value) { if (is_array($value)) { echo '
    • ', $key, ':
        '; foreach ($value as $item) { @@ -75,7 +77,7 @@ } echo '
    • '; } else { - echo '
    • ', $key, ': ', $value, '
    • ' . PHP_EOL; + echo '
    • ', $key, ': ', $value, '
    • '.PHP_EOL; } } ?> diff --git a/docs/examples/example_html.php b/docs/examples/example_html.php index ec4ee9d0..0d5ca26d 100644 --- a/docs/examples/example_html.php +++ b/docs/examples/example_html.php @@ -7,37 +7,39 @@ * * @file example_html.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // customize HTML output -phpCAS::setHTMLHeader( +CAS::setHTMLHeader( ' __TITLE__ @@ -45,7 +47,7 @@

      __TITLE__

      ' ); -phpCAS::setHTMLFooter( +CAS::setHTMLFooter( '
      phpCAS __PHPCAS_VERSION__, @@ -56,21 +58,21 @@ ); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client with HTML output customization -

      Successfull Authentication!

      +

      Successful Authentication!

      -

      the user's login is .

      -

      phpCAS version is .

      +

      the user's login is .

      +

      phpCAS version is .

      diff --git a/docs/examples/example_lang.php b/docs/examples/example_lang.php index 1b6b3941..a44cd2aa 100644 --- a/docs/examples/example_lang.php +++ b/docs/examples/example_lang.php @@ -7,48 +7,50 @@ * * @file example_lang.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // set the language to french -phpCAS::setLang(PHPCAS_LANG_FRENCH); +CAS::setLang(CAS::PHPCAS_LANG_FRENCH); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> @@ -57,7 +59,7 @@

      Authentification réussie !

      -

      L'utilisateur connecté est .

      -

      La version de phpCAS est .

      +

      L'utilisateur connecté est .

      +

      La version de phpCAS est .

      diff --git a/docs/examples/example_logout.php b/docs/examples/example_logout.php index cdf42a79..a03a4107 100644 --- a/docs/examples/example_logout.php +++ b/docs/examples/example_logout.php @@ -1,64 +1,66 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // handle incoming logout requests -phpCAS::handleLogoutRequests(); +CAS::handleLogoutRequests(); -// Or as an advanced featue handle SAML logout requests that emanate from the +// Or as an advanced feature handle SAML logout requests that emanate from the // CAS host exclusively. // Failure to restrict SAML logout requests to authorized hosts could // allow denial of service attacks where at the least the server is // tied up parsing bogus XML messages. -// phpCAS::handleLogoutRequests(true, $cas_real_hosts); +// CAS::handleLogoutRequests(true, $cas_real_hosts); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client -

      Successfull Authentication!

      +

      Successful Authentication!

      -

      the user's login is .

      -

      phpCAS version is .

      +

      the user's login is .

      +

      phpCAS version is .

      diff --git a/docs/examples/example_no_ssl_cn_validation.php b/docs/examples/example_no_ssl_cn_validation.php index bf5ef004..9e3cd60d 100644 --- a/docs/examples/example_no_ssl_cn_validation.php +++ b/docs/examples/example_no_ssl_cn_validation.php @@ -1,68 +1,69 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -// phpCAS::setNoCasServerValidation(); -// You can also disable the validation of the certficate CN. This means the +// CAS::setNoCasServerValidation(); +// You can also disable the validation of the certificate CN. This means the // certificate must be valid but the CN of the certificate must not match the // IP or hostname you are using to access the server -phpCAS::setCasServerCACert($cas_server_ca_cert_path, false); - +CAS::setCasServerCACert($cas_server_ca_cert_path, false); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // logout if desired if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client -

      Successfull Authentication!

      +

      Successful Authentication!

      -

      the user's login is .

      -

      phpCAS version is .

      +

      the user's login is .

      +

      phpCAS version is .

      Logout

      diff --git a/docs/examples/example_pgt_storage_db.php b/docs/examples/example_pgt_storage_db.php index b5097628..1c56af62 100644 --- a/docs/examples/example_pgt_storage_db.php +++ b/docs/examples/example_pgt_storage_db.php @@ -1,49 +1,51 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); -// Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +// Initialize CAS +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // set PGT storage to file in plain format in the same directory as session files -phpCAS::setPGTStorageDB($db, $db_user, $db_password, $db_table); +CAS::setPGTStorageDb($db, $db_user, $db_password, $db_table); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. @@ -57,12 +59,12 @@

      phpCAS proxy example with PGT storage to file

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      '; } else { echo '
      '; diff --git a/docs/examples/example_pgt_storage_file.php b/docs/examples/example_pgt_storage_file.php index d7b420a7..4466b2d1 100644 --- a/docs/examples/example_pgt_storage_file.php +++ b/docs/examples/example_pgt_storage_file.php @@ -1,49 +1,51 @@ -* @author Adam Franco -* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 -* @link https://wiki.jasig.org/display/CASC/phpCAS -*/ + * Example that changes the storage of the pgt tickets to file. + * + * PHP Version 5 + * + * @file example_pgt_storage_db.php + * @category Authentication + * @author Joachim Fritschi + * @author Adam Franco + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ + +// Load the autoloader +require_once '../../vendor/autoload.php'; // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); -// Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +// Initialize CAS +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // set PGT storage to file in plain format in the same directory as session files -phpCAS::setPGTStorageFile(session_save_path()); +CAS::setPGTStorageFile(session_save_path()); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. @@ -57,12 +59,12 @@

      phpCAS proxy example with PGT storage to file

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      '; } else { echo '
      '; diff --git a/docs/examples/example_proxy_GET.php b/docs/examples/example_proxy_GET.php index 665d349b..21be3b61 100755 --- a/docs/examples/example_proxy_GET.php +++ b/docs/examples/example_proxy_GET.php @@ -7,40 +7,44 @@ * * @file example_proxy_GET.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; +use phpCAS\CAS\ProxiedService\ProxiedServiceException; +use phpCAS\CAS\ProxyTicketException; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. @@ -54,14 +58,14 @@

      phpCAS proxied proxy example

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      setUrl($serviceUrl); $service->send(); if ($service->getResponseStatusCode() == 200) { @@ -72,20 +76,20 @@ // The service responded with an error code 404, 500, etc. echo '
      '; echo 'The service responded with a ' - . $service->getResponseStatusCode() . ' error.'; + .$service->getResponseStatusCode().' error.'; echo '
      '; } -} catch (CAS_ProxyTicketException $e) { - if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE) { +} catch (ProxyTicketException $e) { + if ($e->getCode() == CAS::PHPCAS_SERVICE_PT_FAILURE) { echo '
      '; - echo "Your login has timed out. You need to log in again."; + echo 'Your login has timed out. You need to log in again.'; echo '
      '; } else { // Other proxy ticket errors are from bad request format (shouldn't happen) // or CAS server failure (unlikely) so lets just stop if we hit those. throw $e; } -} catch (CAS_ProxiedService_Exception $e) { +} catch (ProxiedServiceException $e) { // Something prevented the service request from being sent or received. // We didn't even get a valid error response (404, 500, etc), so this // might be caused by a network error or a DNS resolution failure. diff --git a/docs/examples/example_proxy_POST.php b/docs/examples/example_proxy_POST.php index 4e061f59..9b530e8b 100755 --- a/docs/examples/example_proxy_POST.php +++ b/docs/examples/example_proxy_POST.php @@ -7,45 +7,49 @@ * * @file example_proxy_POST.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; +use phpCAS\CAS\ProxiedService\ProxiedServiceException; +use phpCAS\CAS\ProxyTicketException; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. -$serviceUrl = $curbase . $curdir . 'example_service_POST.php'; +$serviceUrl = $curbase.$curdir.'example_service_POST.php'; ?> @@ -56,14 +60,14 @@

      phpCAS proxy POST example

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      setUrl($serviceUrl); $service->setContentType('application/x-www-form-urlencoded'); $service->setBody('favorite_color=blue'); @@ -76,21 +80,21 @@ // The service responded with an error code 404, 500, etc. echo '
      '; echo 'The service responded with a ' - . $service->getResponseStatusCode() . ' error.'; + .$service->getResponseStatusCode().' error.'; echo $service->getResponseBody(); echo '
      '; } -} catch (CAS_ProxyTicketException $e) { - if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE) { +} catch (ProxyTicketException $e) { + if ($e->getCode() == CAS::PHPCAS_SERVICE_PT_FAILURE) { echo '
      '; - echo "Your login has timed out. You need to log in again."; + echo 'Your login has timed out. You need to log in again.'; echo '
      '; } else { // Other proxy ticket errors are from bad request format (shouldn't happen) // or CAS server failure (unlikely) so lets just stop if we hit those. throw $e; } -} catch (CAS_ProxiedService_Exception $e) { +} catch (ProxiedServiceException $e) { // Something prevented the service request from being sent or received. // We didn't even get a valid error response (404, 500, etc), so this // might be caused by a network error or a DNS resolution failure. diff --git a/docs/examples/example_proxy_rebroadcast.php b/docs/examples/example_proxy_rebroadcast.php index 2c9bff8f..fdfc5441 100644 --- a/docs/examples/example_proxy_rebroadcast.php +++ b/docs/examples/example_proxy_rebroadcast.php @@ -2,53 +2,55 @@ /** * Example for a proxy that rebroadcasts all PGTs to different servers in the - * cluster + * cluster. * * PHP Version 5 * * @file example_proxy_rebroadcast.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // Set the nodes for rebroadcasting pgtIou/pgtId and logoutRequest -phpCAS::addRebroadcastNode($rebroadcast_node_1); -phpCAS::addRebroadcastNode($rebroadcast_node_2); +CAS::addRebroadcastNode($rebroadcast_node_1); +CAS::addRebroadcastNode($rebroadcast_node_2); // handle incoming logout requests -phpCAS::handleLogoutRequests(); +CAS::handleLogoutRequests(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). ?> @@ -58,6 +60,6 @@

      phpCAS proxy rebroadcast example

      -

      the user's login is .

      +

      the user's login is .

      diff --git a/docs/examples/example_proxy_serviceWeb.php b/docs/examples/example_proxy_serviceWeb.php index 212918fa..5719a41b 100644 --- a/docs/examples/example_proxy_serviceWeb.php +++ b/docs/examples/example_proxy_serviceWeb.php @@ -1,46 +1,48 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. @@ -54,12 +56,12 @@

      phpCAS proxied proxy example (with sessioning)

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      '; } else { echo '
      '; diff --git a/docs/examples/example_proxy_serviceWeb_chaining.php b/docs/examples/example_proxy_serviceWeb_chaining.php index 0ab58ebe..f9b96de3 100644 --- a/docs/examples/example_proxy_serviceWeb_chaining.php +++ b/docs/examples/example_proxy_serviceWeb_chaining.php @@ -1,46 +1,48 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. @@ -54,12 +56,12 @@

      phpCAS proxied proxy example

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      '; } else { echo '
      '; diff --git a/docs/examples/example_renew.php b/docs/examples/example_renew.php index c25c2b81..4baea746 100644 --- a/docs/examples/example_renew.php +++ b/docs/examples/example_renew.php @@ -1,71 +1,73 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::renewAuthentication(); +CAS::renewAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). -// logout if desired -if (isset($_REQUEST['logout'])) { - phpCAS::logout(); +// logout if desired +if (isset($_REQUEST['logout'])) { + CAS::logout(); } -// logout if desired -if (isset($_REQUEST['session'])) { +// logout if desired +if (isset($_REQUEST['session'])) { session_unset(); session_destroy(); unset($_REQUEST['session']); - header("Location: ".$_SERVER['PHP_SELF']); + header('Location: '.$_SERVER['PHP_SELF']); } -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client -

      Successfull Authentication!

      +

      Successful Authentication!

      -

      the user's login is .

      -

      phpCAS version is .

      +

      the user's login is .

      +

      phpCAS version is .

      Logout

      Kill local Session

      diff --git a/docs/examples/example_service.php b/docs/examples/example_service.php index dc5aa411..82346466 100644 --- a/docs/examples/example_service.php +++ b/docs/examples/example_service.php @@ -1,43 +1,46 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; +use phpCAS\CAS\ProxyChain; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // If you want your service to be proxied you have to enable it (default -// disabled) and define an accepable list of proxies that are allowed to +// disabled) and define an acceptable list of proxies that are allowed to // proxy your service. // // Add each allowed proxy definition object. For the normal CAS_ProxyChain @@ -50,47 +53,45 @@ // when validating the proxy tickets. The strings are compared starting from // the beginning and must fully match with the proxies in the list. // Example: -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // 'https://app.example.com/' // ))); -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // '/^https:\/\/app[0-9]\.example\.com\/rest\//', // 'http://client.example.com/' // ))); -phpCAS::allowProxyChain(new CAS_ProxyChain(array($pgtUrlRegexp))); -phpCAS::allowProxyChain( - new CAS_ProxyChain( - array('/^' . $pgtBase . 'example_service_that_proxies.php$/', - '/^' . $pgtBase . 'example_proxy_serviceWeb_chaining.php$/' - ) +CAS::allowProxyChain(new ProxyChain([$pgtUrlRegexp])); +CAS::allowProxyChain( + new ProxyChain( + ['/^'.$pgtBase.'example_service_that_proxies.php$/', + '/^'.$pgtBase.'example_proxy_serviceWeb_chaining.php$/', + ] ) ); -// For quick testing or in certain production screnarios you might want to +// For quick testing or in certain production scenarios you might want to // allow allow any other valid service to proxy your service. To do so, add // the "Any" chain: -// phpcas::allowProxyChain(new CAS_ProxyChain_Any); +// CAS::allowProxyChain(new CAS_ProxyChain_Any); // THIS SETTING IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY // IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER // ON THIS SERVICE. -//phpcas::allowProxyChain(new CAS_ProxyChain_Any); +//CAS::allowProxyChain(new CAS_ProxyChain_Any); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); print '

      I am a service that can be proxied.

      '; // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). require 'script_info.php'; -// for this test, simply print that the authentication was successfull -echo '

      The user\'s login is ' . phpCAS::getUser() . '.

      '; +// for this test, simply print that the authentication was successful +echo '

      The user\'s login is '.CAS::getUser().'.

      '; // increment the number of requests of the session and print it -if (!isset($_SESSION['n'])) { +if (! isset($_SESSION['n'])) { $_SESSION['n'] = 0; } -echo '

      request #' . (++$_SESSION['n']) . '

      '; - -?> +echo '

      request #'.(++$_SESSION['n']).'

      '; diff --git a/docs/examples/example_service_POST.php b/docs/examples/example_service_POST.php index 74be4dfa..359ff4e3 100755 --- a/docs/examples/example_service_POST.php +++ b/docs/examples/example_service_POST.php @@ -1,43 +1,46 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; +use phpCAS\CAS\ProxyChain; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // If you want your service to be proxied you have to enable it (default -// disabled) and define an accepable list of proxies that are allowed to +// disabled) and define an acceptable list of proxies that are allowed to // proxy your service. // // Add each allowed proxy definition object. For the normal CAS_ProxyChain @@ -50,32 +53,32 @@ // when validating the proxy tickets. The strings are compared starting from // the beginning and must fully match with the proxies in the list. // Example: -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // 'https://app.example.com/' // ))); -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // '/^https:\/\/app[0-9]\.example\.com\/rest\//', // 'http://client.example.com/' // ))); -phpCAS::allowProxyChain(new CAS_ProxyChain(array($pgtUrlRegexp))); +CAS::allowProxyChain(new ProxyChain([$pgtUrlRegexp])); -// For quick testing or in certain production screnarios you might want to +// For quick testing or in certain production scenarios you might want to // allow allow any other valid service to proxy your service. To do so, add // the "Any" chain: -// phpcas::allowProxyChain(new CAS_ProxyChain_Any); +// CAS::allowProxyChain(new CAS_ProxyChain_Any); // THIS SETTING IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY // IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER // ON THIS SERVICE. -//phpcas::allowProxyChain(new CAS_ProxyChain_Any); +//CAS::allowProxyChain(new CAS_ProxyChain_Any); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); if ($_SERVER['REQUEST_METHOD'] != 'POST') { header('HTTP/1.1 400 Bad Request'); print - "

      I only respond to POST requests. This is a " - . $_SERVER['REQUEST_METHOD'] . " request.

      "; + '

      I only respond to POST requests. This is a ' + .$_SERVER['REQUEST_METHOD'].' request.

      '; exit; } if (empty($_POST['favorite_color'])) { @@ -87,19 +90,18 @@ print '

      I am a service that responds to POST requests.

      '; // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). require 'script_info.php'; -// for this test, simply print that the authentication was successfull -echo '

      The user\'s login is ' . phpCAS::getUser() . '.

      '; +// for this test, simply print that the authentication was successful +echo '

      The user\'s login is '.CAS::getUser().'.

      '; print - '

      Your favorite color is ' . htmlentities($_POST['favorite_color']) - . '

      '; + '

      Your favorite color is '.htmlentities($_POST['favorite_color']) + .'

      '; // increment the number of requests of the session and print it -if (!isset($_SESSION['n'])) { +if (! isset($_SESSION['n'])) { $_SESSION['n'] = 0; } -echo '

      request #' . (++$_SESSION['n']) . '

      '; - +echo '

      request #'.(++$_SESSION['n']).'

      '; diff --git a/docs/examples/example_service_that_proxies.php b/docs/examples/example_service_that_proxies.php index 7313ebf2..962ab1b6 100644 --- a/docs/examples/example_service_that_proxies.php +++ b/docs/examples/example_service_that_proxies.php @@ -1,43 +1,46 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; +use phpCAS\CAS\ProxyChain; // Enable debugging -phpCAS::setDebug(); -// Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setDebug(); +// Enable verbose error messages. Disable in production! +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::proxy(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::proxy(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // If you want your service to be proxied you have to enable it (default -// disabled) and define an accepable list of proxies that are allowed to +// disabled) and define an acceptable list of proxies that are allowed to // proxy your service. // // Add each allowed proxy definition object. For the normal CAS_ProxyChain @@ -50,35 +53,33 @@ // when validating the proxy tickets. The strings are compared starting from // the beginning and must fully match with the proxies in the list. // Example: -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // 'https://app.example.com/' // ))); -// phpCAS::allowProxyChain(new CAS_ProxyChain(array( +// CAS::allowProxyChain(new CAS_ProxyChain(array( // '/^https:\/\/app[0-9]\.example\.com\/rest\//', // 'http://client.example.com/' // ))); -phpCAS::allowProxyChain(new CAS_ProxyChain(array($pgtUrlRegexp))); +CAS::allowProxyChain(new ProxyChain([$pgtUrlRegexp])); -// For quick testing or in certain production screnarios you might want to +// For quick testing or in certain production scenarios you might want to // allow allow any other valid service to proxy your service. To do so, add // the "Any" chain: -// phpcas::allowProxyChain(new CAS_ProxyChain_Any); +// CAS::allowProxyChain(new CAS_ProxyChain_Any); // THIS SETTING IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY // IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER // ON THIS SERVICE. -//phpcas::allowProxyChain(new CAS_ProxyChain_Any); +//CAS::allowProxyChain(new CAS_ProxyChain_Any); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // moreover, a PGT was retrieved from the CAS server that will // permit to gain accesses to new services. - - ?> @@ -88,12 +89,12 @@

      I am a service that can be proxied. In turn, I proxy another service.

      -

      the user's login is .

      +

      the user's login is .

      Response from service

      '; } else { echo '
      '; diff --git a/docs/examples/example_simple.php b/docs/examples/example_simple.php index 105668ac..78b695ac 100644 --- a/docs/examples/example_simple.php +++ b/docs/examples/example_simple.php @@ -1,63 +1,65 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +// Load the autoloader +require_once '../../vendor/autoload.php'; + // Load the settings from the central config file require_once 'config.php'; -// Load the CAS lib -require_once $phpcas_path . '/CAS.php'; + +use phpCAS\CAS; // Enable debugging -phpCAS::setDebug(); +CAS::setDebug(); // Enable verbose error messages. Disable in production! -phpCAS::setVerbose(true); +CAS::setVerbose(true); // Initialize phpCAS -phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); +CAS::client(CAS::CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below -// phpCAS::setCasServerCACert($cas_server_ca_cert_path); +// CAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! -phpCAS::setNoCasServerValidation(); +CAS::setNoCasServerValidation(); // force CAS authentication -phpCAS::forceAuthentication(); +CAS::forceAuthentication(); // at this step, the user has been authenticated by the CAS server -// and the user's login name can be read with phpCAS::getUser(). +// and the user's login name can be read with CAS::getUser(). // logout if desired if (isset($_REQUEST['logout'])) { - phpCAS::logout(); + CAS::logout(); } -// for this test, simply print that the authentication was successfull +// for this test, simply print that the authentication was successful ?> phpCAS simple client -

      Successfull Authentication!

      +

      Successful Authentication!

      -

      the user's login is .

      -

      phpCAS version is .

      +

      the user's login is .

      +

      phpCAS version is .

      Logout

      diff --git a/docs/examples/script_info.php b/docs/examples/script_info.php index 0a6c954a..af7870ab 100644 --- a/docs/examples/script_info.php +++ b/docs/examples/script_info.php @@ -1,13 +1,12 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..8af6caf0 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,19 @@ + + + + + ./test/ + + + + + + ./source/ + + + diff --git a/source/CAS.php b/source/CAS.php index 38361974..92fc74ca 100644 --- a/source/CAS.php +++ b/source/CAS.php @@ -24,7 +24,6 @@ * * @file CAS/CAS.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @author Olivier Berger * @author Brett Bieber @@ -35,254 +34,249 @@ * @ingroup public */ +namespace phpCAS; + +use Exception; +use phpCAS\CAS\Client; +use phpCAS\CAS\GracefulTerminationException; +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\Languages\Catalan; +use phpCAS\CAS\Languages\English; +use phpCAS\CAS\Languages\French; +use phpCAS\CAS\Languages\German; +use phpCAS\CAS\Languages\Greek; +use phpCAS\CAS\Languages\Japanese; +use phpCAS\CAS\Languages\Spanish; +use phpCAS\CAS\OutOfSequenceBeforeClientException; +use phpCAS\CAS\OutOfSequenceBeforeProxyException; +use phpCAS\CAS\PGTStorage\AbstractStorage; +use phpCAS\CAS\ProxiedService; +use phpCAS\CAS\ProxiedService\Http\Get; +use phpCAS\CAS\ProxiedService\Http\Post; +use phpCAS\CAS\ProxiedService\Imap; +use phpCAS\CAS\ProxyChain\ProxyChainInterface; +use phpCAS\CAS\ProxyTicketException; -// -// hack by Vangelis Haniotakis to handle the absence of $_SERVER['REQUEST_URI'] -// in IIS -// -if (php_sapi_name() != 'cli') { - if (!isset($_SERVER['REQUEST_URI'])) { - $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING']; - } -} +/** + * The CAS class is a simple container for the CAS library. It provides CAS + * authentication for web applications written in PHP. + * + * @class CAS + * @category Authentication + * @author Pascal Aubry + * @author Olivier Berger + * @author Brett Bieber + * @author Joachim Fritschi + * @author Adam Franco + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ +class CAS +{ + // ######################################################################## + // CONSTANTS + // ######################################################################## -// Add a E_USER_DEPRECATED for php versions <= 5.2 -if (!defined('E_USER_DEPRECATED')) { - define('E_USER_DEPRECATED', E_USER_NOTICE); -} + // ------------------------------------------------------------------------ + // CAS VERSIONS + // ------------------------------------------------------------------------ + /** + * phpCAS version. accessible for the user by static::getVersion(). + */ + const PHPCAS_VERSION = '1.3.4+'; -// ######################################################################## -// CONSTANTS -// ######################################################################## + /** + * @addtogroup public + * @{ + */ -// ------------------------------------------------------------------------ -// CAS VERSIONS -// ------------------------------------------------------------------------ + /** + * CAS version 1.0. + */ + const CAS_VERSION_1_0 = '1.0'; -/** - * phpCAS version. accessible for the user by phpCAS::getVersion(). - */ -define('PHPCAS_VERSION', '1.3.4+'); + /** + * CAS version 2.0. + */ + const CAS_VERSION_2_0 = '2.0'; -/** - * @addtogroup public - * @{ - */ + /** + * CAS version 3.0. + */ + const CAS_VERSION_3_0 = '3.0'; -/** - * CAS version 1.0 - */ -define("CAS_VERSION_1_0", '1.0'); -/*! - * CAS version 2.0 -*/ -define("CAS_VERSION_2_0", '2.0'); -/** - * CAS version 3.0 - */ -define("CAS_VERSION_3_0", '3.0'); + // ------------------------------------------------------------------------ + // SAML defines + // ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// SAML defines -// ------------------------------------------------------------------------ + /** + * SAML protocol. + */ + const SAML_VERSION_1_1 = 'S1'; -/** - * SAML protocol - */ -define("SAML_VERSION_1_1", 'S1'); + /** + * XML header for SAML POST. + */ + const SAML_XML_HEADER = ''; -/** - * XML header for SAML POST - */ -define("SAML_XML_HEADER", ''); + /** + * SOAP envelope for SAML POST. + */ + const SAML_SOAP_ENV = ''; -/** - * SOAP envelope for SAML POST - */ -define("SAML_SOAP_ENV", ''); + /** + * SOAP body for SAML POST. + */ + const SAML_SOAP_BODY = ''; -/** - * SOAP body for SAML POST - */ -define("SAML_SOAP_BODY", ''); + /** + * SAMLP request. + */ + const SAMLP_REQUEST = ''; + const SAMLP_REQUEST_CLOSE = ''; -/** - * SAMLP request - */ -define("SAMLP_REQUEST", ''); -define("SAMLP_REQUEST_CLOSE", ''); + /** + * SAMLP artifact tag (for the ticket). + */ + const SAML_ASSERTION_ARTIFACT = ''; -/** - * SAMLP artifact tag (for the ticket) - */ -define("SAML_ASSERTION_ARTIFACT", ''); + /** + * SAMLP close. + */ + const SAML_ASSERTION_ARTIFACT_CLOSE = ''; -/** - * SAMLP close - */ -define("SAML_ASSERTION_ARTIFACT_CLOSE", ''); + /** + * SOAP body close. + */ + const SAML_SOAP_BODY_CLOSE = ''; -/** - * SOAP body close - */ -define("SAML_SOAP_BODY_CLOSE", ''); + /** + * SOAP envelope close. + */ + const SAML_SOAP_ENV_CLOSE = ''; -/** - * SOAP envelope close - */ -define("SAML_SOAP_ENV_CLOSE", ''); + /** + * SAML Attributes. + */ + const SAML_ATTRIBUTES = 'SAMLATTRIBS'; -/** - * SAML Attributes - */ -define("SAML_ATTRIBUTES", 'SAMLATTRIBS'); + /** + * SAML Attributes. + */ + const DEFAULT_ERROR = 'Internal script failure'; -/** - * SAML Attributes - */ -define("DEFAULT_ERROR", 'Internal script failure'); + /** @} */ -/** @} */ -/** - * @addtogroup publicPGTStorage - * @{ - */ -// ------------------------------------------------------------------------ -// FILE PGT STORAGE -// ------------------------------------------------------------------------ -/** - * Default path used when storing PGT's to file - */ -define("CAS_PGT_STORAGE_FILE_DEFAULT_PATH", session_save_path()); -/** @} */ -// ------------------------------------------------------------------------ -// SERVICE ACCESS ERRORS -// ------------------------------------------------------------------------ -/** - * @addtogroup publicServices - * @{ - */ + /** + * @addtogroup publicPGTStorage + * @{ + */ -/** - * phpCAS::service() error code on success - */ -define("PHPCAS_SERVICE_OK", 0); -/** - * phpCAS::service() error code when the PT could not retrieve because - * the CAS server did not respond. - */ -define("PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE", 1); -/** - * phpCAS::service() error code when the PT could not retrieve because - * the response of the CAS server was ill-formed. - */ -define("PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE", 2); -/** - * phpCAS::service() error code when the PT could not retrieve because - * the CAS server did not want to. - */ -define("PHPCAS_SERVICE_PT_FAILURE", 3); -/** - * phpCAS::service() error code when the service was not available. - */ -define("PHPCAS_SERVICE_NOT_AVAILABLE", 4); + // ------------------------------------------------------------------------ + // FILE PGT STORAGE + // ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// SERVICE TYPES -// ------------------------------------------------------------------------ -/** - * phpCAS::getProxiedService() type for HTTP GET - */ -define("PHPCAS_PROXIED_SERVICE_HTTP_GET", 'CAS_ProxiedService_Http_Get'); -/** - * phpCAS::getProxiedService() type for HTTP POST - */ -define("PHPCAS_PROXIED_SERVICE_HTTP_POST", 'CAS_ProxiedService_Http_Post'); -/** - * phpCAS::getProxiedService() type for IMAP - */ -define("PHPCAS_PROXIED_SERVICE_IMAP", 'CAS_ProxiedService_Imap'); + /** + * Default path used when storing PGT's to file. + */ + // const CAS_PGT_STORAGE_FILE_DEFAULT_PATH = session_save_path(); + /** @} */ -/** @} */ -// ------------------------------------------------------------------------ -// LANGUAGES -// ------------------------------------------------------------------------ -/** - * @addtogroup publicLang - * @{ - */ + // ------------------------------------------------------------------------ + // SERVICE ACCESS ERRORS + // ------------------------------------------------------------------------ -define("PHPCAS_LANG_ENGLISH", 'CAS_Languages_English'); -define("PHPCAS_LANG_FRENCH", 'CAS_Languages_French'); -define("PHPCAS_LANG_GREEK", 'CAS_Languages_Greek'); -define("PHPCAS_LANG_GERMAN", 'CAS_Languages_German'); -define("PHPCAS_LANG_JAPANESE", 'CAS_Languages_Japanese'); -define("PHPCAS_LANG_SPANISH", 'CAS_Languages_Spanish'); -define("PHPCAS_LANG_CATALAN", 'CAS_Languages_Catalan'); + /** + * @addtogroup publicServices + * @{ + */ -/** @} */ + /** + * static::service() error code on success. + */ + const PHPCAS_SERVICE_OK = 0; -/** - * @addtogroup internalLang - * @{ - */ + /** + * static::service() error code when the PT could not retrieve because + * the CAS server did not respond. + */ + const PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE = 1; -/** - * phpCAS default language (when phpCAS::setLang() is not used) - */ -define("PHPCAS_LANG_DEFAULT", PHPCAS_LANG_ENGLISH); + /** + * static::service() error code when the PT could not retrieve because + * the response of the CAS server was ill-formed. + */ + const PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE = 2; -/** @} */ -// ------------------------------------------------------------------------ -// DEBUG -// ------------------------------------------------------------------------ -/** - * @addtogroup publicDebug - * @{ - */ + /** + * static::service() error code when the PT could not retrieve because + * the CAS server did not want to. + */ + const PHPCAS_SERVICE_PT_FAILURE = 3; -/** - * The default directory for the debug file under Unix. - */ -function gettmpdir() { -if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); } -if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); } -if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); } -return "/tmp"; -} -define('DEFAULT_DEBUG_DIR', gettmpdir()."/"); + /** + * static::service() error code when the service was not available. + */ + const PHPCAS_SERVICE_NOT_AVAILABLE = 4; -/** @} */ + // ------------------------------------------------------------------------ + // SERVICE TYPES + // ------------------------------------------------------------------------ -// include the class autoloader -require_once dirname(__FILE__) . '/CAS/Autoload.php'; + /** + * static::getProxiedService() type for HTTP GET. + */ + const PHPCAS_PROXIED_SERVICE_HTTP_GET = '\phpCAS\CAS\ProxiedService\Http\Get'; -/** - * The phpCAS class is a simple container for the phpCAS library. It provides CAS - * authentication for web applications written in PHP. - * - * @ingroup public - * @class phpCAS - * @category Authentication - * @package PhpCAS - * @author Pascal Aubry - * @author Olivier Berger - * @author Brett Bieber - * @author Joachim Fritschi - * @author Adam Franco - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ + /** + * static::getProxiedService() type for HTTP POST. + */ + const PHPCAS_PROXIED_SERVICE_HTTP_POST = '\phpCAS\CAS\ProxiedService\Http\Post'; -class phpCAS -{ + /** + * static::getProxiedService() type for IMAP. + */ + const PHPCAS_PROXIED_SERVICE_IMAP = '\phpCAS\CAS\ProxiedService\Imap'; + + /** @} */ + + // ------------------------------------------------------------------------ + // LANGUAGES + // ------------------------------------------------------------------------ /** - * This variable is used by the interface class phpCAS. + * @addtogroup publicLang + * @{ + */ + + const PHPCAS_LANG_ENGLISH = '\phpCAS\CAS\Languages\English'; + const PHPCAS_LANG_FRENCH = '\phpCAS\CAS\Languages\French'; + const PHPCAS_LANG_GREEK = '\phpCAS\CAS\Languages\Greek'; + const PHPCAS_LANG_GERMAN = '\phpCAS\CAS\Languages\German'; + const PHPCAS_LANG_JAPANESE = '\phpCAS\CAS\Languages\Japanese'; + const PHPCAS_LANG_SPANISH = '\phpCAS\CAS\Languages\Spanish'; + const PHPCAS_LANG_CATALAN = '\phpCAS\CAS\Languages\Catalan'; + + /** @} */ + + /** + * @addtogroup internalLang + * @{ + */ + + /** + * CAS default language (when static::setLang() is not used). + */ + const PHPCAS_LANG_DEFAULT = self::PHPCAS_LANG_ENGLISH; + + /** @} */ + + /** + * This variable is used by the interface class CAS. * - * @var CAS_Client + * @var Client * @hideinitializer */ private static $_PHPCAS_CLIENT; @@ -291,27 +285,29 @@ class phpCAS * This variable is used to store where the initializer is called from * (to print a comprehensive error in case of multiple calls). * + * @var string * @hideinitializer */ private static $_PHPCAS_INIT_CALL; /** - * This variable is used to store phpCAS debug mode. + * This variable is used to store CAS debug mode. * + * @var array * @hideinitializer */ private static $_PHPCAS_DEBUG; - /** + /** * This variable is used to enable verbose mode - * This pevents debug info to be show to the user. Since it's a security - * feature the default is false - * - * @hideinitializer - */ + * This prevents debug info to be show to the user. Since it's a security + * feature the default is false. + * + * @var bool + * @hideinitializer + */ private static $_PHPCAS_VERBOSE = false; - // ######################################################################## // INITIALIZATION // ######################################################################## @@ -328,41 +324,52 @@ class phpCAS * @param string $server_hostname the hostname of the CAS server * @param string $server_port the port the CAS server is running on * @param string $server_uri the URI the CAS server is responding on - * @param bool $changeSessionID Allow phpCAS to change the session_id (Single + * @param bool $changeSessionID Allow CAS to change the session_id (Single * Sign Out/handleLogoutRequests is based on that change) * - * @return a newly created CAS_Client object - * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be - * called, only once, and before all other methods (except phpCAS::getVersion() - * and phpCAS::setDebug()). + * @return Client a newly created Client object + * @note Only one of the static::client() and static::proxy functions should be + * called, only once, and before all other methods (except static::getVersion() + * and static::setDebug()). */ - public static function client($server_version, $server_hostname, - $server_port, $server_uri, $changeSessionID = true + public static function client( + $server_version, + $server_hostname, + $server_port, + $server_uri, + $changeSessionID = true ) { - phpCAS :: traceBegin(); - if (is_object(self::$_PHPCAS_CLIENT)) { - phpCAS :: error(self::$_PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . self::$_PHPCAS_INIT_CALL['file'] . ':' . self::$_PHPCAS_INIT_CALL['line'] . ')'); + static::traceBegin(); + if (is_object(static::$_PHPCAS_CLIENT)) { + static::error( + static::$_PHPCAS_INIT_CALL['method'].'() has already been called (at ' + .static::$_PHPCAS_INIT_CALL['file'].':'.static::$_PHPCAS_INIT_CALL['line'].')' + ); } // store where the initializer is called from $dbg = debug_backtrace(); - self::$_PHPCAS_INIT_CALL = array ( + static::$_PHPCAS_INIT_CALL = [ 'done' => true, 'file' => $dbg[0]['file'], 'line' => $dbg[0]['line'], - 'method' => __CLASS__ . '::' . __FUNCTION__ - ); + 'method' => __CLASS__.'::'.__FUNCTION__, + ]; // initialize the object $_PHPCAS_CLIENT try { - self::$_PHPCAS_CLIENT = new CAS_Client( - $server_version, false, $server_hostname, $server_port, $server_uri, + static::$_PHPCAS_CLIENT = new Client( + $server_version, + false, + $server_hostname, + $server_port, + $server_uri, $changeSessionID ); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -372,54 +379,66 @@ public static function client($server_version, $server_hostname, * @param string $server_hostname the hostname of the CAS server * @param string $server_port the port the CAS server is running on * @param string $server_uri the URI the CAS server is responding on - * @param bool $changeSessionID Allow phpCAS to change the session_id (Single + * @param bool $changeSessionID Allow CAS to change the session_id (Single * Sign Out/handleLogoutRequests is based on that change) * - * @return a newly created CAS_Client object - * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be - * called, only once, and before all other methods (except phpCAS::getVersion() - * and phpCAS::setDebug()). + * @return Client a newly created Client object + * @note Only one of the static::client() and static::proxy functions should be + * called, only once, and before all other methods (except static::getVersion() + * and static::setDebug()). */ - public static function proxy($server_version, $server_hostname, - $server_port, $server_uri, $changeSessionID = true + public static function proxy( + $server_version, + $server_hostname, + $server_port, + $server_uri, + $changeSessionID = true ) { - phpCAS :: traceBegin(); - if (is_object(self::$_PHPCAS_CLIENT)) { - phpCAS :: error(self::$_PHPCAS_INIT_CALL['method'] . '() has already been called (at ' . self::$_PHPCAS_INIT_CALL['file'] . ':' . self::$_PHPCAS_INIT_CALL['line'] . ')'); + static::traceBegin(); + if (is_object(static::$_PHPCAS_CLIENT)) { + static::error( + static::$_PHPCAS_INIT_CALL['method'].'() has already been called (at ' + .static::$_PHPCAS_INIT_CALL['file'].':'.static::$_PHPCAS_INIT_CALL['line'].')' + ); } - // store where the initialzer is called from + // store where the initializer is called from $dbg = debug_backtrace(); - self::$_PHPCAS_INIT_CALL = array ( + static::$_PHPCAS_INIT_CALL = [ 'done' => true, 'file' => $dbg[0]['file'], 'line' => $dbg[0]['line'], - 'method' => __CLASS__ . '::' . __FUNCTION__ - ); + 'method' => __CLASS__.'::'.__FUNCTION__, + ]; - // initialize the object $_PHPCAS_CLIENT + // initialize the object $_CAS_CLIENT try { - self::$_PHPCAS_CLIENT = new CAS_Client( - $server_version, true, $server_hostname, $server_port, $server_uri, + static::$_PHPCAS_CLIENT = new Client( + $server_version, + true, + $server_hostname, + $server_port, + $server_uri, $changeSessionID ); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** - * Answer whether or not the client or proxy has been initialized + * Answer whether or not the client or proxy has been initialized. * * @return bool */ - public static function isInitialized () + public static function isInitialized() { - return (is_object(self::$_PHPCAS_CLIENT)); + return (is_object(static::$_PHPCAS_CLIENT)); } /** @} */ + // ######################################################################## // DEBUGGING // ######################################################################## @@ -430,7 +449,7 @@ public static function isInitialized () */ /** - * Set/unset debug mode + * Set/unset debug mode. * * @param string $filename the name of the file used for logging, or false * to stop debugging. @@ -440,63 +459,93 @@ public static function isInitialized () public static function setDebug($filename = '') { if ($filename != false && gettype($filename) != 'string') { - phpCAS :: error('type mismatched for parameter $dbg (should be false or the name of the log file)'); + static::error('type mismatched for parameter $dbg (should be false or the name of the log file)'); } if ($filename === false) { - self::$_PHPCAS_DEBUG['filename'] = false; - + static::$_PHPCAS_DEBUG['filename'] = false; } else { - if (empty ($filename)) { + if (empty($filename)) { if (preg_match('/^Win.*/', getenv('OS'))) { - if (isset ($_ENV['TMP'])) { - $debugDir = $_ENV['TMP'] . '/'; + if (isset($_ENV['TMP'])) { + $debugDir = $_ENV['TMP'].'/'; } else { $debugDir = ''; } } else { - $debugDir = DEFAULT_DEBUG_DIR; + $debugDir = static::getDefaultDebugDir(); } - $filename = $debugDir . 'phpCAS.log'; + $filename = $debugDir.'CAS.log'; } - if (empty (self::$_PHPCAS_DEBUG['unique_id'])) { - self::$_PHPCAS_DEBUG['unique_id'] = substr(strtoupper(md5(uniqid(''))), 0, 4); + if (empty(static::$_PHPCAS_DEBUG['unique_id'])) { + static::$_PHPCAS_DEBUG['unique_id'] = substr(strtoupper(md5(uniqid(''))), 0, 4); } - self::$_PHPCAS_DEBUG['filename'] = $filename; - self::$_PHPCAS_DEBUG['indent'] = 0; + static::$_PHPCAS_DEBUG['filename'] = $filename; + static::$_PHPCAS_DEBUG['indent'] = 0; - phpCAS :: trace('START ('.date("Y-m-d H:i:s").') phpCAS-' . PHPCAS_VERSION . ' ******************'); + static::trace('START ('.date('Y-m-d H:i:s').') CAS-'.static::PHPCAS_VERSION.' ******************'); } } - /** + /** + * Return the default debug directory. + * + * @return string + */ + public static function getDefaultDebugDir() + { + return static::getTmpDir().'/'; + } + + /** + * The default directory for the debug file under Unix. + * + * @return string + */ + public static function getTmpDir() + { + if (! empty($_ENV['TMP'])) { + return realpath($_ENV['TMP']); + } + + if (! empty($_ENV['TMPDIR'])) { + return realpath($_ENV['TMPDIR']); + } + + if (! empty($_ENV['TEMP'])) { + return realpath($_ENV['TEMP']); + } + + return '/tmp'; + } + + /** * Enable verbose errors messages in the website output * This is a security relevant since internal status info may leak an may - * help an attacker. Default is therefore false - * - * @param bool $verbose enable verbose output - * - * @return void - */ + * help an attacker. Default is therefore false. + * + * @param bool $verbose enable verbose output + * + * @return void + */ public static function setVerbose($verbose) { - if ($verbose === true) { - self::$_PHPCAS_VERBOSE = true; + if ($verbose === true) { + static::$_PHPCAS_VERBOSE = true; } else { - self::$_PHPCAS_VERBOSE = false; + static::$_PHPCAS_VERBOSE = false; } } - /** - * Show is verbose mode is on - * - * @return boot verbose - */ - public static function getVerbose() - { - return self::$_PHPCAS_VERBOSE; + * Show is verbose mode is on. + * + * @return bool verbose + */ + public static function getVerbose() + { + return static::$_PHPCAS_VERBOSE; } /** @@ -509,27 +558,24 @@ public static function getVerbose() */ public static function log($str) { - $indent_str = "."; - + $indent_str = '.'; - if (!empty(self::$_PHPCAS_DEBUG['filename'])) { - // Check if file exists and modifiy file permissions to be only - // readable by the webserver - if (!file_exists(self::$_PHPCAS_DEBUG['filename'])) { - touch(self::$_PHPCAS_DEBUG['filename']); + if (! empty(static::$_PHPCAS_DEBUG['filename'])) { + // Check if file exists and modify file permissions to be only + // readable by the web server + if (! file_exists(static::$_PHPCAS_DEBUG['filename'])) { + touch(static::$_PHPCAS_DEBUG['filename']); // Chmod will fail on windows - @chmod(self::$_PHPCAS_DEBUG['filename'], 0600); + @chmod(static::$_PHPCAS_DEBUG['filename'], 0600); } - for ($i = 0; $i < self::$_PHPCAS_DEBUG['indent']; $i++) { - + for ($i = 0; $i < static::$_PHPCAS_DEBUG['indent']; $i++) { $indent_str .= '| '; } - // allow for multiline output with proper identing. Usefull for + // allow for multiline output with proper indenting. Useful for // dumping cas answers etc. - $str2 = str_replace("\n", "\n" . self::$_PHPCAS_DEBUG['unique_id'] . ' ' . $indent_str, $str); - error_log(self::$_PHPCAS_DEBUG['unique_id'] . ' ' . $indent_str . $str2 . "\n", 3, self::$_PHPCAS_DEBUG['filename']); + $str2 = str_replace("\n", "\n".static::$_PHPCAS_DEBUG['unique_id'].' '.$indent_str, $str); + error_log(static::$_PHPCAS_DEBUG['unique_id'].' '.$indent_str.$str2."\n", 3, static::$_PHPCAS_DEBUG['filename']); } - } /** @@ -539,18 +585,19 @@ public static function log($str) * @param string $msg the message to print * * @return void - * @private + * + * @throws GracefulTerminationException */ public static function error($msg) { - phpCAS :: traceBegin(); + static::traceBegin(); $dbg = debug_backtrace(); $function = '?'; $file = '?'; $line = '?'; if (is_array($dbg)) { for ($i = 1; $i < sizeof($dbg); $i++) { - if (is_array($dbg[$i]) && isset($dbg[$i]['class']) ) { + if (is_array($dbg[$i]) && isset($dbg[$i]['class'])) { if ($dbg[$i]['class'] == __CLASS__) { $function = $dbg[$i]['function']; $file = $dbg[$i]['file']; @@ -559,15 +606,15 @@ public static function error($msg) } } } - if (self::$_PHPCAS_VERBOSE) { - echo "
      \nphpCAS error: " . __CLASS__ . "::" . $function . '(): ' . htmlentities($msg) . " in " . $file . " on line " . $line . "
      \n"; + if (static::$_PHPCAS_VERBOSE) { + echo "
      \nCAS error: ".__CLASS__.'::'.$function.'(): '.htmlentities($msg).' in '.$file.' on line '.$line."
      \n"; } else { - echo "
      \nError: ". DEFAULT_ERROR ."
      \n"; + echo "
      \nError: ".static::DEFAULT_ERROR."
      \n"; } - phpCAS :: trace($msg . ' in ' . $file . 'on line ' . $line ); - phpCAS :: traceEnd(); + static::trace($msg.' in '.$file.'on line '.$line); + static::traceEnd(); - throw new CAS_GracefullTerminationException(__CLASS__ . "::" . $function . '(): ' . $msg); + throw new GracefulTerminationException(__CLASS__.'::'.$function.'(): '.$msg); } /** @@ -580,7 +627,7 @@ public static function error($msg) public static function trace($str) { $dbg = debug_backtrace(); - phpCAS :: log($str . ' [' . basename($dbg[0]['file']) . ':' . $dbg[0]['line'] . ']'); + static::log($str.' ['.basename($dbg[0]['file']).':'.$dbg[0]['line'].']'); } /** @@ -593,10 +640,10 @@ public static function traceBegin() { $dbg = debug_backtrace(); $str = '=> '; - if (!empty ($dbg[1]['class'])) { - $str .= $dbg[1]['class'] . '::'; + if (! empty($dbg[1]['class'])) { + $str .= $dbg[1]['class'].'::'; } - $str .= $dbg[1]['function'] . '('; + $str .= $dbg[1]['function'].'('; if (is_array($dbg[1]['args'])) { foreach ($dbg[1]['args'] as $index => $arg) { if ($index != 0) { @@ -605,7 +652,7 @@ public static function traceBegin() if (is_object($arg)) { $str .= get_class($arg); } else { - $str .= str_replace(array("\r\n", "\n", "\r"), "", var_export($arg, true)); + $str .= str_replace(["\r\n", "\n", "\r"], '', var_export($arg, true)); } } } @@ -619,12 +666,12 @@ public static function traceBegin() } else { $line = 'unknown_line'; } - $str .= ') [' . $file . ':' . $line . ']'; - phpCAS :: log($str); - if (!isset(self::$_PHPCAS_DEBUG['indent'])) { - self::$_PHPCAS_DEBUG['indent'] = 0; + $str .= ') ['.$file.':'.$line.']'; + static::log($str); + if (! isset(static::$_PHPCAS_DEBUG['indent'])) { + static::$_PHPCAS_DEBUG['indent'] = 0; } else { - self::$_PHPCAS_DEBUG['indent']++; + static::$_PHPCAS_DEBUG['indent']++; } } @@ -638,44 +685,45 @@ public static function traceBegin() */ public static function traceEnd($res = '') { - if (empty(self::$_PHPCAS_DEBUG['indent'])) { - self::$_PHPCAS_DEBUG['indent'] = 0; + if (empty(static::$_PHPCAS_DEBUG['indent'])) { + static::$_PHPCAS_DEBUG['indent'] = 0; } else { - self::$_PHPCAS_DEBUG['indent']--; + static::$_PHPCAS_DEBUG['indent']--; } - $dbg = debug_backtrace(); $str = ''; if (is_object($res)) { - $str .= '<= ' . get_class($res); + $str .= '<= '.get_class($res); } else { - $str .= '<= ' . str_replace(array("\r\n", "\n", "\r"), "", var_export($res, true)); + $str .= '<= '.str_replace(["\r\n", "\n", "\r"], '', var_export($res, true)); } - phpCAS :: log($str); + static::log($str); } /** - * This method is used to indicate the end of the execution of the program + * This method is used to indicate the end of the execution of the program. * * @return void */ public static function traceExit() { - phpCAS :: log('exit()'); - while (self::$_PHPCAS_DEBUG['indent'] > 0) { - phpCAS :: log('-'); - self::$_PHPCAS_DEBUG['indent']--; + static::log('exit()'); + while (static::$_PHPCAS_DEBUG['indent'] > 0) { + static::log('-'); + static::$_PHPCAS_DEBUG['indent']--; } } /** @} */ + // ######################################################################## // INTERNATIONALIZATION // ######################################################################## + /** - * @addtogroup publicLang - * @{ - */ + * @addtogroup publicLang + * @{ + */ /** * This method is used to set the language used by phpCAS. @@ -689,42 +737,45 @@ public static function traceExit() */ public static function setLang($lang) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setLang($lang); + static::$_PHPCAS_CLIENT->setLang($lang); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } } /** @} */ + // ######################################################################## // VERSION // ######################################################################## + /** - * @addtogroup public - * @{ - */ + * @addtogroup public + * @{ + */ /** - * This method returns the phpCAS version. + * This method returns the CAS version. * - * @return the phpCAS version. + * @return string the CAS version. */ public static function getVersion() { - return PHPCAS_VERSION; + return static::PHPCAS_VERSION; } /** @} */ + // ######################################################################## // HTML OUTPUT // ######################################################################## + /** - * @addtogroup publicOutput - * @{ - */ + * @addtogroup publicOutput + */ /** * This method sets the HTML header used for all outputs. @@ -735,12 +786,12 @@ public static function getVersion() */ public static function setHTMLHeader($header) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setHTMLHeader($header); + static::$_PHPCAS_CLIENT->setHTMLHeader($header); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } } @@ -753,43 +804,45 @@ public static function setHTMLHeader($header) */ public static function setHTMLFooter($footer) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setHTMLFooter($footer); + static::$_PHPCAS_CLIENT->setHTMLFooter($footer); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } } /** @} */ + // ######################################################################## // PGT STORAGE // ######################################################################## + /** - * @addtogroup publicPGTStorage - * @{ - */ + * @addtogroup publicPGTStorage + * @{ + */ /** * This method can be used to set a custom PGT storage object. * - * @param CAS_PGTStorage $storage a PGT storage object that inherits from the - * CAS_PGTStorage class + * @param AbstractStorage $storage a PGT storage object that inherits from + * the AbstractStorage class * * @return void */ - public static function setPGTStorage($storage) + public static function setPGTStorage(AbstractStorage $storage) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->setPGTStorage($storage); + static::$_PHPCAS_CLIENT->setPGTStorage($storage); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -797,30 +850,34 @@ public static function setPGTStorage($storage) * CAS server to PGT requests in a database. * * @param string $dsn_or_pdo a dsn string to use for creating a PDO - * object or a PDO object + * object or a PDO object * @param string $username the username to use when connecting to the - * database + * database * @param string $password the password to use when connecting to the - * database + * database * @param string $table the table to use for storing and retrieving - * PGT's + * PGT's * @param string $driver_options any driver options to use when connecting - * to the database + * to the database * * @return void */ - public static function setPGTStorageDb($dsn_or_pdo, $username='', - $password='', $table='', $driver_options=null + public static function setPGTStorageDb( + $dsn_or_pdo, + $username = '', + $password = '', + $table = '', + $driver_options = null ) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->setPGTStorageDb($dsn_or_pdo, $username, $password, $table, $driver_options); + static::$_PHPCAS_CLIENT->setPGTStorageDb($dsn_or_pdo, $username, $password, $table, $driver_options); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -833,24 +890,27 @@ public static function setPGTStorageDb($dsn_or_pdo, $username='', */ public static function setPGTStorageFile($path = '') { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->setPGTStorageFile($path); + static::$_PHPCAS_CLIENT->setPGTStorageFile($path); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } + /** @} */ + // ######################################################################## // ACCESS TO EXTERNAL SERVICES // ######################################################################## + /** - * @addtogroup publicServices - * @{ - */ + * @addtogroup publicServices + * @{ + */ /** * Answer a proxy-authenticated service handler. @@ -859,44 +919,46 @@ public static function setPGTStorageFile($path = '') * PHPCAS_PROXIED_SERVICE_HTTP_GET; PHPCAS_PROXIED_SERVICE_HTTP_POST; * PHPCAS_PROXIED_SERVICE_IMAP * - * @return CAS_ProxiedService + * @return ProxiedService|Imap|Html|Get|Post * @throws InvalidArgumentException If the service type is unknown. */ - public static function getProxiedService ($type) + public static function getProxiedService($type) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); + $res = null; try { - $res = self::$_PHPCAS_CLIENT->getProxiedService($type); + $res = static::$_PHPCAS_CLIENT->getProxiedService($type); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); + return $res; } /** * Initialize a proxied-service handler with the proxy-ticket it should use. * - * @param CAS_ProxiedService $proxiedService Proxied Service Handler + * @param ProxiedService $proxiedService Proxied Service Handler * * @return void - * @throws CAS_ProxyTicketException If there is a proxy-ticket failure. + * @throws ProxyTicketException If there is a proxy-ticket failure. * The code of the Exception will be one of: * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE * PHPCAS_SERVICE_PT_FAILURE */ - public static function initializeProxiedService (CAS_ProxiedService $proxiedService) + public static function initializeProxiedService(ProxiedService $proxiedService) { - phpCAS::_validateProxyExists(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->initializeProxiedService($proxiedService); + static::$_PHPCAS_CLIENT->initializeProxiedService($proxiedService); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } } @@ -915,18 +977,20 @@ public static function initializeProxiedService (CAS_ProxiedService $proxiedServ * $err_code gives the reason why it failed and $output contains an error * message). */ - public static function serviceWeb($url, & $err_code, & $output) + public static function serviceWeb($url, &$err_code, &$output) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); + $res = null; try { - $res = self::$_PHPCAS_CLIENT->serviceWeb($url, $err_code, $output); + $res = static::$_PHPCAS_CLIENT->serviceWeb($url, $err_code, $output); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd($res); + static::traceEnd($res); + return $res; } @@ -949,36 +1013,40 @@ public static function serviceWeb($url, & $err_code, & $output) * case, $err_code gives the reason why it failed and $err_msg contains an * error message). */ - public static function serviceMail($url, $service, $flags, & $err_code, & $err_msg, & $pt) + public static function serviceMail($url, $service, $flags, &$err_code, &$err_msg, &$pt) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); + $res = null; try { - $res = self::$_PHPCAS_CLIENT->serviceMail($url, $service, $flags, $err_code, $err_msg, $pt); + $res = static::$_PHPCAS_CLIENT->serviceMail($url, $service, $flags, $err_code, $err_msg, $pt); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd($res); + static::traceEnd($res); + return $res; } /** @} */ + // ######################################################################## // AUTHENTICATION // ######################################################################## + /** - * @addtogroup publicAuth - * @{ - */ + * @addtogroup publicAuth + * @{ + */ /** * Set the times authentication will be cached before really accessing the * CAS server in gateway mode: - * - -1: check only once, and then never again (until you pree login) + * - -1: check only once, and then never again (until you pre-login) * - 0: always check - * - n: check every "n" time + * - n: check every "n" time. * * @param int $n an integer. * @@ -986,12 +1054,12 @@ public static function serviceMail($url, $service, $flags, & $err_code, & $err_m */ public static function setCacheTimesForAuthRecheck($n) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n); + static::$_PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } } @@ -1002,9 +1070,9 @@ public static function setCacheTimesForAuthRecheck($n) * parameter, followed by any $additionalArgs you pass. The $logoutTicket * parameter is an opaque string that can be used to map the session-id to * logout request in order to support single-signout in applications that - * manage their own sessions (rather than letting phpCAS start the session). + * manage their own sessions (rather than letting CAS start the session). * - * phpCAS::forceAuthentication() will always exit and forward client unless + * static::forceAuthentication() will always exit and forward client unless * they are already authenticated. To perform an action at the moment the user * logs in (such as registering an account, performing logging, etc), register * a callback function here. @@ -1014,11 +1082,11 @@ public static function setCacheTimesForAuthRecheck($n) * * @return void */ - public static function setPostAuthenticateCallback ($function, array $additionalArgs = array()) + public static function setPostAuthenticateCallback($function, array $additionalArgs = []) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - self::$_PHPCAS_CLIENT->setPostAuthenticateCallback($function, $additionalArgs); + static::$_PHPCAS_CLIENT->setPostAuthenticateCallback($function, $additionalArgs); } /** @@ -1027,7 +1095,7 @@ public static function setPostAuthenticateCallback ($function, array $additional * first parameter, followed by any $additionalArgs you pass. The * $logoutTicket parameter is an opaque string that can be used to map a * session-id to the logout request in order to support single-signout in - * applications that manage their own sessions (rather than letting phpCAS + * applications that manage their own sessions (rather than letting CAS * start and destroy the session). * * @param string $function Callback function @@ -1035,18 +1103,18 @@ public static function setPostAuthenticateCallback ($function, array $additional * * @return void */ - public static function setSingleSignoutCallback ($function, array $additionalArgs = array()) + public static function setSingleSignoutCallback($function, array $additionalArgs = []) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - self::$_PHPCAS_CLIENT->setSingleSignoutCallback($function, $additionalArgs); + static::$_PHPCAS_CLIENT->setSingleSignoutCallback($function, $additionalArgs); } /** * This method is called to check if the user is already authenticated * locally or has a global cas session. A already existing cas session is * determined by a cas gateway call.(cas login call without any interactive - * prompt) + * prompt). * * @return true when the user is authenticated, false when a previous * gateway login failed or the function will not return if the user is @@ -1054,15 +1122,16 @@ public static function setSingleSignoutCallback ($function, array $additionalArg */ public static function checkAuthentication() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - $auth = self::$_PHPCAS_CLIENT->checkAuthentication(); + $auth = static::$_PHPCAS_CLIENT->checkAuthentication(); // store where the authentication has been checked and the result - self::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + static::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + + static::traceEnd($auth); - phpCAS :: traceEnd($auth); return $auth; } @@ -1075,21 +1144,22 @@ public static function checkAuthentication() */ public static function forceAuthentication() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); - $auth = self::$_PHPCAS_CLIENT->forceAuthentication(); + static::traceBegin(); + static::_validateClientExists(); + $auth = static::$_PHPCAS_CLIENT->forceAuthentication(); // store where the authentication has been checked and the result - self::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + static::$_PHPCAS_CLIENT->markAuthenticationCall($auth); - /* if (!$auth) { - phpCAS :: trace('user is not authenticated, redirecting to the CAS server'); - self::$_PHPCAS_CLIENT->forceAuthentication(); - } else { - phpCAS :: trace('no need to authenticate (user `' . phpCAS :: getUser() . '\' is already authenticated)'); - }*/ + // if (! $auth) { + // static::trace('user is not authenticated, redirect to the CAS server'); + // static::$_PHPCAS_CLIENT->forceAuthentication(); + // } else { + // static::trace('no need to authenticate (user `' . static::getUser() . '\' is already authenticated)'); + // } + + static::traceEnd(); - phpCAS :: traceEnd(); return $auth; } @@ -1100,16 +1170,15 @@ public static function forceAuthentication() **/ public static function renewAuthentication() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - $auth = self::$_PHPCAS_CLIENT->renewAuthentication(); + $auth = static::$_PHPCAS_CLIENT->renewAuthentication(); // store where the authentication has been checked and the result - self::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + static::$_PHPCAS_CLIENT->markAuthenticationCall($auth); - //self::$_PHPCAS_CLIENT->renewAuthentication(); - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1120,16 +1189,17 @@ public static function renewAuthentication() */ public static function isAuthenticated() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); // call the isAuthenticated method of the $_PHPCAS_CLIENT object - $auth = self::$_PHPCAS_CLIENT->isAuthenticated(); + $auth = static::$_PHPCAS_CLIENT->isAuthenticated(); // store where the authentication has been checked and the result - self::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + static::$_PHPCAS_CLIENT->markAuthenticationCall($auth); + + static::traceEnd($auth); - phpCAS :: traceEnd($auth); return $auth; } @@ -1142,65 +1212,71 @@ public static function isAuthenticated() */ public static function isSessionAuthenticated() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - return (self::$_PHPCAS_CLIENT->isSessionAuthenticated()); + return (static::$_PHPCAS_CLIENT->isSessionAuthenticated()); } /** * This method returns the CAS user's login name. * * @return string the login name of the authenticated user - * @warning should only be called after phpCAS::forceAuthentication() - * or phpCAS::checkAuthentication(). + * @warning should only be called after static::forceAuthentication() + * or static::checkAuthentication(). * */ public static function getUser() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - return self::$_PHPCAS_CLIENT->getUser(); + return static::$_PHPCAS_CLIENT->getUser(); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** * Answer attributes about the authenticated user. * - * @warning should only be called after phpCAS::forceAuthentication() - * or phpCAS::checkAuthentication(). + * @warning should only be called after static::forceAuthentication() + * or static::checkAuthentication(). * * @return array */ public static function getAttributes() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - return self::$_PHPCAS_CLIENT->getAttributes(); + return static::$_PHPCAS_CLIENT->getAttributes(); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** * Answer true if there are attributes for the authenticated user. * - * @warning should only be called after phpCAS::forceAuthentication() - * or phpCAS::checkAuthentication(). + * @warning should only be called after static::forceAuthentication() + * or static::checkAuthentication(). * * @return bool */ public static function hasAttributes() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - return self::$_PHPCAS_CLIENT->hasAttributes(); + return static::$_PHPCAS_CLIENT->hasAttributes(); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** @@ -1209,18 +1285,20 @@ public static function hasAttributes() * @param string $key attribute name * * @return bool - * @warning should only be called after phpCAS::forceAuthentication() - * or phpCAS::checkAuthentication(). + * @warning should only be called after static::forceAuthentication() + * or static::checkAuthentication(). */ public static function hasAttribute($key) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - return self::$_PHPCAS_CLIENT->hasAttribute($key); + return static::$_PHPCAS_CLIENT->hasAttribute($key); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** @@ -1229,18 +1307,20 @@ public static function hasAttribute($key) * @param string $key attribute name * * @return mixed string for a single value or an array if multiple values exist. - * @warning should only be called after phpCAS::forceAuthentication() - * or phpCAS::checkAuthentication(). + * @warning should only be called after static::forceAuthentication() + * or static::checkAuthentication(). */ public static function getAttribute($key) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); try { - return self::$_PHPCAS_CLIENT->getAttribute($key); + return static::$_PHPCAS_CLIENT->getAttribute($key); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** @@ -1251,24 +1331,24 @@ public static function getAttribute($key) * * @return void */ - public static function handleLogoutRequests($check_client = true, $allowed_clients = false) + public static function handleLogoutRequests($check_client = true, $allowed_clients = null) { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - return (self::$_PHPCAS_CLIENT->handleLogoutRequests($check_client, $allowed_clients)); + static::$_PHPCAS_CLIENT->handleLogoutRequests($check_client, $allowed_clients); } /** * This method returns the URL to be used to login. - * or phpCAS::isAuthenticated(). + * or static::isAuthenticated(). * - * @return the login name of the authenticated user + * @return string the login name of the authenticated user */ public static function getServerLoginURL() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - return self::$_PHPCAS_CLIENT->getServerLoginURL(); + return static::$_PHPCAS_CLIENT->getServerLoginURL(); } /** @@ -1281,21 +1361,21 @@ public static function getServerLoginURL() */ public static function setServerLoginURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setServerLoginURL($url); + static::$_PHPCAS_CLIENT->setServerLoginURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** * Set the serviceValidate URL of the CAS server. - * Used only in CAS 1.0 validations + * Used only in CAS 1.0 validations. * * @param string $url the serviceValidate URL * @@ -1303,21 +1383,21 @@ public static function setServerLoginURL($url = '') */ public static function setServerServiceValidateURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setServerServiceValidateURL($url); + static::$_PHPCAS_CLIENT->setServerServiceValidateURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** * Set the proxyValidate URL of the CAS server. - * Used for all CAS 2.0 validations + * Used for all CAS 2.0 validations. * * @param string $url the proxyValidate URL * @@ -1325,16 +1405,16 @@ public static function setServerServiceValidateURL($url = '') */ public static function setServerProxyValidateURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setServerProxyValidateURL($url); + static::$_PHPCAS_CLIENT->setServerProxyValidateURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1346,29 +1426,29 @@ public static function setServerProxyValidateURL($url = '') */ public static function setServerSamlValidateURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setServerSamlValidateURL($url); + static::$_PHPCAS_CLIENT->setServerSamlValidateURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** * This method returns the URL to be used to login. - * or phpCAS::isAuthenticated(). + * or static::isAuthenticated(). * - * @return the login name of the authenticated user + * @return string the login name of the authenticated user */ public static function getServerLogoutURL() { - phpCAS::_validateClientExists(); + static::_validateClientExists(); - return self::$_PHPCAS_CLIENT->getServerLogoutURL(); + return static::$_PHPCAS_CLIENT->getServerLogoutURL(); } /** @@ -1381,16 +1461,16 @@ public static function getServerLogoutURL() */ public static function setServerLogoutURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setServerLogoutURL($url); + static::$_PHPCAS_CLIENT->setServerLogoutURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1401,29 +1481,29 @@ public static function setServerLogoutURL($url = '') * * @return void */ - public static function logout($params = "") + public static function logout($params = '') { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - $parsedParams = array (); - if ($params != "") { + $parsedParams = []; + if ($params != '') { if (is_string($params)) { - phpCAS :: error('method `phpCAS::logout($url)\' is now deprecated, use `phpCAS::logoutWithUrl($url)\' instead'); + static::error('method `'.__CLASS__.'::logout($url)\' is now deprecated, use `'.__CLASS__.'::logoutWithUrl($url)\' instead'); } - if (!is_array($params)) { - phpCAS :: error('type mismatched for parameter $params (should be `array\')'); + if (! is_array($params)) { + static::error('type mismatched for parameter $params (should be `array\')'); } foreach ($params as $key => $value) { - if ($key != "service" && $key != "url") { - phpCAS :: error('only `url\' and `service\' parameters are allowed for method `phpCAS::logout($params)\''); + if ($key != 'service' && $key != 'url') { + static::error('only `url\' and `service\' parameters are allowed for method `'.__CLASS__.'::logout($params)\''); } $parsedParams[$key] = $value; } } - self::$_PHPCAS_CLIENT->logout($parsedParams); + static::$_PHPCAS_CLIENT->logout($parsedParams); // never reached - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1436,15 +1516,15 @@ public static function logout($params = "") */ public static function logoutWithRedirectService($service) { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - if (!is_string($service)) { - phpCAS :: error('type mismatched for parameter $service (should be `string\')'); + if (! is_string($service)) { + static::error('type mismatched for parameter $service (should be `string\')'); } - self::$_PHPCAS_CLIENT->logout(array ( "service" => $service )); + static::$_PHPCAS_CLIENT->logout(['service' => $service]); // never reached - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1460,16 +1540,16 @@ public static function logoutWithRedirectService($service) public static function logoutWithUrl($url) { trigger_error('Function deprecated for cas servers >= 3.3.5.1', E_USER_DEPRECATED); - phpCAS :: traceBegin(); - if (!is_object(self::$_PHPCAS_CLIENT)) { - phpCAS :: error('this method should only be called after ' . __CLASS__ . '::client() or' . __CLASS__ . '::proxy()'); + static::traceBegin(); + if (! is_object(static::$_PHPCAS_CLIENT)) { + static::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); } - if (!is_string($url)) { - phpCAS :: error('type mismatched for parameter $url (should be `string\')'); + if (! is_string($url)) { + static::error('type mismatched for parameter $url (should be `string\')'); } - self::$_PHPCAS_CLIENT->logout(array ( "url" => $url )); + static::$_PHPCAS_CLIENT->logout(['url' => $url]); // never reached - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1487,23 +1567,23 @@ public static function logoutWithUrl($url) public static function logoutWithRedirectServiceAndUrl($service, $url) { trigger_error('Function deprecated for cas servers >= 3.3.5.1', E_USER_DEPRECATED); - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - if (!is_string($service)) { - phpCAS :: error('type mismatched for parameter $service (should be `string\')'); + if (! is_string($service)) { + static::error('type mismatched for parameter $service (should be `string\')'); } - if (!is_string($url)) { - phpCAS :: error('type mismatched for parameter $url (should be `string\')'); + if (! is_string($url)) { + static::error('type mismatched for parameter $url (should be `string\')'); } - self::$_PHPCAS_CLIENT->logout( - array ( - "service" => $service, - "url" => $url - ) + static::$_PHPCAS_CLIENT->logout( + [ + 'service' => $service, + 'url' => $url, + ] ); // never reached - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1517,16 +1597,16 @@ public static function logoutWithRedirectServiceAndUrl($service, $url) */ public static function setFixedCallbackURL($url = '') { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->setCallbackURL($url); + static::$_PHPCAS_CLIENT->setCallbackURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1539,16 +1619,16 @@ public static function setFixedCallbackURL($url = '') */ public static function setFixedServiceURL($url) { - phpCAS :: traceBegin(); - phpCAS::_validateProxyExists(); + static::traceBegin(); + static::_validateProxyExists(); try { - self::$_PHPCAS_CLIENT->setURL($url); + static::$_PHPCAS_CLIENT->setURL($url); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1558,8 +1638,9 @@ public static function setFixedServiceURL($url) */ public static function getServiceURL() { - phpCAS::_validateProxyExists(); - return (self::$_PHPCAS_CLIENT->getURL()); + static::_validateProxyExists(); + + return (static::$_PHPCAS_CLIENT->getURL()); } /** @@ -1571,15 +1652,17 @@ public static function getServiceURL() * * @return string Proxy Ticket */ - public static function retrievePT($target_service, & $err_code, & $err_msg) + public static function retrievePT($target_service, &$err_code, &$err_msg) { - phpCAS::_validateProxyExists(); + static::_validateProxyExists(); try { - return (self::$_PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg)); + return (static::$_PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg)); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } + + return; } /** @@ -1593,16 +1676,16 @@ public static function retrievePT($target_service, & $err_code, & $err_msg) */ public static function setCasServerCACert($cert, $validate_cn = true) { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->setCasServerCACert($cert, $validate_cn); + static::$_PHPCAS_CLIENT->setCasServerCACert($cert, $validate_cn); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** @@ -1612,38 +1695,37 @@ public static function setCasServerCACert($cert, $validate_cn = true) */ public static function setNoCasServerValidation() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - phpCAS :: trace('You have configured no validation of the legitimacy of the cas server. This is not recommended for production use.'); - self::$_PHPCAS_CLIENT->setNoCasServerValidation(); - phpCAS :: traceEnd(); + static::trace('You have configured no validation of the legitimacy of the CAS server. This is not recommended for production use.'); + static::$_PHPCAS_CLIENT->setNoCasServerValidation(); + static::traceEnd(); } - /** * Disable the removal of a CAS-Ticket from the URL when authenticating * DISABLING POSES A SECURITY RISK: * We normally remove the ticket by an additional redirect as a security * precaution to prevent a ticket in the HTTP_REFERRER or be carried over in - * the URL parameter + * the URL parameter. * * @return void */ public static function setNoClearTicketsFromUrl() { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - self::$_PHPCAS_CLIENT->setNoClearTicketsFromUrl(); - phpCAS :: traceEnd(); + static::$_PHPCAS_CLIENT->setNoClearTicketsFromUrl(); + static::traceEnd(); } /** @} */ /** * Change CURL options. - * CURL is used to connect through HTTPS to CAS server + * CURL is used to connect through HTTPS to CAS server. * * @param string $key the option key * @param string $value the value to set @@ -1652,19 +1734,19 @@ public static function setNoClearTicketsFromUrl() */ public static function setExtraCurlOption($key, $value) { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - self::$_PHPCAS_CLIENT->setExtraCurlOption($key, $value); - phpCAS :: traceEnd(); + static::$_PHPCAS_CLIENT->setExtraCurlOption($key, $value); + static::traceEnd(); } /** * If you want your service to be proxied you have to enable it (default - * disabled) and define an accepable list of proxies that are allowed to + * disabled) and define an acceptable list of proxies that are allowed to * proxy your service. * - * Add each allowed proxy definition object. For the normal CAS_ProxyChain + * Add each allowed proxy definition object. For the normal ProxyChain * class, the constructor takes an array of proxies to match. The list is in * reverse just as seen from the service. Proxies have to be defined in reverse * from the service to the user. If a user hits service A and gets proxied via @@ -1674,39 +1756,39 @@ public static function setExtraCurlOption($key, $value) * when validating the proxy tickets. The strings are compared starting from * the beginning and must fully match with the proxies in the list. * Example: - * phpCAS::allowProxyChain(new CAS_ProxyChain(array( - * 'https://app.example.com/' - * ))); - * phpCAS::allowProxyChain(new CAS_ProxyChain(array( - * '/^https:\/\/app[0-9]\.example\.com\/rest\//', - * 'http://client.example.com/' - * ))); - * - * For quick testing or in certain production screnarios you might want to + * CAS::allowProxyChain(new ProxyChain([ + * 'https://app.example.com/' + * ])); + * CAS::allowProxyChain(new ProxyChain([ + * '/^https:\/\/app[0-9]\.example\.com\/rest\//', + * 'http://client.example.com/' + * ])); + * + * For quick testing or in certain production scenarios you might want to * allow allow any other valid service to proxy your service. To do so, add * the "Any" chain: - * phpcas::allowProxyChain(new CAS_ProxyChain_Any); + * CAS::allowProxyChain(new Any); * THIS SETTING IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY * IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER * ON THIS SERVICE. * - * @param CAS_ProxyChain_Interface $proxy_chain A proxy-chain that will be + * @param ProxyChainInterface $proxy_chain A proxy-chain that will be * matched against the proxies requesting access * * @return void */ - public static function allowProxyChain(CAS_ProxyChain_Interface $proxy_chain) + public static function allowProxyChain(ProxyChainInterface $proxy_chain) { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); - if (self::$_PHPCAS_CLIENT->getServerVersion() !== CAS_VERSION_2_0 - && self::$_PHPCAS_CLIENT->getServerVersion() !== CAS_VERSION_3_0 + if (static::$_PHPCAS_CLIENT->getServerVersion() !== static::CAS_VERSION_2_0 + && static::$_PHPCAS_CLIENT->getServerVersion() !== static::CAS_VERSION_3_0 ) { - phpCAS :: error('this method can only be used with the cas 2.0/3.0 protocols'); + static::error('this method can only be used with the cas 2.0/3.0 protocols'); } - self::$_PHPCAS_CLIENT->getAllowedProxyChains()->allowProxyChain($proxy_chain); - phpCAS :: traceEnd(); + static::$_PHPCAS_CLIENT->getAllowedProxyChains()->allowProxyChain($proxy_chain); + static::traceEnd(); } /** @@ -1715,14 +1797,13 @@ public static function allowProxyChain(CAS_ProxyChain_Interface $proxy_chain) * validated a Proxy Ticket. * * @return array - * @access public * @since 6/25/09 */ - public static function getProxies () + public static function getProxies() { - phpCAS::_validateProxyExists(); + static::_validateProxyExists(); - return(self::$_PHPCAS_CLIENT->getProxies()); + return(static::$_PHPCAS_CLIENT->getProxies()); } // ######################################################################## @@ -1739,17 +1820,17 @@ public static function getProxies () */ public static function addRebroadcastNode($rebroadcastNodeUrl) { - phpCAS::traceBegin(); - phpCAS::log('rebroadcastNodeUrl:'.$rebroadcastNodeUrl); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::log('rebroadcastNodeUrl:'.$rebroadcastNodeUrl); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->addRebroadcastNode($rebroadcastNodeUrl); + static::$_PHPCAS_CLIENT->addRebroadcastNode($rebroadcastNodeUrl); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS::traceEnd(); + static::traceEnd(); } /** @@ -1762,46 +1843,47 @@ public static function addRebroadcastNode($rebroadcastNodeUrl) */ public static function addRebroadcastHeader($header) { - phpCAS :: traceBegin(); - phpCAS::_validateClientExists(); + static::traceBegin(); + static::_validateClientExists(); try { - self::$_PHPCAS_CLIENT->addRebroadcastHeader($header); + static::$_PHPCAS_CLIENT->addRebroadcastHeader($header); } catch (Exception $e) { - phpCAS :: error(get_class($e) . ': ' . $e->getMessage()); + static::error(get_class($e).': '.$e->getMessage()); } - phpCAS :: traceEnd(); + static::traceEnd(); } /** - * Checks if a client already exists + * Checks if a client already exists. * - * @throws CAS_OutOfSequenceBeforeClientException + * @throws OutOfSequenceBeforeClientException * * @return void */ private static function _validateClientExists() { - if (!is_object(self::$_PHPCAS_CLIENT)) { - throw new CAS_OutOfSequenceBeforeClientException(); + if (! is_object(static::$_PHPCAS_CLIENT)) { + throw new OutOfSequenceBeforeClientException(); } } /** - * Checks of a proxy client aready exists + * Checks of a proxy client already exists. * - * @throws CAS_OutOfSequenceBeforeProxyException + * @throws OutOfSequenceBeforeProxyException * * @return void */ private static function _validateProxyExists() { - if (!is_object(self::$_PHPCAS_CLIENT)) { - throw new CAS_OutOfSequenceBeforeProxyException(); + if (! is_object(static::$_PHPCAS_CLIENT)) { + throw new OutOfSequenceBeforeProxyException(); } } } + // ######################################################################## // DOCUMENTATION // ######################################################################## @@ -1904,55 +1986,20 @@ private static function _validateProxyExists() // ######################################################################## // EXAMPLES -/** - * @example example_simple.php - */ -/** - * @example example_service.php - */ -/** - * @example example_service_that_proxies.php - */ -/** - * @example example_service_POST.php - */ -/** - * @example example_proxy_serviceWeb.php - */ -/** - * @example example_proxy_serviceWeb_chaining.php - */ -/** - * @example example_proxy_POST.php - */ -/** - * @example example_proxy_GET.php - */ -/** - * @example example_lang.php - */ -/** - * @example example_html.php - */ -/** - * @example example_pgt_storage_file.php - */ -/** - * @example example_pgt_storage_db.php - */ -/** - * @example example_gateway.php - */ -/** - * @example example_logout.php - */ -/** - * @example example_rebroadcast.php - */ -/** - * @example example_custom_urls.php - */ -/** - * @example example_advanced_saml11.php - */ -?> +/** @example example_simple.php */ +/** @example example_service.php */ +/** @example example_service_that_proxies.php */ +/** @example example_service_POST.php */ +/** @example example_proxy_serviceWeb.php */ +/** @example example_proxy_serviceWeb_chaining.php */ +/** @example example_proxy_POST.php */ +/** @example example_proxy_GET.php */ +/** @example example_lang.php */ +/** @example example_html.php */ +/** @example example_pgt_storage_file.php */ +/** @example example_pgt_storage_db.php */ +/** @example example_gateway.php */ +/** @example example_logout.php */ +/** @example example_rebroadcast.php */ +/** @example example_custom_urls.php */ +/** @example example_advanced_saml11.php */ \ No newline at end of file diff --git a/source/CAS/AuthenticationException.php b/source/CAS/AuthenticationException.php index a14154d4..f7d684ae 100644 --- a/source/CAS/AuthenticationException.php +++ b/source/CAS/AuthenticationException.php @@ -21,88 +21,92 @@ * * @file CAS/AuthenticationException.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use phpCAS\CAS; +use RuntimeException; + /** * This interface defines methods that allow proxy-authenticated service handlers - * to interact with phpCAS. + * to interact with CAS. * * Proxy service handlers must implement this interface as well as call - * phpCAS::initializeProxiedService($this) at some point in their implementation. + * CAS::initializeProxiedService($this) at some point in their implementation. * * While not required, proxy-authenticated service handlers are encouraged to - * implement the CAS_ProxiedService_Testable interface to facilitate unit testing. + * implement the Testable interface to facilitate unit testing. * - * @class CAS_AuthenticationException + * @class AuthenticationException * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_AuthenticationException -extends RuntimeException -implements CAS_Exception +class AuthenticationException extends RuntimeException implements CASExceptionInterface { - /** * This method is used to print the HTML output when the user was not * authenticated. * - * @param CAS_Client $client phpcas client - * @param string $failure the failure that occured - * @param string $cas_url the URL the CAS server was asked for - * @param bool $no_response the response from the CAS server (other - * parameters are ignored if TRUE) - * @param bool $bad_response bad response from the CAS server ($err_code - * and $err_msg ignored if TRUE) - * @param string $cas_response the response of the CAS server - * @param int $err_code the error code given by the CAS server - * @param string $err_msg the error message given by the CAS server + * @param Client $client CAS client + * @param string $failure the failure that occurred + * @param string $cas_url the URL the CAS server was asked for + * @param mixed $no_response the response from the CAS server (other + * parameters are ignored if TRUE) + * @param mixed $bad_response bad response from the CAS server ($err_code + * and $err_msg ignored if TRUE) + * @param string $cas_response the response of the CAS server + * @param int $err_code the error code given by the CAS server + * @param string $err_msg the error message given by the CAS server */ - public function __construct($client,$failure,$cas_url,$no_response, - $bad_response='',$cas_response='',$err_code='',$err_msg='' + public function __construct( + Client $client, + $failure, + $cas_url, + $no_response, + $bad_response = '', + $cas_response = '', + $err_code = 0, + $err_msg = '' ) { - phpCAS::traceBegin(); + CAS::traceBegin(); $lang = $client->getLangObj(); $client->printHTMLHeader($lang->getAuthenticationFailed()); printf( $lang->getYouWereNotAuthenticated(), htmlentities($client->getURL()), - isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:'' + isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN'] : '' ); - phpCAS::trace('CAS URL: '.$cas_url); - phpCAS::trace('Authentication failure: '.$failure); - if ( $no_response ) { - phpCAS::trace('Reason: no response from the CAS server'); + CAS::trace('CAS URL: '.$cas_url); + CAS::trace('Authentication failure: '.$failure); + if ($no_response) { + CAS::trace('Reason: no response from the CAS server'); } else { - if ( $bad_response ) { - phpCAS::trace('Reason: bad response from the CAS server'); + if ($bad_response) { + CAS::trace('Reason: bad response from the CAS server'); } else { switch ($client->getServerVersion()) { - case CAS_VERSION_1_0: - phpCAS::trace('Reason: CAS error'); - break; - case CAS_VERSION_2_0: - case CAS_VERSION_3_0: - if ( empty($err_code) ) { - phpCAS::trace('Reason: no CAS error'); - } else { - phpCAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg); - } - break; + case CAS::CAS_VERSION_1_0: + CAS::trace('Reason: CAS error'); + break; + case CAS::CAS_VERSION_2_0: + case CAS::CAS_VERSION_3_0: + if (empty($err_code)) { + CAS::trace('Reason: no CAS error'); + } else { + CAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg); + } + break; } } - phpCAS::trace('CAS response: '.$cas_response); + CAS::trace('CAS response: '.$cas_response); } $client->printHTMLFooter(); - phpCAS::traceExit(); + CAS::traceExit(); } - } -?> diff --git a/source/CAS/Autoload.php b/source/CAS/Autoload.php deleted file mode 100644 index e56dbdfa..00000000 --- a/source/CAS/Autoload.php +++ /dev/null @@ -1,105 +0,0 @@ - - * @copyright 2008 Regents of the University of Nebraska - * @license http://www1.unl.edu/wdn/wiki/Software_License BSD License - * @link http://code.google.com/p/simplecas/ - **/ - -/** - * Autoload a class - * - * @param string $class Classname to load - * - * @return bool - */ -function CAS_autoload($class) -{ - // Static to hold the Include Path to CAS - static $include_path; - // Check only for CAS classes - if (substr($class, 0, 4) !== 'CAS_') { - return false; - } - // Setup the include path if it's not already set from a previous call - if (empty($include_path)) { - $include_path = array(dirname(dirname(__FILE__)), dirname(dirname(__FILE__)) . '/../test/' ); - } - - // Declare local variable to store the expected full path to the file - - foreach ($include_path as $path) { - $file_path = $path . '/' . str_replace('_', '/', $class) . '.php'; - $fp = @fopen($file_path, 'r', true); - if ($fp) { - fclose($fp); - include $file_path; - if (!class_exists($class, false) && !interface_exists($class, false)) { - die( - new Exception( - 'Class ' . $class . ' was not present in ' . - $file_path . - ' [CAS_autoload]' - ) - ); - } - return true; - } - } - $e = new Exception( - 'Class ' . $class . ' could not be loaded from ' . - $file_path . ', file does not exist (Path="' - . implode(':', $include_path) .'") [CAS_autoload]' - ); - $trace = $e->getTrace(); - if (isset($trace[2]) && isset($trace[2]['function']) - && in_array($trace[2]['function'], array('class_exists', 'interface_exists')) - ) { - return false; - } - if (isset($trace[1]) && isset($trace[1]['function']) - && in_array($trace[1]['function'], array('class_exists', 'interface_exists')) - ) { - return false; - } - die ((string) $e); -} - -// set up __autoload -if (function_exists('spl_autoload_register')) { - if (!(spl_autoload_functions()) - || !in_array('CAS_autoload', spl_autoload_functions()) - ) { - spl_autoload_register('CAS_autoload'); - if (function_exists('__autoload') - && !in_array('__autoload', spl_autoload_functions()) - ) { - // __autoload() was being used, but now would be ignored, add - // it to the autoload stack - spl_autoload_register('__autoload'); - } - } -} elseif (!function_exists('__autoload')) { - - /** - * Autoload a class - * - * @param string $class Class name - * - * @return bool - */ - function __autoload($class) - { - return CAS_autoload($class); - } -} - -?> \ No newline at end of file diff --git a/source/CAS/Exception.php b/source/CAS/CASExceptionInterface.php similarity index 80% rename from source/CAS/Exception.php rename to source/CAS/CASExceptionInterface.php index d956d197..8bd2aa4e 100644 --- a/source/CAS/Exception.php +++ b/source/CAS/CASExceptionInterface.php @@ -21,20 +21,21 @@ * * @file CAS/Exception.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** - * A root exception interface for all exceptions in phpCAS. + * A root exception interface for all exceptions in CAS. * - * All exceptions thrown in phpCAS should implement this interface to allow them - * to be caught as a category by clients. Each phpCAS exception should extend + * All exceptions thrown in CAS should implement this interface to allow them + * to be caught as a category by clients. Each CAS exception should extend * an appropriate SPL exception class that best fits its type. * - * For example, an InvalidArgumentException in phpCAS should be defined as + * For example, an InvalidArgumentException in CAS should be defined as * * class CAS_InvalidArgumentException * extends InvalidArgumentException @@ -44,16 +45,12 @@ * This definition allows the CAS_InvalidArgumentException to be caught as either * an InvalidArgumentException or as a CAS_Exception. * - * @class CAS_Exception + * @class CASExceptionInterface * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS - * */ -interface CAS_Exception +interface CASExceptionInterface { - } -?> \ No newline at end of file diff --git a/source/CAS/Client.php b/source/CAS/Client.php index 124bcf2f..df28500a 100644 --- a/source/CAS/Client.php +++ b/source/CAS/Client.php @@ -21,7 +21,6 @@ * * @file CAS/Client.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @author Olivier Berger * @author Brett Bieber @@ -31,13 +30,34 @@ * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use DOMDocument; +use phpCAS\CAS; +use phpCAS\CAS\Languages\LanguageInterface; +use phpCAS\CAS\PGTStorage\AbstractStorage; +use phpCAS\CAS\PGTStorage\Db; +use phpCAS\CAS\PGTStorage\File; +use phpCAS\CAS\ProxiedService\AbstractProxiedService; +use phpCAS\CAS\ProxiedService\Http; +use phpCAS\CAS\ProxiedService\Http\Get; +use phpCAS\CAS\ProxiedService\Http\Post; +use phpCAS\CAS\ProxiedService\Imap; +use phpCAS\CAS\ProxiedService\ProxiedServiceException; +use phpCAS\CAS\ProxiedService\Testable; +use phpCAS\CAS\ProxyChain\AllowedList; +use phpCAS\CAS\Request\AbstractRequest; +use phpCAS\CAS\Request\CurlMultiRequest; +use phpCAS\CAS\Request\CurlRequest; +use phpCAS\CAS\Request\RequestInterface; +use phpCAS\CAS\TestHarness\DummyRequest; + /** - * The CAS_Client class is a client interface that provides CAS authentication + * The Client class is a client interface that provides CAS authentication * to PHP applications. * - * @class CAS_Client + * @class Client * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @author Olivier Berger * @author Brett Bieber @@ -45,28 +65,26 @@ * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS - * */ - -class CAS_Client +class Client { - // ######################################################################## // HTML OUTPUT // ######################################################################## + /** - * @addtogroup internalOutput - * @{ - */ + * @addtogroup internalOutput + * @{ + */ /** * This method filters a string by replacing special tokens by appropriate values * and prints it. The corresponding tokens are taken into account: * - __CAS_VERSION__ * - __PHPCAS_VERSION__ - * - __SERVER_BASE_URL__ + * - __SERVER_BASE_URL__. * - * Used by CAS_Client::PrintHTMLHeader() and CAS_Client::printHTMLFooter(). + * Used by Client::PrintHTMLHeader() and Client::printHTMLFooter(). * * @param string $str the string to filter and output * @@ -75,23 +93,24 @@ class CAS_Client private function _htmlFilterOutput($str) { $str = str_replace('__CAS_VERSION__', $this->getServerVersion(), $str); - $str = str_replace('__PHPCAS_VERSION__', phpCAS::getVersion(), $str); + $str = str_replace('__PHPCAS_VERSION__', CAS::getVersion(), $str); $str = str_replace('__SERVER_BASE_URL__', $this->_getServerBaseURL(), $str); echo $str; } /** * A string used to print the header of HTML pages. Written by - * CAS_Client::setHTMLHeader(), read by CAS_Client::printHTMLHeader(). + * Client::setHTMLHeader(), read by Client::printHTMLHeader(). * + * @see setHTMLHeader() + * @see printHTMLHeader() * @hideinitializer - * @see CAS_Client::setHTMLHeader, CAS_Client::printHTMLHeader() */ private $_output_header = ''; /** * This method prints the header of the HTML output (after filtering). If - * CAS_Client::setHTMLHeader() was not used, a default header is output. + * Client::setHTMLHeader() was not used, a default header is output. * * @param string $title the title of the page * @@ -112,16 +131,17 @@ public function printHTMLHeader($title) /** * A string used to print the footer of HTML pages. Written by - * CAS_Client::setHTMLFooter(), read by printHTMLFooter(). + * Client::setHTMLFooter(), read by printHTMLFooter(). * + * @see setHTMLFooter() + * @see printHTMLFooter() * @hideinitializer - * @see CAS_Client::setHTMLFooter, CAS_Client::printHTMLFooter() */ private $_output_footer = ''; /** * This method prints the footer of the HTML output (after filtering). If - * CAS_Client::setHTMLFooter() was not used, a default footer is output. + * Client::setHTMLFooter() was not used, a default footer is output. * * @return void * @see _htmlFilterOutput() @@ -130,13 +150,13 @@ public function printHTMLFooter() { $lang = $this->getLangObj(); $this->_htmlFilterOutput( - empty($this->_output_footer)? - (phpcas::getVerbose())? + empty($this->_output_footer) ? + (CAS::getVerbose()) ? '
      phpCAS __PHPCAS_VERSION__ ' .$lang->getUsingServer() .' __SERVER_BASE_URL__ (CAS __CAS_VERSION__)
      ' - :'' - :$this->_output_footer + : '' + : $this->_output_footer ); } @@ -149,9 +169,10 @@ public function printHTMLFooter() */ public function setHTMLHeader($header) { - // Argument Validation - if (gettype($header) != 'string') - throw new CAS_TypeMismatchException($header, '$header', 'string'); + // Argument Validation + if (gettype($header) != 'string') { + throw new TypeMismatchException($header, '$header', 'string'); + } $this->_output_header = $header; } @@ -165,31 +186,32 @@ public function setHTMLHeader($header) */ public function setHTMLFooter($footer) { - // Argument Validation - if (gettype($footer) != 'string') - throw new CAS_TypeMismatchException($footer, '$footer', 'string'); + // Argument Validation + if (gettype($footer) != 'string') { + throw new TypeMismatchException($footer, '$footer', 'string'); + } $this->_output_footer = $footer; } - - + /** @} */ - // ######################################################################## // INTERNATIONALIZATION // ######################################################################## + /** - * @addtogroup internalLang - * @{ - */ + * @addtogroup internalLang + * @{ + */ + /** - * A string corresponding to the language used by phpCAS. Written by - * CAS_Client::setLang(), read by CAS_Client::getLang(). - + * A string corresponding to the language used by CAS. Written by + * Client::setLang(), read by Client::getLang(). + * @note debugging information is always in english (debug purposes only). */ - private $_lang = PHPCAS_LANG_DEFAULT; + private $_lang = CAS::PHPCAS_LANG_DEFAULT; /** * This method is used to set the language used by phpCAS. @@ -200,39 +222,43 @@ public function setHTMLFooter($footer) */ public function setLang($lang) { - // Argument Validation - if (gettype($lang) != 'string') - throw new CAS_TypeMismatchException($lang, '$lang', 'string'); + // Argument Validation + if (gettype($lang) != 'string') { + throw new TypeMismatchException($lang, '$lang', 'string'); + } - phpCAS::traceBegin(); + CAS::traceBegin(); $obj = new $lang(); - if (!($obj instanceof CAS_Languages_LanguageInterface)) { - throw new CAS_InvalidArgumentException( - '$className must implement the CAS_Languages_LanguageInterface' + if (! ($obj instanceof LanguageInterface)) { + throw new InvalidArgumentException( + '$className must implement the \phpCAS\CAS\Languages\LanguageInterface' ); } $this->_lang = $lang; - phpCAS::traceEnd(); + CAS::traceEnd(); } /** - * Create the language + * Create the language. * - * @return CAS_Languages_LanguageInterface object implementing the class + * @return LanguageInterface object implementing the class */ public function getLangObj() { $classname = $this->_lang; + return new $classname(); } /** @} */ + // ######################################################################## // CAS SERVER CONFIG // ######################################################################## + /** - * @addtogroup internalConfig - * @{ - */ + * @addtogroup internalConfig + * @{ + */ /** * a record to store information about the CAS server. @@ -246,24 +272,23 @@ public function getLangObj() * CAS server * - $_server['proxy_url']: the proxy URL of the CAS server * - $_server['proxy_validate_url']: the proxy validating URL of the CAS server - * - $_server['logout_url']: the logout URL of the CAS server + * - $_server['logout_url']: the logout URL of the CAS server. * * $_server['version'], $_server['hostname'], $_server['port'] and - * $_server['uri'] are written by CAS_Client::CAS_Client(), read by - * CAS_Client::getServerVersion(), CAS_Client::_getServerHostname(), - * CAS_Client::_getServerPort() and CAS_Client::_getServerURI(). + * $_server['uri'] are written by Client::Client(), read by + * Client::getServerVersion(), Client::_getServerHostname(), + * Client::_getServerPort() and Client::_getServerURI(). * - * The other fields are written and read by CAS_Client::_getServerBaseURL(), - * CAS_Client::getServerLoginURL(), CAS_Client::getServerServiceValidateURL(), - * CAS_Client::getServerProxyValidateURL() and CAS_Client::getServerLogoutURL(). - * - * @hideinitializer + * The other fields are written and read by Client::_getServerBaseURL(), + * Client::getServerLoginURL(), Client::getServerServiceValidateURL(), + * Client::getServerProxyValidateURL() and Client::getServerLogoutURL(). */ - private $_server = array( + private $_server = [ 'version' => -1, 'hostname' => 'none', 'port' => -1, - 'uri' => 'none'); + 'uri' => 'none', + ]; /** * This method is used to retrieve the version of the CAS server. @@ -313,14 +338,15 @@ private function _getServerURI() private function _getServerBaseURL() { // the URL is build only when needed - if ( empty($this->_server['base_url']) ) { - $this->_server['base_url'] = 'https://' . $this->_getServerHostname(); - if ($this->_getServerPort()!=443) { + if (empty($this->_server['base_url'])) { + $this->_server['base_url'] = 'https://'.$this->_getServerHostname(); + if ($this->_getServerPort() != 443) { $this->_server['base_url'] .= ':' .$this->_getServerPort(); } $this->_server['base_url'] .= $this->_getServerURI(); } + return $this->_server['base_url']; } @@ -330,16 +356,16 @@ private function _getServerBaseURL() * @param bool $gateway true to check authentication, false to force it * @param bool $renew true to force the authentication with the CAS server * - * @return a URL. + * @return string a URL. * @note It is recommended that CAS implementations ignore the "gateway" * parameter if "renew" is set */ - public function getServerLoginURL($gateway=false,$renew=false) + public function getServerLoginURL($gateway = false, $renew = false) { - phpCAS::traceBegin(); + CAS::traceBegin(); // the URL is build only when needed - if ( empty($this->_server['login_url']) ) { - $this->_server['login_url'] = $this->_buildQueryUrl($this->_getServerBaseURL().'login','service='.urlencode($this->getURL())); + if (empty($this->_server['login_url'])) { + $this->_server['login_url'] = $this->_buildQueryUrl($this->_getServerBaseURL().'login', 'service='.urlencode($this->getURL())); } $url = $this->_server['login_url']; if ($renew) { @@ -351,7 +377,8 @@ public function getServerLoginURL($gateway=false,$renew=false) // value be "true" $url = $this->_buildQueryUrl($url, 'gateway=true'); } - phpCAS::traceEnd($url); + CAS::traceEnd($url); + return $url; } @@ -364,14 +391,14 @@ public function getServerLoginURL($gateway=false,$renew=false) */ public function setServerLoginURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } return $this->_server['login_url'] = $url; } - /** * This method sets the serviceValidate URL of the CAS server. * @@ -381,14 +408,14 @@ public function setServerLoginURL($url) */ public function setServerServiceValidateURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } return $this->_server['service_validate_url'] = $url; } - /** * This method sets the proxyValidate URL of the CAS server. * @@ -398,14 +425,14 @@ public function setServerServiceValidateURL($url) */ public function setServerProxyValidateURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } return $this->_server['proxy_validate_url'] = $url; } - /** * This method sets the samlValidate URL of the CAS server. * @@ -415,14 +442,14 @@ public function setServerProxyValidateURL($url) */ public function setServerSamlValidateURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } return $this->_server['saml_validate_url'] = $url; } - /** * This method is used to retrieve the service validating URL of the CAS server. * @@ -430,19 +457,19 @@ public function setServerSamlValidateURL($url) */ public function getServerServiceValidateURL() { - phpCAS::traceBegin(); + CAS::traceBegin(); // the URL is build only when needed - if ( empty($this->_server['service_validate_url']) ) { + if (empty($this->_server['service_validate_url'])) { switch ($this->getServerVersion()) { - case CAS_VERSION_1_0: + case CAS::CAS_VERSION_1_0 : $this->_server['service_validate_url'] = $this->_getServerBaseURL() .'validate'; break; - case CAS_VERSION_2_0: + case CAS::CAS_VERSION_2_0: $this->_server['service_validate_url'] = $this->_getServerBaseURL() .'serviceValidate'; break; - case CAS_VERSION_3_0: + case CAS::CAS_VERSION_3_0: $this->_server['service_validate_url'] = $this->_getServerBaseURL() .'p3/serviceValidate'; break; @@ -452,9 +479,11 @@ public function getServerServiceValidateURL() $this->_server['service_validate_url'], 'service='.urlencode($this->getURL()) ); - phpCAS::traceEnd($url); + CAS::traceEnd($url); + return $url; } + /** * This method is used to retrieve the SAML validating URL of the CAS server. * @@ -462,11 +491,11 @@ public function getServerServiceValidateURL() */ public function getServerSamlValidateURL() { - phpCAS::traceBegin(); + CAS::traceBegin(); // the URL is build only when needed - if ( empty($this->_server['saml_validate_url']) ) { + if (empty($this->_server['saml_validate_url'])) { switch ($this->getServerVersion()) { - case SAML_VERSION_1_1: + case CAS::SAML_VERSION_1_1: $this->_server['saml_validate_url'] = $this->_getServerBaseURL().'samlValidate'; break; } @@ -476,7 +505,8 @@ public function getServerSamlValidateURL() $this->_server['saml_validate_url'], 'TARGET='.urlencode($this->getURL()) ); - phpCAS::traceEnd($url); + CAS::traceEnd($url); + return $url; } @@ -487,17 +517,17 @@ public function getServerSamlValidateURL() */ public function getServerProxyValidateURL() { - phpCAS::traceBegin(); + CAS::traceBegin(); // the URL is build only when needed - if ( empty($this->_server['proxy_validate_url']) ) { + if (empty($this->_server['proxy_validate_url'])) { switch ($this->getServerVersion()) { - case CAS_VERSION_1_0: + case CAS::CAS_VERSION_1_0: $this->_server['proxy_validate_url'] = ''; break; - case CAS_VERSION_2_0: + case CAS::CAS_VERSION_2_0: $this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'proxyValidate'; break; - case CAS_VERSION_3_0: + case CAS::CAS_VERSION_3_0: $this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'p3/proxyValidate'; break; } @@ -506,11 +536,11 @@ public function getServerProxyValidateURL() $this->_server['proxy_validate_url'], 'service='.urlencode($this->getURL()) ); - phpCAS::traceEnd($url); + CAS::traceEnd($url); + return $url; } - /** * This method is used to retrieve the proxy URL of the CAS server. * @@ -519,17 +549,18 @@ public function getServerProxyValidateURL() public function getServerProxyURL() { // the URL is build only when needed - if ( empty($this->_server['proxy_url']) ) { + if (empty($this->_server['proxy_url'])) { switch ($this->getServerVersion()) { - case CAS_VERSION_1_0: + case CAS::CAS_VERSION_1_0: $this->_server['proxy_url'] = ''; break; - case CAS_VERSION_2_0: - case CAS_VERSION_3_0: + case CAS::CAS_VERSION_2_0: + case CAS::CAS_VERSION_3_0: $this->_server['proxy_url'] = $this->_getServerBaseURL().'proxy'; break; } } + return $this->_server['proxy_url']; } @@ -541,9 +572,10 @@ public function getServerProxyURL() public function getServerLogoutURL() { // the URL is build only when needed - if ( empty($this->_server['logout_url']) ) { + if (empty($this->_server['logout_url'])) { $this->_server['logout_url'] = $this->_getServerBaseURL().'logout'; } + return $this->_server['logout_url']; } @@ -556,9 +588,10 @@ public function getServerLogoutURL() */ public function setServerLogoutURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } return $this->_server['logout_url'] = $url; } @@ -566,7 +599,7 @@ public function setServerLogoutURL($url) /** * An array to store extra curl options. */ - private $_curl_options = array(); + private $_curl_options = []; /** * This method is used to set additional user curl options. @@ -584,7 +617,7 @@ public function setExtraCurlOption($key, $value) /** @} */ // ######################################################################## - // Change the internal behaviour of phpcas + // Change the internal behaviour of phpCAS // ######################################################################## /** @@ -594,33 +627,33 @@ public function setExtraCurlOption($key, $value) /** * The class to instantiate for making web requests in readUrl(). - * The class specified must implement the CAS_Request_RequestInterface. - * By default CAS_Request_CurlRequest is used, but this may be overridden to + * The class specified must implement the RequestInterface. + * By default CurlRequest is used, but this may be overridden to * supply alternate request mechanisms for testing. */ - private $_requestImplementation = 'CAS_Request_CurlRequest'; + private $_requestImplementation = '\phpCAS\CAS\Request\CurlRequest'; /** * Override the default implementation used to make web requests in readUrl(). - * This class must implement the CAS_Request_RequestInterface. + * This class must implement the RequestInterface. * * @param string $className name of the RequestImplementation class * * @return void */ - public function setRequestImplementation ($className) + public function setRequestImplementation($className) { $obj = new $className; - if (!($obj instanceof CAS_Request_RequestInterface)) { - throw new CAS_InvalidArgumentException( - '$className must implement the CAS_Request_RequestInterface' + if (! ($obj instanceof RequestInterface)) { + throw new InvalidArgumentException( + '$className must implement the CAS\Request\RequestInterface' ); } $this->_requestImplementation = $className; } /** - * @var boolean $_clearTicketsFromUrl; If true, phpCAS will clear session + * @var bool If true, CAS will clear session * tickets from the URL after a successful authentication. */ private $_clearTicketsFromUrl = true; @@ -635,20 +668,20 @@ public function setRequestImplementation ($className) * * @return void */ - public function setNoClearTicketsFromUrl () + public function setNoClearTicketsFromUrl() { $this->_clearTicketsFromUrl = false; } /** - * @var callback $_postAuthenticateCallbackFunction; + * @var callback */ private $_postAuthenticateCallbackFunction = null; /** - * @var array $_postAuthenticateCallbackArgs; + * @var array */ - private $_postAuthenticateCallbackArgs = array(); + private $_postAuthenticateCallbackArgs = []; /** * Set a callback function to be run when a user authenticates. @@ -657,9 +690,9 @@ public function setNoClearTicketsFromUrl () * followed by any $additionalArgs you pass. The $logoutTicket parameter is an * opaque string that can be used to map a session-id to the logout request * in order to support single-signout in applications that manage their own - * sessions (rather than letting phpCAS start the session). + * sessions (rather than letting CAS start the session). * - * phpCAS::forceAuthentication() will always exit and forward client unless + * CAS::forceAuthentication() will always exit and forward client unless * they are already authenticated. To perform an action at the moment the user * logs in (such as registering an account, performing logging, etc), register * a callback function here. @@ -669,21 +702,21 @@ public function setNoClearTicketsFromUrl () * * @return void */ - public function setPostAuthenticateCallback ($function, array $additionalArgs = array()) + public function setPostAuthenticateCallback($function, array $additionalArgs = []) { $this->_postAuthenticateCallbackFunction = $function; $this->_postAuthenticateCallbackArgs = $additionalArgs; } /** - * @var callback $_signoutCallbackFunction; + * @var callback */ private $_signoutCallbackFunction = null; /** - * @var array $_signoutCallbackArgs; + * @var array */ - private $_signoutCallbackArgs = array(); + private $_signoutCallbackArgs = []; /** * Set a callback function to be run when a single-signout request is received. @@ -692,14 +725,14 @@ public function setPostAuthenticateCallback ($function, array $additionalArgs = * followed by any $additionalArgs you pass. The $logoutTicket parameter is an * opaque string that can be used to map a session-id to the logout request in * order to support single-signout in applications that manage their own sessions - * (rather than letting phpCAS start and destroy the session). + * (rather than letting CAS start and destroy the session). * * @param string $function callback function to call * @param array $additionalArgs optional array of arguments * * @return void */ - public function setSingleSignoutCallback ($function, array $additionalArgs = array()) + public function setSingleSignoutCallback($function, array $additionalArgs = []) { $this->_signoutCallbackFunction = $function; $this->_signoutCallbackArgs = $additionalArgs; @@ -710,21 +743,21 @@ public function setSingleSignoutCallback ($function, array $additionalArgs = arr // ######################################################################## /** - * Ensure that this is actually a proxy object or fail with an exception + * Ensure that this is actually a proxy object or fail with an exception. * - * @throws CAS_OutOfSequenceBeforeProxyException + * @throws OutOfSequenceBeforeProxyException * * @return void */ public function ensureIsProxy() { - if (!$this->isProxy()) { - throw new CAS_OutOfSequenceBeforeProxyException(); + if (! $this->isProxy()) { + throw new OutOfSequenceBeforeProxyException(); } } /** - * Mark the caller of authentication. This will help client integraters determine + * Mark the caller of authentication. This will help client integrators determine * problems with their code flow if they call a function such as getUser() before * authentication has occurred. * @@ -732,17 +765,18 @@ public function ensureIsProxy() * * @return null */ - public function markAuthenticationCall ($auth) + public function markAuthenticationCall($auth) { // store where the authentication has been checked and the result $dbg = debug_backtrace(); - $this->_authentication_caller = array ( + $this->_authentication_caller = [ 'file' => $dbg[1]['file'], 'line' => $dbg[1]['line'], - 'method' => $dbg[1]['class'] . '::' . $dbg[1]['function'], - 'result' => (boolean)$auth - ); + 'method' => $dbg[1]['class'].'::'.$dbg[1]['function'], + 'result' => (boolean) $auth, + ]; } + private $_authentication_caller; /** @@ -750,59 +784,59 @@ public function markAuthenticationCall ($auth) * * @return bool */ - public function wasAuthenticationCalled () + public function wasAuthenticationCalled() { - return !empty($this->_authentication_caller); + return ! empty($this->_authentication_caller); } /** * Ensure that authentication was checked. Terminate with exception if no - * authentication was performed + * authentication was performed. * - * @throws CAS_OutOfSequenceBeforeAuthenticationCallException + * @throws OutOfSequenceBeforeAuthenticationCallException * * @return void */ private function _ensureAuthenticationCalled() { - if (!$this->wasAuthenticationCalled()) { - throw new CAS_OutOfSequenceBeforeAuthenticationCallException(); + if (! $this->wasAuthenticationCalled()) { + throw new OutOfSequenceBeforeAuthenticationCallException(); } } /** * Answer the result of the authentication call. * - * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false + * Throws a OutOfSequenceException if wasAuthenticationCalled() is false * and markAuthenticationCall() didn't happen. * * @return bool */ - public function wasAuthenticationCallSuccessful () + public function wasAuthenticationCallSuccessful() { $this->_ensureAuthenticationCalled(); + return $this->_authentication_caller['result']; } - /** * Ensure that authentication was checked. Terminate with exception if no - * authentication was performed + * authentication was performed. * - * @throws CAS_OutOfSequenceBeforeAuthenticationCallException + * @throws OutOfSequenceBeforeAuthenticationCallException * * @return void */ public function ensureAuthenticationCallSuccessful() { $this->_ensureAuthenticationCalled(); - if (!$this->_authentication_caller['result']) { - throw new CAS_OutOfSequenceException( + if (! $this->_authentication_caller['result']) { + throw new OutOfSequenceException( 'authentication was checked (by ' - . $this->getAuthenticationCallerMethod() - . '() at ' . $this->getAuthenticationCallerFile() - . ':' . $this->getAuthenticationCallerLine() - . ') but the method returned false' + .$this->getAuthenticationCallerMethod() + .'() at '.$this->getAuthenticationCallerFile() + .':'.$this->getAuthenticationCallerLine() + .') but the method returned false' ); } } @@ -810,42 +844,45 @@ public function ensureAuthenticationCallSuccessful() /** * Answer information about the authentication caller. * - * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false + * Throws a OutOfSequenceException if wasAuthenticationCalled() is false * and markAuthenticationCall() didn't happen. * * @return array Keys are 'file', 'line', and 'method' */ - public function getAuthenticationCallerFile () + public function getAuthenticationCallerFile() { $this->_ensureAuthenticationCalled(); + return $this->_authentication_caller['file']; } /** * Answer information about the authentication caller. * - * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false + * Throws a OutOfSequenceException if wasAuthenticationCalled() is false * and markAuthenticationCall() didn't happen. * * @return array Keys are 'file', 'line', and 'method' */ - public function getAuthenticationCallerLine () + public function getAuthenticationCallerLine() { $this->_ensureAuthenticationCalled(); + return $this->_authentication_caller['line']; } /** * Answer information about the authentication caller. * - * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false + * Throws a OutOfSequenceException if wasAuthenticationCalled() is false * and markAuthenticationCall() didn't happen. * * @return array Keys are 'file', 'line', and 'method' */ - public function getAuthenticationCallerMethod () + public function getAuthenticationCallerMethod() { $this->_ensureAuthenticationCalled(); + return $this->_authentication_caller['method']; } @@ -854,13 +891,14 @@ public function getAuthenticationCallerMethod () // ######################################################################## // CONSTRUCTOR // ######################################################################## + /** - * @addtogroup internalConfig - * @{ - */ + * @addtogroup internalConfig + * @{ + */ /** - * CAS_Client constructor. + * Client constructor. * * @param string $server_version the version of the CAS server * @param bool $proxy true if the CAS client is a CAS proxy @@ -870,8 +908,6 @@ public function getAuthenticationCallerMethod () * @param bool $changeSessionID Allow phpCAS to change the session_id * (Single Sign Out/handleLogoutRequests * is based on that change) - * - * @return a newly created CAS_Client object */ public function __construct( $server_version, @@ -881,108 +917,116 @@ public function __construct( $server_uri, $changeSessionID = true ) { - // Argument validation - if (gettype($server_version) != 'string') - throw new CAS_TypeMismatchException($server_version, '$server_version', 'string'); - if (gettype($proxy) != 'boolean') - throw new CAS_TypeMismatchException($proxy, '$proxy', 'boolean'); - if (gettype($server_hostname) != 'string') - throw new CAS_TypeMismatchException($server_hostname, '$server_hostname', 'string'); - if (gettype($server_port) != 'integer') - throw new CAS_TypeMismatchException($server_port, '$server_port', 'integer'); - if (gettype($server_uri) != 'string') - throw new CAS_TypeMismatchException($server_uri, '$server_uri', 'string'); - if (gettype($changeSessionID) != 'boolean') - throw new CAS_TypeMismatchException($changeSessionID, '$changeSessionID', 'boolean'); - - phpCAS::traceBegin(); + // Argument validation + if (gettype($server_version) != 'string') { + throw new TypeMismatchException($server_version, '$server_version', 'string'); + } + if (gettype($proxy) != 'boolean') { + throw new TypeMismatchException($proxy, '$proxy', 'boolean'); + } + if (gettype($server_hostname) != 'string') { + throw new TypeMismatchException($server_hostname, '$server_hostname', 'string'); + } + if (gettype($server_port) != 'integer') { + throw new TypeMismatchException($server_port, '$server_port', 'integer'); + } + if (gettype($server_uri) != 'string') { + throw new TypeMismatchException($server_uri, '$server_uri', 'string'); + } + if (gettype($changeSessionID) != 'boolean') { + throw new TypeMismatchException($changeSessionID, '$changeSessionID', 'boolean'); + } + + CAS::traceBegin(); // true : allow to change the session_id(), false session_id won't be // change and logout won't be handle because of that $this->_setChangeSessionID($changeSessionID); // skip Session Handling for logout requests and if don't want it' - if (session_id()=="" && !$this->_isLogoutRequest()) { + if (session_id() == '' && ! $this->_isLogoutRequest()) { session_start(); - phpCAS :: trace("Starting a new session " . session_id()); + CAS::trace('Starting a new session '.session_id()); } - // Only for debug purposes - if ($this->isSessionAuthenticated()){ - phpCAS :: trace("Session is authenticated as: " . $_SESSION['phpCAS']['user']); - } else { - phpCAS :: trace("Session is not authenticated"); + // Only for debug purposes + if ($this->isSessionAuthenticated()) { + CAS::trace('Session is authenticated as: '.$_SESSION['phpCAS']['user']); + } else { + CAS::trace('Session is not authenticated'); } // are we in proxy mode ? $this->_proxy = $proxy; // Make cookie handling available. if ($this->isProxy()) { - if (!isset($_SESSION['phpCAS'])) { - $_SESSION['phpCAS'] = array(); + if (! isset($_SESSION['phpCAS'])) { + $_SESSION['phpCAS'] = []; } - if (!isset($_SESSION['phpCAS']['service_cookies'])) { - $_SESSION['phpCAS']['service_cookies'] = array(); + if (! isset($_SESSION['phpCAS']['service_cookies'])) { + $_SESSION['phpCAS']['service_cookies'] = []; } - $this->_serviceCookieJar = new CAS_CookieJar( + $this->_serviceCookieJar = new CookieJar( $_SESSION['phpCAS']['service_cookies'] ); } //check version switch ($server_version) { - case CAS_VERSION_1_0: - if ( $this->isProxy() ) { - phpCAS::error( + case CAS::CAS_VERSION_1_0: + if ($this->isProxy()) { + CAS::error( 'CAS proxies are not supported in CAS '.$server_version ); } break; - case CAS_VERSION_2_0: - case CAS_VERSION_3_0: + case CAS::CAS_VERSION_2_0: + case CAS::CAS_VERSION_3_0: break; - case SAML_VERSION_1_1: + case CAS::SAML_VERSION_1_1: break; default: - phpCAS::error( + CAS::error( 'this version of CAS (`'.$server_version - .'\') is not supported by phpCAS '.phpCAS::getVersion() + .'\') is not supported by phpCAS '.CAS::getVersion() ); } $this->_server['version'] = $server_version; // check hostname - if ( empty($server_hostname) - || !preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/', $server_hostname) + if (empty($server_hostname) + || ! preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/', $server_hostname) ) { - phpCAS::error('bad CAS server hostname (`'.$server_hostname.'\')'); + CAS::error('bad CAS server hostname (`'.$server_hostname.'\')'); } $this->_server['hostname'] = $server_hostname; // check port - if ( $server_port == 0 - || !is_int($server_port) + if ($server_port == 0 + || ! is_int($server_port) ) { - phpCAS::error('bad CAS server port (`'.$server_hostname.'\')'); + CAS::error('bad CAS server port (`'.$server_hostname.'\')'); } $this->_server['port'] = $server_port; // check URI - if ( !preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/', $server_uri) ) { - phpCAS::error('bad CAS server URI (`'.$server_uri.'\')'); + if (! preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/', $server_uri)) { + CAS::error('bad CAS server URI (`'.$server_uri.'\')'); } // add leading and trailing `/' and remove doubles - if(strstr($server_uri, '?') === false) $server_uri .= '/'; + if (strstr($server_uri, '?') === false) { + $server_uri .= '/'; + } $server_uri = preg_replace('/\/\//', '/', '/'.$server_uri); $this->_server['uri'] = $server_uri; // set to callback mode if PgtIou and PgtId CGI GET parameters are provided - if ( $this->isProxy() ) { - $this->_setCallbackMode(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId'])); + if ($this->isProxy()) { + $this->_setCallbackMode(! empty($_GET['pgtIou']) && ! empty($_GET['pgtId'])); } - if ( $this->_isCallbackMode() ) { - //callback mode: check that phpCAS is secured - if ( !$this->_isHttps() ) { - phpCAS::error( + if ($this->_isCallbackMode()) { + //callback mode: check that CAS is secured + if (! $this->_isHttps()) { + CAS::error( 'CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server' ); } @@ -990,20 +1034,19 @@ public function __construct( //normal mode: get ticket and remove it from CGI parameters for // developers $ticket = (isset($_GET['ticket']) ? $_GET['ticket'] : null); - if (preg_match('/^[SP]T-/', $ticket) ) { - phpCAS::trace('Ticket \''.$ticket.'\' found'); + if (preg_match('/^[SP]T-/', $ticket)) { + CAS::trace('Ticket \''.$ticket.'\' found'); $this->setTicket($ticket); unset($_GET['ticket']); - } else if ( !empty($ticket) ) { + } elseif (! empty($ticket)) { //ill-formed ticket, halt - phpCAS::error( + CAS::error( 'ill-formed ticket found in the URL (ticket=`' .htmlentities($ticket).'\')' ); } - } - phpCAS::traceEnd(); + CAS::traceEnd(); } /** @} */ @@ -1019,17 +1062,17 @@ public function __construct( * @{ */ - /** - * A variable to whether phpcas will use its own session handling. Default = true + * A variable to whether CAS will use its own session handling. Default = true. + * * @hideinitializer */ private $_change_session_id = true; /** - * Set a parameter whether to allow phpCas to change session_id + * Set a parameter whether to allow phpCAS to change session_id. * - * @param bool $allowed allow phpCas to change session_id + * @param bool $allowed allow phpCAS to change session_id * * @return void */ @@ -1039,7 +1082,7 @@ private function _setChangeSessionID($allowed) } /** - * Get whether phpCas is allowed to change session_id + * Get whether CAS is allowed to change session_id. * * @return bool */ @@ -1062,8 +1105,8 @@ public function getChangeSessionID() */ /** - * The Authenticated user. Written by CAS_Client::_setUser(), read by - * CAS_Client::getUser(). + * The Authenticated user. Written by Client::_setUser(), read by + * Client::getUser(). * * @hideinitializer */ @@ -1086,15 +1129,15 @@ private function _setUser($user) * * @return string the login name of the authenticated user * - * @warning should be called only after CAS_Client::forceAuthentication() or - * CAS_Client::isAuthenticated(), otherwise halt with an error. + * @warning should be called only after Client::forceAuthentication() or + * Client::isAuthenticated(), otherwise halt with an error. */ public function getUser() { - // Sequence validation - $this->ensureAuthenticationCallSuccessful(); + // Sequence validation + $this->ensureAuthenticationCallSuccessful(); - return $this->_getUser(); + return $this->_getUser(); } /** @@ -1102,32 +1145,33 @@ public function getUser() * * @return string the login name of the authenticated user * - * @warning should be called only after CAS_Client::forceAuthentication() or - * CAS_Client::isAuthenticated(), otherwise halt with an error. + * @warning should be called only after Client::forceAuthentication() or + * Client::isAuthenticated(), otherwise halt with an error. */ private function _getUser() { - // This is likely a duplicate check that could be removed.... - if ( empty($this->_user) ) { - phpCAS::error( + // This is likely a duplicate check that could be removed.... + if (empty($this->_user)) { + CAS::error( 'this method should be used only after '.__CLASS__ .'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()' ); } + return $this->_user; } /** * The Authenticated users attributes. Written by - * CAS_Client::setAttributes(), read by CAS_Client::getAttributes(). + * Client::setAttributes(), read by Client::getAttributes(). * @attention client applications should use phpCAS::getAttributes(). * * @hideinitializer */ - private $_attributes = array(); + private $_attributes = []; /** - * Set an array of attributes + * Set an array of attributes. * * @param array $attributes a key value array of attributes * @@ -1139,39 +1183,41 @@ public function setAttributes($attributes) } /** - * Get an key values arry of attributes + * Get an key values array of attributes. * - * @return arry of attributes + * @return array of attributes */ public function getAttributes() { - // Sequence validation - $this->ensureAuthenticationCallSuccessful(); - // This is likely a duplicate check that could be removed.... - if ( empty($this->_user) ) { + // Sequence validation + $this->ensureAuthenticationCallSuccessful(); + // This is likely a duplicate check that could be removed.... + if (empty($this->_user)) { // if no user is set, there shouldn't be any attributes also... - phpCAS::error( + CAS::error( 'this method should be used only after '.__CLASS__ .'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()' ); } + return $this->_attributes; } /** - * Check whether attributes are available + * Check whether attributes are available. * * @return bool attributes available */ public function hasAttributes() { - // Sequence validation - $this->ensureAuthenticationCallSuccessful(); + // Sequence validation + $this->ensureAuthenticationCallSuccessful(); - return !empty($this->_attributes); + return ! empty($this->_attributes); } + /** - * Check whether a specific attribute with a name is available + * Check whether a specific attribute with a name is available. * * @param string $key name of attribute * @@ -1179,14 +1225,14 @@ public function hasAttributes() */ public function hasAttribute($key) { - // Sequence validation - $this->ensureAuthenticationCallSuccessful(); + // Sequence validation + $this->ensureAuthenticationCallSuccessful(); return $this->_hasAttribute($key); } /** - * Check whether a specific attribute with a name is available + * Check whether a specific attribute with a name is available. * * @param string $key name of attribute * @@ -1199,7 +1245,7 @@ private function _hasAttribute($key) } /** - * Get a specific attribute by name + * Get a specific attribute by name. * * @param string $key name of attribute * @@ -1207,37 +1253,40 @@ private function _hasAttribute($key) */ public function getAttribute($key) { - // Sequence validation - $this->ensureAuthenticationCallSuccessful(); + // Sequence validation + $this->ensureAuthenticationCallSuccessful(); if ($this->_hasAttribute($key)) { return $this->_attributes[$key]; } + + return; } /** * This method is called to renew the authentication of the user * If the user is authenticated, renew the connection - * If not, redirect to CAS + * If not, redirect to CAS. * * @return true when the user is authenticated; otherwise halt. */ public function renewAuthentication() { - phpCAS::traceBegin(); + CAS::traceBegin(); // Either way, the user is authenticated by CAS - if (isset( $_SESSION['phpCAS']['auth_checked'])) { + if (isset($_SESSION['phpCAS']['auth_checked'])) { unset($_SESSION['phpCAS']['auth_checked']); } - if ( $this->isAuthenticated(true) ) { - phpCAS::trace('user already authenticated'); + if ($this->isAuthenticated(true)) { + CAS::trace('user already authenticated'); $res = true; } else { $this->redirectToCas(false, true); - // never reached + // never reached $res = false; } - phpCAS::traceEnd(); + CAS::traceEnd(); + return $res; } @@ -1249,11 +1298,11 @@ public function renewAuthentication() */ public function forceAuthentication() { - phpCAS::traceBegin(); + CAS::traceBegin(); - if ( $this->isAuthenticated() ) { + if ($this->isAuthenticated()) { // the user is authenticated, nothing to be done. - phpCAS::trace('no need to authenticate'); + CAS::trace('no need to authenticate'); $res = true; } else { // the user is not authenticated, redirect to the CAS server @@ -1264,7 +1313,8 @@ public function forceAuthentication() // never reached $res = false; } - phpCAS::traceEnd($res); + CAS::traceEnd($res); + return $res; } @@ -1285,8 +1335,9 @@ public function forceAuthentication() */ public function setCacheTimesForAuthRecheck($n) { - if (gettype($n) != 'integer') - throw new CAS_TypeMismatchException($n, '$n', 'string'); + if (gettype($n) != 'integer') { + throw new TypeMismatchException($n, '$n', 'string'); + } $this->_cache_times_for_auth_recheck = $n; } @@ -1300,21 +1351,20 @@ public function setCacheTimesForAuthRecheck($n) */ public function checkAuthentication() { - phpCAS::traceBegin(); - $res = false; - if ( $this->isAuthenticated() ) { - phpCAS::trace('user is authenticated'); + CAS::traceBegin(); + if ($this->isAuthenticated()) { + CAS::trace('user is authenticated'); /* The 'auth_checked' variable is removed just in case it's set. */ unset($_SESSION['phpCAS']['auth_checked']); $res = true; - } else if (isset($_SESSION['phpCAS']['auth_checked'])) { + } elseif (isset($_SESSION['phpCAS']['auth_checked'])) { // the previous request has redirected the client to the CAS server // with gateway=true unset($_SESSION['phpCAS']['auth_checked']); $res = false; } else { // avoid a check against CAS on every request - if (!isset($_SESSION['phpCAS']['unauth_count'])) { + if (! isset($_SESSION['phpCAS']['unauth_count'])) { $_SESSION['phpCAS']['unauth_count'] = -2; // uninitialized } @@ -1327,26 +1377,27 @@ public function checkAuthentication() if ($this->_cache_times_for_auth_recheck != -1) { $_SESSION['phpCAS']['unauth_count']++; - phpCAS::trace( + CAS::trace( 'user is not authenticated (cached for ' .$_SESSION['phpCAS']['unauth_count'].' times of ' .$this->_cache_times_for_auth_recheck.')' ); } else { - phpCAS::trace( + CAS::trace( 'user is not authenticated (cached for until login pressed)' ); } } else { $_SESSION['phpCAS']['unauth_count'] = 0; $_SESSION['phpCAS']['auth_checked'] = true; - phpCAS::trace('user is not authenticated (cache reset)'); + CAS::trace('user is not authenticated (cache reset)'); $this->redirectToCas(true/* gateway */); // never reached $res = false; } } - phpCAS::traceEnd($res); + CAS::traceEnd($res); + return $res; } @@ -1359,26 +1410,26 @@ public function checkAuthentication() * @return true when the user is authenticated. Also may redirect to the * same URL without the ticket. */ - public function isAuthenticated($renew=false) + public function isAuthenticated($renew = false) { - phpCAS::traceBegin(); + CAS::traceBegin(); $res = false; $validate_url = ''; - if ( $this->_wasPreviouslyAuthenticated() ) { + if ($this->_wasPreviouslyAuthenticated()) { if ($this->hasTicket()) { // User has a additional ticket but was already authenticated - phpCAS::trace( + CAS::trace( 'ticket was present and will be discarded, use renewAuthenticate()' ); if ($this->_clearTicketsFromUrl) { - phpCAS::trace("Prepare redirect to : ".$this->getURL()); + CAS::trace('Prepare redirect to : '.$this->getURL()); session_write_close(); header('Location: '.$this->getURL()); flush(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); + CAS::traceExit(); + throw new GracefulTerminationException(); } else { - phpCAS::trace( + CAS::trace( 'Already authenticated, but skipping ticket clearing since setNoClearTicketsFromUrl() was used.' ); $res = true; @@ -1386,72 +1437,75 @@ public function isAuthenticated($renew=false) } else { // the user has already (previously during the session) been // authenticated, nothing to be done. - phpCAS::trace( + CAS::trace( 'user was already authenticated, no need to look for tickets' ); $res = true; } // Mark the auth-check as complete to allow post-authentication - // callbacks to make use of phpCAS::getUser() and similar methods + // callbacks to make use of CAS::getUser() and similar methods $this->markAuthenticationCall($res); } else { if ($this->hasTicket()) { switch ($this->getServerVersion()) { - case CAS_VERSION_1_0: + case CAS::CAS_VERSION_1_0: // if a Service Ticket was given, validate it - phpCAS::trace( + CAS::trace( 'CAS 1.0 ticket `'.$this->getTicket().'\' is present' ); $this->validateCAS10( $validate_url, $text_response, $tree_response, $renew ); // if it fails, it halts - phpCAS::trace( + CAS::trace( 'CAS 1.0 ticket `'.$this->getTicket().'\' was validated' ); $_SESSION['phpCAS']['user'] = $this->_getUser(); $res = true; $logoutTicket = $this->getTicket(); break; - case CAS_VERSION_2_0: - case CAS_VERSION_3_0: + case CAS::CAS_VERSION_2_0: + case CAS::CAS_VERSION_3_0: // if a Proxy Ticket was given, validate it - phpCAS::trace( + CAS::trace( 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' is present' ); $this->validateCAS20( - $validate_url, $text_response, $tree_response, $renew + $validate_url, + $text_response, + $tree_response, + $renew ); // note: if it fails, it halts - phpCAS::trace( + CAS::trace( 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' was validated' ); - if ( $this->isProxy() ) { + if ($this->isProxy()) { $this->_validatePGT( $validate_url, $text_response, $tree_response ); // idem - phpCAS::trace('PGT `'.$this->_getPGT().'\' was validated'); + CAS::trace('PGT `'.$this->_getPGT().'\' was validated'); $_SESSION['phpCAS']['pgt'] = $this->_getPGT(); } $_SESSION['phpCAS']['user'] = $this->_getUser(); - if (!empty($this->_attributes)) { + if (! empty($this->_attributes)) { $_SESSION['phpCAS']['attributes'] = $this->_attributes; } $proxies = $this->getProxies(); - if (!empty($proxies)) { + if (! empty($proxies)) { $_SESSION['phpCAS']['proxies'] = $this->getProxies(); } $res = true; $logoutTicket = $this->getTicket(); break; - case SAML_VERSION_1_1: + case CAS::SAML_VERSION_1_1: // if we have a SAML ticket, validate it. - phpCAS::trace( + CAS::trace( 'SAML 1.1 ticket `'.$this->getTicket().'\' is present' ); $this->validateSA( $validate_url, $text_response, $tree_response, $renew ); // if it fails, it halts - phpCAS::trace( + CAS::trace( 'SAML 1.1 ticket `'.$this->getTicket().'\' was validated' ); $_SESSION['phpCAS']['user'] = $this->_getUser(); @@ -1460,16 +1514,16 @@ public function isAuthenticated($renew=false) $logoutTicket = $this->getTicket(); break; default: - phpCAS::trace('Protocoll error'); + CAS::trace('Protocol error'); break; } } else { // no ticket given, not authenticated - phpCAS::trace('no ticket found'); + CAS::trace('no ticket found'); } // Mark the auth-check as complete to allow post-authentication - // callbacks to make use of phpCAS::getUser() and similar methods + // callbacks to make use of CAS::getUser() and similar methods $this->markAuthenticationCall($res); if ($res) { @@ -1489,16 +1543,17 @@ public function isAuthenticated($renew=false) // without masking error messages. remove the ticket as a // security precaution to prevent a ticket in the HTTP_REFERRER if ($this->_clearTicketsFromUrl) { - phpCAS::trace("Prepare redirect to : ".$this->getURL()); + CAS::trace('Prepare redirect to : '.$this->getURL()); session_write_close(); header('Location: '.$this->getURL()); flush(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); + CAS::traceExit(); + throw new GracefulTerminationException(); } } } - phpCAS::traceEnd($res); + CAS::traceEnd($res); + return $res; } @@ -1507,9 +1562,9 @@ public function isAuthenticated($renew=false) * * @return true if authenticated based soley on $_SESSION variable */ - public function isSessionAuthenticated () + public function isSessionAuthenticated() { - return !empty($_SESSION['phpCAS']['user']); + return ! empty($_SESSION['phpCAS']['user']); } /** @@ -1522,11 +1577,11 @@ public function isSessionAuthenticated () */ private function _wasPreviouslyAuthenticated() { - phpCAS::traceBegin(); + CAS::traceBegin(); - if ( $this->_isCallbackMode() ) { + if ($this->_isCallbackMode()) { // Rebroadcast the pgtIou and pgtId to all nodes - if ($this->_rebroadcast&&!isset($_POST['rebroadcast'])) { + if ($this->_rebroadcast && ! isset($_POST['rebroadcast'])) { $this->_rebroadcast(self::PGTIOU); } $this->_callback(); @@ -1534,10 +1589,10 @@ private function _wasPreviouslyAuthenticated() $auth = false; - if ( $this->isProxy() ) { + if ($this->isProxy()) { // CAS proxy: username and PGT must be present - if ( $this->isSessionAuthenticated() - && !empty($_SESSION['phpCAS']['pgt']) + if ($this->isSessionAuthenticated() + && ! empty($_SESSION['phpCAS']['pgt']) ) { // authentication already done $this->_setUser($_SESSION['phpCAS']['user']); @@ -1545,7 +1600,7 @@ private function _wasPreviouslyAuthenticated() $this->setAttributes($_SESSION['phpCAS']['attributes']); } $this->_setPGT($_SESSION['phpCAS']['pgt']); - phpCAS::trace( + CAS::trace( 'user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `' .$_SESSION['phpCAS']['pgt'].'\'' ); @@ -1553,29 +1608,29 @@ private function _wasPreviouslyAuthenticated() // Include the list of proxies if (isset($_SESSION['phpCAS']['proxies'])) { $this->_setProxies($_SESSION['phpCAS']['proxies']); - phpCAS::trace( + CAS::trace( 'proxies = "' .implode('", "', $_SESSION['phpCAS']['proxies']).'"' ); } $auth = true; - } elseif ( $this->isSessionAuthenticated() + } elseif ($this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) { // these two variables should be empty or not empty at the same time - phpCAS::trace( + CAS::trace( 'username found (`'.$_SESSION['phpCAS']['user'] .'\') but PGT is empty' ); // unset all tickets to enforce authentication unset($_SESSION['phpCAS']); $this->setTicket(''); - } elseif ( !$this->isSessionAuthenticated() - && !empty($_SESSION['phpCAS']['pgt']) + } elseif (! $this->isSessionAuthenticated() + && ! empty($_SESSION['phpCAS']['pgt']) ) { // these two variables should be empty or not empty at the same time - phpCAS::trace( + CAS::trace( 'PGT found (`'.$_SESSION['phpCAS']['pgt'] .'\') but username is empty' ); @@ -1583,22 +1638,22 @@ private function _wasPreviouslyAuthenticated() unset($_SESSION['phpCAS']); $this->setTicket(''); } else { - phpCAS::trace('neither user nor PGT found'); + CAS::trace('neither user nor PGT found'); } } else { // `simple' CAS client (not a proxy): username must be present - if ( $this->isSessionAuthenticated() ) { + if ($this->isSessionAuthenticated()) { // authentication already done $this->_setUser($_SESSION['phpCAS']['user']); if (isset($_SESSION['phpCAS']['attributes'])) { $this->setAttributes($_SESSION['phpCAS']['attributes']); } - phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\''); + CAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\''); // Include the list of proxies if (isset($_SESSION['phpCAS']['proxies'])) { $this->_setProxies($_SESSION['phpCAS']['proxies']); - phpCAS::trace( + CAS::trace( 'proxies = "' .implode('", "', $_SESSION['phpCAS']['proxies']).'"' ); @@ -1606,27 +1661,28 @@ private function _wasPreviouslyAuthenticated() $auth = true; } else { - phpCAS::trace('no user found'); + CAS::trace('no user found'); } } - phpCAS::traceEnd($auth); + CAS::traceEnd($auth); + return $auth; } /** * This method is used to redirect the client to the CAS server. - * It is used by CAS_Client::forceAuthentication() and - * CAS_Client::checkAuthentication(). + * It is used by Client::forceAuthentication() and + * Client::checkAuthentication(). * * @param bool $gateway true to check authentication, false to force it * @param bool $renew true to force the authentication with the CAS server * * @return void */ - public function redirectToCas($gateway=false,$renew=false) + public function redirectToCas($gateway = false, $renew = false) { - phpCAS::traceBegin(); + CAS::traceBegin(); $cas_url = $this->getServerLoginURL($gateway, $renew); session_write_close(); if (php_sapi_name() === 'cli') { @@ -1634,16 +1690,15 @@ public function redirectToCas($gateway=false,$renew=false) } else { header('Location: '.$cas_url); } - phpCAS::trace("Redirect to : ".$cas_url); + CAS::trace('Redirect to : '.$cas_url); $lang = $this->getLangObj(); $this->printHTMLHeader($lang->getAuthenticationWanted()); - printf('

      '. $lang->getShouldHaveBeenRedirected(). '

      ', $cas_url); + printf('

      '.$lang->getShouldHaveBeenRedirected().'

      ', $cas_url); $this->printHTMLFooter(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); + CAS::traceExit(); + throw new GracefulTerminationException(); } - /** * This method is used to logout from CAS. * @@ -1654,114 +1709,116 @@ public function redirectToCas($gateway=false,$renew=false) */ public function logout($params) { - phpCAS::traceBegin(); + CAS::traceBegin(); $cas_url = $this->getServerLogoutURL(); $paramSeparator = '?'; if (isset($params['url'])) { - $cas_url = $cas_url . $paramSeparator . "url=" - . urlencode($params['url']); + $cas_url = $cas_url.$paramSeparator.'url=' + .urlencode($params['url']); $paramSeparator = '&'; } if (isset($params['service'])) { - $cas_url = $cas_url . $paramSeparator . "service=" - . urlencode($params['service']); + $cas_url = $cas_url.$paramSeparator.'service=' + .urlencode($params['service']); } header('Location: '.$cas_url); - phpCAS::trace("Prepare redirect to : ".$cas_url); + CAS::trace('Prepare redirect to : '.$cas_url); - phpCAS::trace("Destroying session : ".session_id()); + CAS::trace('Destroying session : '.session_id()); session_unset(); session_destroy(); if (session_status() === PHP_SESSION_NONE) { - phpCAS::trace("Session terminated"); + CAS::trace('Session terminated'); } else { - phpCAS::error("Session was not terminated"); - phpCAS::trace("Session was not terminated"); + CAS::error('Session was not terminated'); + CAS::trace('Session was not terminated'); } $lang = $this->getLangObj(); $this->printHTMLHeader($lang->getLogout()); - printf('

      '.$lang->getShouldHaveBeenRedirected(). '

      ', $cas_url); + printf('

      '.$lang->getShouldHaveBeenRedirected().'

      ', $cas_url); $this->printHTMLFooter(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); + CAS::traceExit(); + throw new GracefulTerminationException(); } /** - * Check of the current request is a logout request + * Check of the current request is a logout request. * * @return bool is logout request. */ private function _isLogoutRequest() { - return !empty($_POST['logoutRequest']); + return ! empty($_POST['logoutRequest']); } /** * This method handles logout requests. * - * @param bool $check_client true to check the client bofore handling + * @param bool $check_client true to check the client before handling * the request, false not to perform any access control. True by default. * @param bool $allowed_clients an array of host names allowed to send * logout requests. * * @return void */ - public function handleLogoutRequests($check_client=true, $allowed_clients=false) + public function handleLogoutRequests($check_client = true, $allowed_clients = null) { - phpCAS::traceBegin(); - if (!$this->_isLogoutRequest()) { - phpCAS::trace("Not a logout request"); - phpCAS::traceEnd(); + CAS::traceBegin(); + if (! $this->_isLogoutRequest()) { + CAS::trace('Not a logout request'); + CAS::traceEnd(); + return; } - if (!$this->getChangeSessionID() + if (! $this->getChangeSessionID() && is_null($this->_signoutCallbackFunction) ) { - phpCAS::trace( - "phpCAS can't handle logout requests if it is not allowed to change session_id." + CAS::trace( + "CAS can't handle logout requests if it is not allowed to change session_id." ); } - phpCAS::trace("Logout requested"); + CAS::trace('Logout requested'); $decoded_logout_rq = urldecode($_POST['logoutRequest']); - phpCAS::trace("SAML REQUEST: ".$decoded_logout_rq); + CAS::trace('SAML REQUEST: '.$decoded_logout_rq); $allowed = false; + $client = null; if ($check_client) { - if (!$allowed_clients) { - $allowed_clients = array( $this->_getServerHostname() ); + if (! $allowed_clients) { + $allowed_clients = [$this->_getServerHostname()]; } $client_ip = $_SERVER['REMOTE_ADDR']; $client = gethostbyaddr($client_ip); - phpCAS::trace("Client: ".$client."/".$client_ip); + CAS::trace('Client: '.$client.'/'.$client_ip); foreach ($allowed_clients as $allowed_client) { if (($client == $allowed_client) || ($client_ip == $allowed_client) ) { - phpCAS::trace( + CAS::trace( "Allowed client '".$allowed_client ."' matches, logout request is allowed" ); $allowed = true; break; } else { - phpCAS::trace( + CAS::trace( "Allowed client '".$allowed_client."' does not match" ); } } } else { - phpCAS::trace("No access control set"); + CAS::trace('No access control set'); $allowed = true; } // If Logout command is permitted proceed with the logout if ($allowed) { - phpCAS::trace("Logout command allowed"); + CAS::trace('Logout command allowed'); // Rebroadcast the logout request - if ($this->_rebroadcast && !isset($_POST['rebroadcast'])) { + if ($this->_rebroadcast && ! isset($_POST['rebroadcast'])) { $this->_rebroadcast(self::LOGOUT); } // Extract the ticket from the SAML Request preg_match( - "|(.*)|", + '|(.*)|', $decoded_logout_rq, $tick, PREG_OFFSET_CAPTURE, 3 ); $wrappedSamlSessionIndex = preg_replace( @@ -1770,7 +1827,7 @@ public function handleLogoutRequests($check_client=true, $allowed_clients=false) $ticket2logout = preg_replace( '||', '', $wrappedSamlSessionIndex ); - phpCAS::trace("Ticket to logout: ".$ticket2logout); + CAS::trace('Ticket to logout: '.$ticket2logout); // call the post-authenticate callback if registered. if ($this->_signoutCallbackFunction) { @@ -1779,36 +1836,35 @@ public function handleLogoutRequests($check_client=true, $allowed_clients=false) call_user_func_array($this->_signoutCallbackFunction, $args); } - // If phpCAS is managing the session_id, destroy session thanks to + // If CAS is managing the session_id, destroy session thanks to // session_id. if ($this->getChangeSessionID()) { $session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $ticket2logout); - phpCAS::trace("Session id: ".$session_id); + CAS::trace('Session id: '.$session_id); - // destroy a possible application session created before phpcas - if (session_id() !== "") { + // destroy a possible application session created before CAS + if (session_id() !== '') { session_unset(); session_destroy(); } // fix session ID session_id($session_id); - $_COOKIE[session_name()]=$session_id; - $_GET[session_name()]=$session_id; + $_COOKIE[session_name()] = $session_id; + $_GET[session_name()] = $session_id; // Overwrite session session_start(); session_unset(); session_destroy(); - phpCAS::trace("Session ". $session_id . " destroyed"); + CAS::trace('Session '.$session_id.' destroyed'); } } else { - phpCAS::error("Unauthorized logout request from client '".$client."'"); - phpCAS::trace("Unauthorized logout request from client '".$client."'"); + CAS::error("Unauthorized logout request from client '".$client."'"); + CAS::trace("Unauthorized logout request from client '".$client."'"); } flush(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); - + CAS::traceExit(); + throw new GracefulTerminationException(); } /** @} */ @@ -1822,15 +1878,16 @@ public function handleLogoutRequests($check_client=true, $allowed_clients=false) // ######################################################################## // ST // ######################################################################## + /** - * @addtogroup internalBasic - * @{ - */ + * @addtogroup internalBasic + * @{ + */ /** * The Ticket provided in the URL of the request if present - * (empty otherwise). Written by CAS_Client::CAS_Client(), read by - * CAS_Client::getTicket() and CAS_Client::_hasPGT(). + * (empty otherwise). Written by Client::Client(), read by + * Client::getTicket() and Client::_hasPGT(). * * @hideinitializer */ @@ -1841,7 +1898,7 @@ public function handleLogoutRequests($check_client=true, $allowed_clients=false) * * @return string service ticket. */ - public function getTicket() + public function getTicket() { return $this->_ticket; } @@ -1865,7 +1922,7 @@ public function setTicket($st) */ public function hasTicket() { - return !empty($this->_ticket); + return ! empty($this->_ticket); } /** @} */ @@ -1873,10 +1930,11 @@ public function hasTicket() // ######################################################################## // ST VALIDATION // ######################################################################## + /** - * @addtogroup internalBasic - * @{ - */ + * @addtogroup internalBasic + * @{ + */ /** * the certificate of the CAS server CA. @@ -1885,47 +1943,40 @@ public function hasTicket() */ private $_cas_server_ca_cert = null; - /** - - * validate CN of the CAS server certificate - + * validate CN of the CAS server certificate. * - * @hideinitializer - */ - private $_cas_server_cn_validate = true; /** * Set to true not to validate the CAS server. - * + * * @hideinitializer */ private $_no_cas_server_validation = false; - /** * Set the CA certificate of the CAS server. * - * @param string $cert the PEM certificate file name of the CA that emited + * @param string $cert the PEM certificate file name of the CA that emitted * the cert of the server - * @param bool $validate_cn valiate CN of the CAS server certificate + * @param bool $validate_cn validate CN of the CAS server certificate * * @return void */ public function setCasServerCACert($cert, $validate_cn) { - // Argument validation + // Argument validation if (gettype($cert) != 'string') { - throw new CAS_TypeMismatchException($cert, '$cert', 'string'); + throw new TypeMismatchException($cert, '$cert', 'string'); } if (gettype($validate_cn) != 'boolean') { - throw new CAS_TypeMismatchException($validate_cn, '$validate_cn', 'boolean'); + throw new TypeMismatchException($validate_cn, '$validate_cn', 'boolean'); } - if ( !file_exists($cert) && $this->_requestImplementation !== 'CAS_TestHarness_DummyRequest'){ - throw new CAS_InvalidArgumentException("Certificate file does not exist " . $this->_requestImplementation); + if (! file_exists($cert) && $this->_requestImplementation !== '\phpCAS\CAS\TestHarness\DummyRequest') { + throw new InvalidArgumentException('Certificate file does not exist '.$this->_requestImplementation); } $this->_cas_server_ca_cert = $cert; $this->_cas_server_cn_validate = $validate_cn; @@ -1942,8 +1993,8 @@ public function setNoCasServerValidation() } /** - * This method is used to validate a CAS 1,0 ticket; halt on failure, and - * sets $validate_url, $text_reponse and $tree_response on success. + * This method is used to validate a CAS 1.0 ticket; halt on failure, and + * sets $validate_url, $text_response and $tree_response on success. * * @param string &$validate_url reference to the the URL of the request to * the CAS server. @@ -1953,48 +2004,52 @@ public function setNoCasServerValidation() * server, as a DOM XML tree. * @param bool $renew true to force the authentication with the CAS server * - * @return bool true when successfull and issue a CAS_AuthenticationException + * @return bool true when successful and issue a AuthenticationException * and false on an error */ - public function validateCAS10(&$validate_url,&$text_response,&$tree_response,$renew=false) + public function validateCAS10(&$validate_url, &$text_response, &$tree_response, $renew = false) { - phpCAS::traceBegin(); - $result = false; + CAS::traceBegin(); // build the URL to validate the ticket $validate_url = $this->getServerServiceValidateURL() .'&ticket='.urlencode($this->getTicket()); - if ( $renew ) { - // pass the renew - $validate_url .= '&renew=true'; + if ($renew) { + // pass the renew + $validate_url .= '&renew=true'; } // open and read the URL - if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) { - phpCAS::trace( + if (! $this->_readURL($validate_url, $headers, $text_response, $err_msg)) { + CAS::trace( 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')' ); - throw new CAS_AuthenticationException( + throw new AuthenticationException( $this, 'CAS 1.0 ticket not validated', $validate_url, true/*$no_response*/ ); - $result = false; } if (preg_match('/^no\n/', $text_response)) { - phpCAS::trace('Ticket has not been validated'); - throw new CAS_AuthenticationException( - $this, 'ST not validated', $validate_url, false/*$no_response*/, - false/*$bad_response*/, $text_response + CAS::trace('Ticket has not been validated'); + throw new AuthenticationException( + $this, + 'ST not validated', + $validate_url, + false/*$no_response*/, + false/*$bad_response*/, + $text_response ); - $result = false; - } else if (!preg_match('/^yes\n/', $text_response)) { - phpCAS::trace('ill-formed response'); - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, $text_response + } elseif (! preg_match('/^yes\n/', $text_response)) { + CAS::trace('ill-formed response'); + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, + $text_response ); - $result = false; } // ticket has been validated, extract the user name $arr = preg_split('/\n/', $text_response); @@ -2005,25 +2060,26 @@ public function validateCAS10(&$validate_url,&$text_response,&$tree_response,$re $this->_renameSession($this->getTicket()); } // at this step, ticket has been validated and $this->_user has been set, - phpCAS::traceEnd(true); + CAS::traceEnd(true); + return true; } /** @} */ - // ######################################################################## // SAML VALIDATION // ######################################################################## + /** - * @addtogroup internalSAML - * @{ - */ + * @addtogroup internalSAML + * @{ + */ /** * This method is used to validate a SAML TICKET; halt on failure, and sets - * $validate_url, $text_reponse and $tree_response on success. These - * parameters are used later by CAS_Client::_validatePGT() for CAS proxies. + * $validate_url, $text_response and $tree_response on success. These + * parameters are used later by Client::_validatePGT() for CAS proxies. * * @param string &$validate_url reference to the the URL of the request to * the CAS server. @@ -2033,95 +2089,104 @@ public function validateCAS10(&$validate_url,&$text_response,&$tree_response,$re * server, as a DOM XML tree. * @param bool $renew true to force the authentication with the CAS server * - * @return bool true when successfull and issue a CAS_AuthenticationException + * @return bool true when successful and issue a AuthenticationException * and false on an error */ - public function validateSA(&$validate_url,&$text_response,&$tree_response,$renew=false) + public function validateSA(&$validate_url, &$text_response, &$tree_response, $renew = false) { - phpCAS::traceBegin(); + CAS::traceBegin(); $result = false; // build the URL to validate the ticket $validate_url = $this->getServerSamlValidateURL(); - if ( $renew ) { - // pass the renew - $validate_url .= '&renew=true'; + if ($renew) { + // pass the renew + $validate_url .= '&renew=true'; } // open and read the URL - if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) { - phpCAS::trace( + if (! $this->_readURL($validate_url, $headers, $text_response, $err_msg)) { + CAS::trace( 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')' ); - throw new CAS_AuthenticationException( + throw new AuthenticationException( $this, 'SA not validated', $validate_url, true/*$no_response*/ ); } - phpCAS::trace('server version: '.$this->getServerVersion()); + CAS::trace('server version: '.$this->getServerVersion()); // analyze the result depending on the version switch ($this->getServerVersion()) { - case SAML_VERSION_1_1: + case CAS::SAML_VERSION_1_1: // create new DOMDocument Object $dom = new DOMDocument(); - // Fix possible whitspace problems + // Fix possible whitespace problems $dom->preserveWhiteSpace = false; // read the response of the CAS server into a DOM object - if (!($dom->loadXML($text_response))) { - phpCAS::trace('dom->loadXML() failed'); - throw new CAS_AuthenticationException( - $this, 'SA not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + if (! ($dom->loadXML($text_response))) { + CAS::trace('dom->loadXML() failed'); + throw new AuthenticationException( + $this, + 'SA not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; } // read the root node of the XML tree - if (!($tree_response = $dom->documentElement)) { - phpCAS::trace('documentElement() failed'); - throw new CAS_AuthenticationException( - $this, 'SA not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + if (! ($tree_response = $dom->documentElement)) { + CAS::trace('documentElement() failed'); + throw new AuthenticationException( + $this, + 'SA not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; - } else if ( $tree_response->localName != 'Envelope' ) { + } elseif ($tree_response->localName != 'Envelope') { // insure that tag name is 'Envelope' - phpCAS::trace( + CAS::trace( 'bad XML root node (should be `Envelope\' instead of `' .$tree_response->localName.'\'' ); - throw new CAS_AuthenticationException( - $this, 'SA not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + throw new AuthenticationException( + $this, + 'SA not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; - } else if ($tree_response->getElementsByTagName("NameIdentifier")->length != 0) { + } elseif ($tree_response->getElementsByTagName('NameIdentifier')->length != 0) { // check for the NameIdentifier tag in the SAML response - $success_elements = $tree_response->getElementsByTagName("NameIdentifier"); - phpCAS::trace('NameIdentifier found'); + $success_elements = $tree_response->getElementsByTagName('NameIdentifier'); + CAS::trace('NameIdentifier found'); $user = trim($success_elements->item(0)->nodeValue); - phpCAS::trace('user = `'.$user.'`'); + CAS::trace('user = `'.$user.'`'); $this->_setUser($user); $this->_setSessionAttributes($text_response); $result = true; } else { - phpCAS::trace('no tag found in SAML payload'); - throw new CAS_AuthenticationException( - $this, 'SA not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + CAS::trace('no tag found in SAML payload'); + throw new AuthenticationException( + $this, + 'SA not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; } } if ($result) { $this->_renameSession($this->getTicket()); } // at this step, ST has been validated and $this->_user has been set, - phpCAS::traceEnd($result); + CAS::traceEnd($result); + return $result; } @@ -2131,31 +2196,31 @@ public function validateSA(&$validate_url,&$text_response,&$tree_response,$renew * * @param string $text_response the SAML payload. * - * @return bool true when successfull and false if no attributes a found + * @return bool true when successful and false if no attributes a found */ private function _setSessionAttributes($text_response) { - phpCAS::traceBegin(); + CAS::traceBegin(); $result = false; - $attr_array = array(); + $attr_array = []; // create new DOMDocument Object $dom = new DOMDocument(); - // Fix possible whitspace problems + // Fix possible whitespace problems $dom->preserveWhiteSpace = false; if (($dom->loadXML($text_response))) { $xPath = new DOMXpath($dom); $xPath->registerNamespace('samlp', 'urn:oasis:names:tc:SAML:1.0:protocol'); $xPath->registerNamespace('saml', 'urn:oasis:names:tc:SAML:1.0:assertion'); - $nodelist = $xPath->query("//saml:Attribute"); + $nodelist = $xPath->query('//saml:Attribute'); if ($nodelist) { foreach ($nodelist as $node) { - $xres = $xPath->query("saml:AttributeValue", $node); - $name = $node->getAttribute("AttributeName"); - $value_array = array(); + $xres = $xPath->query('saml:AttributeValue', $node); + $name = $node->getAttribute('AttributeName'); + $value_array = []; foreach ($xres as $node2) { $value_array[] = $node2->nodeValue; } @@ -2165,19 +2230,20 @@ private function _setSessionAttributes($text_response) foreach ($attr_array as $attr_key => $attr_value) { if (count($attr_value) > 1) { $this->_attributes[$attr_key] = $attr_value; - phpCAS::trace("* " . $attr_key . "=" . print_r($attr_value, true)); + CAS::trace('* '.$attr_key.'='.print_r($attr_value, true)); } else { $this->_attributes[$attr_key] = $attr_value[0]; - phpCAS::trace("* " . $attr_key . "=" . $attr_value[0]); + CAS::trace('* '.$attr_key.'='.$attr_value[0]); } } $result = true; } else { - phpCAS::trace("SAML Attributes are empty"); + CAS::trace('SAML Attributes are empty'); $result = false; } } - phpCAS::traceEnd($result); + CAS::traceEnd($result); + return $result; } @@ -2192,14 +2258,15 @@ private function _setSessionAttributes($text_response) // ######################################################################## // PROXYING // ######################################################################## + /** - * @addtogroup internalProxy - * @{ - */ + * @addtogroup internalProxy + * @{ + */ /** * A boolean telling if the client is a CAS proxy or not. Written by - * CAS_Client::CAS_Client(), read by CAS_Client::isProxy(). + * Client::Client(), read by Client::isProxy(). */ private $_proxy; @@ -2209,29 +2276,30 @@ private function _setSessionAttributes($text_response) private $_serviceCookieJar; /** - * Tells if a CAS client is a CAS proxy or not + * Tells if a CAS client is a CAS proxy or not. * - * @return true when the CAS client is a CAs proxy, false otherwise + * @return true when the CAS client is a CAS proxy, false otherwise */ public function isProxy() { return $this->_proxy; } - /** @} */ + // ######################################################################## // PGT // ######################################################################## + /** - * @addtogroup internalProxy - * @{ - */ + * @addtogroup internalProxy + * @{ + */ /** - * the Proxy Grnting Ticket given by the CAS server (empty otherwise). - * Written by CAS_Client::_setPGT(), read by CAS_Client::_getPGT() and - * CAS_Client::_hasPGT(). + * the Proxy Granting Ticket given by the CAS server (empty otherwise). + * Written by Client::_setPGT(), read by Client::_getPGT() and + * Client::_hasPGT(). * * @hideinitializer */ @@ -2266,7 +2334,7 @@ private function _setPGT($pgt) */ private function _hasPGT() { - return !empty($this->_pgt); + return ! empty($this->_pgt); } /** @} */ @@ -2274,10 +2342,12 @@ private function _hasPGT() // ######################################################################## // CALLBACK MODE // ######################################################################## + /** - * @addtogroup internalCallback - * @{ - */ + * @addtogroup internalCallback + * @{ + */ + /** * each PHP script using phpCAS in proxy mode is its own callback to get the * PGT back from the CAS server. callback_mode is detected by the constructor @@ -2286,8 +2356,8 @@ private function _hasPGT() /** * a boolean to know if the CAS client is running in callback mode. Written by - * CAS_Client::setCallBackMode(), read by CAS_Client::_isCallbackMode(). - * + * Client::setCallBackMode(), read by Client::_isCallbackMode(). + * * @hideinitializer */ private $_callback_mode = false; @@ -2305,10 +2375,10 @@ private function _setCallbackMode($callback_mode) } /** - * This method returns true when the CAs client is running i callback mode, + * This method returns true when the CAS client is running in callback mode, * false otherwise. * - * @return A boolean. + * @return bool */ private function _isCallbackMode() { @@ -2318,7 +2388,7 @@ private function _isCallbackMode() /** * the URL that should be used for the PGT callback (in fact the URL of the * current request without any CGI parameter). Written and read by - * CAS_Client::_getCallbackURL(). + * Client::_getCallbackURL(). * * @hideinitializer */ @@ -2327,26 +2397,44 @@ private function _isCallbackMode() /** * This method returns the URL that should be used for the PGT callback (in * fact the URL of the current request without any CGI parameter, except if - * phpCAS::setFixedCallbackURL() was used). + * CAS::setFixedCallbackURL() was used). * - * @return The callback URL + * @return string The callback URL */ private function _getCallbackURL() { // the URL is built when needed only - if ( empty($this->_callback_url) ) { - $final_uri = ''; + if (empty($this->_callback_url)) { // remove the ticket if present in the URL $final_uri = 'https://'; $final_uri .= $this->_getClientUrl(); - $request_uri = $_SERVER['REQUEST_URI']; + $request_uri = $this->_getRequestUri(); $request_uri = preg_replace('/\?.*$/', '', $request_uri); $final_uri .= $request_uri; $this->_callback_url = $final_uri; } + return $this->_callback_url; } + /** + * Encapsulate logic to retrieve the request URI. + * + * @return string + */ + private function _getRequestUri() + { + // + // hack by Vangelis Haniotakis to handle the absence of $_SERVER['REQUEST_URI'] + // in IIS + // + if (php_sapi_name() != 'cli' && ! isset($_SERVER['REQUEST_URI'])) { + $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']; + } + + return $_SERVER['REQUEST_URI']; + } + /** * This method sets the callback url. * @@ -2356,65 +2444,69 @@ private function _getCallbackURL() */ public function setCallbackURL($url) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } - return $this->_callback_url = $url; + $this->_callback_url = $url; } /** - * This method is called by CAS_Client::CAS_Client() when running in callback + * This method is called by Client::Client() when running in callback * mode. It stores the PGT and its PGT Iou, prints its output and halts. * * @return void */ private function _callback() { - phpCAS::traceBegin(); + CAS::traceBegin(); if (preg_match('/PGTIOU-[\.\-\w]/', $_GET['pgtIou'])) { if (preg_match('/[PT]GT-[\.\-\w]/', $_GET['pgtId'])) { $this->printHTMLHeader('phpCAS callback'); $pgt_iou = $_GET['pgtIou']; $pgt = $_GET['pgtId']; - phpCAS::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')'); + CAS::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')'); echo '

      Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\').

      '; $this->_storePGT($pgt, $pgt_iou); $this->printHTMLFooter(); - phpCAS::traceExit("Successfull Callback"); + CAS::trace('Successful Callback'); + CAS::traceExit(); } else { - phpCAS::error('PGT format invalid' . $_GET['pgtId']); - phpCAS::traceExit('PGT format invalid' . $_GET['pgtId']); + CAS::error('PGT format invalid'.$_GET['pgtId']); + CAS::traceExit(); } } else { - phpCAS::error('PGTiou format invalid' . $_GET['pgtIou']); - phpCAS::traceExit('PGTiou format invalid' . $_GET['pgtIou']); + CAS::error('PGTiou format invalid'.$_GET['pgtIou']); + CAS::traceExit(); } // Flush the buffer to prevent from sending anything other then a 200 // Success Status back to the CAS Server. The Exception would normally // report as a 500 error. flush(); - throw new CAS_GracefullTerminationException(); + throw new GracefulTerminationException(); } - /** @} */ // ######################################################################## // PGT STORAGE // ######################################################################## + /** - * @addtogroup internalPGTStorage - * @{ - */ + * @addtogroup internalPGTStorage + * @{ + */ /** + * @var AbstractStorage + * * an instance of a class inheriting of PGTStorage, used to deal with PGT - * storage. Created by CAS_Client::setPGTStorageFile(), used - * by CAS_Client::setPGTStorageFile() and CAS_Client::_initPGTStorage(). + * storage. Created by Client::setPGTStorageFile(), used + * by Client::setPGTStorageFile() and Client::_initPGTStorage(). * * @hideinitializer */ @@ -2429,7 +2521,7 @@ private function _callback() private function _initPGTStorage() { // if no SetPGTStorageXxx() has been used, default to file - if ( !is_object($this->_pgt_storage) ) { + if (! is_object($this->_pgt_storage)) { $this->setPGTStorageFile(); } @@ -2445,7 +2537,7 @@ private function _initPGTStorage() * * @return void */ - private function _storePGT($pgt,$pgt_iou) + private function _storePGT($pgt, $pgt_iou) { // ensure that storage is initialized $this->_initPGTStorage(); @@ -2459,7 +2551,7 @@ private function _storePGT($pgt,$pgt_iou) * * @param string $pgt_iou the PGT Iou * - * @return mul The PGT corresponding to the Iou, false when not found. + * @return mixed The PGT corresponding to the Iou, false when not found. */ private function _loadPGT($pgt_iou) { @@ -2472,24 +2564,25 @@ private function _loadPGT($pgt_iou) /** * This method can be used to set a custom PGT storage object. * - * @param CAS_PGTStorage_AbstractStorage $storage a PGT storage object that - * inherits from the CAS_PGTStorage_AbstractStorage class + * @param AbstractStorage $storage a PGT storage object that + * inherits from the AbstractStorage class * - * @return void + * @throws TypeMismatchException */ - public function setPGTStorage($storage) + public function setPGTStorage(AbstractStorage $storage) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); // check that the storage has not already been set - if ( is_object($this->_pgt_storage) ) { - phpCAS::error('PGT storage already defined'); + if (is_object($this->_pgt_storage)) { + CAS::error('PGT storage already defined'); } // check to make sure a valid storage object was specified - if ( !($storage instanceof CAS_PGTStorage_AbstractStorage) ) - throw new CAS_TypeMismatchException($storage, '$storage', 'CAS_PGTStorage_AbstractStorage object'); + if (! ($storage instanceof AbstractStorage)) { + throw new TypeMismatchException($storage, '$storage', '\phpCAS\CAS\PGTStorage\AbstractStorage object'); + } // store the PGTStorage object $this->_pgt_storage = $storage; @@ -2513,25 +2606,34 @@ public function setPGTStorage($storage) * @return void */ public function setPGTStorageDb( - $dsn_or_pdo, $username='', $password='', $table='', $driver_options=null + $dsn_or_pdo, $username = '', $password = '', $table = '', $driver_options = null ) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - // Argument validation - if ((is_object($dsn_or_pdo) && !($dsn_or_pdo instanceof PDO)) || gettype($dsn_or_pdo) != 'string') - throw new CAS_TypeMismatchException($dsn_or_pdo, '$dsn_or_pdo', 'string or PDO object'); - if (gettype($username) != 'string') - throw new CAS_TypeMismatchException($username, '$username', 'string'); - if (gettype($password) != 'string') - throw new CAS_TypeMismatchException($password, '$password', 'string'); - if (gettype($table) != 'string') - throw new CAS_TypeMismatchException($table, '$password', 'string'); + // Argument validation + if ((is_object($dsn_or_pdo) && ! ($dsn_or_pdo instanceof PDO)) || gettype($dsn_or_pdo) != 'string') { + throw new TypeMismatchException($dsn_or_pdo, '$dsn_or_pdo', 'string or PDO object'); + } + if (gettype($username) != 'string') { + throw new TypeMismatchException($username, '$username', 'string'); + } + if (gettype($password) != 'string') { + throw new TypeMismatchException($password, '$password', 'string'); + } + if (gettype($table) != 'string') { + throw new TypeMismatchException($table, '$password', 'string'); + } // create the storage object $this->setPGTStorage( - new CAS_PGTStorage_Db( - $this, $dsn_or_pdo, $username, $password, $table, $driver_options + new Db( + $this, + $dsn_or_pdo, + $username, + $password, + $table, + $driver_options ) ); } @@ -2544,75 +2646,85 @@ public function setPGTStorageDb( * * @return void */ - public function setPGTStorageFile($path='') + public function setPGTStorageFile($path = '') { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - // Argument validation - if (gettype($path) != 'string') - throw new CAS_TypeMismatchException($path, '$path', 'string'); + // Argument validation + if (gettype($path) != 'string') { + throw new TypeMismatchException($path, '$path', 'string'); + } // create the storage object - $this->setPGTStorage(new CAS_PGTStorage_File($this, $path)); + $this->setPGTStorage(new File($this, $path)); } - // ######################################################################## // PGT VALIDATION // ######################################################################## + /** - * This method is used to validate a PGT; halt on failure. - * - * @param string &$validate_url the URL of the request to the CAS server. - * @param string $text_response the response of the CAS server, as is - * (XML text); result of - * CAS_Client::validateCAS10() or - * CAS_Client::validateCAS20(). - * @param string $tree_response the response of the CAS server, as a DOM XML - * tree; result of CAS_Client::validateCAS10() or CAS_Client::validateCAS20(). - * - * @return bool true when successfull and issue a CAS_AuthenticationException - * and false on an error - */ - private function _validatePGT(&$validate_url,$text_response,$tree_response) - { - phpCAS::traceBegin(); - if ( $tree_response->getElementsByTagName("proxyGrantingTicket")->length == 0) { - phpCAS::trace(' not found'); - // authentication succeded, but no PGT Iou was transmitted - throw new CAS_AuthenticationException( - $this, 'Ticket validated but no PGT Iou transmitted', - $validate_url, false/*$no_response*/, false/*$bad_response*/, + * This method is used to validate a PGT; halt on failure. + * + * @param string &$validate_url the URL of the request to the CAS server. + * @param string $text_response the response of the CAS server, as is + * (XML text); result of + * Client::validateCAS10() or + * Client::validateCAS20(). + * @param DOMDocument $tree_response the response of the CAS server, as a DOM XML + * tree; result of Client::validateCAS10() or Client::validateCAS20(). + * + * @return bool true when successful and issue a AuthenticationException + * and false on an error + */ + private function _validatePGT(&$validate_url, $text_response, $tree_response) + { + CAS::traceBegin(); + if ($tree_response->getElementsByTagName('proxyGrantingTicket')->length == 0) { + CAS::trace(' not found'); + // authentication succeeded, but no PGT Iou was transmitted + throw new AuthenticationException( + $this, + 'Ticket validated but no PGT Iou transmitted', + $validate_url, + false/*$no_response*/, + false/*$bad_response*/, $text_response ); } else { // PGT Iou transmitted, extract it $pgt_iou = trim( - $tree_response->getElementsByTagName("proxyGrantingTicket")->item(0)->nodeValue + $tree_response->getElementsByTagName('proxyGrantingTicket')->item(0)->nodeValue ); if (preg_match('/PGTIOU-[\.\-\w]/', $pgt_iou)) { $pgt = $this->_loadPGT($pgt_iou); - if ( $pgt == false ) { - phpCAS::trace('could not load PGT'); - throw new CAS_AuthenticationException( + if ($pgt == false) { + CAS::trace('could not load PGT'); + throw new AuthenticationException( $this, 'PGT Iou was transmitted but PGT could not be retrieved', - $validate_url, false/*$no_response*/, - false/*$bad_response*/, $text_response + $validate_url, + false/*$no_response*/, + false/*$bad_response*/, + $text_response ); } $this->_setPGT($pgt); } else { - phpCAS::trace('PGTiou format error'); - throw new CAS_AuthenticationException( - $this, 'PGT Iou was transmitted but has wrong format', - $validate_url, false/*$no_response*/, false/*$bad_response*/, + CAS::trace('PGTiou format error'); + throw new AuthenticationException( + $this, + 'PGT Iou was transmitted but has wrong format', + $validate_url, + false/*$no_response*/, + false/*$bad_response*/, $text_response ); } } - phpCAS::traceEnd(true); + CAS::traceEnd(true); + return true; } @@ -2624,18 +2736,19 @@ private function _validatePGT(&$validate_url,$text_response,$tree_response) * This method is used to retrieve PT's from the CAS server thanks to a PGT. * * @param string $target_service the service to ask for with the PT. - * @param string &$err_code an error code (PHPCAS_SERVICE_OK on success). + * @param string &$err_code an error code (CAS::PHPCAS_SERVICE_OK on success). * @param string &$err_msg an error message (empty on success). * - * @return a Proxy Ticket, or false on error. + * @return mixed a Proxy Ticket, or false on error. */ - public function retrievePT($target_service,&$err_code,&$err_msg) + public function retrievePT($target_service, &$err_code, &$err_msg) { - // Argument validation - if (gettype($target_service) != 'string') - throw new CAS_TypeMismatchException($target_service, '$target_service', 'string'); + // Argument validation + if (gettype($target_service) != 'string') { + throw new TypeMismatchException($target_service, '$target_service', 'string'); + } - phpCAS::traceBegin(); + CAS::traceBegin(); // by default, $err_msg is set empty and $pt to true. On error, $pt is // set to false and $err_msg to an error message. At the end, if $pt is false @@ -2648,92 +2761,97 @@ public function retrievePT($target_service,&$err_code,&$err_msg) .urlencode($target_service).'&pgt='.$this->_getPGT(); // open and read the URL - if ( !$this->_readURL($cas_url, $headers, $cas_response, $err_msg) ) { - phpCAS::trace( + if (! $this->_readURL($cas_url, $headers, $cas_response, $err_msg)) { + CAS::trace( 'could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')' ); - $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE; + $err_code = CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE; $err_msg = 'could not retrieve PT (no response from the CAS server)'; - phpCAS::traceEnd(false); + CAS::traceEnd(false); + return false; } + $dom = null; $bad_response = false; - if ( !$bad_response ) { + if (! $bad_response) { // create new DOMDocument object $dom = new DOMDocument(); - // Fix possible whitspace problems + // Fix possible whitespace problems $dom->preserveWhiteSpace = false; // read the response of the CAS server into a DOM object - if ( !($dom->loadXML($cas_response))) { - phpCAS::trace('dom->loadXML() failed'); + if (! ($dom->loadXML($cas_response))) { + CAS::trace('dom->loadXML() failed'); // read failed $bad_response = true; } } - if ( !$bad_response ) { + if (! $bad_response && isset($dom)) { // read the root node of the XML tree - if ( !($root = $dom->documentElement) ) { - phpCAS::trace('documentElement failed'); + if (! ($root = $dom->documentElement)) { + CAS::trace('documentElement failed'); // read failed $bad_response = true; } } - if ( !$bad_response ) { + if (! $bad_response && isset($root)) { // insure that tag name is 'serviceResponse' - if ( $root->localName != 'serviceResponse' ) { - phpCAS::trace('localName failed'); + if ($root->localName != 'serviceResponse') { + CAS::trace('localName failed'); // bad root node $bad_response = true; } } - if ( !$bad_response ) { + if (! $bad_response && isset($root)) { // look for a proxySuccess tag - if ( $root->getElementsByTagName("proxySuccess")->length != 0) { - $proxy_success_list = $root->getElementsByTagName("proxySuccess"); + if ($root->getElementsByTagName('proxySuccess')->length != 0) { + $proxy_success_list = $root->getElementsByTagName('proxySuccess'); - // authentication succeded, look for a proxyTicket tag - if ( $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->length != 0) { - $err_code = PHPCAS_SERVICE_OK; + // authentication succeeded, look for a proxyTicket tag + if ($proxy_success_list->item(0)->getElementsByTagName('proxyTicket')->length != 0) { + $err_code = CAS::PHPCAS_SERVICE_OK; $err_msg = ''; $pt = trim( - $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->item(0)->nodeValue + $proxy_success_list->item(0)->getElementsByTagName('proxyTicket')->item(0)->nodeValue ); - phpCAS::trace('original PT: '.trim($pt)); - phpCAS::traceEnd($pt); + CAS::trace('original PT: '.trim($pt)); + CAS::traceEnd($pt); + return $pt; } else { - phpCAS::trace(' was found, but not '); + CAS::trace(' was found, but not '); } - } else if ($root->getElementsByTagName("proxyFailure")->length != 0) { + } elseif ($root->getElementsByTagName('proxyFailure')->length != 0) { // look for a proxyFailure tag - $proxy_failure_list = $root->getElementsByTagName("proxyFailure"); + $proxy_failure_list = $root->getElementsByTagName('proxyFailure'); // authentication failed, extract the error - $err_code = PHPCAS_SERVICE_PT_FAILURE; + $err_code = CAS::PHPCAS_SERVICE_PT_FAILURE; $err_msg = 'PT retrieving failed (code=`' .$proxy_failure_list->item(0)->getAttribute('code') .'\', message=`' .trim($proxy_failure_list->item(0)->nodeValue) .'\')'; - phpCAS::traceEnd(false); + CAS::traceEnd(false); + return false; } else { - phpCAS::trace('neither nor found'); + CAS::trace('neither nor found'); } } // at this step, we are sure that the response of the CAS server was - // illformed - $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE; + // ill-formed + $err_code = CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE; $err_msg = 'Invalid response from the CAS server (response=`' .$cas_response.'\')'; - phpCAS::traceEnd(false); + CAS::traceEnd(false); + return false; } @@ -2749,7 +2867,7 @@ public function retrievePT($target_service,&$err_code,&$err_msg) */ /** - * This method is used to acces a remote URL. + * This method is used to access a remote URL. * * @param string $url the URL to access. * @param string &$headers an array containing the HTTP header lines of the @@ -2763,19 +2881,21 @@ public function retrievePT($target_service,&$err_code,&$err_msg) */ private function _readURL($url, &$headers, &$body, &$err_msg) { - phpCAS::traceBegin(); + CAS::traceBegin(); $className = $this->_requestImplementation; + /** @var AbstractRequest $request */ $request = new $className(); + // TODO: Remove this from client and move to RequestInterface if (count($this->_curl_options)) { $request->setCurlOptions($this->_curl_options); } $request->setUrl($url); - if (empty($this->_cas_server_ca_cert) && !$this->_no_cas_server_validation) { - phpCAS::error( - 'one of the methods phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.' + if (empty($this->_cas_server_ca_cert) && ! $this->_no_cas_server_validation) { + CAS::error( + 'one of the methods CAS::setCasServerCACert() or CAS::setNoCasServerValidation() must be called.' ); } if ($this->_cas_server_ca_cert != '') { @@ -2785,13 +2905,13 @@ private function _readURL($url, &$headers, &$body, &$err_msg) } // add extra stuff if SAML - if ($this->getServerVersion() == SAML_VERSION_1_1) { - $request->addHeader("soapaction: http://www.oasis-open.org/committees/security"); - $request->addHeader("cache-control: no-cache"); - $request->addHeader("pragma: no-cache"); - $request->addHeader("accept: text/xml"); - $request->addHeader("connection: keep-alive"); - $request->addHeader("content-type: text/xml"); + if ($this->getServerVersion() == CAS::SAML_VERSION_1_1) { + $request->addHeader('soapaction: http://www.oasis-open.org/committees/security'); + $request->addHeader('cache-control: no-cache'); + $request->addHeader('pragma: no-cache'); + $request->addHeader('accept: text/xml'); + $request->addHeader('connection: keep-alive'); + $request->addHeader('content-type: text/xml'); $request->makePost(); $request->setPostBody($this->_buildSAMLPayload()); } @@ -2800,13 +2920,15 @@ private function _readURL($url, &$headers, &$body, &$err_msg) $headers = $request->getResponseHeaders(); $body = $request->getResponseBody(); $err_msg = ''; - phpCAS::traceEnd(true); + CAS::traceEnd(true); + return true; } else { $headers = ''; $body = ''; $err_msg = $request->getErrorMessage(); - phpCAS::traceEnd(false); + CAS::traceEnd(false); + return false; } } @@ -2814,25 +2936,33 @@ private function _readURL($url, &$headers, &$body, &$err_msg) /** * This method is used to build the SAML POST body sent to /samlValidate URL. * - * @return the SOAP-encased SAMLP artifact (the ticket). + * @return string the SOAP-encased SAMLP artifact (the ticket). */ private function _buildSAMLPayload() { - phpCAS::traceBegin(); + CAS::traceBegin(); //get the ticket $sa = urlencode($this->getTicket()); - $body = SAML_SOAP_ENV.SAML_SOAP_BODY.SAMLP_REQUEST - .SAML_ASSERTION_ARTIFACT.$sa.SAML_ASSERTION_ARTIFACT_CLOSE - .SAMLP_REQUEST_CLOSE.SAML_SOAP_BODY_CLOSE.SAML_SOAP_ENV_CLOSE; + $body = + CAS::SAML_SOAP_ENV + .CAS::SAML_SOAP_BODY + .CAS::SAMLP_REQUEST + .CAS::SAML_ASSERTION_ARTIFACT + .$sa + .CAS::SAML_ASSERTION_ARTIFACT_CLOSE + .CAS::SAMLP_REQUEST_CLOSE + .CAS::SAML_SOAP_BODY_CLOSE + .CAS::SAML_SOAP_ENV_CLOSE; + + CAS::traceEnd($body); - phpCAS::traceEnd($body); return ($body); } - /** @} **/ - + /** @} */ + // ######################################################################## // ACCESS TO EXTERNAL SERVICES // ######################################################################## @@ -2841,49 +2971,53 @@ private function _buildSAMLPayload() * @addtogroup internalProxyServices * @{ */ - - + /** * Answer a proxy-authenticated service handler. * * @param string $type The service type. One of: - * PHPCAS_PROXIED_SERVICE_HTTP_GET, PHPCAS_PROXIED_SERVICE_HTTP_POST, - * PHPCAS_PROXIED_SERVICE_IMAP + * CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET, + * CAS::PHPCAS_PROXIED_SERVICE_HTTP_POST, + * CAS::PHPCAS_PROXIED_SERVICE_IMAP * - * @return CAS_ProxiedService + * @return ProxiedService|Imap|Http|Get|Post * @throws InvalidArgumentException If the service type is unknown. */ - public function getProxiedService ($type) + public function getProxiedService($type) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - $this->ensureAuthenticationCallSuccessful(); + $this->ensureAuthenticationCallSuccessful(); - // Argument validation - if (gettype($type) != 'string') - throw new CAS_TypeMismatchException($type, '$type', 'string'); + // Argument validation + if (gettype($type) != 'string') { + throw new TypeMismatchException($type, '$type', 'string'); + } switch ($type) { - case PHPCAS_PROXIED_SERVICE_HTTP_GET: - case PHPCAS_PROXIED_SERVICE_HTTP_POST: + case CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET: + case CAS::PHPCAS_PROXIED_SERVICE_HTTP_POST: $requestClass = $this->_requestImplementation; $request = new $requestClass(); + // TODO: Remove this from client and move to RequestInterface if (count($this->_curl_options)) { $request->setCurlOptions($this->_curl_options); } $proxiedService = new $type($request, $this->_serviceCookieJar); - if ($proxiedService instanceof CAS_ProxiedService_Testable) { + if ($proxiedService instanceof Testable) { $proxiedService->setCasClient($this); } + return $proxiedService; - case PHPCAS_PROXIED_SERVICE_IMAP; - $proxiedService = new CAS_ProxiedService_Imap($this->_getUser()); - if ($proxiedService instanceof CAS_ProxiedService_Testable) { + case CAS::PHPCAS_PROXIED_SERVICE_IMAP; + $proxiedService = new Imap($this->_getUser()); + if ($proxiedService instanceof Testable) { $proxiedService->setCasClient($this); } + return $proxiedService; default: - throw new CAS_InvalidArgumentException( + throw new InvalidArgumentException( "Unknown proxied-service type, $type." ); } @@ -2892,35 +3026,35 @@ public function getProxiedService ($type) /** * Initialize a proxied-service handler with the proxy-ticket it should use. * - * @param CAS_ProxiedService $proxiedService service handler + * @param ProxiedService $proxiedService service handler * * @return void * - * @throws CAS_ProxyTicketException If there is a proxy-ticket failure. + * @throws ProxyTicketException If there is a proxy-ticket failure. * The code of the Exception will be one of: - * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_FAILURE - * @throws CAS_ProxiedService_Exception If there is a failure getting the + * CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE + * CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE + * CAS::PHPCAS_SERVICE_PT_FAILURE + * @throws ProxiedServiceException If there is a failure getting the * url from the proxied service. */ - public function initializeProxiedService (CAS_ProxiedService $proxiedService) + public function initializeProxiedService(ProxiedService $proxiedService) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - $this->ensureAuthenticationCallSuccessful(); + $this->ensureAuthenticationCallSuccessful(); $url = $proxiedService->getServiceUrl(); - if (!is_string($url)) { - throw new CAS_ProxiedService_Exception( - "Proxied Service ".get_class($proxiedService) - ."->getServiceUrl() should have returned a string, returned a " - .gettype($url)." instead." + if (! is_string($url)) { + throw new ProxiedServiceException( + 'Proxied Service '.get_class($proxiedService) + .'->getServiceUrl() should have returned a string, returned a ' + .gettype($url).' instead.' ); } $pt = $this->retrievePT($url, $err_code, $err_msg); - if (!$pt) { - throw new CAS_ProxyTicketException($err_msg, $err_code); + if (! $pt) { + throw new ProxyTicketException($err_msg, $err_code); } $proxiedService->setProxyTicket($pt); } @@ -2930,42 +3064,48 @@ public function initializeProxiedService (CAS_ProxiedService $proxiedService) * * @param string $url the service to access. * @param int &$err_code an error code Possible values are - * PHPCAS_SERVICE_OK (on success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, PHPCAS_SERVICE_PT_FAILURE, - * PHPCAS_SERVICE_NOT_AVAILABLE. + * CAS::PHPCAS_SERVICE_OK (on success), + * CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, + * CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * CAS::PHPCAS_SERVICE_PT_FAILURE, + * CAS::PHPCAS_SERVICE_NOT_AVAILABLE. * @param string &$output the output of the service (also used to give an error * message on failure). * * @return true on success, false otherwise (in this later case, $err_code * gives the reason why it failed and $output contains an error message). */ - public function serviceWeb($url,&$err_code,&$output) + public function serviceWeb($url, &$err_code, &$output) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - $this->ensureAuthenticationCallSuccessful(); + $this->ensureAuthenticationCallSuccessful(); - // Argument validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } try { - $service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + $service = $this->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); $service->setUrl($url); $service->send(); $output = $service->getResponseBody(); - $err_code = PHPCAS_SERVICE_OK; + $err_code = CAS::PHPCAS_SERVICE_OK; + return true; - } catch (CAS_ProxyTicketException $e) { + } catch (ProxyTicketException $e) { $err_code = $e->getCode(); $output = $e->getMessage(); + return false; - } catch (CAS_ProxiedService_Exception $e) { + } catch (ProxiedServiceException $e) { $lang = $this->getLangObj(); $output = sprintf( $lang->getServiceUnavailable(), $url, $e->getMessage() ); - $err_code = PHPCAS_SERVICE_NOT_AVAILABLE; + $err_code = CAS::PHPCAS_SERVICE_NOT_AVAILABLE; + return false; } } @@ -2978,60 +3118,68 @@ public function serviceWeb($url,&$err_code,&$output) * @param string $serviceUrl a string giving for CAS retrieve Proxy ticket * @param string $flags options given to imap_open(). * @param int &$err_code an error code Possible values are - * PHPCAS_SERVICE_OK (on success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, PHPCAS_SERVICE_PT_FAILURE, - * PHPCAS_SERVICE_NOT_AVAILABLE. + * CAS::PHPCAS_SERVICE_OK (on success), + * CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, + * CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * CAS::PHPCAS_SERVICE_PT_FAILURE, + * CAS::PHPCAS_SERVICE_NOT_AVAILABLE. * @param string &$err_msg an error message on failure * @param string &$pt the Proxy Ticket (PT) retrieved from the CAS * server to access the URL on success, false on error). * - * @return object an IMAP stream on success, false otherwise (in this later + * @return bool|object an IMAP stream on success, false otherwise (in this later * case, $err_code gives the reason why it failed and $err_msg contains an * error message). */ - public function serviceMail($url,$serviceUrl,$flags,&$err_code,&$err_msg,&$pt) + public function serviceMail($url, $serviceUrl, $flags, &$err_code, &$err_msg, &$pt) { - // Sequence validation + // Sequence validation $this->ensureIsProxy(); - $this->ensureAuthenticationCallSuccessful(); + $this->ensureAuthenticationCallSuccessful(); - // Argument validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); - if (gettype($serviceUrl) != 'string') - throw new CAS_TypeMismatchException($serviceUrl, '$serviceUrl', 'string'); - if (gettype($flags) != 'integer') - throw new CAS_TypeMismatchException($flags, '$flags', 'string'); + // Argument validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } + if (gettype($serviceUrl) != 'string') { + throw new TypeMismatchException($serviceUrl, '$serviceUrl', 'string'); + } + if (gettype($flags) != 'integer') { + throw new TypeMismatchException($flags, '$flags', 'string'); + } try { - $service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_IMAP); + $service = $this->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_IMAP); $service->setServiceUrl($serviceUrl); $service->setMailbox($url); $service->setOptions($flags); $stream = $service->open(); - $err_code = PHPCAS_SERVICE_OK; + $err_code = CAS::PHPCAS_SERVICE_OK; $pt = $service->getImapProxyTicket(); + return $stream; - } catch (CAS_ProxyTicketException $e) { + } catch (ProxyTicketException $e) { $err_msg = $e->getMessage(); $err_code = $e->getCode(); $pt = false; + return false; - } catch (CAS_ProxiedService_Exception $e) { + } catch (ProxiedServiceException $e) { $lang = $this->getLangObj(); $err_msg = sprintf( $lang->getServiceUnavailable(), $url, $e->getMessage() ); - $err_code = PHPCAS_SERVICE_NOT_AVAILABLE; + $err_code = CAS::PHPCAS_SERVICE_NOT_AVAILABLE; $pt = false; + return false; } } - /** @} **/ + /** @} */ // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // XX XX @@ -3042,22 +3190,23 @@ public function serviceMail($url,$serviceUrl,$flags,&$err_code,&$err_msg,&$pt) // ######################################################################## // PT // ######################################################################## + /** - * @addtogroup internalService - * @{ - */ + * @addtogroup internalService + * @{ + */ /** * This array will store a list of proxies in front of this application. This * property will only be populated if this script is being proxied rather than * accessed directly. * - * It is set in CAS_Client::validateCAS20() and can be read by - * CAS_Client::getProxies() + * It is set in Client::validateCAS20() and can be read by + * Client::getProxies() * * @access private */ - private $_proxies = array(); + private $_proxies = []; /** * Answer an array of proxies that are sitting in front of this application. @@ -3066,6 +3215,7 @@ public function serviceMail($url,$serviceUrl,$flags,&$err_code,&$err_msg,&$pt) * validated a Proxy Ticket. * * @return array + * * @access public */ public function getProxies() @@ -3074,17 +3224,18 @@ public function getProxies() } /** - * Set the Proxy array, probably from persistant storage. + * Set the Proxy array, probably from persistent storage. * * @param array $proxies An array of proxies * * @return void + * * @access private */ private function _setProxies($proxies) { $this->_proxies = $proxies; - if (!empty($proxies)) { + if (! empty($proxies)) { // For proxy-authenticated requests people are not viewing the URL // directly since the client is another application making a // web-service call. @@ -3099,49 +3250,51 @@ private function _setProxies($proxies) /** * A container of patterns to be allowed as proxies in front of the cas client. * - * @var CAS_ProxyChain_AllowedList + * @var AllowedList */ private $_allowed_proxy_chains; /** - * Answer the CAS_ProxyChain_AllowedList object for this client. + * Answer the AllowedList object for this client. * - * @return CAS_ProxyChain_AllowedList + * @return AllowedList */ - public function getAllowedProxyChains () + public function getAllowedProxyChains() { if (empty($this->_allowed_proxy_chains)) { - $this->_allowed_proxy_chains = new CAS_ProxyChain_AllowedList(); + $this->_allowed_proxy_chains = new AllowedList(); } + return $this->_allowed_proxy_chains; } /** @} */ + // ######################################################################## // PT VALIDATION // ######################################################################## + /** - * @addtogroup internalProxied - * @{ - */ + * @addtogroup internalProxied + * @{ + */ /** * This method is used to validate a cas 2.0 ST or PT; halt on failure - * Used for all CAS 2.0 validations + * Used for all CAS 2.0 validations. * - * @param string &$validate_url the url of the reponse - * @param string &$text_response the text of the repsones - * @param string &$tree_response the domxml tree of the respones + * @param string &$validate_url the url of the response + * @param string &$text_response the text of the responses + * @param string &$tree_response the DOM xml tree of the responses * @param bool $renew true to force the authentication with the CAS server * - * @return bool true when successfull and issue a CAS_AuthenticationException + * @return bool true when successful and issue a AuthenticationException * and false on an error */ - public function validateCAS20(&$validate_url,&$text_response,&$tree_response, $renew=false) + public function validateCAS20(&$validate_url, &$text_response, &$tree_response, $renew = false) { - phpCAS::traceBegin(); - phpCAS::trace($text_response); - $result = false; + CAS::traceBegin(); + CAS::trace($text_response); // build the URL to validate the ticket if ($this->getAllowedProxyChains()->isProxyingAllowed()) { $validate_url = $this->getServerProxyValidateURL().'&ticket=' @@ -3151,142 +3304,161 @@ public function validateCAS20(&$validate_url,&$text_response,&$tree_response, $r .urlencode($this->getTicket()); } - if ( $this->isProxy() ) { + if ($this->isProxy()) { // pass the callback url for CAS proxies $validate_url .= '&pgtUrl='.urlencode($this->_getCallbackURL()); } - if ( $renew ) { - // pass the renew - $validate_url .= '&renew=true'; + if ($renew) { + // pass the renew + $validate_url .= '&renew=true'; } // open and read the URL - if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) { - phpCAS::trace( + if (! $this->_readURL($validate_url, $headers, $text_response, $err_msg)) { + CAS::trace( 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')' ); - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, true/*$no_response*/ ); - $result = false; } // create new DOMDocument object $dom = new DOMDocument(); - // Fix possible whitspace problems + // Fix possible whitespace problems $dom->preserveWhiteSpace = false; // CAS servers should only return data in utf-8 - $dom->encoding = "utf-8"; + $dom->encoding = 'utf-8'; // read the response of the CAS server into a DOMDocument object - if ( !($dom->loadXML($text_response))) { + if (! ($dom->loadXML($text_response))) { // read failed - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, $text_response + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, + $text_response ); - $result = false; - } else if ( !($tree_response = $dom->documentElement) ) { + } elseif (! ($tree_response = $dom->documentElement)) { // read the root node of the XML tree // read failed - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, $text_response + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, + $text_response ); - $result = false; - } else if ($tree_response->localName != 'serviceResponse') { + } elseif ($tree_response->localName != 'serviceResponse') { // insure that tag name is 'serviceResponse' // bad root node - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, $text_response + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, + $text_response ); - $result = false; - } else if ($tree_response->getElementsByTagName("authenticationSuccess")->length != 0) { - // authentication succeded, extract the user name + } elseif ($tree_response->getElementsByTagName('authenticationSuccess')->length != 0) { + // authentication succeeded, extract the user name $success_elements = $tree_response - ->getElementsByTagName("authenticationSuccess"); - if ( $success_elements->item(0)->getElementsByTagName("user")->length == 0) { + ->getElementsByTagName('authenticationSuccess'); + if ($success_elements->item(0)->getElementsByTagName('user')->length == 0) { // no user specified => error - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, $text_response + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, + $text_response ); - $result = false; } else { $this->_setUser( trim( - $success_elements->item(0)->getElementsByTagName("user")->item(0)->nodeValue + $success_elements->item(0)->getElementsByTagName('user')->item(0)->nodeValue ) ); $this->_readExtraAttributesCas20($success_elements); // Store the proxies we are sitting behind for authorization checking - $proxyList = array(); - if ( sizeof($arr = $success_elements->item(0)->getElementsByTagName("proxy")) > 0) { + $proxyList = []; + if (sizeof($arr = $success_elements->item(0)->getElementsByTagName('proxy')) > 0) { foreach ($arr as $proxyElem) { - phpCAS::trace("Found Proxy: ".$proxyElem->nodeValue); + CAS::trace('Found Proxy: '.$proxyElem->nodeValue); $proxyList[] = trim($proxyElem->nodeValue); } $this->_setProxies($proxyList); - phpCAS::trace("Storing Proxy List"); + CAS::trace('Storing Proxy List'); } // Check if the proxies in front of us are allowed - if (!$this->getAllowedProxyChains()->isProxyListAllowed($proxyList)) { - throw new CAS_AuthenticationException( - $this, 'Proxy not allowed', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + if (! $this->getAllowedProxyChains()->isProxyListAllowed($proxyList)) { + throw new AuthenticationException( + $this, + 'Proxy not allowed', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; } else { $result = true; } } - } else if ( $tree_response->getElementsByTagName("authenticationFailure")->length != 0) { - // authentication succeded, extract the error code and message + } elseif ($tree_response->getElementsByTagName('authenticationFailure')->length != 0) { + // authentication succeeded, extract the error code and message $auth_fail_list = $tree_response - ->getElementsByTagName("authenticationFailure"); - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, false/*$bad_response*/, + ->getElementsByTagName('authenticationFailure'); + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + false/*$bad_response*/, $text_response, $auth_fail_list->item(0)->getAttribute('code')/*$err_code*/, trim($auth_fail_list->item(0)->nodeValue)/*$err_msg*/ ); - $result = false; } else { - throw new CAS_AuthenticationException( - $this, 'Ticket not validated', $validate_url, - false/*$no_response*/, true/*$bad_response*/, + throw new AuthenticationException( + $this, + 'Ticket not validated', + $validate_url, + false/*$no_response*/, + true/*$bad_response*/, $text_response ); - $result = false; } if ($result) { $this->_renameSession($this->getTicket()); } // at this step, Ticket has been validated and $this->_user has been set, - phpCAS::traceEnd($result); + CAS::traceEnd($result); + return $result; } - /** * This method will parse the DOM and pull out the attributes from the XML * payload and put them into an array, then put the array into the session. * * @param string $success_elements payload of the response * - * @return bool true when successfull, halt otherwise by calling - * CAS_Client::_authError(). + * @return bool true when successful, halt otherwise by calling + * Client::_authError(). */ private function _readExtraAttributesCas20($success_elements) { - phpCAS::traceBegin(); + CAS::traceBegin(); - $extra_attributes = array(); + $extra_attributes = []; // "Jasig Style" Attributes: // @@ -3304,15 +3476,15 @@ private function _readExtraAttributesCas20($success_elements) // // // - if ( $success_elements->item(0)->getElementsByTagName("attributes")->length != 0) { + if ($success_elements->item(0)->getElementsByTagName('attributes')->length != 0) { $attr_nodes = $success_elements->item(0) - ->getElementsByTagName("attributes"); - phpCas :: trace("Found nested jasig style attributes"); + ->getElementsByTagName('attributes'); + CAS::trace('Found nested jasig style attributes'); if ($attr_nodes->item(0)->hasChildNodes()) { // Nested Attributes foreach ($attr_nodes->item(0)->childNodes as $attr_child) { - phpCas :: trace( - "Attribute [".$attr_child->localName."] = " + CAS::trace( + 'Attribute ['.$attr_child->localName.'] = ' .$attr_child->nodeValue ); $this->_addAttributeToArray( @@ -3338,7 +3510,7 @@ private function _readExtraAttributesCas20($success_elements) // // // - phpCas :: trace("Testing for rubycas style attributes"); + CAS::trace('Testing for rubycas style attributes'); $childnodes = $success_elements->item(0)->childNodes; foreach ($childnodes as $attr_node) { switch ($attr_node->localName) { @@ -3348,8 +3520,8 @@ private function _readExtraAttributesCas20($success_elements) continue; default: if (strlen(trim($attr_node->nodeValue))) { - phpCas :: trace( - "Attribute [".$attr_node->localName."] = ".$attr_node->nodeValue + CAS::trace( + 'Attribute ['.$attr_node->localName.'] = '.$attr_node->nodeValue ); $this->_addAttributeToArray( $extra_attributes, $attr_node->localName, @@ -3380,25 +3552,25 @@ private function _readExtraAttributesCas20($success_elements) // // // - if (!count($extra_attributes) - && $success_elements->item(0)->getElementsByTagName("attribute")->length != 0 + if (! count($extra_attributes) + && $success_elements->item(0)->getElementsByTagName('attribute')->length != 0 ) { $attr_nodes = $success_elements->item(0) - ->getElementsByTagName("attribute"); + ->getElementsByTagName('attribute'); $firstAttr = $attr_nodes->item(0); - if (!$firstAttr->hasChildNodes() + if (! $firstAttr->hasChildNodes() && $firstAttr->hasAttribute('name') && $firstAttr->hasAttribute('value') ) { - phpCas :: trace("Found Name-Value style attributes"); + CAS::trace('Found Name-Value style attributes'); // Nested Attributes foreach ($attr_nodes as $attr_node) { if ($attr_node->hasAttribute('name') && $attr_node->hasAttribute('value') ) { - phpCas :: trace( - "Attribute [".$attr_node->getAttribute('name') - ."] = ".$attr_node->getAttribute('value') + CAS::trace( + 'Attribute ['.$attr_node->getAttribute('name') + .'] = '.$attr_node->getAttribute('value') ); $this->_addAttributeToArray( $extra_attributes, $attr_node->getAttribute('name'), @@ -3410,7 +3582,8 @@ private function _readExtraAttributesCas20($success_elements) } $this->setAttributes($extra_attributes); - phpCAS::traceEnd(); + CAS::traceEnd(); + return true; } @@ -3428,9 +3601,9 @@ private function _addAttributeToArray(array &$attributeArray, $name, $value) // If multiple attributes exist, add as an array value if (isset($attributeArray[$name])) { // Initialize the array with the existing value - if (!is_array($attributeArray[$name])) { + if (! is_array($attributeArray[$name])) { $existingValue = $attributeArray[$name]; - $attributeArray[$name] = array($existingValue); + $attributeArray[$name] = [$existingValue]; } $attributeArray[$name][] = trim($value); @@ -3455,17 +3628,17 @@ private function _addAttributeToArray(array &$attributeArray, $name, $value) // ######################################################################## // URL // ######################################################################## + /** - * the URL of the current request (without any ticket CGI parameter). Written - * and read by CAS_Client::getURL(). - * - * @hideinitializer - */ + * the URL of the current request (without any ticket CGI parameter). Written + * and read by Client::getURL(). + * + * @hideinitializer + */ private $_url = ''; - /** - * This method sets the URL of the current request + * This method sets the URL of the current request. * * @param string $url url to set for service * @@ -3473,9 +3646,10 @@ private function _addAttributeToArray(array &$attributeArray, $name, $value) */ public function setURL($url) { - // Argument Validation - if (gettype($url) != 'string') - throw new CAS_TypeMismatchException($url, '$url', 'string'); + // Argument Validation + if (gettype($url) != 'string') { + throw new TypeMismatchException($url, '$url', 'string'); + } $this->_url = $url; } @@ -3484,54 +3658,52 @@ public function setURL($url) * This method returns the URL of the current request (without any ticket * CGI parameter). * - * @return The URL + * @return string The URL */ public function getURL() { - phpCAS::traceBegin(); + CAS::traceBegin(); // the URL is built when needed only - if ( empty($this->_url) ) { - $final_uri = ''; + if (empty($this->_url)) { // remove the ticket if present in the URL $final_uri = ($this->_isHttps()) ? 'https' : 'http'; $final_uri .= '://'; $final_uri .= $this->_getClientUrl(); - $request_uri = explode('?', $_SERVER['REQUEST_URI'], 2); - $final_uri .= $request_uri[0]; + $request_uri = explode('?', $this->_getRequestUri(), 2); + $final_uri .= $request_uri[0]; if (isset($request_uri[1]) && $request_uri[1]) { - $query_string= $this->_removeParameterFromQueryString('ticket', $request_uri[1]); + $query_string = $this->_removeParameterFromQueryString('ticket', $request_uri[1]); // If the query string still has anything left, // append it to the final URI if ($query_string !== '') { - $final_uri .= "?$query_string"; + $final_uri .= "?$query_string"; } } - phpCAS::trace("Final URI: $final_uri"); + CAS::trace("Final URI: $final_uri"); $this->setURL($final_uri); } - phpCAS::traceEnd($this->_url); + CAS::traceEnd($this->_url); + return $this->_url; } - /** - * Try to figure out the phpCas client URL with possible Proxys / Ports etc. + * Try to figure out the CAS client URL with possible Proxies / Ports etc. * * @return string Server URL with domain:port */ private function _getClientUrl() { - $server_url = ''; - if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { + if (! empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { // explode the host list separated by comma and use the first host $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']); // see rfc7239#5.3 and rfc7230#2.7.1: port is in HTTP_X_FORWARDED_HOST if non default return $hosts[0]; - } else if (!empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) { + } elseif (! empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) { $server_url = $_SERVER['HTTP_X_FORWARDED_SERVER']; } else { if (empty($_SERVER['SERVER_NAME'])) { @@ -3540,7 +3712,7 @@ private function _getClientUrl() $server_url = $_SERVER['SERVER_NAME']; } } - if (!strpos($server_url, ':')) { + if (! strpos($server_url, ':')) { if (empty($_SERVER['HTTP_X_FORWARDED_PORT'])) { $server_port = $_SERVER['SERVER_PORT']; } else { @@ -3548,28 +3720,29 @@ private function _getClientUrl() $server_port = $ports[0]; } - if ( ($this->_isHttps() && $server_port!=443) - || (!$this->_isHttps() && $server_port!=80) + if (($this->_isHttps() && $server_port != 443) + || (! $this->_isHttps() && $server_port != 80) ) { $server_url .= ':'; $server_url .= $server_port; } } + return $server_url; } /** - * This method checks to see if the request is secured via HTTPS + * This method checks to see if the request is secured via HTTPS. * * @return bool true if https, false otherwise */ private function _isHttps() { - if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + if (! empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { return ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'); } - if ( isset($_SERVER['HTTPS']) - && !empty($_SERVER['HTTPS']) + if (isset($_SERVER['HTTPS']) + && ! empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') !== 0 ) { return true; @@ -3579,7 +3752,7 @@ private function _isHttps() } /** - * Removes a parameter from a query string + * Removes a parameter from a query string. * * @param string $parameterName name of parameter * @param string $queryString query string @@ -3590,7 +3763,8 @@ private function _isHttps() */ private function _removeParameterFromQueryString($parameterName, $queryString) { - $parameterName = preg_quote($parameterName); + $parameterName = preg_quote($parameterName); + return preg_replace( "/&$parameterName(=[^&]*)?|^$parameterName(=[^&]*)?&?/", '', $queryString @@ -3600,22 +3774,23 @@ private function _removeParameterFromQueryString($parameterName, $queryString) /** * This method is used to append query parameters to an url. Since the url * might already contain parameter it has to be detected and to build a proper - * URL + * URL. * * @param string $url base url to add the query params to * @param string $query params in query form with & separated * - * @return url with query params + * @return string url with query params */ private function _buildQueryUrl($url, $query) { $url .= (strstr($url, '?') === false) ? '?' : '&'; $url .= $query; + return $url; } /** - * Renaming the session + * Renaming the session. * * @param string $ticket name of the ticket * @@ -3623,45 +3798,45 @@ private function _buildQueryUrl($url, $query) */ private function _renameSession($ticket) { - phpCAS::traceBegin(); + CAS::traceBegin(); if ($this->getChangeSessionID()) { - if (!empty($this->_user)) { + if (! empty($this->_user)) { $old_session = $_SESSION; - phpCAS :: trace("Killing session: ". session_id()); + CAS::trace('Killing session: '.session_id()); session_destroy(); // set up a new session, of name based on the ticket $session_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $ticket); - phpCAS :: trace("Starting session: ". $session_id); + CAS::trace('Starting session: '.$session_id); session_id($session_id); session_start(); - phpCAS :: trace("Restoring old session vars"); + CAS::trace('Restoring old session vars'); $_SESSION = $old_session; } else { - phpCAS :: trace ( - 'Session should only be renamed after successfull authentication' + CAS::trace( + 'Session should only be renamed after successful authentication' ); } } else { - phpCAS :: trace( - "Skipping session rename since phpCAS is not handling the session." + CAS::trace( + 'Skipping session rename since CAS is not handling the session.' ); } - phpCAS::traceEnd(); + CAS::traceEnd(); } - // ######################################################################## // AUTHENTICATION ERROR HANDLING // ######################################################################## + /** * This method is used to print the HTML output when the user was not * authenticated. * - * @param string $failure the failure that occured + * @param string $failure the failure that occurred * @param string $cas_url the URL the CAS server was asked for - * @param bool $no_response the response from the CAS server (other + * @param mixed $no_response the response from the CAS server (other * parameters are ignored if true) - * @param bool $bad_response bad response from the CAS server ($err_code + * @param mixed $bad_response bad response from the CAS server ($err_code * and $err_msg ignored if true) * @param string $cas_response the response of the CAS server * @param int $err_code the error code given by the CAS server @@ -3673,47 +3848,47 @@ private function _authError( $failure, $cas_url, $no_response, - $bad_response='', - $cas_response='', - $err_code='', - $err_msg='' + $bad_response = '', + $cas_response = '', + $err_code = 0, + $err_msg = '' ) { - phpCAS::traceBegin(); + CAS::traceBegin(); $lang = $this->getLangObj(); $this->printHTMLHeader($lang->getAuthenticationFailed()); printf( $lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()), - isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:'' + isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN'] : '' ); - phpCAS::trace('CAS URL: '.$cas_url); - phpCAS::trace('Authentication failure: '.$failure); - if ( $no_response ) { - phpCAS::trace('Reason: no response from the CAS server'); + CAS::trace('CAS URL: '.$cas_url); + CAS::trace('Authentication failure: '.$failure); + if ($no_response) { + CAS::trace('Reason: no response from the CAS server'); } else { - if ( $bad_response ) { - phpCAS::trace('Reason: bad response from the CAS server'); + if ($bad_response) { + CAS::trace('Reason: bad response from the CAS server'); } else { switch ($this->getServerVersion()) { - case CAS_VERSION_1_0: - phpCAS::trace('Reason: CAS error'); + case CAS::CAS_VERSION_1_0: + CAS::trace('Reason: CAS error'); break; - case CAS_VERSION_2_0: - case CAS_VERSION_3_0: - if ( empty($err_code) ) { - phpCAS::trace('Reason: no CAS error'); + case CAS::CAS_VERSION_2_0: + case CAS::CAS_VERSION_3_0: + if (empty($err_code)) { + CAS::trace('Reason: no CAS error'); } else { - phpCAS::trace( + CAS::trace( 'Reason: ['.$err_code.'] CAS error: '.$err_msg ); } break; } } - phpCAS::trace('CAS response: '.$cas_response); + CAS::trace('CAS response: '.$cas_response); } $this->printHTMLFooter(); - phpCAS::traceExit(); - throw new CAS_GracefullTerminationException(); + CAS::traceExit(); + throw new GracefulTerminationException(); } // ######################################################################## @@ -3725,7 +3900,7 @@ private function _authError( * array of the nodes. */ private $_rebroadcast = false; - private $_rebroadcast_nodes = array(); + private $_rebroadcast_nodes = []; /** * Constants used for determining rebroadcast node type. @@ -3739,16 +3914,17 @@ private function _authError( * @param String $nodeURL The node URL. * * @return string hostname - * */ private function _getNodeType($nodeURL) { - phpCAS::traceBegin(); - if (preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $nodeURL)) { - phpCAS::traceEnd(self::IP); + CAS::traceBegin(); + if (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $nodeURL)) { + CAS::traceEnd(self::IP); + return self::IP; } else { - phpCAS::traceEnd(self::HOSTNAME); + CAS::traceEnd(self::HOSTNAME); + return self::HOSTNAME; } } @@ -3762,9 +3938,10 @@ private function _getNodeType($nodeURL) */ public function addRebroadcastNode($rebroadcastNodeUrl) { - // Argument validation - if ( !(bool)preg_match("/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i", $rebroadcastNodeUrl)) - throw new CAS_TypeMismatchException($rebroadcastNodeUrl, '$rebroadcastNodeUrl', 'url'); + // Argument validation + if (! (bool) preg_match('/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $rebroadcastNodeUrl)) { + throw new TypeMismatchException($rebroadcastNodeUrl, '$rebroadcastNodeUrl', 'url'); + } // Store the rebroadcast node and set flag $this->_rebroadcast = true; @@ -3774,7 +3951,7 @@ public function addRebroadcastNode($rebroadcastNodeUrl) /** * An array to store extra rebroadcast curl options. */ - private $_rebroadcast_headers = array(); + private $_rebroadcast_headers = []; /** * This method is used to add header parameters when rebroadcasting @@ -3786,8 +3963,9 @@ public function addRebroadcastNode($rebroadcastNodeUrl) */ public function addRebroadcastHeader($header) { - if (gettype($header) != 'string') - throw new CAS_TypeMismatchException($header, '$header', 'string'); + if (gettype($header) != 'string') { + throw new TypeMismatchException($header, '$header', 'string'); + } $this->_rebroadcast_headers[] = $header; } @@ -3799,7 +3977,7 @@ public function addRebroadcastHeader($header) const PGTIOU = 1; /** - * This method rebroadcasts logout/pgtIou requests. Can be LOGOUT,PGTIOU + * This method rebroadcasts logout/pgtIou requests. Can be LOGOUT,PGTIOU. * * @param int $type type of rebroadcasting. * @@ -3807,41 +3985,41 @@ public function addRebroadcastHeader($header) */ private function _rebroadcast($type) { - phpCAS::traceBegin(); + CAS::traceBegin(); - $rebroadcast_curl_options = array( + $rebroadcast_curl_options = [ CURLOPT_FAILONERROR => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 1, - CURLOPT_TIMEOUT => 4); + CURLOPT_TIMEOUT => 4, ]; // Try to determine the IP address of the server - if (!empty($_SERVER['SERVER_ADDR'])) { + if (! empty($_SERVER['SERVER_ADDR'])) { $ip = $_SERVER['SERVER_ADDR']; - } else if (!empty($_SERVER['LOCAL_ADDR'])) { + } elseif (! empty($_SERVER['LOCAL_ADDR'])) { // IIS 7 $ip = $_SERVER['LOCAL_ADDR']; } // Try to determine the DNS name of the server - if (!empty($ip)) { + if (! empty($ip)) { $dns = gethostbyaddr($ip); } - $multiClassName = 'CAS_Request_CurlMultiRequest'; + $multiClassName = '\phpCAS\CAS\Request\CurlMultiRequest'; $multiRequest = new $multiClassName(); for ($i = 0; $i < sizeof($this->_rebroadcast_nodes); $i++) { - if ((($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::HOSTNAME) && !empty($dns) && (stripos($this->_rebroadcast_nodes[$i], $dns) === false)) - || (($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::IP) && !empty($ip) && (stripos($this->_rebroadcast_nodes[$i], $ip) === false)) + if ((($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::HOSTNAME) && ! empty($dns) && (stripos($this->_rebroadcast_nodes[$i], $dns) === false)) + || (($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::IP) && ! empty($ip) && (stripos($this->_rebroadcast_nodes[$i], $ip) === false)) ) { - phpCAS::trace( + CAS::trace( 'Rebroadcast target URL: '.$this->_rebroadcast_nodes[$i] - .$_SERVER['REQUEST_URI'] + .$this->_getRequestUri() ); $className = $this->_requestImplementation; $request = new $className(); - $url = $this->_rebroadcast_nodes[$i].$_SERVER['REQUEST_URI']; + $url = $this->_rebroadcast_nodes[$i].$this->_getRequestUri(); $request->setUrl($url); if (count($this->_rebroadcast_headers)) { @@ -3854,7 +4032,7 @@ private function _rebroadcast($type) $request->setPostBody( 'rebroadcast=false&logoutRequest='.$_POST['logoutRequest'] ); - } else if ($type == self::PGTIOU) { + } elseif ($type == self::PGTIOU) { // pgtIou/pgtId rebroadcast $request->setPostBody('rebroadcast=false'); } @@ -3863,10 +4041,10 @@ private function _rebroadcast($type) $multiRequest->addRequest($request); } else { - phpCAS::trace( + CAS::trace( 'Rebroadcast not sent to self: ' - .$this->_rebroadcast_nodes[$i].' == '.(!empty($ip)?$ip:'') - .'/'.(!empty($dns)?$dns:'') + .$this->_rebroadcast_nodes[$i].' == '.(! empty($ip) ? $ip : '') + .'/'.(! empty($dns) ? $dns : '') ); } } @@ -3874,10 +4052,8 @@ private function _rebroadcast($type) if ($multiRequest->getNumRequests() > 0) { $multiRequest->send(); } - phpCAS::traceEnd(); + CAS::traceEnd(); } /** @} */ } - -?> diff --git a/source/CAS/CookieJar.php b/source/CAS/CookieJar.php index 549b8929..7438bcca 100644 --- a/source/CAS/CookieJar.php +++ b/source/CAS/CookieJar.php @@ -21,26 +21,27 @@ * * @file CAS/CookieJar.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use phpCAS\CAS; + /** * This class provides access to service cookies and handles parsing of response * headers to pull out cookie values. * * @class CAS_CookieJar * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_CookieJar +class CookieJar { - private $_cookies; /** @@ -48,26 +49,22 @@ class CAS_CookieJar * should store cookies. * * @param array &$storageArray Array to store cookies - * - * @return void */ - public function __construct (array &$storageArray) + public function __construct(array &$storageArray) { - $this->_cookies =& $storageArray; + $this->_cookies = &$storageArray; } /** * Store cookies for a web service request. - * Cookie storage is based on RFC 2965: http://www.ietf.org/rfc/rfc2965.txt + * Cookie storage is based on RFC 2965: http://www.ietf.org/rfc/rfc2965.txt. * * @param string $request_url The URL that generated the response headers. * @param array $response_headers An array of the HTTP response header strings. * * @return void - * - * @access private */ - public function storeCookies ($request_url, $response_headers) + public function storeCookies($request_url, $response_headers) { $urlParts = parse_url($request_url); $defaultDomain = $urlParts['host']; @@ -78,54 +75,52 @@ public function storeCookies ($request_url, $response_headers) foreach ($cookies as $cookie) { // Enforce the same-origin policy by verifying that the cookie // would match the url that is setting it - if (!$this->cookieMatchesTarget($cookie, $urlParts)) { + if (! $this->cookieMatchesTarget($cookie, $urlParts)) { continue; } // store the cookie $this->storeCookie($cookie); - phpCAS::trace($cookie['name'].' -> '.$cookie['value']); + CAS::trace($cookie['name'].' -> '.$cookie['value']); } } /** * Retrieve cookies applicable for a web service request. - * Cookie applicability is based on RFC 2965: http://www.ietf.org/rfc/rfc2965.txt + * Cookie applicability is based on RFC 2965: http://www.ietf.org/rfc/rfc2965.txt. * * @param string $request_url The url that the cookies will be for. * * @return array An array containing cookies. E.g. array('name' => 'val'); - * - * @access private */ - public function getCookies ($request_url) + public function getCookies($request_url) { - if (!count($this->_cookies)) { - return array(); + if (! count($this->_cookies)) { + return []; } // If our request URL can't be parsed, no cookies apply. $target = parse_url($request_url); if ($target === false) { - return array(); + return []; } $this->expireCookies(); - $matching_cookies = array(); + $matching_cookies = []; foreach ($this->_cookies as $key => $cookie) { if ($this->cookieMatchesTarget($cookie, $target)) { $matching_cookies[$cookie['name']] = $cookie['value']; } } + return $matching_cookies; } - /** * Parse Cookies without PECL - * From the comments in http://php.net/manual/en/function.http-parse-cookie.php + * From the comments in http://php.net/manual/en/function.http-parse-cookie.php. * * @param array $header array of header lines. * @param string $defaultDomain The domain to use if none is specified in @@ -133,17 +128,18 @@ public function getCookies ($request_url) * * @return array of cookies */ - protected function parseCookieHeaders( $header, $defaultDomain ) + protected function parseCookieHeaders($header, $defaultDomain) { - phpCAS::traceBegin(); - $cookies = array(); - foreach ( $header as $line ) { - if ( preg_match('/^Set-Cookie2?: /i', $line)) { + CAS::traceBegin(); + $cookies = []; + foreach ($header as $line) { + if (preg_match('/^Set-Cookie2?: /i', $line)) { $cookies[] = $this->parseCookieHeader($line, $defaultDomain); } } - phpCAS::traceEnd($cookies); + CAS::traceEnd($cookies); + return $cookies; } @@ -158,27 +154,27 @@ protected function parseCookieHeaders( $header, $defaultDomain ) * * @return array */ - protected function parseCookieHeader ($line, $defaultDomain) + protected function parseCookieHeader($line, $defaultDomain) { - if (!$defaultDomain) { - throw new CAS_InvalidArgumentException( + if (! $defaultDomain) { + throw new InvalidArgumentException( '$defaultDomain was not provided.' ); } // Set our default values - $cookie = array( + $cookie = [ 'domain' => $defaultDomain, 'path' => '/', 'secure' => false, - ); + ]; $line = preg_replace('/^Set-Cookie2?: /i', '', trim($line)); // trim any trailing semicolons. $line = trim($line, ';'); - phpCAS::trace("Cookie Line: $line"); + CAS::trace("Cookie Line: $line"); // This implementation makes the assumption that semicolons will not // be present in quoted attribute values. While attribute values that @@ -187,7 +183,7 @@ protected function parseCookieHeader ($line, $defaultDomain) // assumption. $attributeStrings = explode(';', $line); - foreach ( $attributeStrings as $attributeString ) { + foreach ($attributeStrings as $attributeString) { // split on the first equals sign and use the rest as value $attributeParts = explode('=', $attributeString, 2); @@ -211,13 +207,13 @@ protected function parseCookieHeader ($line, $defaultDomain) $cookie['expires'] = strtotime($attributeValue); break; case 'max-age': - $cookie['max-age'] = (int)$attributeValue; + $cookie['max-age'] = (int) $attributeValue; // Set an expiry time based on the max-age if ($cookie['max-age']) { $cookie['expires'] = time() + $cookie['max-age']; } else { // If max-age is zero, then the cookie should be removed - // imediately so set an expiry before now. + // immediately so set an expiry before now. $cookie['expires'] = time() - 1; } break; @@ -249,37 +245,32 @@ protected function parseCookieHeader ($line, $defaultDomain) * @param array $cookie A cookie array as created by parseCookieHeaders() * * @return void - * - * @access protected */ - protected function storeCookie ($cookie) + protected function storeCookie($cookie) { // Discard any old versions of this cookie. $this->discardCookie($cookie); $this->_cookies[] = $cookie; - } /** - * Discard an existing cookie + * Discard an existing cookie. * * @param array $cookie An cookie * * @return void - * - * @access protected */ - protected function discardCookie ($cookie) + protected function discardCookie($cookie) { - if (!isset($cookie['domain']) - || !isset($cookie['path']) - || !isset($cookie['path']) + if (! isset($cookie['domain']) + || ! isset($cookie['path']) + || ! isset($cookie['path']) ) { - throw new CAS_InvalidArgumentException('Invalid Cookie array passed.'); + throw new InvalidArgumentException('Invalid Cookie array passed.'); } foreach ($this->_cookies as $key => $old_cookie) { - if ( $cookie['domain'] == $old_cookie['domain'] + if ($cookie['domain'] == $old_cookie['domain'] && $cookie['path'] == $old_cookie['path'] && $cookie['name'] == $old_cookie['name'] ) { @@ -292,10 +283,8 @@ protected function discardCookie ($cookie) * Go through our stored cookies and remove any that are expired. * * @return void - * - * @access protected */ - protected function expireCookies () + protected function expireCookies() { foreach ($this->_cookies as $key => $cookie) { if (isset($cookie['expires']) && $cookie['expires'] < time()) { @@ -311,18 +300,16 @@ protected function expireCookies () * @param array $target An array of URL attributes as generated by parse_url(). * * @return bool - * - * @access private */ - protected function cookieMatchesTarget ($cookie, $target) + protected function cookieMatchesTarget($cookie, $target) { - if (!is_array($target)) { - throw new CAS_InvalidArgumentException( + if (! is_array($target)) { + throw new InvalidArgumentException( '$target must be an array of URL attributes as generated by parse_url().' ); } - if (!isset($target['host'])) { - throw new CAS_InvalidArgumentException( + if (! isset($target['host'])) { + throw new InvalidArgumentException( '$target must be an array of URL attributes as generated by parse_url().' ); } @@ -333,7 +320,7 @@ protected function cookieMatchesTarget ($cookie, $target) } // Verify that the host matches - // Match domain and mulit-host cookies + // Match domain and multi-host cookies if (strpos($cookie['domain'], '.') === 0) { // .host.domain.edu cookies are valid for host.domain.edu if (substr($cookie['domain'], 1) == $target['host']) { @@ -342,7 +329,7 @@ protected function cookieMatchesTarget ($cookie, $target) // non-exact host-name matches. // check that the target host a.b.c.edu is within .b.c.edu $pos = strripos($target['host'], $cookie['domain']); - if (!$pos) { + if (! $pos) { return false; } // verify that the cookie domain is the last part of the host. @@ -367,7 +354,7 @@ protected function cookieMatchesTarget ($cookie, $target) // Verify that the port matches if (isset($cookie['ports']) - && !in_array($target['port'], $cookie['ports']) + && ! in_array($target['port'], $cookie['ports']) ) { return false; } @@ -379,7 +366,4 @@ protected function cookieMatchesTarget ($cookie, $target) return true; } - } - -?> diff --git a/source/CAS/GracefullTerminationException.php b/source/CAS/GracefulTerminationException.php similarity index 75% rename from source/CAS/GracefullTerminationException.php rename to source/CAS/GracefulTerminationException.php index 6d845dfa..332dc8d9 100644 --- a/source/CAS/GracefullTerminationException.php +++ b/source/CAS/GracefulTerminationException.php @@ -19,32 +19,30 @@ * * PHP Version 5 * - * @file CAS/GracefullTerminationException.php + * @file CAS/GracefulTerminationException.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use RuntimeException; + /** - * An exception for terminatinating execution or to throw for unit testing + * An exception for terminating execution or to throw for unit testing. * - * @class CAS_GracefullTerminationException.php + * @class GracefulTerminationException * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_GracefullTerminationException -extends RuntimeException -implements CAS_Exception +class GracefulTerminationException extends RuntimeException implements CASExceptionInterface { - /** * Test if exceptions should be thrown or if we should just exit. * In production usage we want to just exit cleanly when prompting the user @@ -53,11 +51,9 @@ class CAS_GracefullTerminationException * with our tests. * * @param string $message Message Text - * @param string $code Error code - * - * @return void + * @param int $code Error code */ - public function __construct ($message = 'Terminate Gracefully', $code = 0) + public function __construct($message = 'Terminate Gracefully', $code = 0) { // Exit cleanly to avoid filling up the logs with uncaught exceptions. if (self::$_exitWhenThrown) { @@ -69,18 +65,17 @@ public function __construct ($message = 'Terminate Gracefully', $code = 0) } private static $_exitWhenThrown = true; + /** - * Force phpcas to thow Exceptions instead of calling exit() - * Needed for unit testing. Generally shouldn't be used in production due to - * an increase in Apache error logging if CAS_GracefulTerminiationExceptions - * are not caught and handled. - * - * @return void - */ + * Force CAS to throw Exceptions instead of calling exit() + * Needed for unit testing. Generally should not be used in production due to + * an increase in Apache error logging if GracefulTerminiationExceptions + * are not caught and handled. + * + * @return void + */ public static function throwInsteadOfExiting() { self::$_exitWhenThrown = false; } - } -?> \ No newline at end of file diff --git a/source/CAS/InvalidArgumentException.php b/source/CAS/InvalidArgumentException.php index ba43d39f..7745d994 100644 --- a/source/CAS/InvalidArgumentException.php +++ b/source/CAS/InvalidArgumentException.php @@ -21,26 +21,24 @@ * * @file CAS/InvalidArgumentException.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use InvalidArgumentException as BaseInvalidArgumentException; + /** * Exception that denotes invalid arguments were passed. * - * @class CAS_InvalidArgumentException + * @class InvalidArgumentException * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_InvalidArgumentException -extends InvalidArgumentException -implements CAS_Exception +class InvalidArgumentException extends BaseInvalidArgumentException implements CASExceptionInterface { - } -?> \ No newline at end of file diff --git a/source/CAS/Languages/Catalan.php b/source/CAS/Languages/Catalan.php index a0b64d8e..9799cd54 100644 --- a/source/CAS/Languages/Catalan.php +++ b/source/CAS/Languages/Catalan.php @@ -21,18 +21,18 @@ * * @file CAS/Language/Catalan.php * @category Authentication - * @package PhpCAS * @author Iván-Benjamín García Torà * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * Catalan language class + * Catalan language class. * - * @class CAS_Languages_Catalan + * @class Catalan * @category Authentication - * @package PhpCAS * @author Iván-Benjamín García Torà * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,73 +40,73 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_Catalan implements CAS_Languages_LanguageInterface +class Catalan implements LanguageInterface { /** - * Get the using server string - * - * @return string using server - */ + * Get the using server string. + * + * @return string using server + */ public function getUsingServer() { return 'usant servidor'; } /** - * Get authentication wanted string - * - * @return string authentication wanted - */ + * Get authentication wanted string. + * + * @return string authentication wanted + */ public function getAuthenticationWanted() { return 'Autentificació CAS necessària!'; } /** - * Get logout string - * - * @return string logout - */ + * Get logout string. + * + * @return string logout + */ public function getLogout() { return 'Sortida de CAS necessària!'; } /** - * Get the should have been redirected string - * - * @return string should habe been redirected - */ + * Get the should have been redirected string. + * + * @return string should habe been redirected + */ public function getShouldHaveBeenRedirected() { return 'Ja hauria d\ haver estat redireccionat al servidor CAS. Feu click aquí per a continuar.'; } /** - * Get authentication failed string - * - * @return string authentication failed - */ + * Get authentication failed string. + * + * @return string authentication failed + */ public function getAuthenticationFailed() { return 'Autentificació CAS fallida!'; } /** - * Get the your were not authenticated string - * - * @return string not authenticated - */ + * Get the your were not authenticated string. + * + * @return string not authenticated + */ public function getYouWereNotAuthenticated() { return '

      No estàs autentificat.

      Pots tornar a intentar-ho fent click aquí.

      Si el problema persisteix hauría de contactar amb l\'administrador d\'aquest llocc.

      '; } /** - * Get the service unavailable string - * - * @return string service unavailable - */ + * Get the service unavailable string. + * + * @return string service unavailable + */ public function getServiceUnavailable() { return 'El servei `%s\' no està disponible (%s).'; diff --git a/source/CAS/Languages/English.php b/source/CAS/Languages/English.php index 002c1ba4..a7948ad9 100644 --- a/source/CAS/Languages/English.php +++ b/source/CAS/Languages/English.php @@ -21,18 +21,18 @@ * * @file CAS/Language/English.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * English language class + * English language class. * - * @class CAS_Languages_English + * @class English * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,10 +40,10 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_English implements CAS_Languages_LanguageInterface +class English implements LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -53,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -63,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -73,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -83,32 +83,32 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string - * - * @return string authentication failed - */ + * Get authentication failed string. + * + * @return string authentication failed + */ public function getAuthenticationFailed() { return 'CAS Authentication failed!'; } /** - * Get the your were not authenticated string - * - * @return string not authenticated - */ + * Get the your were not authenticated string. + * + * @return string not authenticated + */ public function getYouWereNotAuthenticated() { return '

      You were not authenticated.

      You may submit your request again by clicking here.

      If the problem persists, you may contact the administrator of this site.

      '; } /** - * Get the service unavailable string - * - * @return string service unavailable - */ + * Get the service unavailable string. + * + * @return string service unavailable + */ public function getServiceUnavailable() { return 'The service `%s\' is not available (%s).'; } -} \ No newline at end of file +} diff --git a/source/CAS/Languages/French.php b/source/CAS/Languages/French.php index b99847a7..08a80403 100644 --- a/source/CAS/Languages/French.php +++ b/source/CAS/Languages/French.php @@ -21,18 +21,18 @@ * * @file CAS/Language/French.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * French language class + * French language class. * - * @class CAS_Languages_French + * @class French * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,10 +40,10 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_French implements CAS_Languages_LanguageInterface +class French implements LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -53,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -63,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -73,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -83,7 +83,7 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ @@ -93,7 +93,7 @@ public function getAuthenticationFailed() } /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ @@ -103,7 +103,7 @@ public function getYouWereNotAuthenticated() } /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ @@ -112,5 +112,3 @@ public function getServiceUnavailable() return 'Le service `%s\' est indisponible (%s)'; } } - -?> \ No newline at end of file diff --git a/source/CAS/Languages/German.php b/source/CAS/Languages/German.php index ed3150a8..0df320fd 100644 --- a/source/CAS/Languages/German.php +++ b/source/CAS/Languages/German.php @@ -21,18 +21,18 @@ * * @file CAS/Language/German.php * @category Authentication - * @package PhpCAS * @author Henrik Genssen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * German language class + * German language class. * - * @class CAS_Languages_German + * @class German * @category Authentication - * @package PhpCAS * @author Henrik Genssen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,10 +40,10 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_German implements CAS_Languages_LanguageInterface +class German implements LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -53,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -63,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -73,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -83,7 +83,7 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ @@ -93,7 +93,7 @@ public function getAuthenticationFailed() } /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ @@ -103,7 +103,7 @@ public function getYouWereNotAuthenticated() } /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ @@ -112,5 +112,3 @@ public function getServiceUnavailable() return 'Der Dienst `%s\' ist nicht verfügbar (%s).'; } } - -?> diff --git a/source/CAS/Languages/Greek.php b/source/CAS/Languages/Greek.php index 888ce241..69bd999c 100644 --- a/source/CAS/Languages/Greek.php +++ b/source/CAS/Languages/Greek.php @@ -21,18 +21,18 @@ * * @file CAS/Language/Greek.php * @category Authentication - * @package PhpCAS * @author Vangelis Haniotakis * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * Greek language class + * Greek language class. * - * @class CAS_Languages_Greek + * @class Greek * @category Authentication - * @package PhpCAS * @author Vangelis Haniotakis * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,10 +40,10 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_Greek implements CAS_Languages_LanguageInterface +class Greek implements LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -53,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -63,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -73,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -83,7 +83,7 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ @@ -93,7 +93,7 @@ public function getAuthenticationFailed() } /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ @@ -103,7 +103,7 @@ public function getYouWereNotAuthenticated() } /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ @@ -112,4 +112,3 @@ public function getServiceUnavailable() return 'Η υπηρεσία `%s\' δεν είναι διαθέσιμη (%s).'; } } -?> diff --git a/source/CAS/Languages/Japanese.php b/source/CAS/Languages/Japanese.php index a15bf17b..33eb101c 100644 --- a/source/CAS/Languages/Japanese.php +++ b/source/CAS/Languages/Japanese.php @@ -21,27 +21,29 @@ * * @file CAS/Language/Japanese.php * @category Authentication - * @package PhpCAS * @author fnorif * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** * Japanese language class. Now Encoding is UTF-8. * - * @class CAS_Languages_Japanese + * @class Japanese * @category Authentication - * @package PhpCAS * @author fnorif * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS * + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang **/ -class CAS_Languages_Japanese implements CAS_Languages_LanguageInterface +class Japanese implements LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -51,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -61,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -71,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -81,7 +83,7 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ @@ -91,7 +93,7 @@ public function getAuthenticationFailed() } /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ @@ -101,7 +103,7 @@ public function getYouWereNotAuthenticated() } /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ @@ -110,4 +112,3 @@ public function getServiceUnavailable() return 'サービス `%s\' は利用できません (%s)。'; } } -?> diff --git a/source/CAS/Languages/LanguageInterface.php b/source/CAS/Languages/LanguageInterface.php index 5de93aa7..2a783806 100644 --- a/source/CAS/Languages/LanguageInterface.php +++ b/source/CAS/Languages/LanguageInterface.php @@ -21,18 +21,18 @@ * * @file CAS/Language/LanguageInterface.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * Language Interface class for all internationalization files + * Language Interface class for all internationalization files. * - * @class CAS_Languages_LanguageInterface + * @class LanguageInterface * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS @@ -40,57 +40,54 @@ * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ - -interface CAS_Languages_LanguageInterface +interface LanguageInterface { /** - * Get the using server string + * Get the using server string. * * @return string using server */ public function getUsingServer(); /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ public function getAuthenticationWanted(); /** - * Get logout string + * Get logout string. * * @return string logout */ public function getLogout(); /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ public function getShouldHaveBeenRedirected(); /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ public function getAuthenticationFailed(); /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ public function getYouWereNotAuthenticated(); /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ public function getServiceUnavailable(); - } -?> \ No newline at end of file diff --git a/source/CAS/Languages/Spanish.php b/source/CAS/Languages/Spanish.php index 5675a41d..76631bb2 100644 --- a/source/CAS/Languages/Spanish.php +++ b/source/CAS/Languages/Spanish.php @@ -21,31 +21,29 @@ * * @file CAS/Language/Spanish.php * @category Authentication - * @package PhpCAS * @author Iván-Benjamín García Torà * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Languages; + /** - * Spanish language class + * Spanish language class. * - * @class CAS_Languages_Spanish + * @class Spanish * @category Authentication - * @package PhpCAS * @author Iván-Benjamín García Torà * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS * - * @sa @link internalLang Internationalization @endlink * @ingroup internalLang */ -class CAS_Languages_Spanish implements CAS_Languages_LanguageInterface +class Spanish implements LanguageInterface { - /** - * Get the using server string + * Get the using server string. * * @return string using server */ @@ -55,7 +53,7 @@ public function getUsingServer() } /** - * Get authentication wanted string + * Get authentication wanted string. * * @return string authentication wanted */ @@ -65,7 +63,7 @@ public function getAuthenticationWanted() } /** - * Get logout string + * Get logout string. * * @return string logout */ @@ -75,7 +73,7 @@ public function getLogout() } /** - * Get the should have been redirected string + * Get the should have been redirected string. * * @return string should habe been redirected */ @@ -85,7 +83,7 @@ public function getShouldHaveBeenRedirected() } /** - * Get authentication failed string + * Get authentication failed string. * * @return string authentication failed */ @@ -95,7 +93,7 @@ public function getAuthenticationFailed() } /** - * Get the your were not authenticated string + * Get the your were not authenticated string. * * @return string not authenticated */ @@ -105,7 +103,7 @@ public function getYouWereNotAuthenticated() } /** - * Get the service unavailable string + * Get the service unavailable string. * * @return string service unavailable */ @@ -114,4 +112,3 @@ public function getServiceUnavailable() return 'El servicio `%s\' no está disponible (%s).'; } } -?> diff --git a/source/CAS/OutOfSequenceBeforeAuthenticationCallException.php b/source/CAS/OutOfSequenceBeforeAuthenticationCallException.php index ef830979..160aa2a3 100644 --- a/source/CAS/OutOfSequenceBeforeAuthenticationCallException.php +++ b/source/CAS/OutOfSequenceBeforeAuthenticationCallException.php @@ -22,34 +22,30 @@ * * @file CAS/OutOfSequenceBeforeAuthenticationCallException.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** * This class defines Exceptions that should be thrown when the sequence of * operations is invalid. In this case it should be thrown when an * authentication call has not yet happened. * - * @class CAS_OutOfSequenceBeforeAuthenticationCallException + * @class OutOfSequenceBeforeAuthenticationCallException * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_OutOfSequenceBeforeAuthenticationCallException -extends CAS_OutOfSequenceException -implements CAS_Exception +class OutOfSequenceBeforeAuthenticationCallException extends OutOfSequenceException implements CASExceptionInterface { /** - * Return standard error meessage - * - * @return void + * Return standard error message. */ - public function __construct () + public function __construct() { parent::__construct('An authentication call hasn\'t happened yet.'); } diff --git a/source/CAS/OutOfSequenceBeforeClientException.php b/source/CAS/OutOfSequenceBeforeClientException.php index f1ea7e24..4dd2338b 100644 --- a/source/CAS/OutOfSequenceBeforeClientException.php +++ b/source/CAS/OutOfSequenceBeforeClientException.php @@ -22,37 +22,33 @@ * * @file CAS/OutOfSequenceBeforeClientException.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** * This class defines Exceptions that should be thrown when the sequence of * operations is invalid. In this case it should be thrown when the client() or * proxy() call has not yet happened and no client or proxy object exists. * - * @class CAS_OutOfSequenceBeforeClientException + * @class OutOfSequenceBeforeClientException * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_OutOfSequenceBeforeClientException -extends CAS_OutOfSequenceException -implements CAS_Exception +class OutOfSequenceBeforeClientException extends OutOfSequenceException implements CASExceptionInterface { /** - * Return standard error message - * - * @return void + * Return standard error message. */ - public function __construct () + public function __construct() { parent::__construct( - 'this method cannot be called before phpCAS::client() or phpCAS::proxy()' + 'this method cannot be called before CAS::client() or CAS::proxy()' ); } } diff --git a/source/CAS/OutOfSequenceBeforeProxyException.php b/source/CAS/OutOfSequenceBeforeProxyException.php index 8038542e..b97c74c9 100644 --- a/source/CAS/OutOfSequenceBeforeProxyException.php +++ b/source/CAS/OutOfSequenceBeforeProxyException.php @@ -22,38 +22,33 @@ * * @file CAS/OutOfSequenceBeforeProxyException.php * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** * This class defines Exceptions that should be thrown when the sequence of * operations is invalid. In this case it should be thrown when the proxy() call * has not yet happened and no proxy object exists. * - * @class CAS_OutOfSequenceBeforeProxyException + * @class OutOfSequenceBeforeProxyException * @category Authentication - * @package PhpCAS * @author Joachim Fritschi * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_OutOfSequenceBeforeProxyException -extends CAS_OutOfSequenceException -implements CAS_Exception +class OutOfSequenceBeforeProxyException extends OutOfSequenceException implements CASExceptionInterface { - /** - * Return standard error message - * - * @return void + * Return standard error message. */ - public function __construct () + public function __construct() { parent::__construct( - 'this method cannot be called before phpCAS::proxy()' + 'this method cannot be called before CAS::proxy()' ); } } diff --git a/source/CAS/OutOfSequenceException.php b/source/CAS/OutOfSequenceException.php index d101811b..9b4ac5c9 100644 --- a/source/CAS/OutOfSequenceException.php +++ b/source/CAS/OutOfSequenceException.php @@ -22,28 +22,27 @@ * * @file CAS/OutOfSequenceException.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use BadMethodCallException; + /** * This class defines Exceptions that should be thrown when the sequence of * operations is invalid. Examples are: * - Requesting the response before executing a request. * - Changing the URL of a request after executing the request. * - * @class CAS_OutOfSequenceException + * @class OutOfSequenceException * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_OutOfSequenceException -extends BadMethodCallException -implements CAS_Exception +class OutOfSequenceException extends BadMethodCallException implements CASExceptionInterface { - } diff --git a/source/CAS/PGTStorage/AbstractStorage.php b/source/CAS/PGTStorage/AbstractStorage.php index c1648984..cbecb8ea 100644 --- a/source/CAS/PGTStorage/AbstractStorage.php +++ b/source/CAS/PGTStorage/AbstractStorage.php @@ -21,29 +21,31 @@ * * @file CAS/PGTStorage/AbstractStorage.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\PGTStorage; + +use phpCAS\CAS; +use phpCAS\CAS\Client; + /** * Basic class for PGT storage * The CAS_PGTStorage_AbstractStorage class is a generic class for PGT storage. - * This class should not be instanciated itself but inherited by specific PGT + * This class should not be instantiated itself but inherited by specific PGT * storage classes. * * @class CAS_PGTStorage_AbstractStorage * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS * * @ingroup internalPGTStorage */ - -abstract class CAS_PGTStorage_AbstractStorage +abstract class AbstractStorage { /** * @addtogroup internalPGTStorage @@ -57,22 +59,20 @@ abstract class CAS_PGTStorage_AbstractStorage /** * The constructor of the class, should be called only by inherited classes. * - * @param CAS_Client $cas_parent the CAS _client instance that creates the + * @param Client $cas_parent the CAS _client instance that creates the * current object. * - * @return void - * * @protected */ - function __construct($cas_parent) + public function __construct(Client $cas_parent) { - phpCAS::traceBegin(); - if ( !$cas_parent->isProxy() ) { - phpCAS::error( + CAS::traceBegin(); + if (! $cas_parent->isProxy()) { + CAS::error( 'defining PGT storage makes no sense when not using a CAS proxy' ); } - phpCAS::traceEnd(); + CAS::traceEnd(); } // ######################################################################## @@ -87,36 +87,36 @@ function __construct($cas_parent) * * @public */ - function getStorageType() + public function getStorageType() { - phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + CAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); } /** - * This virtual method returns an informational string giving informations on the + * This virtual method returns an informational string giving information on the * parameters of the storage.(used for debugging purposes). * * @return void * * @public */ - function getStorageInfo() + public function getStorageInfo() { - phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + CAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); } // ######################################################################## // ERROR HANDLING // ######################################################################## - /** + /* * string used to store an error message. Written by * PGTStorage::setErrorMessage(), read by PGTStorage::getErrorMessage(). * * @hideinitializer * @deprecated not used. */ - var $_error_message=false; + public $_error_message; /** * This method sets en error message, which can be read later by @@ -128,7 +128,7 @@ function getStorageInfo() * * @deprecated not used. */ - function setErrorMessage($error_message) + public function setErrorMessage($error_message) { $this->_error_message = $error_message; } @@ -136,12 +136,12 @@ function setErrorMessage($error_message) /** * This method returns an error message set by PGTStorage::setErrorMessage(). * - * @return an error message when set by PGTStorage::setErrorMessage(), FALSE + * @return string an error message when set by PGTStorage::setErrorMessage(), FALSE * otherwise. * * @deprecated not used. */ - function getErrorMessage() + public function getErrorMessage() { return $this->_error_message; } @@ -150,22 +150,22 @@ function getErrorMessage() // INITIALIZATION // ######################################################################## - /** + /* * a boolean telling if the storage has already been initialized. Written by * PGTStorage::init(), read by PGTStorage::isInitialized(). * * @hideinitializer */ - var $_initialized = false; + public $_initialized = false; /** - * This method tells if the storage has already been intialized. + * This method tells if the storage has already been initialized. * - * @return a boolean + * @return bool * * @protected */ - function isInitialized() + public function isInitialized() { return $this->_initialized; } @@ -175,7 +175,7 @@ function isInitialized() * * @return void */ - function init() + public function init() { $this->_initialized = true; } @@ -190,14 +190,13 @@ function init() * @param string $pgt the PGT * @param string $pgt_iou the PGT iou * - * @return void + * @return mixed * * @note Should never be called. - * */ - function write($pgt,$pgt_iou) + public function write($pgt, $pgt_iou) { - phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + CAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); } /** @@ -206,17 +205,14 @@ function write($pgt,$pgt_iou) * * @param string $pgt_iou the PGT iou * - * @return void + * @return mixed * * @note Should never be called. */ - function read($pgt_iou) + public function read($pgt_iou) { - phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + CAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); } /** @} */ - } - -?> diff --git a/source/CAS/PGTStorage/Db.php b/source/CAS/PGTStorage/Db.php index c331ca09..9fa2b2b7 100644 --- a/source/CAS/PGTStorage/Db.php +++ b/source/CAS/PGTStorage/Db.php @@ -21,13 +21,17 @@ * * @file CAS/PGTStorage/Db.php * @category Authentication - * @package PhpCAS * @author Daniel Frett * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -define('CAS_PGT_STORAGE_DB_DEFAULT_TABLE', 'cas_pgts'); +namespace phpCAS\CAS\PGTStorage; + +use PDO; +use PDOException; +use phpCAS\CAS; +use phpCAS\CAS\Client; /** * Basic class for PGT database storage @@ -35,30 +39,30 @@ * * @class CAS_PGTStorage_Db * @category Authentication - * @package PhpCAS * @author Daniel Frett * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS * * @ingroup internalPGTStorageDb */ - -class CAS_PGTStorage_Db extends CAS_PGTStorage_AbstractStorage +class Db extends AbstractStorage { + const CAS_PGT_STORAGE_DB_DEFAULT_TABLE = 'cas_pgts'; + /** * @addtogroup internalCAS_PGTStorageDb * @{ */ /** - * the PDO object to use for database interactions + * the PDO object to use for database interactions. */ private $_pdo; /** * This method returns the PDO object to use for database interactions. * - * @return the PDO object + * @return PDO the PDO object */ private function _getPdo() { @@ -66,22 +70,23 @@ private function _getPdo() } /** - * database connection options to use when creating a new PDO object + * database connection options to use when creating a new PDO object. */ private $_dsn; private $_username; private $_password; private $_table_options; + private $_driver_options; /** - * the table to use for storing/retrieving pgt's + * the table to use for storing/retrieving pgt's. */ private $_table; /** - * This method returns the table to use when storing/retrieving PGT's + * This method returns the table to use when storing/retrieving PGT's. * - * @return the name of the pgt storage table. + * @return string the name of the pgt storage table. */ private function _getTable() { @@ -96,18 +101,19 @@ private function _getTable() * This method returns an informational string giving the type of storage * used by the object (used for debugging purposes). * - * @return an informational string. + * @return string an informational string. */ public function getStorageType() { - return "db"; + return 'db'; } /** - * This method returns an informational string giving informations on the + * This method returns an informational string giving information on the * parameters of the storage.(used for debugging purposes). * - * @return an informational string. + * @return string an informational string. + * * @public */ public function getStorageInfo() @@ -122,33 +128,37 @@ public function getStorageInfo() /** * The class constructor. * - * @param CAS_Client $cas_parent the CAS_Client instance that creates - * the object. + * @param Client $cas_parent the CAS_Client instance that creates + * the object. * @param string $dsn_or_pdo a dsn string to use for creating a PDO - * object or a PDO object + * object or a PDO object * @param string $username the username to use when connecting to - * the database + * the database * @param string $password the password to use when connecting to - * the database + * the database * @param string $table the table to use for storing and - * retrieving PGT's + * retrieving PGT's * @param string $driver_options any driver options to use when - * connecting to the database + * connecting to the database */ public function __construct( - $cas_parent, $dsn_or_pdo, $username='', $password='', $table='', - $driver_options=null + Client $cas_parent, + $dsn_or_pdo, + $username = '', + $password = '', + $table = '', + $driver_options = null ) { - phpCAS::traceBegin(); + CAS::traceBegin(); // call the ancestor's constructor parent::__construct($cas_parent); // set default values - if ( empty($table) ) { - $table = CAS_PGT_STORAGE_DB_DEFAULT_TABLE; + if (empty($table)) { + $table = self::CAS_PGT_STORAGE_DB_DEFAULT_TABLE; } - if ( !is_array($driver_options) ) { - $driver_options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); + if (! is_array($driver_options)) { + $driver_options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; } // store the specified parameters @@ -164,7 +174,7 @@ public function __construct( // store the table name $this->_table = $table; - phpCAS::traceEnd(); + CAS::traceEnd(); } // ######################################################################## @@ -178,8 +188,8 @@ public function __construct( */ public function init() { - phpCAS::traceBegin(); - // if the storage has already been initialized, return immediatly + CAS::traceBegin(); + // if the storage has already been initialized, return immediately if ($this->isInitialized()) { return; } @@ -188,19 +198,18 @@ public function init() parent::init(); // create the PDO object if it doesn't exist already - if (!($this->_pdo instanceof PDO)) { + if (! ($this->_pdo instanceof PDO)) { try { $this->_pdo = new PDO( $this->_dsn, $this->_username, $this->_password, $this->_driver_options ); - } - catch(PDOException $e) { - phpCAS::error('Database connection error: ' . $e->getMessage()); + } catch (PDOException $e) { + CAS::error('Database connection error: '.$e->getMessage()); } } - phpCAS::traceEnd(); + CAS::traceEnd(); } // ######################################################################## @@ -209,12 +218,12 @@ public function init() /** * attribute that stores the previous error mode for the PDO handle while - * processing a transaction + * processing a transaction. */ private $_errMode; /** - * This method will enable the Exception error mode on the PDO object + * This method will enable the Exception error mode on the PDO object. * * @return void */ @@ -227,7 +236,7 @@ private function _setErrorMode() } /** - * this method will reset the error mode on the PDO object + * this method will reset the error mode on the PDO object. * * @return void */ @@ -243,52 +252,52 @@ private function _resetErrorMode() // ######################################################################## // these queries are potentially unsafe because the person using this library // can set the table to use, but there is no reliable way to escape SQL - // fieldnames in PDO yet + // field names in PDO yet /** - * This method returns the query used to create a pgt storage table + * This method returns the query used to create a pgt storage table. * - * @return the create table SQL, no bind params in query + * @return string the create table SQL, no bind params in query */ protected function createTableSql() { - return 'CREATE TABLE ' . $this->_getTable() - . ' (pgt_iou VARCHAR(255) NOT NULL PRIMARY KEY, pgt VARCHAR(255) NOT NULL)'; + return 'CREATE TABLE '.$this->_getTable() + .' (pgt_iou VARCHAR(255) NOT NULL PRIMARY KEY, pgt VARCHAR(255) NOT NULL)'; } /** - * This method returns the query used to store a pgt + * This method returns the query used to store a pgt. * - * @return the store PGT SQL, :pgt and :pgt_iou are the bind params contained + * @return string the store PGT SQL, :pgt and :pgt_iou are the bind params contained * in the query */ protected function storePgtSql() { - return 'INSERT INTO ' . $this->_getTable() - . ' (pgt_iou, pgt) VALUES (:pgt_iou, :pgt)'; + return 'INSERT INTO '.$this->_getTable() + .' (pgt_iou, pgt) VALUES (:pgt_iou, :pgt)'; } /** * This method returns the query used to retrieve a pgt. the first column - * of the first row should contain the pgt + * of the first row should contain the pgt. * - * @return the retrieve PGT SQL, :pgt_iou is the only bind param contained + * @return string the retrieve PGT SQL, :pgt_iou is the only bind param contained * in the query */ protected function retrievePgtSql() { - return 'SELECT pgt FROM ' . $this->_getTable() . ' WHERE pgt_iou = :pgt_iou'; + return 'SELECT pgt FROM '.$this->_getTable().' WHERE pgt_iou = :pgt_iou'; } /** * This method returns the query used to delete a pgt. * - * @return the delete PGT SQL, :pgt_iou is the only bind param contained in + * @return string the delete PGT SQL, :pgt_iou is the only bind param contained in * the query */ protected function deletePgtSql() { - return 'DELETE FROM ' . $this->_getTable() . ' WHERE pgt_iou = :pgt_iou'; + return 'DELETE FROM '.$this->_getTable().' WHERE pgt_iou = :pgt_iou'; } // ######################################################################## @@ -296,16 +305,16 @@ protected function deletePgtSql() // ######################################################################## /** - * This method creates the database table used to store pgt's and pgtiou's + * This method creates the database table used to store pgt's and pgtiou's. * * @return void */ public function createTable() { - phpCAS::traceBegin(); + CAS::traceBegin(); // initialize this PGTStorage object if it hasn't been initialized yet - if ( !$this->isInitialized() ) { + if (! $this->isInitialized()) { $this->init(); } @@ -316,25 +325,23 @@ public function createTable() try { $pdo->beginTransaction(); - $query = $pdo->query($this->createTableSQL()); + $query = $pdo->query($this->createTableSql()); $query->closeCursor(); $pdo->commit(); - } - catch(PDOException $e) { - // attempt rolling back the transaction before throwing a phpCAS error + } catch (PDOException $e) { + // attempt rolling back the transaction before throwing a CAS error try { $pdo->rollBack(); + } catch (PDOException $e) { } - catch(PDOException $e) { - } - phpCAS::error('error creating PGT storage table: ' . $e->getMessage()); + CAS::error('error creating PGT storage table: '.$e->getMessage()); } // reset the PDO object $this->_resetErrorMode(); - phpCAS::traceEnd(); + CAS::traceEnd(); } /** @@ -348,7 +355,7 @@ public function createTable() */ public function write($pgt, $pgt_iou) { - phpCAS::traceBegin(); + CAS::traceBegin(); // initialize the PDO object for this method $pdo = $this->_getPdo(); @@ -364,21 +371,19 @@ public function write($pgt, $pgt_iou) $query->closeCursor(); $pdo->commit(); - } - catch(PDOException $e) { - // attempt rolling back the transaction before throwing a phpCAS error + } catch (PDOException $e) { + // attempt rolling back the transaction before throwing a CAS error try { $pdo->rollBack(); + } catch (PDOException $e) { } - catch(PDOException $e) { - } - phpCAS::error('error writing PGT to database: ' . $e->getMessage()); + CAS::error('error writing PGT to database: '.$e->getMessage()); } // reset the PDO object $this->_resetErrorMode(); - phpCAS::traceEnd(); + CAS::traceEnd(); } /** @@ -387,11 +392,11 @@ public function write($pgt, $pgt_iou) * * @param string $pgt_iou the PGT iou * - * @return the corresponding PGT, or FALSE on error + * @return mixed the corresponding PGT, or FALSE on error */ public function read($pgt_iou) { - phpCAS::traceBegin(); + CAS::traceBegin(); $pgt = false; // initialize the PDO object for this method @@ -415,26 +420,22 @@ public function read($pgt_iou) $query->closeCursor(); $pdo->commit(); - } - catch(PDOException $e) { - // attempt rolling back the transaction before throwing a phpCAS error + } catch (PDOException $e) { + // attempt rolling back the transaction before throwing a CAS error try { $pdo->rollBack(); + } catch (PDOException $e) { } - catch(PDOException $e) { - } - phpCAS::trace('error reading PGT from database: ' . $e->getMessage()); + CAS::trace('error reading PGT from database: '.$e->getMessage()); } // reset the PDO object $this->_resetErrorMode(); - phpCAS::traceEnd(); + CAS::traceEnd(); + return $pgt; } /** @} */ - } - -?> diff --git a/source/CAS/PGTStorage/File.php b/source/CAS/PGTStorage/File.php index d3bcf809..3fc1eaef 100644 --- a/source/CAS/PGTStorage/File.php +++ b/source/CAS/PGTStorage/File.php @@ -21,51 +21,52 @@ * * @file CAS/PGTStorage/AbstractStorage.php * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\PGTStorage; + +use phpCAS\CAS; +use phpCAS\CAS\Client; + /** * The CAS_PGTStorage_File class is a class for PGT file storage. An instance of * this class is returned by CAS_Client::SetPGTStorageFile(). * * @class CAS_PGTStorage_File * @category Authentication - * @package PhpCAS * @author Pascal Aubry * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS * - * * @ingroup internalPGTStorageFile */ - -class CAS_PGTStorage_File extends CAS_PGTStorage_AbstractStorage +class File extends AbstractStorage { /** - * @addtogroup internalPGTStorageFile + * @addtogroup internalPGTStorage * @{ */ - /** + /* * a string telling where PGT's should be stored on the filesystem. Written by * PGTStorageFile::PGTStorageFile(), read by getPath(). * * @private */ - var $_path; + public $_path; /** * This method returns the name of the directory where PGT's should be stored * on the filesystem. * - * @return the name of a directory (with leading and trailing '/') + * @return string the name of a directory (with leading and trailing '/') * * @private */ - function getPath() + public function getPath() { return $this->_path; } @@ -78,22 +79,24 @@ function getPath() * This method returns an informational string giving the type of storage * used by the object (used for debugging purposes). * - * @return an informational string. + * @return string an informational string. + * * @public */ - function getStorageType() + public function getStorageType() { - return "file"; + return 'file'; } /** - * This method returns an informational string giving informations on the + * This method returns an informational string giving information on the * parameters of the storage.(used for debugging purposes). * - * @return an informational string. + * @return string an informational string. + * * @public */ - function getStorageInfo() + public function getStorageInfo() { return 'path=`'.$this->getPath().'\''; } @@ -105,33 +108,28 @@ function getStorageInfo() /** * The class constructor, called by CAS_Client::SetPGTStorageFile(). * - * @param CAS_Client $cas_parent the CAS_Client instance that creates the object. + * @param Client $cas_parent the CAS_Client instance that creates the object. * @param string $path the path where the PGT's should be stored * - * @return void - * * @public */ - function __construct($cas_parent,$path) + public function __construct(Client $cas_parent, $path) { - phpCAS::traceBegin(); + CAS::traceBegin(); // call the ancestor's constructor parent::__construct($cas_parent); if (empty($path)) { - $path = CAS_PGT_STORAGE_FILE_DEFAULT_PATH; + $path = session_save_path(); } // check that the path is an absolute path - if (getenv("OS")=="Windows_NT") { - - if (!preg_match('`^[a-zA-Z]:`', $path)) { - phpCAS::error('an absolute path is needed for PGT storage to file'); + if (getenv('OS') == 'Windows_NT') { + if (! preg_match('`^[a-zA-Z]:`', $path)) { + CAS::error('an absolute path is needed for PGT storage to file'); } - } else { - - if ( $path[0] != '/' ) { - phpCAS::error('an absolute path is needed for PGT storage to file'); + if ($path[0] != '/') { + CAS::error('an absolute path is needed for PGT storage to file'); } // store the path (with a leading and trailing '/') @@ -140,7 +138,7 @@ function __construct($cas_parent,$path) } $this->_path = $path; - phpCAS::traceEnd(); + CAS::traceEnd(); } // ######################################################################## @@ -151,18 +149,19 @@ function __construct($cas_parent,$path) * This method is used to initialize the storage. Halts on error. * * @return void + * * @public */ - function init() + public function init() { - phpCAS::traceBegin(); - // if the storage has already been initialized, return immediatly + CAS::traceBegin(); + // if the storage has already been initialized, return immediately if ($this->isInitialized()) { return; } // call the ancestor's method (mark as initialized) parent::init(); - phpCAS::traceEnd(); + CAS::traceEnd(); } // ######################################################################## @@ -174,16 +173,18 @@ function init() * * @param string $pgt_iou the PGT iou. * - * @return a filename + * @return string a filename + * * @private */ - function getPGTIouFilename($pgt_iou) + public function getPGTIouFilename($pgt_iou) { - phpCAS::traceBegin(); - $filename = $this->getPath()."phpcas-".hash("sha256", $pgt_iou); -// $filename = $this->getPath().$pgt_iou.'.plain'; - phpCAS::trace("Sha256 filename:" . $filename); - phpCAS::traceEnd(); + CAS::traceBegin(); + $filename = $this->getPath().'CAS-'.hash('sha256', $pgt_iou); + // $filename = $this->getPath().$pgt_iou.'.plain'; + CAS::trace('Sha256 filename:'.$filename); + CAS::traceEnd(); + return $filename; } @@ -198,27 +199,27 @@ function getPGTIouFilename($pgt_iou) * * @public */ - function write($pgt,$pgt_iou) + public function write($pgt, $pgt_iou) { - phpCAS::traceBegin(); + CAS::traceBegin(); $fname = $this->getPGTIouFilename($pgt_iou); - if (!file_exists($fname)) { + if (! file_exists($fname)) { touch($fname); // Chmod will fail on windows @chmod($fname, 0600); - if ($f=fopen($fname, "w")) { + if ($f = fopen($fname, 'w')) { if (fputs($f, $pgt) === false) { - phpCAS::error('could not write PGT to `'.$fname.'\''); + CAS::error('could not write PGT to `'.$fname.'\''); } - phpCAS::trace('Successful write of PGT to `'.$fname.'\''); + CAS::trace('Successful write of PGT to `'.$fname.'\''); fclose($f); } else { - phpCAS::error('could not open `'.$fname.'\''); + CAS::error('could not open `'.$fname.'\''); } } else { - phpCAS::error('File exists: `'.$fname.'\''); + CAS::error('File exists: `'.$fname.'\''); } - phpCAS::traceEnd(); + CAS::traceEnd(); } /** @@ -227,35 +228,32 @@ function write($pgt,$pgt_iou) * * @param string $pgt_iou the PGT iou * - * @return the corresponding PGT, or FALSE on error - * - * @public + * @return mixed the corresponding PGT, or FALSE on error */ - function read($pgt_iou) + public function read($pgt_iou) { - phpCAS::traceBegin(); + CAS::traceBegin(); $pgt = false; $fname = $this->getPGTIouFilename($pgt_iou); if (file_exists($fname)) { - if (!($f=fopen($fname, "r"))) { - phpCAS::error('could not open `'.$fname.'\''); + if (! ($f = fopen($fname, 'r'))) { + CAS::error('could not open `'.$fname.'\''); } else { - if (($pgt=fgets($f)) === false) { - phpCAS::error('could not read PGT from `'.$fname.'\''); + if (($pgt = fgets($f)) === false) { + CAS::error('could not read PGT from `'.$fname.'\''); } - phpCAS::trace('Successful read of PGT to `'.$fname.'\''); + CAS::trace('Successful read of PGT to `'.$fname.'\''); fclose($f); } // delete the PGT file @unlink($fname); } else { - phpCAS::error('No such file `'.$fname.'\''); + CAS::error('No such file `'.$fname.'\''); } - phpCAS::traceEnd($pgt); + CAS::traceEnd($pgt); + return $pgt; } /** @} */ - } -?> \ No newline at end of file diff --git a/source/CAS/ProxiedService.php b/source/CAS/ProxiedService.php index d70ca9c1..5a660ff2 100644 --- a/source/CAS/ProxiedService.php +++ b/source/CAS/ProxiedService.php @@ -21,39 +21,38 @@ * * @file CAS/ProxiedService.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** * This interface defines methods that allow proxy-authenticated service handlers * to interact with phpCAS. * * Proxy service handlers must implement this interface as well as call - * phpCAS::initializeProxiedService($this) at some point in their implementation. + * CAS::initializeProxiedService($this) at some point in their implementation. * * While not required, proxy-authenticated service handlers are encouraged to - * implement the CAS_ProxiedService_Testable interface to facilitate unit testing. + * implement the Testable interface to facilitate unit testing. * - * @class CAS_ProxiedService + * @class ProxiedService * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_ProxiedService +interface ProxiedService { - /** * Answer a service identifier (URL) for whom we should fetch a proxy ticket. * * @return string - * @throws Exception If no service url is available. + * @throws \Exception If no service url is available. */ - public function getServiceUrl (); + public function getServiceUrl(); /** * Register a proxy ticket with the ProxiedService that it can use when @@ -63,10 +62,8 @@ public function getServiceUrl (); * * @return void * @throws InvalidArgumentException If the $proxyTicket is invalid. - * @throws CAS_OutOfSequenceException If called after a proxy ticket has + * @throws OutOfSequenceException If called after a proxy ticket has * already been initialized/set. */ - public function setProxyTicket ($proxyTicket); - + public function setProxyTicket($proxyTicket); } -?> diff --git a/source/CAS/ProxiedService/Abstract.php b/source/CAS/ProxiedService/AbstractProxiedService.php similarity index 70% rename from source/CAS/ProxiedService/Abstract.php rename to source/CAS/ProxiedService/AbstractProxiedService.php index fade9e70..823d0574 100644 --- a/source/CAS/ProxiedService/Abstract.php +++ b/source/CAS/ProxiedService/AbstractProxiedService.php @@ -21,30 +21,34 @@ * * @file CAS/ProxiedService/Abstract.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\ProxiedService; + /** * This class implements common methods for ProxiedService implementations included - * with phpCAS. + * with CAS. * - * @class CAS_ProxiedService_Abstract + * @class AbstractProxiedService * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -abstract class CAS_ProxiedService_Abstract -implements CAS_ProxiedService, CAS_ProxiedService_Testable +abstract class AbstractProxiedService implements ProxiedService, Testable { - /** * The proxy ticket that can be used when making service requests. - * @var string $_proxyTicket; + * @var string; */ private $_proxyTicket; @@ -55,18 +59,18 @@ abstract class CAS_ProxiedService_Abstract * * @return void * @throws InvalidArgumentException If the $proxyTicket is invalid. - * @throws CAS_OutOfSequenceException If called after a proxy ticket has + * @throws OutOfSequenceException If called after a proxy ticket has * already been initialized/set. */ - public function setProxyTicket ($proxyTicket) + public function setProxyTicket($proxyTicket) { if (empty($proxyTicket)) { - throw new CAS_InvalidArgumentException( + throw new InvalidArgumentException( 'Trying to initialize with an empty proxy ticket.' ); } - if (!empty($this->_proxyTicket)) { - throw new CAS_OutOfSequenceException( + if (! empty($this->_proxyTicket)) { + throw new OutOfSequenceException( 'Already initialized, cannot change the proxy ticket.' ); } @@ -77,13 +81,13 @@ public function setProxyTicket ($proxyTicket) * Answer the proxy ticket to be used when making requests. * * @return string - * @throws CAS_OutOfSequenceException If called before a proxy ticket has + * @throws OutOfSequenceException If called before a proxy ticket has * already been initialized/set. */ - protected function getProxyTicket () + protected function getProxyTicket() { if (empty($this->_proxyTicket)) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'No proxy ticket yet. Call $this->initializeProxyTicket() to aquire the proxy ticket.' ); } @@ -92,27 +96,27 @@ protected function getProxyTicket () } /** - * @var CAS_Client $_casClient; + * @var Client; */ private $_casClient; /** - * Use a particular CAS_Client->initializeProxiedService() rather than the - * static phpCAS::initializeProxiedService(). + * Use a particular Client->initializeProxiedService() rather than the + * static CAS::initializeProxiedService(). * * This method should not be called in standard operation, but is needed for unit * testing. * - * @param CAS_Client $casClient cas client + * @param Client $casClient cas client * * @return void - * @throws CAS_OutOfSequenceException If called after a proxy ticket has + * @throws OutOfSequenceException If called after a proxy ticket has * already been initialized/set. */ - public function setCasClient (CAS_Client $casClient) + public function setCasClient(Client $casClient) { - if (!empty($this->_proxyTicket)) { - throw new CAS_OutOfSequenceException( + if (! empty($this->_proxyTicket)) { + throw new OutOfSequenceException( 'Already initialized, cannot change the CAS_Client.' ); } @@ -123,27 +127,25 @@ public function setCasClient (CAS_Client $casClient) /** * Fetch our proxy ticket. * - * Descendent classes should call this method once their service URL is available + * Descendant classes should call this method once their service URL is available * to initialize their proxy ticket. * * @return void - * @throws CAS_OutOfSequenceException If called after a proxy ticket has + * @throws OutOfSequenceException If called after a proxy ticket has * already been initialized. */ protected function initializeProxyTicket() { - if (!empty($this->_proxyTicket)) { - throw new CAS_OutOfSequenceException( + if (! empty($this->_proxyTicket)) { + throw new OutOfSequenceException( 'Already initialized, cannot initialize again.' ); } // Allow usage of a particular CAS_Client for unit testing. if (empty($this->_casClient)) { - phpCAS::initializeProxiedService($this); + CAS::initializeProxiedService($this); } else { $this->_casClient->initializeProxiedService($this); } } - } -?> diff --git a/source/CAS/ProxiedService/Http.php b/source/CAS/ProxiedService/Http.php index 7c9824fa..18c862b5 100644 --- a/source/CAS/ProxiedService/Http.php +++ b/source/CAS/ProxiedService/Http.php @@ -21,39 +21,38 @@ * * @file CAS/ProxiedService/Http.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService; + /** * This interface defines methods that clients should use for configuring, sending, * and receiving proxied HTTP requests. * - * @class CAS_ProxiedService_Http + * @class Http * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_ProxiedService_Http +interface Http { - /********************************************************* * Configure the Request *********************************************************/ /** - * Set the URL of the Request + * Set the URL of the Request. * * @param string $url Url to set * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws \phpCAS\CAS\OutOfSequenceException If called after the Request has been sent. */ - public function setUrl ($url); + public function setUrl($url); /********************************************************* * 2. Send the Request @@ -63,9 +62,9 @@ public function setUrl ($url); * Perform the request. * * @return bool TRUE on success, FALSE on failure. - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws \phpCAS\CAS\OutOfSequenceException If called multiple times. */ - public function send (); + public function send(); /********************************************************* * 3. Access the response @@ -75,17 +74,15 @@ public function send (); * Answer the headers of the response. * * @return array An array of header strings. - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws \phpCAS\CAS\OutOfSequenceException If called before the Request has been sent. */ - public function getResponseHeaders (); + public function getResponseHeaders(); /** * Answer the body of response. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws \phpCAS\CAS\OutOfSequenceException If called before the Request has been sent. */ - public function getResponseBody (); - + public function getResponseBody(); } -?> diff --git a/source/CAS/ProxiedService/Http/Abstract.php b/source/CAS/ProxiedService/Http/AbstractHttpProxiedService.php similarity index 66% rename from source/CAS/ProxiedService/Http/Abstract.php rename to source/CAS/ProxiedService/Http/AbstractHttpProxiedService.php index abeddf8b..39d3aeb1 100644 --- a/source/CAS/ProxiedService/Http/Abstract.php +++ b/source/CAS/ProxiedService/Http/AbstractHttpProxiedService.php @@ -21,50 +21,58 @@ * * @file CAS/ProxiedService/Http/Abstract.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService\Http; + +use phpCAS\CAS; +use phpCAS\CAS\CookieJar; +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\ProxiedService\AbstractProxiedService; +use phpCAS\CAS\ProxiedService\Http; +use phpCAS\CAS\ProxiedService\ProxiedServiceException; +use phpCAS\CAS\ProxyTicketException; +use phpCAS\CAS\Request\RequestInterface; + /** * This class implements common methods for ProxiedService implementations included - * with phpCAS. + * with CAS. * - * @class CAS_ProxiedService_Http_Abstract + * @class AbstractHttpProxiedService * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -abstract class CAS_ProxiedService_Http_Abstract extends -CAS_ProxiedService_Abstract implements CAS_ProxiedService_Http +abstract class AbstractHttpProxiedService extends AbstractProxiedService implements Http { /** * The HTTP request mechanism talking to the target service. * - * @var CAS_Request_RequestInterface $requestHandler + * @var RequestInterface */ protected $requestHandler; /** * The storage mechanism for cookies set by the target service. * - * @var CAS_CookieJar $_cookieJar + * @var CookieJar */ private $_cookieJar; /** * Constructor. * - * @param CAS_Request_RequestInterface $requestHandler request handler object - * @param CAS_CookieJar $cookieJar cookieJar object - * - * @return void + * @param RequestInterface $requestHandler request handler object + * @param CookieJar $cookieJar cookieJar object */ - public function __construct(CAS_Request_RequestInterface $requestHandler, - CAS_CookieJar $cookieJar + public function __construct( + RequestInterface $requestHandler, + CookieJar $cookieJar ) { $this->requestHandler = $requestHandler; $this->_cookieJar = $cookieJar; @@ -72,7 +80,7 @@ public function __construct(CAS_Request_RequestInterface $requestHandler, /** * The target service url. - * @var string $_url; + * @var string; */ private $_url; @@ -80,13 +88,13 @@ public function __construct(CAS_Request_RequestInterface $requestHandler, * Answer a service identifier (URL) for whom we should fetch a proxy ticket. * * @return string - * @throws Exception If no service url is available. + * @throws ProxiedServiceException If no service url is available. */ public function getServiceUrl() { if (empty($this->_url)) { - throw new CAS_ProxiedService_Exception( - 'No URL set via ' . get_class($this) . '->setUrl($url).' + throw new ProxiedServiceException( + 'No URL set via '.get_class($this).'->setUrl($url).' ); } @@ -98,22 +106,23 @@ public function getServiceUrl() *********************************************************/ /** - * Set the URL of the Request + * Set the URL of the Request. * * @param string $url url to set * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. + * @throws InvalidArgumentException */ public function setUrl($url) { if ($this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set the URL, request already sent.' ); } - if (!is_string($url)) { - throw new CAS_InvalidArgumentException('$url must be a string.'); + if (! is_string($url)) { + throw new InvalidArgumentException('$url must be a string.'); } $this->_url = $url; @@ -127,38 +136,38 @@ public function setUrl($url) * Perform the request. * * @return void - * @throws CAS_OutOfSequenceException If called multiple times. - * @throws CAS_ProxyTicketException If there is a proxy-ticket failure. + * @throws OutOfSequenceException If called multiple times. + * @throws ProxyTicketException If there is a proxy-ticket failure. * The code of the Exception will be one of: - * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_FAILURE - * @throws CAS_ProxiedService_Exception If there is a failure sending the + * CAS::CAS_SERVICE_PT_NO_SERVER_RESPONSE + * CAS::CAS_SERVICE_PT_BAD_SERVER_RESPONSE + * CAS::CAS_SERVICE_PT_FAILURE + * @throws ProxiedServiceException If there is a failure sending the * request to the target service. */ public function send() { if ($this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot send, request already sent.' ); } - phpCAS::traceBegin(); + CAS::traceBegin(); // Get our proxy ticket and append it to our URL. $this->initializeProxyTicket(); $url = $this->getServiceUrl(); if (strstr($url, '?') === false) { - $url = $url . '?ticket=' . $this->getProxyTicket(); + $url = $url.'?ticket='.$this->getProxyTicket(); } else { - $url = $url . '&ticket=' . $this->getProxyTicket(); + $url = $url.'&ticket='.$this->getProxyTicket(); } try { $this->makeRequest($url); - } catch (Exception $e) { - phpCAS::traceEnd(); + } catch (ProxiedServiceException $e) { + CAS::traceEnd(); throw $e; } } @@ -166,43 +175,43 @@ public function send() /** * Indicator of the number of requests (including redirects performed. * - * @var int $_numRequests; + * @var int; */ private $_numRequests = 0; /** * The response headers. * - * @var array $_responseHeaders; + * @var array; */ - private $_responseHeaders = array(); + private $_responseHeaders = []; /** * The response status code. * - * @var string $_responseStatusCode; + * @var string; */ private $_responseStatusCode = ''; /** * The response headers. * - * @var string $_responseBody; + * @var string; */ private $_responseBody = ''; /** - * Build and perform a request, following redirects + * Build and perform a request, following redirects. * * @param string $url url for the request * * @return void - * @throws CAS_ProxyTicketException If there is a proxy-ticket failure. + * @throws ProxyTicketException If there is a proxy-ticket failure. * The code of the Exception will be one of: - * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_FAILURE - * @throws CAS_ProxiedService_Exception If there is a failure sending the + * CAS_SERVICE_PT_NO_SERVER_RESPONSE + * CAS_SERVICE_PT_BAD_SERVER_RESPONSE + * CAS_SERVICE_PT_FAILURE + * @throws ProxiedServiceException If there is a failure sending the * request to the target service. */ protected function makeRequest($url) @@ -211,8 +220,8 @@ protected function makeRequest($url) $this->_numRequests++; if ($this->_numRequests > 4) { $message = 'Exceeded the maximum number of redirects (3) in proxied service request.'; - phpCAS::trace($message); - throw new CAS_ProxiedService_Exception($message); + CAS::trace($message); + throw new ProxiedServiceException($message); } // Create a new request. @@ -226,12 +235,12 @@ protected function makeRequest($url) $this->populateRequest($request); // Perform the request. - phpCAS::trace('Performing proxied service request to \'' . $url . '\''); - if (!$request->send()) { + CAS::trace('Performing proxied service request to \''.$url.'\''); + if (! $request->send()) { $message = 'Could not perform proxied service request to URL`' - . $url . '\'. ' . $request->getErrorMessage(); - phpCAS::trace($message); - throw new CAS_ProxiedService_Exception($message); + .$url.'\'. '.$request->getErrorMessage(); + CAS::trace($message); + throw new ProxiedServiceException($message); } // Store any cookies from the response; @@ -240,10 +249,9 @@ protected function makeRequest($url) // Follow any redirects if ($redirectUrl = $this->getRedirectUrl($request->getResponseHeaders()) ) { - phpCAS::trace('Found redirect:' . $redirectUrl); + CAS::trace('Found redirect:'.$redirectUrl); $this->makeRequest($redirectUrl); } else { - $this->_responseHeaders = $request->getResponseHeaders(); $this->_responseBody = $request->getResponseBody(); $this->_responseStatusCode = $request->getResponseStatusCode(); @@ -251,15 +259,13 @@ protected function makeRequest($url) } /** - * Add any other parts of the request needed by concrete classes + * Add any other parts of the request needed by concrete classes. * - * @param CAS_Request_RequestInterface $request request interface object + * @param RequestInterface $request request interface object * * @return void */ - abstract protected function populateRequest( - CAS_Request_RequestInterface $request - ); + abstract protected function populateRequest(RequestInterface $request); /** * Answer a redirect URL if a redirect header is found, otherwise null. @@ -272,12 +278,13 @@ protected function getRedirectUrl(array $responseHeaders) { // Check for the redirect after authentication foreach ($responseHeaders as $header) { - if ( preg_match('/^(Location:|URI:)\s*([^\s]+.*)$/', $header, $matches) + if (preg_match('/^(Location:|URI:)\s*([^\s]+.*)$/', $header, $matches) ) { return trim(array_pop($matches)); } } - return null; + + return; } /********************************************************* @@ -298,12 +305,12 @@ protected function hasBeenSent() * Answer the headers of the response. * * @return array An array of header strings. - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ public function getResponseHeaders() { - if (!$this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + if (! $this->hasBeenSent()) { + throw new OutOfSequenceException( 'Cannot access response, request not sent yet.' ); } @@ -312,15 +319,15 @@ public function getResponseHeaders() } /** - * Answer HTTP status code of the response + * Answer HTTP status code of the response. * * @return int - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ public function getResponseStatusCode() { - if (!$this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + if (! $this->hasBeenSent()) { + throw new OutOfSequenceException( 'Cannot access response, request not sent yet.' ); } @@ -332,12 +339,12 @@ public function getResponseStatusCode() * Answer the body of response. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ public function getResponseBody() { - if (!$this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + if (! $this->hasBeenSent()) { + throw new OutOfSequenceException( 'Cannot access response, request not sent yet.' ); } @@ -355,6 +362,4 @@ public function getCookies() { return $this->_cookieJar->getCookies($this->getServiceUrl()); } - } -?> diff --git a/source/CAS/ProxiedService/Http/Get.php b/source/CAS/ProxiedService/Http/Get.php index 78e35de1..435d0071 100644 --- a/source/CAS/ProxiedService/Http/Get.php +++ b/source/CAS/ProxiedService/Http/Get.php @@ -1,39 +1,42 @@ - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ + /** + * Licensed to Jasig under one or more contributor license + * agreements. See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + * + * Jasig licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * PHP Version 5 + * + * @file CAS/ProxiedService/Http/Get.php + * @category Authentication + * @author Adam Franco + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ -/** +namespace phpCAS\CAS\ProxiedService\Http; + +use phpCAS\CAS\Request\RequestInterface; + + /** * This class is used to make proxied service requests via the HTTP GET method. * * Usage Example: * * try { - * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + * $service = CAS::getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); * $service->setUrl('http://www.example.com/path/'); * $service->send(); * if ($service->getResponseStatusCode() == 200) @@ -42,15 +45,15 @@ * // The service responded with an error code 404, 500, etc. * throw new Exception('The service responded with an error.'); * - * } catch (CAS_ProxyTicketException $e) { - * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE) + * } catch (ProxyTicketException $e) { + * if ($e->getCode() == CAS::PHPCAS_SERVICE_PT_FAILURE) * return "Your login has timed out. You need to log in again."; * else * // Other proxy ticket errors are from bad request format * // (shouldn't happen) or CAS server failure (unlikely) * // so lets just stop if we hit those. * throw $e; - * } catch (CAS_ProxiedService_Exception $e) { + * } catch (ProxiedService_Exception $e) { * // Something prevented the service request from being sent or received. * // We didn't even get a valid error response (404, 500, etc), so this * // might be caused by a network error or a DNS resolution failure. @@ -58,28 +61,24 @@ * throw $e; * } * - * @class CAS_ProxiedService_Http_Get + * @class Get * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxiedService_Http_Get -extends CAS_ProxiedService_Http_Abstract +class Get extends AbstractHttpProxiedService { - /** - * Add any other parts of the request needed by concrete classes + * Add any other parts of the request needed by concrete classes. * - * @param CAS_Request_RequestInterface $request request interface + * @param RequestInterface $request request interface * * @return void */ - protected function populateRequest (CAS_Request_RequestInterface $request) + protected function populateRequest(RequestInterface $request) { // do nothing, since the URL has already been sent and that is our // only data. } } -?> diff --git a/source/CAS/ProxiedService/Http/Post.php b/source/CAS/ProxiedService/Http/Post.php index 7d4ecd3c..c3213aa6 100644 --- a/source/CAS/ProxiedService/Http/Post.php +++ b/source/CAS/ProxiedService/Http/Post.php @@ -21,19 +21,24 @@ * * @file CAS/ProxiedService/Http/Post.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService\Http; + +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\Request\RequestInterface; +use phpCAS\CAS\ProxiedService\ProxiedServiceException; + /** * This class is used to make proxied service requests via the HTTP POST method. * * Usage Example: * * try { - * $service = phpCAS::getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_POST); + * $service = CAS::getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_POST); * $service->setUrl('http://www.example.com/path/'); * $service->setContentType('text/xml'); * $service->setBody('example.search'); @@ -44,15 +49,15 @@ * // The service responded with an error code 404, 500, etc. * throw new Exception('The service responded with an error.'); * - * } catch (CAS_ProxyTicketException $e) { - * if ($e->getCode() == PHPCAS_SERVICE_PT_FAILURE) + * } catch (ProxyTicketException $e) { + * if ($e->getCode() == CAS_SERVICE_PT_FAILURE) * return "Your login has timed out. You need to log in again."; * else * // Other proxy ticket errors are from bad request format * // (shouldn't happen) or CAS server failure (unlikely) so lets just * // stop if we hit those. * throw $e; - * } catch (CAS_ProxiedService_Exception $e) { + * } catch (ProxiedService_Exception $e) { * // Something prevented the service request from being sent or received. * // We didn't even get a valid error response (404, 500, etc), so this * // might be caused by a network error or a DNS resolution failure. @@ -60,28 +65,25 @@ * throw $e; * } * - * @class CAS_ProxiedService_Http_Post + * @class Post * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxiedService_Http_Post -extends CAS_ProxiedService_Http_Abstract +class Post extends AbstractHttpProxiedService { - /** - * The content-type of this request + * The content-type of this request. * - * @var string $_contentType + * @var string */ private $_contentType; /** - * The body of the this request + * The body of the this request. * - * @var string $_body + * @var string */ private $_body; @@ -91,12 +93,12 @@ class CAS_ProxiedService_Http_Post * @param string $contentType content type * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setContentType ($contentType) + public function setContentType($contentType) { if ($this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set the content type, request already sent.' ); } @@ -110,12 +112,12 @@ public function setContentType ($contentType) * @param string $body body to set * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setBody ($body) + public function setBody($body) { if ($this->hasBeenSent()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set the body, request already sent.' ); } @@ -124,29 +126,27 @@ public function setBody ($body) } /** - * Add any other parts of the request needed by concrete classes + * Add any other parts of the request needed by concrete classes. * - * @param CAS_Request_RequestInterface $request request interface class + * @param RequestInterface $request request interface class * * @return void + * @throws ProxiedServiceException */ - protected function populateRequest (CAS_Request_RequestInterface $request) + protected function populateRequest(RequestInterface $request) { - if (empty($this->_contentType) && !empty($this->_body)) { - throw new CAS_ProxiedService_Exception( - "If you pass a POST body, you must specify a content type via " + if (empty($this->_contentType) && ! empty($this->_body)) { + throw new ProxiedServiceException( + 'If you pass a POST body, you must specify a content type via ' .get_class($this).'->setContentType($contentType).' ); } $request->makePost(); - if (!empty($this->_body)) { + if (! empty($this->_body)) { $request->addHeader('Content-Type: '.$this->_contentType); $request->addHeader('Content-Length: '.strlen($this->_body)); $request->setPostBody($this->_body); } } - - } -?> diff --git a/source/CAS/ProxiedService/Imap.php b/source/CAS/ProxiedService/Imap.php index 847da28c..84c0c95a 100644 --- a/source/CAS/ProxiedService/Imap.php +++ b/source/CAS/ProxiedService/Imap.php @@ -21,30 +21,33 @@ * * @file CAS/ProxiedService/Imap.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService; + +use phpCAS\CAS; +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\ProxyTicketException; + /** - * Provides access to a proxy-authenticated IMAP stream + * Provides access to a proxy-authenticated IMAP stream. * - * @class CAS_ProxiedService_Imap + * @class Imap * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxiedService_Imap -extends CAS_ProxiedService_Abstract +class Imap extends AbstractProxiedService { - /** * The username to send via imap_open. * - * @var string $_username; + * @var string; */ private $_username; @@ -52,13 +55,11 @@ class CAS_ProxiedService_Imap * Constructor. * * @param string $username Username - * - * @return void */ - public function __construct ($username) + public function __construct($username) { - if (!is_string($username) || !strlen($username)) { - throw new CAS_InvalidArgumentException('Invalid username.'); + if (! is_string($username) || ! strlen($username)) { + throw new InvalidArgumentException('Invalid username.'); } $this->_username = $username; @@ -66,7 +67,7 @@ public function __construct ($username) /** * The target service url. - * @var string $_url; + * @var string; */ private $_url; @@ -74,12 +75,12 @@ public function __construct ($username) * Answer a service identifier (URL) for whom we should fetch a proxy ticket. * * @return string - * @throws Exception If no service url is available. + * @throws ProxiedServiceException If no service url is available. */ - public function getServiceUrl () + public function getServiceUrl() { if (empty($this->_url)) { - throw new CAS_ProxiedService_Exception( + throw new ProxiedServiceException( 'No URL set via '.get_class($this).'->getServiceUrl($url).' ); } @@ -97,17 +98,18 @@ public function getServiceUrl () * @param string $url Url to set * * @return void - * @throws CAS_OutOfSequenceException If called after the stream has been opened. + * @throws OutOfSequenceException If called after the stream has been opened. + * @throws InvalidArgumentException */ - public function setServiceUrl ($url) + public function setServiceUrl($url) { if ($this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set the URL, stream already opened.' ); } - if (!is_string($url) || !strlen($url)) { - throw new CAS_InvalidArgumentException('Invalid url.'); + if (! is_string($url) || ! strlen($url)) { + throw new InvalidArgumentException('Invalid url.'); } $this->_url = $url; @@ -116,7 +118,7 @@ public function setServiceUrl ($url) /** * The mailbox to open. See the $mailbox parameter of imap_open(). * - * @var string $_mailbox + * @var string */ private $_mailbox; @@ -126,17 +128,18 @@ public function setServiceUrl ($url) * @param string $mailbox Mailbox to set * * @return void - * @throws CAS_OutOfSequenceException If called after the stream has been opened. + * @throws OutOfSequenceException If called after the stream has been opened. + * @throws InvalidArgumentException */ - public function setMailbox ($mailbox) + public function setMailbox($mailbox) { if ($this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set the mailbox, stream already opened.' ); } - if (!is_string($mailbox) || !strlen($mailbox)) { - throw new CAS_InvalidArgumentException('Invalid mailbox.'); + if (! is_string($mailbox) || ! strlen($mailbox)) { + throw new InvalidArgumentException('Invalid mailbox.'); } $this->_mailbox = $mailbox; @@ -145,7 +148,7 @@ public function setMailbox ($mailbox) /** * A bit mask of options to pass to imap_open() as the $options parameter. * - * @var int $_options + * @var int */ private $_options = null; @@ -156,17 +159,18 @@ public function setMailbox ($mailbox) * @param int $options Options for the stream * * @return void - * @throws CAS_OutOfSequenceException If called after the stream has been opened. + * @throws OutOfSequenceException If called after the stream has been opened. + * @throws InvalidArgumentException */ - public function setOptions ($options) + public function setOptions($options) { if ($this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Cannot set options, stream already opened.' ); } - if (!is_int($options)) { - throw new CAS_InvalidArgumentException('Invalid options.'); + if (! is_int($options)) { + throw new InvalidArgumentException('Invalid options.'); } $this->_options = $options; @@ -178,49 +182,49 @@ public function setOptions ($options) /** * Open the IMAP stream (similar to imap_open()). - * * @return resource Returns an IMAP stream on success - * @throws CAS_OutOfSequenceException If called multiple times. - * @throws CAS_ProxyTicketException If there is a proxy-ticket failure. + * @throws OutOfSequenceException If called multiple times. + * @throws ProxyTicketException If there is a proxy-ticket failure. * The code of the Exception will be one of: - * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE - * PHPCAS_SERVICE_PT_FAILURE - * @throws CAS_ProxiedService_Exception If there is a failure sending the + * CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE + * CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE + * CAS::PHPCAS_SERVICE_PT_FAILURE + * @throws ProxiedServiceException If there is a failure sending the * request to the target service. */ - public function open () + public function open() { if ($this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException('Stream already opened.'); + throw new OutOfSequenceException('Stream already opened.'); } if (empty($this->_mailbox)) { - throw new CAS_ProxiedService_Exception( + throw new ProxiedServiceException( 'You must specify a mailbox via '.get_class($this) .'->setMailbox($mailbox)' ); } - phpCAS::traceBegin(); + CAS::traceBegin(); // Get our proxy ticket and append it to our URL. $this->initializeProxyTicket(); - phpCAS::trace('opening IMAP mailbox `'.$this->_mailbox.'\'...'); + CAS::trace('opening IMAP mailbox `'.$this->_mailbox.'\'...'); $this->_stream = @imap_open( $this->_mailbox, $this->_username, $this->getProxyTicket(), $this->_options ); if ($this->_stream) { - phpCAS::trace('ok'); + CAS::trace('ok'); } else { - phpCAS::trace('could not open mailbox'); + CAS::trace('could not open mailbox'); // @todo add localization integration. - $message = 'IMAP Error: '.$this->_url.' '. var_export(imap_errors(), true); - phpCAS::trace($message); - throw new CAS_ProxiedService_Exception($message); + $message = 'IMAP Error: '.$this->_url.' '.var_export(imap_errors(), true); + CAS::trace($message); + throw new ProxiedServiceException($message); } - phpCAS::traceEnd(); + CAS::traceEnd(); + return $this->_stream; } @@ -229,52 +233,53 @@ public function open () * * @return bool */ - protected function hasBeenOpened () + protected function hasBeenOpened() { - return !empty($this->_stream); + return ! empty($this->_stream); } /********************************************************* * 3. Access the result *********************************************************/ /** - * The IMAP stream + * The IMAP stream. * - * @var resource $_stream + * @var resource */ private $_stream; /** - * Answer the IMAP stream + * Answer the IMAP stream. * * @return resource */ - public function getStream () + public function getStream() { - if (!$this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException( + if (! $this->hasBeenOpened()) { + throw new OutOfSequenceException( 'Cannot access stream, not opened yet.' ); } + return $this->_stream; } /** - * CAS_Client::serviceMail() needs to return the proxy ticket for some reason, + * Client::serviceMail() needs to return the proxy ticket for some reason, * so this method provides access to it. * * @return string - * @throws CAS_OutOfSequenceException If called before the stream has been + * @throws OutOfSequenceException If called before the stream has been * opened. */ - public function getImapProxyTicket () + public function getImapProxyTicket() { - if (!$this->hasBeenOpened()) { - throw new CAS_OutOfSequenceException( + if (! $this->hasBeenOpened()) { + throw new OutOfSequenceException( 'Cannot access errors, stream not opened yet.' ); } + return $this->getProxyTicket(); } } -?> diff --git a/source/CAS/ProxiedService/Exception.php b/source/CAS/ProxiedService/ProxiedServiceException.php similarity index 86% rename from source/CAS/ProxiedService/Exception.php rename to source/CAS/ProxiedService/ProxiedServiceException.php index 5a1e6962..20e2f374 100644 --- a/source/CAS/ProxiedService/Exception.php +++ b/source/CAS/ProxiedService/ProxiedServiceException.php @@ -21,26 +21,25 @@ * * @file CAS/ProxiedService/Exception.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService; + +use Exception; +use phpCAS\CAS\CASExceptionInterface; + /** * An Exception for problems communicating with a proxied service. * - * @class CAS_ProxiedService_Exception + * @class ProxiedServiceException * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxiedService_Exception -extends Exception -implements CAS_Exception +class ProxiedServiceException extends Exception implements CASExceptionInterface { - } -?> diff --git a/source/CAS/ProxiedService/Testable.php b/source/CAS/ProxiedService/Testable.php index 51f07676..24298521 100644 --- a/source/CAS/ProxiedService/Testable.php +++ b/source/CAS/ProxiedService/Testable.php @@ -21,55 +21,54 @@ * * @file CAS/ProxiedService/Testabel.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxiedService; + +use phpCAS\CAS\Client; + /** * This interface defines methods that allow proxy-authenticated service handlers * to be tested in unit tests. * * Classes implementing this interface SHOULD store the CAS_Client passed and - * initialize themselves with that client rather than via the static phpCAS + * initialize themselves with that client rather than via the static CAS * method. For example: * * / ** * * Fetch our proxy ticket. * * / * protected function initializeProxyTicket() { - * // Allow usage of a particular CAS_Client for unit testing. + * // Allow usage of a particular Client for unit testing. * if (is_null($this->casClient)) - * phpCAS::initializeProxiedService($this); + * CAS::initializeProxiedService($this); * else * $this->casClient->initializeProxiedService($this); * } * - * @class CAS_ProxiedService_Testabel + * @class Testable * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_ProxiedService_Testable +interface Testable { - /** - * Use a particular CAS_Client->initializeProxiedService() rather than the - * static phpCAS::initializeProxiedService(). + * Use a particular Client->initializeProxiedService() rather than the + * static CAS::initializeProxiedService(). * * This method should not be called in standard operation, but is needed for unit * testing. * - * @param CAS_Client $casClient Cas client object + * @param Client $casClient Cas client object * * @return void - * @throws CAS_OutOfSequenceException If called after a proxy ticket has + * @throws \phpCAS\CAS\OutOfSequenceException If called after a proxy ticket has * already been initialized/set. */ - public function setCasClient (CAS_Client $casClient); - + public function setCasClient(Client $casClient); } -?> diff --git a/source/CAS/ProxyChain.php b/source/CAS/ProxyChain.php index 2594d141..4bde77c9 100644 --- a/source/CAS/ProxyChain.php +++ b/source/CAS/ProxyChain.php @@ -21,29 +21,29 @@ * * @file CAS/ProxyChain.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + +use phpCAS\CAS; +use phpCAS\CAS\ProxyChain\ProxyChainInterface; + /** * A normal proxy-chain definition that lists each level of the chain as either * a string or regular expression. * - * @class CAS_ProxyChain + * @class ProxyChain * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_ProxyChain -implements CAS_ProxyChain_Interface +class ProxyChain implements ProxyChainInterface { - - protected $chain = array(); + protected $chain = []; /** * A chain is an array of strings or regexp strings that will be matched @@ -53,7 +53,7 @@ class CAS_ProxyChain * down. * Proxies have to be defined in reverse from the service to the user. If a * user hits service A get proxied via B to service C the list of acceptable - * proxies on C would be array(B,A); + * proxies on C would be array(B,A);. * * @param array $chain A chain of proxies */ @@ -79,37 +79,39 @@ public function matches(array $list) $proxy_url = $list[$i]; if (preg_match('/^\/.*\/[ixASUXu]*$/s', $search)) { if (preg_match($search, $proxy_url)) { - phpCAS::trace( - "Found regexp " . $search . " matching " . $proxy_url + CAS::trace( + 'Found regexp '.$search.' matching '.$proxy_url ); } else { - phpCAS::trace( - "No regexp match " . $search . " != " . $proxy_url + CAS::trace( + 'No regexp match '.$search.' != '.$proxy_url ); $mismatch = true; break; } } else { if (strncasecmp($search, $proxy_url, strlen($search)) == 0) { - phpCAS::trace( - "Found string " . $search . " matching " . $proxy_url + CAS::trace( + 'Found string '.$search.' matching '.$proxy_url ); } else { - phpCAS::trace( - "No match " . $search . " != " . $proxy_url + CAS::trace( + 'No match '.$search.' != '.$proxy_url ); $mismatch = true; break; } } } - if (!$mismatch) { - phpCAS::trace("Proxy chain matches"); + if (! $mismatch) { + CAS::trace('Proxy chain matches'); + return true; } } else { - phpCAS::trace("Proxy chain skipped: size mismatch"); + CAS::trace('Proxy chain skipped: size mismatch'); } + return false; } @@ -120,7 +122,7 @@ public function matches(array $list) * * @return bool */ - protected function isSizeValid (array $list) + protected function isSizeValid(array $list) { return (sizeof($this->chain) == sizeof($list)); } diff --git a/source/CAS/ProxyChain/AllowedList.php b/source/CAS/ProxyChain/AllowedList.php index 62d196ab..43487bde 100644 --- a/source/CAS/ProxyChain/AllowedList.php +++ b/source/CAS/ProxyChain/AllowedList.php @@ -21,32 +21,34 @@ * * @file CAS/ProxyChain/AllowedList.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxyChain; + +use phpCAS\CAS; /** * ProxyChain is a container for storing chains of valid proxies that can - * be used to validate proxied requests to a service + * be used to validate proxied requests to a service. * * @class CAS_ProxyChain_AllowedList * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_ProxyChain_AllowedList +class AllowedList { - - private $_chains = array(); + /** + * @var ProxyChainInterface[] + */ + private $_chains = []; /** - * Check whether proxies are allowed by configuration + * Check whether proxies are allowed by configuration. * * @return bool */ @@ -56,19 +58,19 @@ public function isProxyingAllowed() } /** - * Add a chain of proxies to the list of possible chains + * Add a chain of proxies to the list of possible chains. * - * @param CAS_ProxyChain_Interface $chain A chain of proxies + * @param ProxyChainInterface $chain A chain of proxies * * @return void */ - public function allowProxyChain(CAS_ProxyChain_Interface $chain) + public function allowProxyChain(ProxyChainInterface $chain) { $this->_chains[] = $chain; } /** - * Check if the proxies found in the response match the allowed proxies + * Check if the proxies found in the response match the allowed proxies. * * @param array $proxies list of proxies to check * @@ -76,44 +78,48 @@ public function allowProxyChain(CAS_ProxyChain_Interface $chain) */ public function isProxyListAllowed(array $proxies) { - phpCAS::traceBegin(); + CAS::traceBegin(); if (empty($proxies)) { - phpCAS::trace("No proxies were found in the response"); - phpCAS::traceEnd(true); + CAS::trace('No proxies were found in the response'); + CAS::traceEnd(true); + return true; - } elseif (!$this->isProxyingAllowed()) { - phpCAS::trace("Proxies are not allowed"); - phpCAS::traceEnd(false); + } elseif (! $this->isProxyingAllowed()) { + CAS::trace('Proxies are not allowed'); + CAS::traceEnd(false); + return false; } else { $res = $this->contains($proxies); - phpCAS::traceEnd($res); + CAS::traceEnd($res); + return $res; } } /** * Validate the proxies from the proxy ticket validation against the - * chains that were definded. + * chains that were defined. * * @param array $list List of proxies from the proxy ticket validation. * - * @return if any chain fully matches the supplied list + * @return bool if any chain fully matches the supplied list */ public function contains(array $list) { - phpCAS::traceBegin(); + CAS::traceBegin(); $count = 0; foreach ($this->_chains as $chain) { - phpCAS::trace("Checking chain ". $count++); + CAS::trace('Checking chain '.$count++); if ($chain->matches($list)) { - phpCAS::traceEnd(true); + CAS::traceEnd(true); + return true; } } - phpCAS::trace("No proxy chain matches."); - phpCAS::traceEnd(false); + CAS::trace('No proxy chain matches.'); + CAS::traceEnd(false); + return false; } } -?> diff --git a/source/CAS/ProxyChain/Any.php b/source/CAS/ProxyChain/Any.php index 0cd92f74..2c4bfecd 100644 --- a/source/CAS/ProxyChain/Any.php +++ b/source/CAS/ProxyChain/Any.php @@ -21,33 +21,33 @@ * * @file CAS/ProxyChain/Any.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxyChain; + +use phpCAS\CAS; + /** * A proxy-chain definition that will match any list of proxies. * - * Use this class for quick testing or in certain production screnarios you + * Use this class for quick testing or in certain production scenarios you * might want to allow allow any other valid service to proxy your service. * * THIS CLASS IS HOWEVER NOT RECOMMENDED FOR PRODUCTION AND HAS SECURITY * IMPLICATIONS: YOU ARE ALLOWING ANY SERVICE TO ACT ON BEHALF OF A USER * ON THIS SERVICE. * - * @class CAS_ProxyChain_Any + * @class Any * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxyChain_Any -implements CAS_ProxyChain_Interface +class Any implements ProxyChainInterface { - /** * Match a list of proxies. * @@ -57,8 +57,8 @@ class CAS_ProxyChain_Any */ public function matches(array $list) { - phpCAS::trace("Using CAS_ProxyChain_Any. No proxy validation is performed."); + CAS::trace('Using \phpCAS\CAS\ProxyChain\Any. No proxy validation is performed.'); + return true; } - } diff --git a/source/CAS/ProxyChain/Interface.php b/source/CAS/ProxyChain/ProxyChainInterface.php similarity index 95% rename from source/CAS/ProxyChain/Interface.php rename to source/CAS/ProxyChain/ProxyChainInterface.php index d247115d..cc015b0e 100644 --- a/source/CAS/ProxyChain/Interface.php +++ b/source/CAS/ProxyChain/ProxyChainInterface.php @@ -21,26 +21,25 @@ * * @file CAS/ProxyChain/Interface.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxyChain; + /** * An interface for classes that define a list of allowed proxies in front of * the current application. * * @class CAS_ProxyChain_Interface * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_ProxyChain_Interface +interface ProxyChainInterface { - /** * Match a list of proxies. * @@ -49,5 +48,4 @@ interface CAS_ProxyChain_Interface * @return bool */ public function matches(array $list); - -} \ No newline at end of file +} diff --git a/source/CAS/ProxyChain/Trusted.php b/source/CAS/ProxyChain/Trusted.php index 7fa61296..cd3d635a 100644 --- a/source/CAS/ProxyChain/Trusted.php +++ b/source/CAS/ProxyChain/Trusted.php @@ -21,29 +21,28 @@ * * @file CAS/ProxyChain/Trusted.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\ProxyChain; + +use phpCAS\CAS\ProxyChain; + /** * A proxy-chain definition that defines a chain up to a trusted proxy and - * delegates the resposibility of validating the rest of the chain to that + * delegates the responsibility of validating the rest of the chain to that * trusted proxy. * * @class CAS_ProxyChain_Trusted * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxyChain_Trusted -extends CAS_ProxyChain -implements CAS_ProxyChain_Interface +class Trusted extends ProxyChain implements ProxyChainInterface { - /** * Validate the size of the the list as compared to our chain. * @@ -51,9 +50,20 @@ class CAS_ProxyChain_Trusted * * @return bool */ - protected function isSizeValid (array $list) + protected function isSizeValid(array $list) { return (sizeof($this->chain) <= sizeof($list)); } + /** + * Match a list of proxies. + * + * @param array $list The list of proxies in front of this service. + * + * @return bool + */ + public function matches(array $list) + { + return parent::matches($list); + } } diff --git a/source/CAS/ProxyTicketException.php b/source/CAS/ProxyTicketException.php index 72330466..fee3e583 100644 --- a/source/CAS/ProxyTicketException.php +++ b/source/CAS/ProxyTicketException.php @@ -21,48 +21,45 @@ * * @class CAS/ProxyTicketException.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS - * */ +namespace phpCAS\CAS; + +use BadMethodCallException; +use phpCAS\CAS; + /** * An Exception for errors related to fetching or validating proxy tickets. * - * @class CAS_ProxyTicketException + * @class ProxyTicketException * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_ProxyTicketException -extends BadMethodCallException -implements CAS_Exception +class ProxyTicketException extends BadMethodCallException implements CASExceptionInterface { - /** - * Constructor + * Constructor. * * @param string $message Message text * @param int $code Error code - * - * @return void */ - public function __construct ($message, $code = PHPCAS_SERVICE_PT_FAILURE) + public function __construct($message, $code = CAS::PHPCAS_SERVICE_PT_FAILURE) { // Warn if the code is not in our allowed list - $ptCodes = array( - PHPCAS_SERVICE_PT_FAILURE, - PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, - PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, - ); - if (!in_array($code, $ptCodes)) { + $ptCodes = [ + CAS::PHPCAS_SERVICE_PT_FAILURE, + CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, + CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + ]; + if (! in_array($code, $ptCodes)) { trigger_error( 'Invalid code '.$code - .' passed. Must be one of PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, or PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE.' + .' passed. Must be one of CAS::PHPCAS_SERVICE_PT_FAILURE, CAS::PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, or CAS::PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE.' ); } diff --git a/source/CAS/Request/AbstractRequest.php b/source/CAS/Request/AbstractRequest.php index f3dd28b7..d9e751ab 100644 --- a/source/CAS/Request/AbstractRequest.php +++ b/source/CAS/Request/AbstractRequest.php @@ -21,35 +21,35 @@ * * @file CAS/Request/AbstractRequest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use phpCAS\CAS\OutOfSequenceException; + /** - * Provides support for performing web-requests via curl + * Provides support for performing web-requests via curl. * - * @class CAS_Request_AbstractRequest + * @class AbstractRequest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -abstract class CAS_Request_AbstractRequest -implements CAS_Request_RequestInterface +abstract class AbstractRequest implements RequestInterface { - protected $url = null; - protected $cookies = array(); - protected $headers = array(); + protected $cookies = []; + protected $headers = []; protected $isPost = false; protected $postBody = null; protected $caCertPath = null; protected $validateCN = true; private $_sent = false; - private $_responseHeaders = array(); + private $_responseHeaders = []; private $_responseBody = null; private $_errorMessage = ''; @@ -58,17 +58,17 @@ abstract class CAS_Request_AbstractRequest *********************************************************/ /** - * Set the URL of the Request + * Set the URL of the Request. * * @param string $url Url to set * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setUrl ($url) + public function setUrl($url) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -83,12 +83,12 @@ public function setUrl ($url) * @param string $value value of entry * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addCookie ($name, $value) + public function addCookie($name, $value) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -99,17 +99,17 @@ public function addCookie ($name, $value) /** * Add an array of cookies to the request. * The cookie array is of the form - * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2') + * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2'). * * @param array $cookies cookies to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addCookies (array $cookies) + public function addCookies(array $cookies) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -123,12 +123,12 @@ public function addCookies (array $cookies) * @param string $header Header to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addHeader ($header) + public function addHeader($header) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -142,12 +142,12 @@ public function addHeader ($header) * @param array $headers headers to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addHeaders (array $headers) + public function addHeaders(array $headers) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -159,12 +159,12 @@ public function addHeaders (array $headers) * Make the request a POST request rather than the default GET request. * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function makePost () + public function makePost() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -173,22 +173,22 @@ public function makePost () } /** - * Add a POST body to the request + * Add a POST body to the request. * * @param string $body body to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setPostBody ($body) + public function setPostBody($body) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } - if (!$this->isPost) { - throw new CAS_OutOfSequenceException( + if (! $this->isPost) { + throw new OutOfSequenceException( 'Cannot add a POST body to a GET request, use makePost() first.' ); } @@ -200,15 +200,15 @@ public function setPostBody ($body) * Specify the path to an SSL CA certificate to validate the server with. * * @param string $caCertPath path to cert - * @param bool $validate_cn valdiate CN of certificate + * @param bool $validate_cn validate CN of certificate * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setSslCaCert ($caCertPath,$validate_cn=true) + public function setSslCaCert($caCertPath, $validate_cn = true) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } @@ -224,21 +224,22 @@ public function setSslCaCert ($caCertPath,$validate_cn=true) * Perform the request. * * @return bool TRUE on success, FALSE on failure. - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws OutOfSequenceException If called multiple times. */ - public function send () + public function send() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot send again.' ); } - if (is_null($this->url) || !$this->url) { - throw new CAS_OutOfSequenceException( + if (is_null($this->url) || ! $this->url) { + throw new OutOfSequenceException( 'A url must be specified via setUrl() before the request can be sent.' ); } $this->_sent = true; + return $this->sendRequest(); } @@ -247,7 +248,7 @@ public function send () * * @return bool TRUE on success, FALSE on failure. */ - abstract protected function sendRequest (); + abstract protected function sendRequest(); /** * Store the response headers. @@ -256,7 +257,7 @@ abstract protected function sendRequest (); * * @return void */ - protected function storeResponseHeaders (array $headers) + protected function storeResponseHeaders(array $headers) { $this->_responseHeaders = array_merge($this->_responseHeaders, $headers); } @@ -268,7 +269,7 @@ protected function storeResponseHeaders (array $headers) * * @return void */ - protected function storeResponseHeader ($header) + protected function storeResponseHeader($header) { $this->_responseHeaders[] = $header; } @@ -280,7 +281,7 @@ protected function storeResponseHeader ($header) * * @return void */ - protected function storeResponseBody ($body) + protected function storeResponseBody($body) { $this->_responseBody = $body; } @@ -292,7 +293,7 @@ protected function storeResponseBody ($body) * * @return void */ - protected function storeErrorMessage ($message) + protected function storeErrorMessage($message) { $this->_errorMessage .= $message; } @@ -305,38 +306,40 @@ protected function storeErrorMessage ($message) * Answer the headers of the response. * * @return array An array of header strings. - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getResponseHeaders () + public function getResponseHeaders() { - if (!$this->_sent) { - throw new CAS_OutOfSequenceException( + if (! $this->_sent) { + throw new OutOfSequenceException( 'Request has not been sent yet. Cannot '.__METHOD__ ); } + return $this->_responseHeaders; } /** - * Answer HTTP status code of the response + * Answer HTTP status code of the response. * * @return int - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. + * @throws RequestException */ - public function getResponseStatusCode () + public function getResponseStatusCode() { - if (!$this->_sent) { - throw new CAS_OutOfSequenceException( + if (! $this->_sent) { + throw new OutOfSequenceException( 'Request has not been sent yet. Cannot '.__METHOD__ ); } - if (!preg_match( + if (! preg_match( '/HTTP\/[0-9.]+\s+([0-9]+)\s*(.*)/', $this->_responseHeaders[0], $matches ) ) { - throw new CAS_Request_Exception( + throw new RequestException( 'Bad response, no status code was found in the first line.' ); } @@ -348,12 +351,12 @@ public function getResponseStatusCode () * Answer the body of response. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getResponseBody () + public function getResponseBody() { - if (!$this->_sent) { - throw new CAS_OutOfSequenceException( + if (! $this->_sent) { + throw new OutOfSequenceException( 'Request has not been sent yet. Cannot '.__METHOD__ ); } @@ -365,15 +368,16 @@ public function getResponseBody () * Answer a message describing any errors if the request failed. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getErrorMessage () + public function getErrorMessage() { - if (!$this->_sent) { - throw new CAS_OutOfSequenceException( + if (! $this->_sent) { + throw new OutOfSequenceException( 'Request has not been sent yet. Cannot '.__METHOD__ ); } + return $this->_errorMessage; } } diff --git a/source/CAS/Request/CurlMultiRequest.php b/source/CAS/Request/CurlMultiRequest.php index 410aba0e..1eab09aa 100644 --- a/source/CAS/Request/CurlMultiRequest.php +++ b/source/CAS/Request/CurlMultiRequest.php @@ -21,28 +21,30 @@ * * @file CAS/Request/AbstractRequest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; + /** * This interface defines a class library for performing multiple web requests * in batches. Implementations of this interface may perform requests serially * or in parallel. * - * @class CAS_Request_CurlMultiRequest + * @class CurlMultiRequest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Request_CurlMultiRequest -implements CAS_Request_MultiRequestInterface +class CurlMultiRequest implements MultiRequestInterface { - private $_requests = array(); + private $_requests = []; private $_sent = false; /********************************************************* @@ -54,22 +56,22 @@ class CAS_Request_CurlMultiRequest * Note, implementations will likely restrict requests to their own concrete * class hierarchy. * - * @param CAS_Request_RequestInterface $request reqest to add + * @param RequestInterface $request request to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. - * @throws CAS_InvalidArgumentException If passed a Request of the wrong - * implmentation. + * @throws OutOfSequenceException If called after the Request has been sent. + * @throws InvalidArgumentException If passed a Request of the wrong + * implementation. */ - public function addRequest (CAS_Request_RequestInterface $request) + public function addRequest(RequestInterface $request) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } - if (!$request instanceof CAS_Request_CurlRequest) { - throw new CAS_InvalidArgumentException( + if (! $request instanceof CurlRequest) { + throw new InvalidArgumentException( 'As a CAS_Request_CurlMultiRequest, I can only work with CAS_Request_CurlRequest objects.' ); } @@ -85,10 +87,11 @@ public function addRequest (CAS_Request_RequestInterface $request) public function getNumRequests() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot '.__METHOD__ ); } + return count($this->_requests); } @@ -98,20 +101,20 @@ public function getNumRequests() /** * Perform the request. After sending, all requests will have their - * responses poulated. + * responses populated. * * @return bool TRUE on success, FALSE on failure. - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws OutOfSequenceException If called multiple times. */ - public function send () + public function send() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot send again.' ); } - if (!count($this->_requests)) { - throw new CAS_OutOfSequenceException( + if (! count($this->_requests)) { + throw new OutOfSequenceException( 'At least one request must be added via addRequest() before the multi-request can be sent.' ); } @@ -119,7 +122,7 @@ public function send () $this->_sent = true; // Initialize our handles and configure all requests. - $handles = array(); + $handles = []; $multiHandle = curl_multi_init(); foreach ($this->_requests as $i => $request) { $handle = $request->_initAndConfigure(); diff --git a/source/CAS/Request/CurlRequest.php b/source/CAS/Request/CurlRequest.php index dd866dc8..1f4f452f 100644 --- a/source/CAS/Request/CurlRequest.php +++ b/source/CAS/Request/CurlRequest.php @@ -21,48 +21,49 @@ * * @file CAS/Request/CurlRequest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use phpCAS\CAS; +use phpCAS\CAS\OutOfSequenceException; + /** - * Provides support for performing web-requests via curl + * Provides support for performing web-requests via curl. * - * @class CAS_Request_CurlRequest + * @class CurlRequest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Request_CurlRequest -extends CAS_Request_AbstractRequest -implements CAS_Request_RequestInterface +class CurlRequest extends AbstractRequest implements RequestInterface { - /** - * Set additional curl options + * Set additional curl options. * * @param array $options option to set * * @return void */ - public function setCurlOptions (array $options) + public function setCurlOptions(array $options) { $this->_curlOptions = $options; } - private $_curlOptions = array(); + + private $_curlOptions = []; /** * Send the request and store the results. * * @return bool true on success, false on failure. */ - protected function sendRequest () + protected function sendRequest() { - phpCAS::traceBegin(); + CAS::traceBegin(); /********************************************************* * initialize the CURL session @@ -73,22 +74,22 @@ protected function sendRequest () * Perform the query *********************************************************/ $buf = curl_exec($ch); - if ( $buf === false ) { - phpCAS::trace('curl_exec() failed'); + if ($buf === false) { + CAS::trace('curl_exec() failed'); $this->storeErrorMessage( 'CURL error #'.curl_errno($ch).': '.curl_error($ch) ); $res = false; } else { $this->storeResponseBody($buf); - phpCAS::trace("Response Body: \n".$buf."\n"); + CAS::trace("Response Body: \n".$buf."\n"); $res = true; - } // close the CURL session curl_close($ch); - phpCAS::traceEnd($res); + CAS::traceEnd($res); + return $res; } @@ -107,7 +108,7 @@ private function _initAndConfigure() $ch = curl_init($this->url); if (version_compare(PHP_VERSION, '5.1.3', '>=')) { - //only avaible in php5 + //only available in php5 curl_setopt_array($ch, $this->_curlOptions); } else { foreach ($this->_curlOptions as $key => $value) { @@ -126,7 +127,7 @@ private function _initAndConfigure() } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_CAINFO, $this->caCertPath); - phpCAS::trace('CURL: Set CURLOPT_CAINFO ' . $this->caCertPath); + CAS::trace('CURL: Set CURLOPT_CAINFO '.$this->caCertPath); } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); @@ -139,13 +140,13 @@ private function _initAndConfigure() curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the HTTP header with a callback - curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, '_curlReadHeaders')); + curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, '_curlReadHeaders']); /********************************************************* * Add cookie headers to our request. *********************************************************/ if (count($this->cookies)) { - $cookieStrings = array(); + $cookieStrings = []; foreach ($this->cookies as $name => $val) { $cookieStrings[] = $name.'='.$val; } @@ -175,11 +176,11 @@ private function _initAndConfigure() * This method should NOT be used outside of the CurlRequest or the * CurlMultiRequest. * - * @param string $body body to stor + * @param string $body body to store * * @return void */ - private function _storeResponseBody ($body) + private function _storeResponseBody($body) { $this->storeResponseBody($body); } @@ -187,14 +188,176 @@ private function _storeResponseBody ($body) /** * Internal method for capturing the headers from a curl request. * - * @param handle $ch handle of curl - * @param string $header header + * @param resource $ch handle of curl + * @param string $header header * - * @return void + * @return int */ - private function _curlReadHeaders ($ch, $header) + private function _curlReadHeaders($ch, $header) { $this->storeResponseHeader($header); + return strlen($header); } + + /** + * Set the URL of the Request. + * + * @param string $url url to set + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setUrl($url) + { + parent::setUrl($url); + } + + /** + * Add a cookie to the request. + * + * @param string $name name of cookie + * @param string $value value of cookie + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addCookie($name, $value) + { + parent::addCookie($name, $value); + } + + /** + * Add an array of cookies to the request. + * The cookie array is of the form + * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2'). + * + * @param array $cookies cookies to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addCookies(array $cookies) + { + // TODO: Implement addCookies() method. + } + + /** + * Add a header string to the request. + * + * @param string $header header to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addHeader($header) + { + // TODO: Implement addHeader() method. + } + + /** + * Add an array of header strings to the request. + * + * @param array $headers headers to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addHeaders(array $headers) + { + // TODO: Implement addHeaders() method. + } + + /** + * Make the request a POST request rather than the default GET request. + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function makePost() + { + // TODO: Implement makePost() method. + } + + /** + * Add a POST body to the request. + * + * @param string $body body to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setPostBody($body) + { + // TODO: Implement setPostBody() method. + } + + /** + * Specify the path to an SSL CA certificate to validate the server with. + * + * @param string $caCertPath path to cert file + * @param bool $validate_cn validate CN of SSL certificate + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setSslCaCert($caCertPath, $validate_cn = true) + { + // TODO: Implement setSslCaCert() method. + } + + /** + * Perform the request. + * + * @return bool TRUE on success, FALSE on failure. + * @throws OutOfSequenceException If called multiple times. + */ + public function send() + { + // TODO: Implement send() method. + } + + /** + * Answer the headers of the response. + * + * @return array An array of header strings. + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseHeaders() + { + // TODO: Implement getResponseHeaders() method. + } + + /** + * Answer HTTP status code of the response. + * + * @return int + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseStatusCode() + { + // TODO: Implement getResponseStatusCode() method. + } + + /** + * Answer the body of response. + * + * @return string + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseBody() + { + // TODO: Implement getResponseBody() method. + } + + /** + * Answer a message describing any errors if the request failed. + * + * @return string + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getErrorMessage() + { + // TODO: Implement getErrorMessage() method. + } } diff --git a/source/CAS/Request/MultiRequestInterface.php b/source/CAS/Request/MultiRequestInterface.php index abc44868..e13cccf3 100644 --- a/source/CAS/Request/MultiRequestInterface.php +++ b/source/CAS/Request/MultiRequestInterface.php @@ -21,27 +21,29 @@ * * @file CAS/Request/MultiRequestInterface.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; + /** * This interface defines a class library for performing multiple web requests * in batches. Implementations of this interface may perform requests serially * or in parallel. * - * @class CAS_Request_MultiRequestInterface + * @class MultiRequestInterface * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_Request_MultiRequestInterface +interface MultiRequestInterface { - /********************************************************* * Add Requests *********************************************************/ @@ -51,22 +53,22 @@ interface CAS_Request_MultiRequestInterface * Note, implementations will likely restrict requests to their own concrete * class hierarchy. * - * @param CAS_Request_RequestInterface $request request interface + * @param RequestInterface $request request interface * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been - * sent. - * @throws CAS_InvalidArgumentException If passed a Request of the wrong - * implmentation. + * @throws OutOfSequenceException If called after the Request has been + * sent. + * @throws InvalidArgumentException If passed a Request of the wrong + * implementation. */ - public function addRequest (CAS_Request_RequestInterface $request); + public function addRequest(RequestInterface $request); /** * Retrieve the number of requests added to this batch. * * @return number of request elements */ - public function getNumRequests (); + public function getNumRequests(); /********************************************************* * 2. Send the Request @@ -74,10 +76,10 @@ public function getNumRequests (); /** * Perform the request. After sending, all requests will have their - * responses poulated. + * responses populated. * * @return bool TRUE on success, FALSE on failure. - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws OutOfSequenceException If called multiple times. */ - public function send (); + public function send(); } diff --git a/source/CAS/Request/Exception.php b/source/CAS/Request/RequestException.php similarity index 84% rename from source/CAS/Request/Exception.php rename to source/CAS/Request/RequestException.php index 14ff3c6b..cdb7d063 100644 --- a/source/CAS/Request/Exception.php +++ b/source/CAS/Request/RequestException.php @@ -21,25 +21,25 @@ * * @file CAS/Request/Exception.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use Exception; +use phpCAS\CAS\CASExceptionInterface; + /** - * An Exception for problems performing requests + * An Exception for problems performing requests. * - * @class CAS_Request_Exception + * @class Exception * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Request_Exception -extends Exception -implements CAS_Exception +class RequestException extends Exception implements CASExceptionInterface { - } diff --git a/source/CAS/Request/RequestInterface.php b/source/CAS/Request/RequestInterface.php index cc11ba43..31bb6c65 100644 --- a/source/CAS/Request/RequestInterface.php +++ b/source/CAS/Request/RequestInterface.php @@ -21,38 +21,39 @@ * * @file CAS/Request/RequestInterface.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Request; + +use phpCAS\CAS\OutOfSequenceException; + /** * This interface defines a class library for performing web requests. * - * @class CAS_Request_RequestInterface + * @class RequestInterface * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_Request_RequestInterface +interface RequestInterface { - /********************************************************* * Configure the Request *********************************************************/ /** - * Set the URL of the Request + * Set the URL of the Request. * * @param string $url url to set * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setUrl ($url); + public function setUrl($url); /** * Add a cookie to the request. @@ -61,21 +62,21 @@ public function setUrl ($url); * @param string $value value of cookie * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addCookie ($name, $value); + public function addCookie($name, $value); /** * Add an array of cookies to the request. * The cookie array is of the form - * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2') + * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2'). * * @param array $cookies cookies to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addCookies (array $cookies); + public function addCookies(array $cookies); /** * Add a header string to the request. @@ -83,9 +84,9 @@ public function addCookies (array $cookies); * @param string $header header to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addHeader ($header); + public function addHeader($header); /** * Add an array of header strings to the request. @@ -93,41 +94,38 @@ public function addHeader ($header); * @param array $headers headers to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function addHeaders (array $headers); + public function addHeaders(array $headers); /** * Make the request a POST request rather than the default GET request. * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function makePost (); + public function makePost(); /** - * Add a POST body to the request + * Add a POST body to the request. * * @param string $body body to add * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setPostBody ($body); - + public function setPostBody($body); /** * Specify the path to an SSL CA certificate to validate the server with. * * @param string $caCertPath path to cert file - * @param boolean $validate_cn validate CN of SSL certificate + * @param bool $validate_cn validate CN of SSL certificate * * @return void - * @throws CAS_OutOfSequenceException If called after the Request has been sent. + * @throws OutOfSequenceException If called after the Request has been sent. */ - public function setSslCaCert ($caCertPath, $validate_cn = true); - - + public function setSslCaCert($caCertPath, $validate_cn = true); /********************************************************* * 2. Send the Request @@ -137,9 +135,9 @@ public function setSslCaCert ($caCertPath, $validate_cn = true); * Perform the request. * * @return bool TRUE on success, FALSE on failure. - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws OutOfSequenceException If called multiple times. */ - public function send (); + public function send(); /********************************************************* * 3. Access the response @@ -149,31 +147,31 @@ public function send (); * Answer the headers of the response. * * @return array An array of header strings. - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getResponseHeaders (); + public function getResponseHeaders(); /** - * Answer HTTP status code of the response + * Answer HTTP status code of the response. * * @return int - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getResponseStatusCode (); + public function getResponseStatusCode(); /** * Answer the body of response. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getResponseBody (); + public function getResponseBody(); /** * Answer a message describing any errors if the request failed. * * @return string - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. */ - public function getErrorMessage (); + public function getErrorMessage(); } diff --git a/source/CAS/TestHarness/DummyRequest.php b/source/CAS/TestHarness/DummyRequest.php new file mode 100755 index 00000000..a51f4949 --- /dev/null +++ b/source/CAS/TestHarness/DummyRequest.php @@ -0,0 +1,288 @@ + + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ + +namespace phpCAS\CAS\TestHarness; + +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\Request\AbstractRequest; +use phpCAS\CAS\Request\RequestInterface; + +/** + * Provides support for performing dummy web-requests. + * + * @class CAS_TestHarness_DummyRequest + * @category Authentication + * @author Adam Franco + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ +class DummyRequest extends AbstractRequest implements RequestInterface +{ + private static $_responses = []; + + /** + * Configure a URL/Response that the test harness will respond to. + * + * @param ResponseInterface $response response interface + * + * @return void + */ + public static function addResponse( + ResponseInterface $response + ) { + self::$_responses[] = $response; + } + + /** + * Clear out the URLs/Responses that the test harness will respond to. + * + * @return void + */ + public static function clearResponses() + { + self::$_responses = []; + } + + /** + * Send the request and store the results. + * + * @return bool TRUE on success, FALSE on failure. + */ + protected function sendRequest() + { + foreach (self::$_responses as $response) { + if ($response->matchesUrl($this->url)) { + if (! $response->validateUrl($this->url)) { + $this->storeErrorMessage('Validation of url failed.'); + + return false; + } + if (! $response->validateRequestHeaders($this->headers)) { + $this->storeErrorMessage('Validation of headers failed.'); + + return false; + } + if (! $response->validateRequestCookies($this->cookies)) { + $this->storeErrorMessage('Validation of cookies failed.'); + + return false; + } + if (! $response->validateRequestIsPost($this->isPost)) { + $this->storeErrorMessage( + 'Validation of GET/POST type failed.' + ); + + return false; + } + if (! $response->validatePostBody($this->postBody)) { + $this->storeErrorMessage('Validation of POST body failed.'); + + return false; + } + if (! $response->validateCaCert($this->caCertPath)) { + $this->storeErrorMessage('Validation of CA cert failed.'); + + return false; + } + + $this->storeResponseHeaders($response->getResponseHeaders()); + $this->storeResponseBody($response->getResponseBody()); + + return true; + } + } + // print_r("\n404 URL ".$this->url." not found in test harness.\n"); + + $this->storeErrorMessage( + '404 URL '.$this->url.' not found in test harness.' + ); + + return false; + } + + /** + * Set the URL of the Request. + * + * @param string $url url to set + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setUrl($url) + { + parent::setUrl($url); + } + + /** + * Add a cookie to the request. + * + * @param string $name name of cookie + * @param string $value value of cookie + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addCookie($name, $value) + { + parent::addCookie($name, $value); + } + + /** + * Add an array of cookies to the request. + * The cookie array is of the form + * array('cookie_name' => 'cookie_value', 'cookie_name2' => cookie_value2'). + * + * @param array $cookies cookies to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addCookies(array $cookies) + { + parent::addCookies($cookies); + } + + /** + * Add a header string to the request. + * + * @param string $header header to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addHeader($header) + { + parent::addHeader($header); + } + + /** + * Add an array of header strings to the request. + * + * @param array $headers headers to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function addHeaders(array $headers) + { + parent::addHeaders($headers); + } + + /** + * Make the request a POST request rather than the default GET request. + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function makePost() + { + parent::makePost(); + } + + /** + * Add a POST body to the request. + * + * @param string $body body to add + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setPostBody($body) + { + parent::setPostBody($body); + } + + /** + * Specify the path to an SSL CA certificate to validate the server with. + * + * @param string $caCertPath path to cert file + * @param bool $validate_cn validate CN of SSL certificate + * + * @return void + * @throws OutOfSequenceException If called after the Request has been sent. + */ + public function setSslCaCert($caCertPath, $validate_cn = true) + { + parent::setSslCaCert($caCertPath, $validate_cn); + } + + /** + * Perform the request. + * + * @return bool TRUE on success, FALSE on failure. + * @throws OutOfSequenceException If called multiple times. + */ + public function send() + { + return parent::send(); + } + + /** + * Answer the headers of the response. + * + * @return array An array of header strings. + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseHeaders() + { + return parent::getResponseHeaders(); + } + + /** + * Answer HTTP status code of the response. + * + * @return int + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseStatusCode() + { + return parent::getResponseStatusCode(); + } + + /** + * Answer the body of response. + * + * @return string + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getResponseBody() + { + return parent::getResponseBody(); + } + + /** + * Answer a message describing any errors if the request failed. + * + * @return string + * @throws OutOfSequenceException If called before the Request has been sent. + */ + public function getErrorMessage() + { + return parent::getErrorMessage(); + } +} diff --git a/source/CAS/TypeMismatchException.php b/source/CAS/TypeMismatchException.php index 4a13c2df..2b89e1db 100644 --- a/source/CAS/TypeMismatchException.php +++ b/source/CAS/TypeMismatchException.php @@ -19,26 +19,25 @@ * * PHP Version 5 * - * @file CAS/InvalidArgumentException.php + * @file CAS/TypeMismatchException.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS; + /** * Exception that denotes invalid arguments were passed. * - * @class CAS_InvalidArgumentException + * @class TypeMismatchException * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_TypeMismatchException -extends CAS_InvalidArgumentException +class TypeMismatchException extends InvalidArgumentException { /** * Constructor, provides a nice message. @@ -47,12 +46,14 @@ class CAS_TypeMismatchException * @param string $argumentName Argument Name * @param string $type Type * @param string $message Error Message - * @param integer $code Code - * - * @return void + * @param int $code Code */ - public function __construct ( - $argument, $argumentName, $type, $message = '', $code = 0 + public function __construct( + $argument, + $argumentName, + $type, + $message = '', + $code = 0 ) { if (is_object($argument)) { $foundType = get_class($argument).' object'; @@ -62,9 +63,8 @@ public function __construct ( parent::__construct( 'type mismatched for parameter ' - . $argumentName . ' (should be \'' . $type .' \'), ' - . $foundType . ' given. ' . $message, $code + .$argumentName.' (should be \''.$type.' \'), ' + .$foundType.' given. '.$message, $code ); } } -?> diff --git a/test/CAS/TestHarness/BasicResponse.php b/test/CAS/TestHarness/BasicResponse.php index afcfc39d..849ecb99 100755 --- a/test/CAS/TestHarness/BasicResponse.php +++ b/test/CAS/TestHarness/BasicResponse.php @@ -21,39 +21,41 @@ * * @file CAS/TestHarness/BasicResponse * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\TestHarness; +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\Request\RequestException; + /** * The BasicResponse allows tests to dynamically create a response that can be used * in unit tests. * - * @class CAS_TestHarness_BasicResponse + * @class BasicResponse * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_TestHarness_BasicResponse implements CAS_TestHarness_ResponseInterface +class BasicResponse implements ResponseInterface { protected $scheme = 'http'; protected $host = null; protected $port = null; protected $path = '/'; - protected $queryParams = array(); - protected $responseHeaders = array(); + protected $sent = false; + protected $queryParams = []; + protected $responseHeaders = []; protected $responseBody = ''; protected $verifyIsPost = null; protected $postBodyToMatch = null; - protected $headersToHave = array(); - protected $headersToNotHave = array(); - protected $cookiesToHave = array(); - protected $cookiesToNotHave = array(); + protected $headersToHave = []; + protected $headersToNotHave = []; + protected $cookiesToHave = []; + protected $cookiesToNotHave = []; protected $certPathToMatch = null; protected $caCertPathToMatch = null; @@ -67,9 +69,7 @@ class CAS_TestHarness_BasicResponse implements CAS_TestHarness_ResponseInterface * @param string $scheme 'http' or 'https' * @param string $host Hostname * @param string $path Path - * @param integer $port Portnumber - * - * @return void + * @param int $port Port number */ public function __construct($scheme, $host, $path, $port = null) { @@ -82,7 +82,7 @@ public function __construct($scheme, $host, $path, $port = null) /** * Add query parameters that must exist for the response to match a URL. * - * @param array $queryParams Query paremeters + * @param array $queryParams Query parameters * * @return void */ @@ -104,7 +104,7 @@ public function setResponseHeaders(array $responseHeaders) } /** - * Set the response body to return + * Set the response body to return. * * @param string $responseBody body to return * @@ -148,7 +148,7 @@ public function ensurePostBodyEquals($postBodyToMatch) } /** - * Ensure that the request has a given header string + * Ensure that the request has a given header string. * * @param string $header header that the request must match * @@ -160,7 +160,7 @@ public function ensureHasHeader($header) } /** - * Ensure that the request does not have a given header string + * Ensure that the request does not have a given header string. * * @param string $header header the must not match * @@ -172,10 +172,10 @@ public function ensureDoesNotHaveHeader($header) } /** - * Ensure that the request has a given cookie + * Ensure that the request has a given cookie. * * @param string $name name of cookie - * @param string $value If null, the presense of the cookie will be checked, + * @param string $value If null, the presence of the cookie will be checked, * but not its value. * * @return void @@ -186,7 +186,7 @@ public function ensureHasCookie($name, $value = null) } /** - * Ensure that the request does not have a given cookie + * Ensure that the request does not have a given cookie. * * @param string $name name of cookie * @@ -194,7 +194,7 @@ public function ensureHasCookie($name, $value = null) */ public function ensureDoesNotHaveCookie($name) { - $this->cookiesNotToHave[] = $name; + $this->cookiesToNotHave[] = $name; } /** @@ -267,13 +267,13 @@ public function matchesUrl($url) } if (count($this->queryParams)) { - if (!isset($parts['query'])) { + if (! isset($parts['query'])) { return false; } parse_str($parts['query'], $query); foreach ($this->queryParams as $name => $value) { - if (!isset($query[$name])) { + if (! isset($query[$name])) { return false; } if ($query[$name] != $value) { @@ -296,25 +296,26 @@ public function getResponseHeaders() } /** - * Answer HTTP status code of the response + * Answer HTTP status code of the response. * * @return int - * @throws CAS_OutOfSequenceException If called before the Request has been sent. + * @throws OutOfSequenceException If called before the Request has been sent. + * @throws RequestException */ public function getResponseStatusCode() { - if (!$this->sent) { - throw new CAS_OutOfSequenceException( - 'Request has not been sent yet. Cannot ' . __METHOD__ + if (! $this->sent) { + throw new OutOfSequenceException( + 'Request has not been sent yet. Cannot '.__METHOD__ ); } - if (!preg_match( + if (! preg_match( '/HTTP\/[0-9.]+\s+([0-9]+)\s*(.*)/', $this->responseHeaders[0], $matches ) ) { - throw new CAS_Request_Exception( - "Bad response, no status code was found in the first line." + throw new RequestException( + 'Bad response, no status code was found in the first line.' ); } @@ -322,11 +323,10 @@ public function getResponseStatusCode() } /** - * Answer the response body + * Answer the response body. * * @return string */ - public function getResponseBody() { return $this->responseBody; @@ -359,7 +359,7 @@ public function validateUrl($url) public function validateRequestHeaders(array $headers) { foreach ($this->headersToHave as $headerToCheck) { - if (!in_array($headerToCheck, $headers)) { + if (! in_array($headerToCheck, $headers)) { return false; } } @@ -368,6 +368,7 @@ public function validateRequestHeaders(array $headers) return false; } } + return true; } @@ -381,10 +382,10 @@ public function validateRequestHeaders(array $headers) public function validateRequestCookies(array $cookies) { foreach ($this->cookiesToHave as $name => $value) { - if (!isset($cookies[$name])) { + if (! isset($cookies[$name])) { return false; } - if (!is_null($value) && $cookies[$name] != $value) { + if (! is_null($value) && $cookies[$name] != $value) { return false; } } @@ -393,6 +394,7 @@ public function validateRequestCookies(array $cookies) return false; } } + return true; } @@ -405,11 +407,12 @@ public function validateRequestCookies(array $cookies) */ public function validateRequestIsPost($isPost) { - if ($this->verifyIsPost === true && !$isPost) { + if ($this->verifyIsPost === true && ! $isPost) { return false; - } else if ($this->verifyIsPost === false && $isPost) { + } elseif ($this->verifyIsPost === false && $isPost) { return false; } + return true; } @@ -422,11 +425,12 @@ public function validateRequestIsPost($isPost) */ public function validatePostBody($postBody) { - if (!is_null($this->postBodyToMatch) + if (! is_null($this->postBodyToMatch) && $this->postBodyToMatch != $postBody ) { return false; } + return true; } @@ -439,11 +443,12 @@ public function validatePostBody($postBody) */ public function validateCert($certPath) { - if (!is_null($this->certPathToMatch) + if (! is_null($this->certPathToMatch) && $this->certPathToMatch != $certPath ) { return false; } + return true; } @@ -456,12 +461,12 @@ public function validateCert($certPath) */ public function validateCaCert($caCertPath) { - if (!is_null($this->caCertPathToMatch) + if (! is_null($this->caCertPathToMatch) && $this->caCertPathToMatch != $caCertPath ) { return false; } + return true; } - } diff --git a/test/CAS/TestHarness/DummyMultiRequest.php b/test/CAS/TestHarness/DummyMultiRequest.php index e257e6fb..32c5b83d 100755 --- a/test/CAS/TestHarness/DummyMultiRequest.php +++ b/test/CAS/TestHarness/DummyMultiRequest.php @@ -21,29 +21,32 @@ * * @file CAS/TestHarness/DummyMultiRequest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\TestHarness; + +use phpCAS\CAS\InvalidArgumentException; +use phpCAS\CAS\OutOfSequenceException; +use phpCAS\CAS\Request\MultiRequestInterface; +use phpCAS\CAS\Request\RequestInterface; + /** * This interface defines a class library for performing multiple web requests * in batches. Implementations of this interface may perform requests serially * or in parallel. * - * @class CAS_TestHarness_DummyMultiRequest + * @class DummyMultiRequest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - -class CAS_TestHarness_DummyMultiRequest implements -CAS_Request_MultiRequestInterface +class DummyMultiRequest implements MultiRequestInterface { - private $_requests = array(); + private $_requests = []; private $_sent = false; /********************************************************* @@ -55,23 +58,23 @@ class CAS_TestHarness_DummyMultiRequest implements * Note, implementations will likely restrict requests to their own concrete * class hierarchy. * - * @param CAS_Request_RequestInterface $request request interface + * @param RequestInterface $request request interface * * @return void * - * @throws CAS_OutOfSequenceException If called after the Request has been sent. - * @throws CAS_InvalidArgumentException If passed a Request of the wrong - * implmentation. + * @throws OutOfSequenceException If called after the Request has been sent. + * @throws InvalidArgumentException If passed a Request of the wrong + * implementation. */ - public function addRequest(CAS_Request_RequestInterface $request) + public function addRequest(RequestInterface $request) { if ($this->_sent) { - throw new CAS_OutOfSequenceException( - 'Request has already been sent cannot ' . __METHOD__ + throw new OutOfSequenceException( + 'Request has already been sent cannot '.__METHOD__ ); } - if (!$request instanceof CAS_TestHarness_DummyRequest) { - throw new CAS_InvalidArgumentException( + if (! $request instanceof DummyRequest) { + throw new InvalidArgumentException( 'As a CAS_TestHarness_DummyMultiRequest, I can only work with CAS_TestHarness_DummyRequest objects.' ); } @@ -85,21 +88,21 @@ public function addRequest(CAS_Request_RequestInterface $request) /** * Perform the request. After sending, all requests will have their - * responses poulated. + * responses populated. * * @return bool TRUE on success, FALSE on failure. * - * @throws CAS_OutOfSequenceException If called multiple times. + * @throws OutOfSequenceException If called multiple times. */ public function send() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( + throw new OutOfSequenceException( 'Request has already been sent cannot send again.' ); } - if (!count($this->_requests)) { - throw new CAS_OutOfSequenceException( + if (! count($this->_requests)) { + throw new OutOfSequenceException( 'At least one request must be added via addRequest() before the multi-request can be sent.' ); } @@ -119,10 +122,11 @@ public function send() public function getNumRequests() { if ($this->_sent) { - throw new CAS_OutOfSequenceException( - 'Request has already been sent cannot ' . __METHOD__ + throw new OutOfSequenceException( + 'Request has already been sent cannot '.__METHOD__ ); } + return count($this->_requests); } } diff --git a/test/CAS/TestHarness/DummyRequest.php b/test/CAS/TestHarness/DummyRequest.php deleted file mode 100755 index 005d80b2..00000000 --- a/test/CAS/TestHarness/DummyRequest.php +++ /dev/null @@ -1,116 +0,0 @@ - - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ - -/** - * Provides support for performing dummy web-requests - * - * @class CAS_TestHarness_DummyRequest - * @category Authentication - * @package PhpCAS - * @author Adam Franco - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ -class CAS_TestHarness_DummyRequest extends CAS_Request_AbstractRequest -implements CAS_Request_RequestInterface -{ - private static $_responses = array(); - - /** - * Configure a URL/Response that the test harness will respond to. - * - * @param CAS_TestHarness_ResponseInterface $response response interface - * - * @return void - */ - public static function addResponse( - CAS_TestHarness_ResponseInterface $response - ) { - self::$_responses[] = $response; - } - - /** - * Clear out the URLs/Responses that the test harness will respond to. - * - * @return void - */ - public static function clearResponses() - { - self::$_responses = array(); - } - - /** - * Send the request and store the results. - * - * @return bool TRUE on success, FALSE on failure. - */ - protected function sendRequest() - { - foreach (self::$_responses as $response) { - if ($response->matchesUrl($this->url)) { - if (!$response->validateUrl($this->url)) { - $this->storeErrorMessage('Validation of url failed.'); - return false; - } - if (!$response->validateRequestHeaders($this->headers)) { - $this->storeErrorMessage('Validation of headers failed.'); - return false; - } - if (!$response->validateRequestCookies($this->cookies)) { - $this->storeErrorMessage('Validation of cookies failed.'); - return false; - } - if (!$response->validateRequestIsPost($this->isPost)) { - $this->storeErrorMessage( - 'Validation of GET/POST type failed.' - ); - return false; - } - if (!$response->validatePostBody($this->postBody)) { - $this->storeErrorMessage('Validation of POST body failed.'); - return false; - } - if (!$response->validateCaCert($this->caCertPath)) { - $this->storeErrorMessage('Validation of CA cert failed.'); - return false; - } - - $this->storeResponseHeaders($response->getResponseHeaders()); - $this->storeResponseBody($response->getResponseBody()); - return true; - } - } - // print_r("\n404 URL ".$this->url." not found in test harness.\n"); - - $this->storeErrorMessage( - '404 URL ' . $this->url . ' not found in test harness.' - ); - return false; - } -} diff --git a/test/CAS/TestHarness/ResponseInterface.php b/test/CAS/TestHarness/ResponseInterface.php index a93c01f6..fc5f031f 100755 --- a/test/CAS/TestHarness/ResponseInterface.php +++ b/test/CAS/TestHarness/ResponseInterface.php @@ -21,27 +21,26 @@ * * @file CAS/TestHarness/ResponseInterface.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\TestHarness; + /** * Implementations of this interface can validate a request and provide response * headers and body, allowing the spoofing of responses to web requests for testing * purposes. * - * @class CAS_TestHarness_ResponseInterface + * @class ResponseInterface * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -interface CAS_TestHarness_ResponseInterface +interface ResponseInterface { - /** * Test if this response should be supplied for the URL passed. * @@ -59,7 +58,7 @@ public function matchesUrl($url); public function getResponseHeaders(); /** - * Answer the response body + * Answer the response body. * * @return string */ @@ -132,5 +131,4 @@ public function validateCert($certPath); * @return bool TRUE if the cert path is correct. */ public function validateCaCert($caCertPath); - } diff --git a/test/CAS/Tests/AuthenticationTest.php b/test/CAS/Tests/AuthenticationTest.php index 3b198cf0..96fe0a80 100644 --- a/test/CAS/Tests/AuthenticationTest.php +++ b/test/CAS/Tests/AuthenticationTest.php @@ -21,26 +21,33 @@ * * @file CAS/Tests/AuthenticationTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\GracefulTerminationException; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_AuthenticationTest + * @class AuthenticationTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_AuthenticationTest extends PHPUnit_Framework_TestCase +class AuthenticationTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -52,10 +59,11 @@ class CAS_Tests_AuthenticationTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - // phpCAS::setDebug(dirname(__FILE__).'/../test.log'); + // CAS::setDebug(dirname(__FILE__).'/../test.log'); // error_reporting(E_ALL); + @session_start(); - CAS_GracefullTerminationException::throwInsteadOfExiting(); + GracefulTerminationException::throwInsteadOfExiting(); $_SERVER['SERVER_NAME'] = 'www.clientapp.com'; $_SERVER['SERVER_PORT'] = '80'; @@ -64,10 +72,10 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version true, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -75,7 +83,7 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); /********************************************************* @@ -83,18 +91,18 @@ protected function setUp() *********************************************************/ // Set up our response. - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response ->setResponseBody( @@ -105,8 +113,7 @@ protected function setUp() " ); - CAS_TestHarness_DummyRequest::addResponse($response); - + DummyRequest::addResponse($response); } /** @@ -117,12 +124,12 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); - $_SESSION = array(); + DummyRequest::clearResponses(); + $_SESSION = []; } /** - * Test that the user is redirected to the CAS server + * Test that the user is redirected to the CAS server. * * @return void */ @@ -132,11 +139,11 @@ public function testRedirect() ob_start(); $this->object->forceAuthentication(); $this->assertTrue( - false, 'Should have thrown a CAS_GracefullTerminationException.' + false, 'Should have thrown a GracefulTerminationException.' ); - } catch (CAS_GracefullTerminationException $e) { + } catch (GracefulTerminationException $e) { ob_end_clean(); - // It would be great to test for the existance of headers here, but + // It would be great to test for the existence of headers here, but // the don't get set properly due to output before the test. } } diff --git a/test/CAS/Tests/Cas20AttributesTest.php b/test/CAS/Tests/Cas20AttributesTest.php index 50466225..2c7fda48 100755 --- a/test/CAS/Tests/Cas20AttributesTest.php +++ b/test/CAS/Tests/Cas20AttributesTest.php @@ -21,26 +21,32 @@ * * @file CAS/Tests/Cas20AttributeTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_Cas20AttributeTest + * @class Cas20AttributeTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_Cas20AttributesTest extends PHPUnit_Framework_TestCase +class Cas20AttributesTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -59,10 +65,10 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version false, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -70,10 +76,10 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); $this->object->setNoClearTicketsFromUrl(); - // phpCAS::setDebug(dirname(__FILE__).'/../test.log'); + // CAS::setDebug(dirname(__FILE__).'/../test.log'); } /** @@ -84,29 +90,29 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** - * Verify that phpCAS will successfully fetch RubyCAS-style attributes: + * Verify that phpCAS will successfully fetch RubyCAS-style attributes:. * * @return void */ - public function testRubycasAttributes() + public function testRubyCasAttributes() { // Set up our response. - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -124,7 +130,7 @@ public function testRubycasAttributes() " ); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->isAuthenticated(); @@ -143,25 +149,25 @@ public function testRubycasAttributes() } /** - * Verify that phpCAS will successfully fetch RubyCAS-style attributes: + * Verify that phpCAS will successfully fetch RubyCAS-style attributes:. * * @return void */ public function testJasigAttributes() { // Set up our response. - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -181,7 +187,7 @@ public function testJasigAttributes() " ); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->isAuthenticated(); @@ -196,28 +202,27 @@ public function testJasigAttributes() $this->assertEquals('Jasig', $attras['attraStyle']); $this->validateUserAttributes(); - } /** - * Test Jasig Attributes with international characters + * Test Jasig Attributes with international characters. * * @return void */ public function testJasigAttributesInternational() { // Set up our response. - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -232,7 +237,7 @@ public function testJasigAttributesInternational() " ); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->isAuthenticated(); @@ -255,29 +260,28 @@ public function testJasigAttributesInternational() // array access $this->assertArrayHasKey('givenName', $attras); $this->assertEquals('Iñtërnâtiônàlizætiøn', $attras['givenName']); - } /** - * Verify that phpCAS will successfully fetch name-value-style attributes: + * Verify that phpCAS will successfully fetch name-value-style attributes:. * * @return void */ public function testNameValueAttributes() { // Set up our response. - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -295,7 +299,7 @@ public function testNameValueAttributes() " ); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->isAuthenticated(); @@ -304,7 +308,7 @@ public function testNameValueAttributes() $attras = $this->object->getAttributes(); $this->assertTrue( $this->object->hasAttribute('attraStyle'), - "Should have an attraStyle attribute" + 'Should have an attraStyle attribute' ); // direct access $this->assertEquals( @@ -328,7 +332,7 @@ public function validateUserAttributes() $attras = $this->object->getAttributes(); $this->assertInternalType('array', $attras); - if (count($attras) != 4 || !is_array($attras['memberOf'])) { + if (count($attras) != 4 || ! is_array($attras['memberOf'])) { print "\n"; print_r($attras); } @@ -377,6 +381,4 @@ public function validateUserAttributes() ) ); } - } -?> diff --git a/test/CAS/Tests/CookieJarExposed.php b/test/CAS/Tests/CookieJarExposed.php new file mode 100644 index 00000000..d4f32bef --- /dev/null +++ b/test/CAS/Tests/CookieJarExposed.php @@ -0,0 +1,63 @@ + + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ + +namespace phpCAS\CAS\Tests; + +use BadMethodCallException; +use phpCAS\CAS\CookieJar; + +/** + * Test harness for the cookie Jar to allow us to test protected methods. + * + * @class CookieJarExposed + * @category Authentication + * @author Adam Franco + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 + * @link https://wiki.jasig.org/display/CASC/phpCAS + */ +class CookieJarExposed extends CookieJar +{ + /** + * Wrapper to call protected methods. + * + * @param string $method function name + * @param array $args function args + * + * @throws BadMethodCallException + * + * @return mixed + */ + public function __call($method, array $args = []) + { + if (! method_exists($this, $method)) { + throw new BadMethodCallException("method '$method' does not exist"); + } + + return call_user_func_array([$this, $method], $args); + } +} diff --git a/test/CAS/Tests/CookieJarTest.php b/test/CAS/Tests/CookieJarTest.php index 5cb237d6..1ad4e094 100755 --- a/test/CAS/Tests/CookieJarTest.php +++ b/test/CAS/Tests/CookieJarTest.php @@ -21,62 +21,39 @@ * * @file CAS/Tests/CookieJarTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -/** - * Test harness for the cookie Jar to allow us to test protected methods. - * - * @class CAS_Tests_CookieJarExposed - * @category Authentication - * @package PhpCAS - * @author Adam Franco - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 - * @link https://wiki.jasig.org/display/CASC/phpCAS - */ +namespace phpCAS\CAS\Tests; -class CAS_Tests_CookieJarExposed extends CAS_CookieJar -{ - /** - * Wrapper to call protected methods - * - * @param string $method function name - * @param array $args function args - * - * @throws BadMethodCallException - * - * @return mixed - */ - public function __call($method, array $args = array()) - { - if (!method_exists($this, $method)) { - throw new BadMethodCallException("method '$method' does not exist"); - } - return call_user_func_array(array($this, $method), $args); - } -} +use phpCAS\CAS\CookieJar; +use PHPUnit_Framework_TestCase; /** * Test class for verifying the operation of cookie handling methods used in * serviceWeb() proxy calls. * - * @class CAS_Tests_CookieJarTest + * @class CookieJarTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_CookieJarTest extends PHPUnit_Framework_TestCase +class CookieJarTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var CookieJarExposed */ protected $object; + protected $cookieArray; + protected $serviceUrl_1; + protected $responseHeaders_1; + protected $serviceUrl_1b; + protected $serviceUrl_1c; + /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. @@ -85,11 +62,11 @@ class CAS_Tests_CookieJarTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - $this->cookieArray = array(); - $this->object = new CAS_Tests_CookieJarExposed($this->cookieArray); + $this->cookieArray = []; + $this->object = new CookieJarExposed($this->cookieArray); $this->serviceUrl_1 = 'http://service.example.com/lookup/?action=search&query=username'; - $this->responseHeaders_1 = array('HTTP/1.1 302 Found', + $this->responseHeaders_1 = ['HTTP/1.1 302 Found', 'Date: Tue, 07 Sep 2010 17:51:54 GMT', 'Server: Apache/2.2.3 (Red Hat)', 'X-Powered-By: PHP/5.1.6', 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/', @@ -99,7 +76,7 @@ protected function setUp() 'Location: https://cas.example.edu:443/cas/login?service=http%3A%2F%2Fservice.example.edu%2Flookup%2F%3Faction%3Dsearch%26query%3Dusername', 'Content-Length: 525', 'Connection: close', 'Content-Type: text/html; charset=UTF-8', - ); + ]; $this->serviceUrl_1b = 'http://service.example.com/lookup/?action=search&query=another_username'; $this->serviceUrl_1c = 'http://service.example.com/make_changes.php'; @@ -115,7 +92,7 @@ protected function setUp() ); // Add service cookies as if we just made are request to serviceUrl_1 - // and recieved responseHeaders_1 as the header to the response. + // and received responseHeaders_1 as the header to the response. $this->object ->storeCookies($this->serviceUrl_1, $this->responseHeaders_1); } @@ -128,7 +105,6 @@ protected function setUp() */ protected function tearDown() { - } /********************************************************* @@ -185,7 +161,7 @@ public function testPublicGetCookiesDifferentPath() */ public function testPublicGetCookiesSecure() { - $headers = array('Set-Cookie: person="bob jones"; path=/; Secure'); + $headers = ['Set-Cookie: person="bob jones"; path=/; Secure']; $url = 'https://service.example.com/lookup/?action=search&query=username'; $this->object->storeCookies($url, $headers); @@ -196,7 +172,7 @@ public function testPublicGetCookiesSecure() $this->assertEquals('k1jut1r1bqrumpei837kk4jks0', $cookies['SID']); $this->assertArrayNotHasKey('person', $cookies); - // Ensure that the SID cookie is avalailable to https urls. + // Ensure that the SID cookie is available to https urls. $cookies = $this->object ->getCookies('https://service.example.com/lookup/'); $this->assertArrayHasKey('SID', $cookies); @@ -213,7 +189,7 @@ public function testPublicGetCookiesSecure() */ public function testPublicGetCookiesSecureLC() { - $headers = array('Set-Cookie: person="bob jones"; path=/; secure'); + $headers = ['Set-Cookie: person="bob jones"; path=/; secure']; $url = 'https://service.example.com/lookup/?action=search&query=username'; $this->object->storeCookies($url, $headers); @@ -235,7 +211,7 @@ public function testPublicGetCookiesSecureLC() /** * Verify that when no domain is set for the cookie, it will be unavailable - * to other hosts + * to other hosts. * * @return void */ @@ -258,32 +234,32 @@ public function testPublicGetCookiesDifferentHost() } /** - * Verify that our set with the domain name will work + * Verify that our set with the domain name will work. * * @return void */ public function testPublicGetCookiesDomain() { - $headers = array( - 'Set-Cookie: SID="thisisthesid"; domain=".example.org"; path=/' - ); + $headers = [ + 'Set-Cookie: SID="thisisthesid"; domain=".example.org"; path=/', + ]; $url = 'http://host.example.org/path/to/somthing'; $this->object->storeCookies($url, $headers); // Ensure the SID cookie is available to the domain $cookies = $this->object->getCookies('http://example.org/path/'); $this->assertArrayHasKey( - 'SID', $cookies, "example.org should match .example.org cookies" + 'SID', $cookies, 'example.org should match .example.org cookies' ); // Ensure the SID cookie is available to the host $cookies = $this->object->getCookies('http://host.example.org/path/'); $this->assertArrayHasKey( - 'SID', $cookies, "host.example.org should match .example.org cookies" + 'SID', $cookies, 'host.example.org should match .example.org cookies' ); $this->assertEquals( 'thisisthesid', $cookies['SID'], - "host.example.org should match .example.org cookies" + 'host.example.org should match .example.org cookies' ); // Ensure the SID cookie is NOT available to a subdomain of the host @@ -298,15 +274,15 @@ public function testPublicGetCookiesDomain() } /** - * Verify that our set with the host name explicitly will work + * Verify that our set with the host name explicitly will work. * * @return void */ public function testPublicGetCookiesDomainHost() { - $headers = array( - 'Set-Cookie: SID="thisisthesid"; domain="host.example.org"; path=/' - ); + $headers = [ + 'Set-Cookie: SID="thisisthesid"; domain="host.example.org"; path=/', + ]; $url = 'http://host.example.org/path/to/somthing'; $this->object->storeCookies($url, $headers); @@ -321,11 +297,11 @@ public function testPublicGetCookiesDomainHost() $cookies = $this->object->getCookies('http://host.example.org/path/'); $this->assertArrayHasKey( 'SID', $cookies, - "host.example.org should match host.example.org cookies" + 'host.example.org should match host.example.org cookies' ); $this->assertEquals( 'thisisthesid', $cookies['SID'], - "host.example.org should match host.example.org cookies" + 'host.example.org should match host.example.org cookies' ); // Ensure the SID cookie is NOT available to a subdomain of the host @@ -340,15 +316,15 @@ public function testPublicGetCookiesDomainHost() } /** - * Verify that our set with the host name explicitly will work + * Verify that our set with the host name explicitly will work. * * @return void */ public function testPublicGetCookiesDomainHostDotted() { - $headers = array( - 'Set-Cookie: SID="thisisthesid"; domain=".host.example.org"; path=/' - ); + $headers = [ + 'Set-Cookie: SID="thisisthesid"; domain=".host.example.org"; path=/', + ]; $url = 'http://host.example.org/path/to/somthing'; $this->object->storeCookies($url, $headers); @@ -363,11 +339,11 @@ public function testPublicGetCookiesDomainHostDotted() $cookies = $this->object->getCookies('http://host.example.org/path/'); $this->assertArrayHasKey( 'SID', $cookies, - "host.example.org should match .host.example.org cookies" + 'host.example.org should match .host.example.org cookies' ); $this->assertEquals( 'thisisthesid', $cookies['SID'], - "host.example.org should match host.example.org cookies" + 'host.example.org should match host.example.org cookies' ); // Ensure the SID cookie IS available to a subdomain of the host @@ -375,7 +351,7 @@ public function testPublicGetCookiesDomainHostDotted() ->getCookies('http://sub.host.example.org/path/'); $this->assertArrayHasKey( 'SID', $cookies, - "sub.host.example.org should match .host.example.org cookies" + 'sub.host.example.org should match .host.example.org cookies' ); } @@ -386,8 +362,8 @@ public function testPublicGetCookiesDomainHostDotted() */ public function testPublicStoreCookies() { - $array = array(); - $cookieJar = new CAS_CookieJar($array); + $array = []; + $cookieJar = new CookieJar($array); $this->assertEquals(0, count($array)); $cookieJar->storeCookies($this->serviceUrl_1, $this->responseHeaders_1); $this->assertEquals(1, count($array)); @@ -407,7 +383,7 @@ public function testPublicStoreCookiesMaxAge() ); // Send set-cookie header to remove the cookie - $headers = array('Set-Cookie2: person="bob jones"; path=/; max-age=2'); + $headers = ['Set-Cookie2: person="bob jones"; path=/; max-age=2']; $this->object->storeCookies($this->serviceUrl_1, $headers); // Ensure that the cookie exists after 1 second @@ -425,7 +401,7 @@ public function testPublicStoreCookiesMaxAge() /** * Verify that cookie header with max-age=0 will remove the cookie. * Documented in RFC2965 section 3.2.2 - * http://www.ietf.org/rfc/rfc2965.txt + * http://www.ietf.org/rfc/rfc2965.txt. * * @return void */ @@ -437,9 +413,9 @@ public function testPublicStoreCookiesRemoveViaMaxAge0() ); // Send set-cookie header to remove the cookie - $headers = array( - 'Set-Cookie2: SID=k1jut1r1bqrumpei837kk4jks0; path=/; max-age=0' - ); + $headers = [ + 'Set-Cookie2: SID=k1jut1r1bqrumpei837kk4jks0; path=/; max-age=0', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $this->assertEquals( @@ -450,7 +426,7 @@ public function testPublicStoreCookiesRemoveViaMaxAge0() /** * Verify that cookie header with expires in the past will remove the cookie. * Documented in RFC2965 section 3.2.2 - * http://www.ietf.org/rfc/rfc2965.txt + * http://www.ietf.org/rfc/rfc2965.txt. * * @return void */ @@ -462,9 +438,9 @@ public function testPublicStoreCookiesRemoveViaExpiresPast() ); // Send set-cookie header to remove the cookie - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; expires=Fri, 31-Dec-2009 23:59:59 GMT' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; expires=Fri, 31-Dec-2009 23:59:59 GMT', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $this->assertEquals( @@ -487,10 +463,10 @@ public function testPublicStoreCookiesDontStoreExpiresPast() ); // Send set-cookie header to remove the cookie - $headers = array( + $headers = [ 'Set-Cookie: bob=jones; path=/; expires=' - . gmdate('D, d-M-Y H:i:s e', time() - 90000) - ); + .gmdate('D, d-M-Y H:i:s e', time() - 90000), + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1); @@ -499,7 +475,7 @@ public function testPublicStoreCookiesDontStoreExpiresPast() } /** - * Verify that cookie header that expires in the futre will not be removed. + * Verify that cookie header that expires in the future will not be removed. * * http://www.ietf.org/rfc/rfc2965.txt * @@ -513,10 +489,10 @@ public function testPublicStoreCookiesExpiresFuture() ); // Send set-cookie header to remove the cookie - $headers = array( + $headers = [ 'Set-Cookie: bob=jones; path=/; expires=' - . gmdate('D, d-M-Y H:i:s e', time() + 600) - ); + .gmdate('D, d-M-Y H:i:s e', time() + 600), + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1); @@ -531,9 +507,9 @@ public function testPublicStoreCookiesExpiresFuture() */ public function testPublicStoreCookiesHttponly() { - $headers = array( - 'Set-Cookie: SID="hello world"; path=/; domain=.example.com; HttpOnly' - ); + $headers = [ + 'Set-Cookie: SID="hello world"; path=/; domain=.example.com; HttpOnly', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1b); @@ -542,7 +518,7 @@ public function testPublicStoreCookiesHttponly() $this->assertEquals('hello world', $cookies['SID']); $this->assertEquals( 1, count($cookies), - "Should only a single SID cookie, not a cookie for the HttpOnly attribute" + 'Should only a single SID cookie, not a cookie for the HttpOnly attribute' ); } @@ -553,9 +529,9 @@ public function testPublicStoreCookiesHttponly() */ public function testPublicStoreCookiesComment() { - $headers = array( - 'Set-Cookie: SID="hello world"; path=/; domain=.example.com; HttpOnly; comment="A session cookie"' - ); + $headers = [ + 'Set-Cookie: SID="hello world"; path=/; domain=.example.com; HttpOnly; comment="A session cookie"', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1b); @@ -564,7 +540,7 @@ public function testPublicStoreCookiesComment() $this->assertEquals('hello world', $cookies['SID']); $this->assertEquals( 1, count($cookies), - "Should only a single SID cookie, not a cookie for the comment attribute" + 'Should only a single SID cookie, not a cookie for the comment attribute' ); } @@ -601,9 +577,9 @@ public function test_public_storeCookies_QuotedSemicolon() */ public function testPublicStoreCookiesQuotedEquals() { - $headers = array( - 'Set-Cookie: SID="hello=world"; path=/; domain=.example.com' - ); + $headers = [ + 'Set-Cookie: SID="hello=world"; path=/; domain=.example.com', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1b); @@ -623,9 +599,9 @@ public function testPublicStoreCookiesQuotedEquals() */ public function testPublicStoreCookiesQuotedEscapedQuote() { - $headers = array( - 'Set-Cookie: SID="hello\"world"; path=/; domain=.example.com' - ); + $headers = [ + 'Set-Cookie: SID="hello\"world"; path=/; domain=.example.com', + ]; $this->object->storeCookies($this->serviceUrl_1, $headers); $cookies = $this->object->getCookies($this->serviceUrl_1b); @@ -664,15 +640,15 @@ public function testProtectedParseCookieHeaders() } /** - * Test the addition of a domain to the parsing of cookie headers + * Test the addition of a domain to the parsing of cookie headers. * * @return void */ public function testProtectedParseCookieHeadersWithDomain() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -686,15 +662,15 @@ public function testProtectedParseCookieHeadersWithDomain() } /** - * Test the addition of a domain to the parsing of cookie headers + * Test the addition of a domain to the parsing of cookie headers. * * @return void */ public function testProtectedParseCookieHeadersWithHostname() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=service.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=service.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -714,9 +690,9 @@ public function testProtectedParseCookieHeadersWithHostname() */ public function testProtectedParseCookieHeadersNonDefaultHostname() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=service2.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/; domain=service2.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -736,9 +712,9 @@ public function testProtectedParseCookieHeadersNonDefaultHostname() */ public function testProtectedParseCookieHeadersWithPath() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/something/; domain=service2.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; path=/something/; domain=service2.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -752,15 +728,15 @@ public function testProtectedParseCookieHeadersWithPath() } /** - * Test the addition of a 'Secure' parameter + * Test the addition of a 'Secure' parameter. * * @return void */ public function testProtectedParseCookieHeadersSecure() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; Secure; path=/something/; domain=service2.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; Secure; path=/something/; domain=service2.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -774,15 +750,15 @@ public function testProtectedParseCookieHeadersSecure() } /** - * Test the addition of a 'Secure' parameter that is lower-case + * Test the addition of a 'Secure' parameter that is lower-case. * * @return void */ public function testProtectedParseCookieHeadersSecureLC() { - $headers = array( - 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; secure; path=/something/; domain=service2.example.com' - ); + $headers = [ + 'Set-Cookie: SID=k1jut1r1bqrumpei837kk4jks0; secure; path=/something/; domain=service2.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -796,13 +772,13 @@ public function testProtectedParseCookieHeadersSecureLC() } /** - * Test the inclusion of a trailing semicolon + * Test the inclusion of a trailing semicolon. * * @return void */ public function testProtectedParseCookieHeadersTrailingSemicolon() { - $headers = array('Set-Cookie: SID="hello world"; path=/;'); + $headers = ['Set-Cookie: SID="hello world"; path=/;']; $cookies = $this->object ->parseCookieHeaders($headers, 'service.example.com'); @@ -816,7 +792,7 @@ public function testProtectedParseCookieHeadersTrailingSemicolon() } /** - * Test setting a single service cookie + * Test setting a single service cookie. * * @return void */ @@ -829,18 +805,18 @@ public function testProtectedSetCookie() } /** - * Test setting a single service cookie + * Test setting a single service cookie. * * @return void */ public function testProtectedStoreCookieWithDuplicates() { - $headers = array('Set-Cookie: SID="hello world"; path=/'); + $headers = ['Set-Cookie: SID="hello world"; path=/']; $cookiesToSet = $this->object ->parseCookieHeaders($headers, 'service.example.com'); $this->object->storeCookie($cookiesToSet[0]); - $headers = array('Set-Cookie: SID="goodbye world"; path=/'); + $headers = ['Set-Cookie: SID="goodbye world"; path=/']; $cookiesToSet = $this->object ->parseCookieHeaders($headers, 'service.example.com'); $this->object->storeCookie($cookiesToSet[0]); @@ -852,14 +828,14 @@ public function testProtectedStoreCookieWithDuplicates() } /** - * Test setting two service cookies + * Test setting two service cookies. * * @return void */ public function testProtectedStoreCookieTwoCookies() { // Second cookie - $headers = array('Set-Cookie: message="hello world"; path=/'); + $headers = ['Set-Cookie: message="hello world"; path=/']; $cookiesToSet = $this->object ->parseCookieHeaders($headers, 'service.example.com'); $this->object->storeCookie($cookiesToSet[0]); @@ -872,7 +848,7 @@ public function testProtectedStoreCookieTwoCookies() } /** - * Test setting two service cookies + * Test setting two service cookies. * * @return void */ @@ -880,9 +856,9 @@ public function testProtectedStoreCookieTwoCookiesOneAtDomain() { // Second cookie - $headers = array( - 'Set-Cookie: message="hello world"; path=/; domain=.example.com' - ); + $headers = [ + 'Set-Cookie: message="hello world"; path=/; domain=.example.com', + ]; $cookiesToSet = $this->object ->parseCookieHeaders($headers, 'service.example.com'); $this->object->storeCookie($cookiesToSet[0]); @@ -901,9 +877,9 @@ public function testProtectedStoreCookieTwoCookiesOneAtDomain() */ public function testProtectedCookieMatchesTargetDomainCookie() { - $headers = array( - 'Set-Cookie: message="hello world"; path=/; domain=.example.com' - ); + $headers = [ + 'Set-Cookie: message="hello world"; path=/; domain=.example.com', + ]; $cookies = $this->object ->parseCookieHeaders($headers, 'otherhost.example.com'); @@ -914,6 +890,4 @@ public function testProtectedCookieMatchesTargetDomainCookie() ) ); } - } -?> diff --git a/test/CAS/Tests/MultiRequestTest.php b/test/CAS/Tests/MultiRequestTest.php index fbf48501..5b6ff5fb 100755 --- a/test/CAS/Tests/MultiRequestTest.php +++ b/test/CAS/Tests/MultiRequestTest.php @@ -21,29 +21,29 @@ * * @file CAS/Tests/MultiRequestTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyMultiRequest; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_MultiRequestTest + * @class MultiRequestTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_MultiRequestTest extends PHPUnit_Framework_TestCase +class MultiRequestTest extends PHPUnit_Framework_TestCase { - /** - * @var CAS_Client - */ - protected $object; - /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. @@ -56,57 +56,56 @@ protected function setUp() /********************************************************* * Enumerate our responses *********************************************************/ - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.jasig.org', '/some/path' ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); - $response->setResponseBody("I am Jasig"); - CAS_TestHarness_DummyRequest::addResponse($response); + $response->setResponseBody('I am Jasig'); + DummyRequest::addResponse($response); - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.example.org', '/some/other/path' ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); - $response->setResponseBody("I am Example"); - CAS_TestHarness_DummyRequest::addResponse($response); + $response->setResponseBody('I am Example'); + DummyRequest::addResponse($response); - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.educause.edu', '/path' ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); - $response->setResponseBody("I am Educause"); - CAS_TestHarness_DummyRequest::addResponse($response); - + $response->setResponseBody('I am Educause'); + DummyRequest::addResponse($response); } /** @@ -117,48 +116,45 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** - * Test a single request - * - * @return voud + * Test a single request. */ public function testSingle() { - $request = new CAS_TestHarness_DummyRequest(); + $request = new DummyRequest(); $request->setUrl('http://www.example.org/some/other/path'); $this->assertTrue($request->send()); - $this->assertEquals("I am Example", $request->getResponseBody()); + $this->assertEquals('I am Example', $request->getResponseBody()); } /** - * Test a multiple requests + * Test a multiple requests. * * @return void */ public function testMultiple() { - $multi = new CAS_TestHarness_DummyMultiRequest(); + $multi = new DummyMultiRequest(); - $request1 = new CAS_TestHarness_DummyRequest(); + $request1 = new DummyRequest(); $request1->setUrl('http://www.jasig.org/some/path'); $multi->addRequest($request1); - $request2 = new CAS_TestHarness_DummyRequest(); + $request2 = new DummyRequest(); $request2->setUrl('http://www.example.org/some/other/path'); $multi->addRequest($request2); - $request3 = new CAS_TestHarness_DummyRequest(); + $request3 = new DummyRequest(); $request3->setUrl('http://www.educause.edu/path'); $multi->addRequest($request3); $multi->send(); - $this->assertEquals("I am Jasig", $request1->getResponseBody()); - $this->assertEquals("I am Example", $request2->getResponseBody()); - $this->assertEquals("I am Educause", $request3->getResponseBody()); + $this->assertEquals('I am Jasig', $request1->getResponseBody()); + $this->assertEquals('I am Example', $request2->getResponseBody()); + $this->assertEquals('I am Educause', $request3->getResponseBody()); } } -?> diff --git a/test/CAS/Tests/ProxyChainsTest.php b/test/CAS/Tests/ProxyChainsTest.php index ff97e706..d7656eeb 100644 --- a/test/CAS/Tests/ProxyChainsTest.php +++ b/test/CAS/Tests/ProxyChainsTest.php @@ -21,28 +21,39 @@ * * @file CAS/Tests/MultiRequestTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS\ProxyChain; +use phpCAS\CAS\ProxyChain\AllowedList; +use phpCAS\CAS\ProxyChain\Any; +use phpCAS\CAS\ProxyChain\Trusted; +use PHPUnit_Framework_TestCase; + /** - * Test class for verifying the operation of the proxy-chains validation system + * Test class for verifying the operation of the proxy-chains validation system. * - * @class CAS_Tests_ProxyChainsTests + * @class ProxyChainsTests * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_ProxyChainsTest extends PHPUnit_Framework_TestCase +class ProxyChainsTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var AllowedList */ protected $object; + protected $list_size_0; + protected $list_size_1; + protected $list_size_2; + protected $list_size_3; + protected $list_size_4; /** * Sets up the fixture, for example, opens a network connection. @@ -52,21 +63,21 @@ class CAS_Tests_ProxyChainsTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - $this->object = new CAS_ProxyChain_AllowedList; - $this->list_size_0 = array(); - $this->list_size_1 = array('https://service1.example.com/rest',); - $this->list_size_2 = array('https://service1.example.com/rest', + $this->object = new AllowedList; + $this->list_size_0 = []; + $this->list_size_1 = ['https://service1.example.com/rest']; + $this->list_size_2 = ['https://service1.example.com/rest', 'http://service2.example.com/my/path', - ); - $this->list_size_3 = array('https://service1.example.com/rest', + ]; + $this->list_size_3 = ['https://service1.example.com/rest', 'http://service2.example.com/my/path', 'http://service3.example.com/other/', - ); - $this->list_size_4 = array('https://service1.example.com/rest', + ]; + $this->list_size_4 = ['https://service1.example.com/rest', 'http://service2.example.com/my/path', 'http://service3.example.com/other/', 'https://service4.example.com/', - ); + ]; } /** @@ -77,7 +88,6 @@ protected function setUp() */ protected function tearDown() { - } /********************************************************* @@ -85,7 +95,7 @@ protected function tearDown() *********************************************************/ /** - * Verify that not configuring any proxies will prevent acccess. + * Verify that not configuring any proxies will prevent access. * * @return void */ @@ -114,13 +124,13 @@ public function testNone() } /** - * Verify that using the CAS_ProxyChain_Any will work with any URL. + * Verify that using the Any will work with any URL. * * @return void */ public function testAny() { - $this->object->allowProxyChain(new CAS_ProxyChain_Any); + $this->object->allowProxyChain(new Any); $this->assertTrue( $this->object->isProxyListAllowed($this->list_size_0), 'Should allow any proxies in front.' @@ -144,7 +154,7 @@ public function testAny() } /** - * Verify that using the CAS_ProxyChain will only allow an exact match to + * Verify that using the ProxyChain will only allow an exact match to * the chain. * * @return void @@ -152,10 +162,10 @@ public function testAny() public function testExactMatch2() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('https://service1.example.com/rest', + new ProxyChain( + ['https://service1.example.com/rest', 'http://service2.example.com/my/path', - ) + ] ) ); $this->assertTrue( @@ -181,7 +191,7 @@ public function testExactMatch2() } /** - * Verify that using the CAS_ProxyChain will only allow an exact match to + * Verify that using the ProxyChain will only allow an exact match to * the chain. * * @return void @@ -189,10 +199,10 @@ public function testExactMatch2() public function testExactMatch2Failure() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('https://service1.example.com/rest', + new ProxyChain( + ['https://service1.example.com/rest', 'http://other.example.com/my/path', - ) + ] ) ); $this->assertTrue( @@ -218,7 +228,7 @@ public function testExactMatch2Failure() } /** - * Verify that using the CAS_ProxyChain_Trusted will allow an exact match or + * Verify that using the Trusted will allow an exact match or * greater length of chain. * * @return void @@ -226,10 +236,10 @@ public function testExactMatch2Failure() public function testTrustedMatch2() { $this->object->allowProxyChain( - new CAS_ProxyChain_Trusted( - array('https://service1.example.com/rest', + new Trusted( + ['https://service1.example.com/rest', 'http://service2.example.com/my/path', - ) + ] ) ); $this->assertTrue( @@ -255,18 +265,18 @@ public function testTrustedMatch2() } /** - * Verify that using the CAS_ProxyChain will match strings as prefixes + * Verify that using the ProxyChain will match strings as prefixes. * * @return void */ public function testPrefixMatch3() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('https://service1.example.com/', + new ProxyChain( + ['https://service1.example.com/', 'http://service2.example.com/my', 'http://service3.example.com/', - ) + ] ) ); $this->assertTrue( @@ -292,17 +302,17 @@ public function testPrefixMatch3() } /** - * Verify that using the CAS_ProxyChain will match with Regular expressions + * Verify that using the ProxyChain will match with Regular expressions. * * @return void */ public function testRegexMatch2() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('/^https?:\/\/service1\.example\.com\/.*/', + new ProxyChain( + ['/^https?:\/\/service1\.example\.com\/.*/', '/^http:\/\/service[0-9]\.example\.com\/[^\/]+\/path/', - ) + ] ) ); $this->assertTrue( @@ -328,19 +338,19 @@ public function testRegexMatch2() } /** - * Verify that using the CAS_ProxyChain will match a mixture of with Regular - * expressions and plain strings + * Verify that using the ProxyChain will match a mixture of with Regular + * expressions and plain strings. * * @return void */ public function testMixedRegexMatch3() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('https://service1.example.com/', + new ProxyChain( + ['https://service1.example.com/', '/^http:\/\/service[0-9]\.example\.com\/[^\/]+\/path/', 'http://service3.example.com/', - ) + ] ) ); $this->assertTrue($this->object->isProxyListAllowed($this->list_size_0)); @@ -351,19 +361,19 @@ public function testMixedRegexMatch3() } /** - * Verify that using the CAS_ProxyChain_Trusted will match a mixture of with - * Regular expressions and plain strings + * Verify that using the Trusted will match a mixture of with + * Regular expressions and plain strings. * * @return void */ public function testMixedRegexTrusted3() { $this->object->allowProxyChain( - new CAS_ProxyChain_Trusted( - array('https://service1.example.com/', + new Trusted( + ['https://service1.example.com/', '/^http:\/\/service[0-9]\.example\.com\/[^\/]+\/path/', 'http://service3.example.com/', - ) + ] ) ); $this->assertTrue($this->object->isProxyListAllowed($this->list_size_0)); @@ -374,17 +384,17 @@ public function testMixedRegexTrusted3() } /** - * Verify that using the CAS_ProxyChain will allow regex modifiers + * Verify that using the ProxyChain will allow regex modifiers. * * @return void */ public function testRegexModifiers() { $this->object->allowProxyChain( - new CAS_ProxyChain( - array('/^https?:\/\/service1\.EXAMPLE\.com\/.*/i', + new ProxyChain( + ['/^https?:\/\/service1\.EXAMPLE\.com\/.*/i', '/^http:\/\/serVice[0-9]\.example\.com\/[^\/]+\/path/ix', - ) + ] ) ); $this->assertTrue( diff --git a/test/CAS/Tests/ProxyTicketValidationTest.php b/test/CAS/Tests/ProxyTicketValidationTest.php index 6621098c..f3bedb14 100755 --- a/test/CAS/Tests/ProxyTicketValidationTest.php +++ b/test/CAS/Tests/ProxyTicketValidationTest.php @@ -21,26 +21,36 @@ * * @file CAS/Tests/ProxyTicketValidationTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\AuthenticationException; +use phpCAS\CAS\Client; +use phpCAS\CAS\ProxyChain; +use phpCAS\CAS\ProxyChain\Any; +use phpCAS\CAS\ProxyChain\Trusted; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_ProxyTicketValidationTest + * @class ProxyTicketValidationTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_ProxyTicketValidationTest extends PHPUnit_Framework_TestCase +class ProxyTicketValidationTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -59,12 +69,12 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; - // $_GET['ticket'] = 'ST-123456-asdfasdfasgww2323radf3'; + // $_GET['ticket'] = 'ST-123456-asdfasdfasgww2323radf3'; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version false, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -72,30 +82,30 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); /********************************************************* * Enumerate our responses *********************************************************/ // Valid ticket response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxyValidate' ); $response->matchQueryParameters( - array('service' => 'http://www.service.com/', + ['service' => 'http://www.service.com/', 'ticket' => 'ST-123456-asdfasdfasgww2323radf3', - ) + ] ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -110,24 +120,24 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); // Invalid ticket response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxyValidate' ); $response->matchQueryParameters( - array('service' => 'http://www.service.com/',) + ['service' => 'http://www.service.com/'] ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -138,7 +148,7 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); } /** @@ -149,7 +159,7 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** @@ -161,7 +171,7 @@ public function testValidationSuccess() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains() - ->allowProxyChain(new CAS_ProxyChain_Any()); + ->allowProxyChain(new Any()); $result = $this->object ->validateCAS20($url, $text_response, $tree_response); $this->assertTrue($result); @@ -181,7 +191,7 @@ public function testValidationSuccess() } /** - * Test that our list of proxies is available + * Test that our list of proxies is available. * * @return void */ @@ -189,16 +199,16 @@ public function testValidationSuccessProxyList() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains() - ->allowProxyChain(new CAS_ProxyChain_Any()); + ->allowProxyChain(new Any()); $result = $this->object ->validateCAS20($url, $text_response, $tree_response); $this->assertTrue($result); $this->assertEquals( - array('http://firstproxy.com/mysite/test', - 'https://anotherdomain.org/mysite/test2' - ), + ['http://firstproxy.com/mysite/test', + 'https://anotherdomain.org/mysite/test2', + ], $this->object->getProxies(), - "The list of proxies in front of the client." + 'The list of proxies in front of the client.' ); } @@ -207,7 +217,7 @@ public function testValidationSuccessProxyList() * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testInvalidTicketFailure() @@ -231,7 +241,7 @@ public function testInvalidTicketFailure() } /** - * Test that our list of proxies is not availible on ticket failure. + * Test that our list of proxies is not available on ticket failure. * * @return void */ @@ -240,19 +250,19 @@ public function testInvalidTicketProxyList() $this->object->setTicket('ST-1856339-aA5Yuvrxzpv8Tau1cYQ7'); ob_start(); try { - $result = $this->object + $this->object ->validateCAS20($url, $text_response, $tree_response); - } catch (CAS_AuthenticationException $e) { + } catch (AuthenticationException $e) { } ob_end_clean(); $this->assertEquals( - array(), $this->object->getProxies(), - "The list of proxies in front of the client." + [], $this->object->getProxies(), + 'The list of proxies in front of the client.' ); } /** - * Test allowed proxies + * Test allowed proxies. * * @return void */ @@ -260,15 +270,15 @@ public function testAllowedProxiesStringSuccess() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('http://firstproxy.com', - 'https://anotherdomain.org/mysite/test2' - ) + new ProxyChain( + ['http://firstproxy.com', + 'https://anotherdomain.org/mysite/test2', + ] ) ); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('https://anotherdomain.php') + new ProxyChain( + ['https://anotherdomain.php'] ) ); $result = $this->object @@ -298,13 +308,13 @@ public function testAllowedProxiesTrustedSuccess() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain_Trusted( - array('http://firstproxy.com') + new Trusted( + ['http://firstproxy.com'] ) ); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('https://anotherdomain.php') + new ProxyChain( + ['https://anotherdomain.php'] ) ); $result = $this->object @@ -327,19 +337,19 @@ public function testAllowedProxiesTrustedSuccess() } /** - * Test that proxies fail if one is missing from the chain + * Test that proxies fail if one is missing from the chain. * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testAllowedProxiesStringFailureMissingProxy() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('https://anotherdomain.php') + new ProxyChain( + ['https://anotherdomain.php'] ) ); $result = $this->object @@ -348,26 +358,26 @@ public function testAllowedProxiesStringFailureMissingProxy() } /** - * Test that proxies fail if in wrong order and definded as string + * Test that proxies fail if in wrong order and defined as string. * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testAllowedProxiesStringFailureWrongOrder() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('https://anotherdomain.org/mysite/test2', - 'http://firstproxy.com' - ) + new ProxyChain( + ['https://anotherdomain.org/mysite/test2', + 'http://firstproxy.com', + ] ) ); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('https://anotherdomain.php') + new ProxyChain( + ['https://anotherdomain.php'] ) ); $result = $this->object @@ -376,11 +386,11 @@ public function testAllowedProxiesStringFailureWrongOrder() } /** - * Test that if proxies exist a response with proxies will fail unless allowed + * Test that if proxies exist a response with proxies will fail unless allowed. * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testAllowedProxiesFailure() @@ -393,7 +403,7 @@ public function testAllowedProxiesFailure() } /** - * Test that regexp filtering of allowed proxies works + * Test that regexp filtering of allowed proxies works. * * @return void */ @@ -401,13 +411,13 @@ public function testAllowedProxiesRegexpSuccess() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain(array('/badregexp/')) + new ProxyChain(['/badregexp/']) ); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('/http\:\/\/firstproxy\.com.*$/', - '/^https\:\/\/anotherdomain.org\/mysite\/test2$/' - ) + new ProxyChain( + ['/http\:\/\/firstproxy\.com.*$/', + '/^https\:\/\/anotherdomain.org\/mysite\/test2$/', + ] ) ); $result = $this->object @@ -416,19 +426,19 @@ public function testAllowedProxiesRegexpSuccess() } /** - * Wrong regexp to mach proxies + * Wrong regexp to mach proxies. * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testAllowedProxiesRegexpFailureWrong() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('/^http:\/\/secondproxy\.com/', '/^https.*$/') + new ProxyChain( + ['/^http:\/\/secondproxy\.com/', '/^https.*$/'] ) ); $result = $this->object->validateCAS20( @@ -438,21 +448,21 @@ public function testAllowedProxiesRegexpFailureWrong() } /** - * Wrong order of valid regexp + * Wrong order of valid regexp. * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testAllowedProxiesRegexpFailureWrongOrder() { $this->object->setTicket('ST-123456-asdfasdfasgww2323radf3'); $this->object->getAllowedProxyChains()->allowProxyChain( - new CAS_ProxyChain( - array('/^https\:\/\/anotherdomain.org\/mysite\/test2$/', - '/http\:\/\/firstproxy\.com.*$/' - ) + new ProxyChain( + ['/^https\:\/\/anotherdomain.org\/mysite\/test2$/', + '/http\:\/\/firstproxy\.com.*$/', + ] ) ); $result = $this->object->validateCAS20( @@ -461,4 +471,3 @@ public function testAllowedProxiesRegexpFailureWrongOrder() $this->assertFalse($result); } } -?> diff --git a/test/CAS/Tests/ServiceMailTest.php b/test/CAS/Tests/ServiceMailTest.php index a7ba3e42..78aca0e6 100755 --- a/test/CAS/Tests/ServiceMailTest.php +++ b/test/CAS/Tests/ServiceMailTest.php @@ -21,26 +21,32 @@ * * @file CAS/Tests/ServiceMailTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_ServiceMailTest + * @class ServiceMailTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_ServiceMailTest extends PHPUnit_Framework_TestCase +class ServiceMailTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -52,7 +58,7 @@ class CAS_Tests_ServiceMailTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - // phpCAS::setDebug(dirname(__FILE__).'/../test.log'); + // CAS::setDebug(dirname(__FILE__).'/../test.log'); // error_reporting(E_ALL); $_SERVER['SERVER_NAME'] = 'www.clientapp.com'; @@ -62,10 +68,10 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version true, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -73,18 +79,18 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); - // Bypass PGT storage since CAS_Client->callback() will exit. Just build + // Bypass PGT storage since Client->callback() will exit. Just build // up the session manually so that we are in a state from which we can // attempt to fetch proxy tickets and make proxied requests. $_SESSION['phpCAS']['user'] = 'jdoe'; $_SESSION['phpCAS']['pgt'] = 'PGT-clientapp-abc123'; - $_SESSION['phpCAS']['proxies'] = array(); - $_SESSION['phpCAS']['service_cookies'] = array(); - $_SESSION['phpCAS']['attributes'] = array(); + $_SESSION['phpCAS']['proxies'] = []; + $_SESSION['phpCAS']['service_cookies'] = []; + $_SESSION['phpCAS']['attributes'] = []; // Force Authentication to initialize the client. $this->object->forceAuthentication(); @@ -98,25 +104,25 @@ protected function setUp() *********************************************************/ // Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'imap://mail.example.edu/path/to/something', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -127,32 +133,32 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); /********************************************************* * 2. Proxy Ticket Error *********************************************************/ // Error Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'imap://mail.example.edu/path/that/doesnt/exist', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -164,13 +170,13 @@ protected function setUp() ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); /********************************************************* * Ensure that IMAP constants are defined even if the IMAP * module is not installed. *********************************************************/ - if (!defined('OP_READONLY')) { + if (! defined('OP_READONLY')) { // Not sure what this should actually be. It is defined as: // REGISTER_LONG_CONSTANT( // "OP_READONLY", OP_READONLY, CONST_PERSISTENT | CONST_CS @@ -179,7 +185,6 @@ protected function setUp() // For now, just ensure that it is an integer. define('OP_READONLY', 1); } - } /** @@ -190,7 +195,7 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** @@ -222,7 +227,7 @@ public function testServiceMail() // OP_READONLY, $err_code, $err_msg, $pt // ); // $this->assertInternalType('resource', $stream); - // $this->assertEquals(PHPCAS_SERVICE_OK, $err_code); + // $this->assertEquals(CAS_SERVICE_OK, $err_code); // $this->assertEquals('', $err_msg); // $this->assertEquals('PT-asdfas-dfasgww2323radf3', $pt); } @@ -240,10 +245,10 @@ public function testServiceMailPtError() OP_READONLY, $err_code, $err_msg, $pt ); $this->assertFalse( - $stream, "serviceMail() should have returned false on a PT error." + $stream, 'serviceMail() should have returned false on a PT error.' ); - $this->assertEquals(PHPCAS_SERVICE_PT_FAILURE, $err_code); - $this->assertStringStartsWith("PT retrieving failed", $err_msg); + $this->assertEquals(CAS::PHPCAS_SERVICE_PT_FAILURE, $err_code); + $this->assertStringStartsWith('PT retrieving failed', $err_msg); $this->assertFalse($pt, '$pt should be false.'); } @@ -266,7 +271,7 @@ public function testServiceMailServiceError() // $stream, // "serviceMail() should have returned false on a service error." // ); - // $this->assertEquals(PHPCAS_SERVICE_NOT_AVAILABLE, $err_code); + // $this->assertEquals(CAS_SERVICE_NOT_AVAILABLE, $err_code); // $this->assertStringStartsWith("The service", $err_msg); // $this->assertFalse($pt, '$pt should be false.'); } @@ -282,7 +287,7 @@ public function testImap() $this->markTestIncomplete('This test has not been implemented yet.'); // $service = $this->object->getProxiedService( - // PHPCAS_PROXIED_SERVICE_IMAP + // CAS_PROXIED_SERVICE_IMAP // ); // $service->setServiceUrl('imap://mail.example.edu/path/to/something'); // $service->setMailbox('mailbox_name'); @@ -293,7 +298,6 @@ public function testImap() // $this->assertEquals( // 'PT-asdfas-dfasgww2323radf3', $service->getImapProxyTicket() // ); - } /** @@ -302,17 +306,17 @@ public function testImap() * * @return void * - * @expectedException CAS_ProxyTicketException + * @expectedException \phpCAS\CAS\ProxyTicketException */ public function testPtException() { - $service = $this->object->getProxiedService(PHPCAS_PROXIED_SERVICE_IMAP); + $service = $this->object->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_IMAP); $service->setServiceUrl( 'imap://mail.example.edu/path/that/doesnt/exist' ); $service->setMailbox('mailbox_name'); $service->setOptions(OP_READONLY); - $stream = $service->open(); + $service->open(); } /** @@ -321,7 +325,7 @@ public function testPtException() * * @return void * - * @expectedException CAS_ProxiedService_Exception + * @expectedException \phpCAS\CAS\ProxiedService\ProxiedServiceException */ public function testHttpGetServiceFailure() { @@ -329,7 +333,7 @@ public function testHttpGetServiceFailure() $this->markTestIncomplete('This test has not been implemented yet.'); // $service = $this->object->getProxiedService( - // PHPCAS_PROXIED_SERVICE_IMAP + // CAS_PROXIED_SERVICE_IMAP // ); // $service->setServiceUrl('ssh://me.example.net'); // $service->setMailbox('mailbox_name'); @@ -337,4 +341,3 @@ public function testHttpGetServiceFailure() // $stream = $service->open(); } } -?> diff --git a/test/CAS/Tests/ServiceTicketValidationTest.php b/test/CAS/Tests/ServiceTicketValidationTest.php index 95aeb517..c32c70d1 100755 --- a/test/CAS/Tests/ServiceTicketValidationTest.php +++ b/test/CAS/Tests/ServiceTicketValidationTest.php @@ -21,26 +21,32 @@ * * @file CAS/Tests/ServiceTicketValidationTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_ServiceTicketValidationTest + * @class ServiceTicketValidationTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_ServiceTicketValidationTest extends PHPUnit_Framework_TestCase +class ServiceTicketValidationTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -59,12 +65,12 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; // $_GET['ticket'] = 'ST-123456-asdfasdfasgww2323radf3'; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version false, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -72,30 +78,30 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); /********************************************************* * Enumerate our responses *********************************************************/ // Valid ticket response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->matchQueryParameters( - array('service' => 'http://www.service.com/', + ['service' => 'http://www.service.com/', 'ticket' => 'ST-123456-asdfasdfasgww2323radf3', - ) + ] ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -107,24 +113,24 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); // Invalid ticket response - $response = new CAS_TestHarness_BasicResponse( - 'https', 'cas.example.edu', '/cas/serviceValidate' + $response = new BasicResponse( + 'https', 'cas.example.edu', '/cas/serviceValidate' ); $response->matchQueryParameters( - array('service' => 'http://www.service.com/',) + ['service' => 'http://www.service.com/'] ); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -135,7 +141,7 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); } /** @@ -146,7 +152,7 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** @@ -178,28 +184,29 @@ public function testValidationSuccess() * * @return void * - * @expectedException CAS_AuthenticationException + * @expectedException \phpCAS\CAS\AuthenticationException * @outputBuffering enabled */ public function testInvalidTicketFailure() { $this->object->setTicket('ST-1856339-aA5Yuvrxzpv8Tau1cYQ7'); - ob_start(); - $result = $this->object - ->validateCAS20($url, $text_response, $tree_response); - ob_end_clean(); - $this->assertTrue($result); - $this->assertEquals( - " - - Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized - - -", - $text_response - ); - $this->assertInstanceOf('DOMElement', $tree_response); + // ob_start(); + try { + $result = $this->object->validateCAS20($url, $text_response, $tree_response); + // ob_end_clean(); + $this->assertTrue($result); + $this->assertEquals( + " + + Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized + + + ", + $text_response + ); + $this->assertInstanceOf('DOMElement', $tree_response); + } catch (\Error $e) { + echo PHP_EOL.PHP_EOL.$e.PHP_EOL.PHP_EOL; + } } - } -?> diff --git a/test/CAS/Tests/ServiceWebTest.php b/test/CAS/Tests/ServiceWebTest.php index 9798ee38..a44ef347 100755 --- a/test/CAS/Tests/ServiceWebTest.php +++ b/test/CAS/Tests/ServiceWebTest.php @@ -21,26 +21,32 @@ * * @file CAS/Tests/ServiceWebTest.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ +namespace phpCAS\CAS\Tests; + +use phpCAS\CAS; +use phpCAS\CAS\Client; +use phpCAS\CAS\TestHarness\BasicResponse; +use phpCAS\CAS\TestHarness\DummyRequest; +use PHPUnit_Framework_TestCase; + /** * Test class for verifying the operation of service tickets. * - * @class CAS_Tests_ServiceWebTest + * @class ServiceWebTest * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -class CAS_Tests_ServiceWebTest extends PHPUnit_Framework_TestCase +class ServiceWebTest extends PHPUnit_Framework_TestCase { /** - * @var CAS_Client + * @var Client */ protected $object; @@ -52,7 +58,7 @@ class CAS_Tests_ServiceWebTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - // phpCAS::setDebug(dirname(__FILE__).'/../test.log'); + // CAS::setDebug(dirname(__FILE__).'/../test.log'); // error_reporting(E_ALL); $_SERVER['SERVER_NAME'] = 'www.clientapp.com'; @@ -62,10 +68,10 @@ protected function setUp() $_SERVER['REQUEST_URI'] = '/'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $_SERVER['PHP_SELF'] = '/index.php'; - $_SESSION = array(); + $_SESSION = []; - $this->object = new CAS_Client( - CAS_VERSION_2_0, // Server Version + $this->object = new Client( + CAS::CAS_VERSION_2_0, // Server Version true, // Proxy 'cas.example.edu', // Server Hostname 443, // Server port @@ -73,17 +79,17 @@ protected function setUp() false // Start Session ); - $this->object->setRequestImplementation('CAS_TestHarness_DummyRequest'); + $this->object->setRequestImplementation('\phpCAS\CAS\TestHarness\DummyRequest'); $this->object->setCasServerCACert('/path/to/ca_cert.crt', true); - // Bypass PGT storage since CAS_Client->callback() will exit. Just build + // Bypass PGT storage since Client->callback() will exit. Just build // up the session manually so that we are in a state from which we can // attempt to fetch proxy tickets and make proxied requests. $_SESSION['phpCAS']['user'] = 'jdoe'; $_SESSION['phpCAS']['pgt'] = 'PGT-clientapp-abc123'; - $_SESSION['phpCAS']['proxies'] = array(); - $_SESSION['phpCAS']['service_cookies'] = array(); - $_SESSION['phpCAS']['attributes'] = array(); + $_SESSION['phpCAS']['proxies'] = []; + $_SESSION['phpCAS']['service_cookies'] = []; + $_SESSION['phpCAS']['attributes'] = []; // Force Authentication to initialize the client. $this->object->forceAuthentication(); @@ -97,25 +103,25 @@ protected function setUp() *********************************************************/ // Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'http://www.service.com/my_webservice', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -126,53 +132,53 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); // Valid Service Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.service.com', '/my_webservice' ); $response->matchQueryParameters( - array('ticket' => 'PT-asdfas-dfasgww2323radf3',) + ['ticket' => 'PT-asdfas-dfasgww2323radf3'] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/plain;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); - $response->setResponseBody("Hello from the service."); - CAS_TestHarness_DummyRequest::addResponse($response); + $response->setResponseBody('Hello from the service.'); + DummyRequest::addResponse($response); /********************************************************* * 2. Proxy Ticket Error *********************************************************/ // Error Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'http://www.service.com/my_other_webservice', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -184,31 +190,31 @@ protected function setUp() ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); /********************************************************* * 3. Server that doesn't respond/exist (sending failure) *********************************************************/ // Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array('targetService' => 'ssh://me.example.net', + ['targetService' => 'ssh://me.example.net', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -219,32 +225,32 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); /********************************************************* * 4. Service With Error status. *********************************************************/ // Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'http://www.service.com/my_webservice_that_has_problems', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -255,18 +261,18 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); // Service Error Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.service.com', '/my_webservice_that_has_problems' ); $response->matchQueryParameters( - array('ticket' => 'PT-12345-abscasdfasdf',) + ['ticket' => 'PT-12345-abscasdfasdf'] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 500 INTERNAL SERVER ERROR', + ['HTTP/1.1 500 INTERNAL SERVER ERROR', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', @@ -274,35 +280,35 @@ protected function setUp() 'Content-Type: text/plain;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); - $response->setResponseBody("Problems have Occurred."); - CAS_TestHarness_DummyRequest::addResponse($response); + $response->setResponseBody('Problems have Occurred.'); + DummyRequest::addResponse($response); /********************************************************* * 5. Valid Proxy ticket and POST service *********************************************************/ // Proxy ticket Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'https', 'cas.example.edu', '/cas/proxy' ); $response->matchQueryParameters( - array( + [ 'targetService' => 'http://www.service.com/post_webservice', 'pgt' => 'PGT-clientapp-abc123', - ) + ] ); $response->ensureIsGet(); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/html;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( " @@ -313,14 +319,14 @@ protected function setUp() " ); $response->ensureCaCertPathEquals('/path/to/ca_cert.crt'); - CAS_TestHarness_DummyRequest::addResponse($response); + DummyRequest::addResponse($response); // Valid Service Response - $response = new CAS_TestHarness_BasicResponse( + $response = new BasicResponse( 'http', 'www.service.com', '/post_webservice' ); $response->matchQueryParameters( - array('ticket' => 'PT-posting-dfasgww2323radf3',) + ['ticket' => 'PT-posting-dfasgww2323radf3'] ); $response->ensureIsPost(); $response->ensurePostBodyEquals( @@ -328,26 +334,25 @@ protected function setUp() ); $response->ensureHasHeader( 'Content-Length: ' - . strlen( + .strlen( 'doSomethingwith this' ) ); $response->ensureHasHeader('Content-Type: text/xml'); $response->setResponseHeaders( - array('HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', + ['HTTP/1.1 200 OK', 'Date: Wed, 29 Sep 2010 19:20:57 GMT', 'Server: Apache-Coyote/1.1', 'Pragma: no-cache', 'Expires: Thu, 01 Jan 1970 00:00:00 GMT', 'Cache-Control: no-cache, no-store', 'Content-Type: text/xml;charset=UTF-8', 'Content-Language: en-US', 'Via: 1.1 cas.example.edu', 'Connection: close', 'Transfer-Encoding: chunked', - ) + ] ); $response->setResponseBody( - "Yay, it worked." + 'Yay, it worked.' ); - CAS_TestHarness_DummyRequest::addResponse($response); - + DummyRequest::addResponse($response); } /** @@ -358,7 +363,7 @@ protected function setUp() */ protected function tearDown() { - CAS_TestHarness_DummyRequest::clearResponses(); + DummyRequest::clearResponses(); } /** @@ -385,8 +390,8 @@ public function testServiceWeb() 'http://www.service.com/my_webservice', $err_code, $output ); $this->assertTrue($result, $output); - $this->assertEquals(PHPCAS_SERVICE_OK, $err_code); - $this->assertEquals("Hello from the service.", $output); + $this->assertEquals(CAS::PHPCAS_SERVICE_OK, $err_code); + $this->assertEquals('Hello from the service.', $output); } /** @@ -402,10 +407,10 @@ public function testServiceWebPtError() ); $this->assertFalse( $result, - "serviceWeb() should have returned false on a PT error." + 'serviceWeb() should have returned false on a PT error.' ); - $this->assertEquals(PHPCAS_SERVICE_PT_FAILURE, $err_code); - $this->assertStringStartsWith("PT retrieving failed", $output); + $this->assertEquals(CAS::PHPCAS_SERVICE_PT_FAILURE, $err_code); + $this->assertStringStartsWith('PT retrieving failed', $output); } /** @@ -421,10 +426,10 @@ public function testServiceWebServiceError() ); $this->assertFalse( $result, - "serviceWeb() should have returned false on a service error." + 'serviceWeb() should have returned false on a service error.' ); - $this->assertEquals(PHPCAS_SERVICE_NOT_AVAILABLE, $err_code); - $this->assertStringStartsWith("The service", $output); + $this->assertEquals(CAS::PHPCAS_SERVICE_NOT_AVAILABLE, $err_code); + $this->assertStringStartsWith('The service', $output); } /** @@ -435,12 +440,12 @@ public function testServiceWebServiceError() public function testHttpGet() { $service = $this->object - ->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + ->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); $service->setUrl('http://www.service.com/my_webservice'); $service->send(); $this->assertEquals(200, $service->getResponseStatusCode()); $this->assertEquals( - "Hello from the service.", $service->getResponseBody() + 'Hello from the service.', $service->getResponseBody() ); } @@ -450,12 +455,12 @@ public function testHttpGet() * * @return void * - * @expectedException CAS_ProxyTicketException + * @expectedException \phpCAS\CAS\ProxyTicketException */ public function testPtException() { $service = $this->object - ->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + ->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); $service->setUrl('http://www.service.com/my_other_webservice'); $this->assertFalse($service->send(), 'Sending should have failed'); } @@ -466,12 +471,12 @@ public function testPtException() * * @return void * - * @expectedException CAS_ProxiedService_Exception + * @expectedException \phpCAS\CAS\ProxiedService\ProxiedServiceException */ public function testHttpGetServiceFailure() { $service = $this->object - ->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + ->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); $service->setUrl('ssh://me.example.net'); $service->send(); } @@ -486,13 +491,13 @@ public function testHttpGetServiceFailure() public function testHttpGetService500Error() { $service = $this->object - ->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET); + ->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_GET); $service ->setUrl('http://www.service.com/my_webservice_that_has_problems'); $service->send(); $this->assertEquals(500, $service->getResponseStatusCode()); $this->assertEquals( - "Problems have Occurred.", $service->getResponseBody() + 'Problems have Occurred.', $service->getResponseBody() ); } @@ -504,7 +509,7 @@ public function testHttpGetService500Error() public function testHttpPost() { $service = $this->object - ->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_POST); + ->getProxiedService(CAS::PHPCAS_PROXIED_SERVICE_HTTP_POST); $service->setUrl('http://www.service.com/post_webservice'); $service->setBody( 'doSomethingwith this' @@ -513,9 +518,8 @@ public function testHttpPost() $service->send(); $this->assertEquals(200, $service->getResponseStatusCode()); $this->assertEquals( - "Yay, it worked.", + 'Yay, it worked.', $service->getResponseBody() ); } } -?> diff --git a/test/README.txt b/test/README.md similarity index 68% rename from test/README.txt rename to test/README.md index d193398b..a3fc168d 100755 --- a/test/README.txt +++ b/test/README.md @@ -1,27 +1,23 @@ -************************** -* Unit Tests for phpCAS -************************** +# Unit Tests for phpCAS These unit tests currently only cover a small portion of the operation of phpCAS. - -************************** -* Running tests -************************** +# Running tests 1. Install PHPUnit using instructions on this page: - http://pear.phpunit.de/ -2. cd to the phpcas/test/ directory. + http://pear.phpunit.de/ + +2. cd to the ```phpCAS/test/``` directory. 3. Run the following command: - phpunit TestSuite.php + ```bash + phpunit TestSuite.php + ``` +# Creating tests -************************** -* Creating tests -************************** -Any files you place in phpcas/test/tests/ whose name ends with 'Test.php' will +Any files you place in CAS/test/tests/ whose name ends with 'Test.php' will be added as a test file. A template test file can be created via the following: @@ -31,7 +27,7 @@ A template test file can be created via the following: 2. Move the skeleton to our tests/ directory. mv source/CAS/CAS_ClientTest.php test/tests/ClientTest.php -Notes: +## Notes: You may want to clear the session in the setUp() method of the test so that each test has a clean state to start from. diff --git a/test/TestSuite.php b/test/TestSuite.php index f0b78a05..5328ee63 100755 --- a/test/TestSuite.php +++ b/test/TestSuite.php @@ -21,81 +21,76 @@ * * @file TestSuite.php * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ -ob_start(); -require_once dirname(__FILE__) . '/../source/CAS.php'; +namespace phpCAS\CAS; + +use PHPUnit_Framework_TestSuite; /** - * Suite of all tests + * Suite of all tests. * * @class TestSuite * @category Authentication - * @package PhpCAS * @author Adam Franco * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://wiki.jasig.org/display/CASC/phpCAS */ - class TestSuite extends PHPUnit_Framework_TestSuite { /** - * Create a new testsuite + * Create a new test suite. * - * @return PhpcasTestSuite + * @return TestSuite */ public static function suite() { - $suite = new TestSuite('phpCAS Test Suite'); + $suite = new self('phpCAS Test Suite'); + + self::recursiveAddTests($suite, dirname(__FILE__).'/CAS/Tests'); - self::recursiveAddTests($suite, dirname(__FILE__) . '/CAS/Tests'); return $suite; } /** - * Empty function - * - * @return void - */ + * Empty function. + * + * @return void + */ protected function setUp() { - } /** - * Empty function + * Empty function. * * @return void */ protected function tearDown() { - } /** - * Recursively add test files in subdirectories + * Recursively add test files in subdirectories. * * @param PHPUnit_Framework_TestSuite $suite a test suite class * @param string $dir dir from which to add tests * * @return void - * - * @access protected */ protected static function recursiveAddTests( PHPUnit_Framework_TestSuite $suite, $dir ) { foreach (scandir($dir) as $file) { if (preg_match('/Test\.php$/', $file)) { - $suite->addTestFile($dir . '/' . $file); - } else if (is_dir($dir . '/' . $file) + $suite->addTestFile($dir.'/'.$file); + } elseif (is_dir($dir.'/'.$file) && preg_match('/^[a-z0-9]+/i', $file) ) { - self::recursiveAddTests($suite, $dir . '/' . $file); + self::recursiveAddTests($suite, $dir.'/'.$file); } } }