code:
OpenID Example Code
-------------------

After you've installed this package (see ../README), you can use these
example packages to get started.  They'll show you what this package
can do, and you can use them as the basis for your own OpenID support.

consumer/: OpenID Example Consumer
==================================

NOTE: If you want to try the example consumer without installing this
package, just make sure you add the package's 'Auth' directory to your
PHP include path.

To try the example consumer implementation, just copy the consumer/
directory into a place on your web server and point your browser at
the new directory.

1. Check to be sure that /tmp is in your "open_basedir" configuration,
   if open_basedir is being used to restrict PHP's file I/O.  See
   http://us2.php.net/features.safe-mode for more information.  For
   example, in your php.ini, change

   open_basedir = "..."

   to

   open_basedir = "/tmp:..."

   (If you really don't want to add /tmp to your open_basedir, you can
   modify consumer/common.php and change $store_path so it doesn't
   create the store directory in /tmp.)

2. Copy or symlink the consumer/ directory into a part of your
   webserver's docroot.  For example, if your DocumentRoot is
   /var/www/, do this:

   # cd /var/www
   # ln -s /path/to/PHP-OpenID-X.Y.Z/examples/consumer

3. Navigate to http://www.example.com/consumer and enter an OpenID
   into the form presented there and click "Verify".

consumer/ Files
===============

The 'index.php' file will render a form and get you started.  These
are the example consumer files:

  consumer/index.php - Renders a form so you can begin the OpenID auth
process.  The form submits the OpenID to try_auth.php.

  consumer/try_auth.php - Starts the authentication with the OpenID
server that manages your OpenID and redirects your browser to the
server's login page.  Instructs the server to return to
finish_auth.php when you're done authenticating.

  consumer/finish_auth.php - Finishes the authentication by checking
the server's response.  Tells you if the authentication was
successful.

  consumer/common.php - Includes the setup code you'll need to create
a Consumer object and participate in an OpenID authentication.

server/: OpenID Example Server
==============================

To try the example server, follow these steps:

1. Copy or symlink the server/ directory into a part of your
   webserver's docroot.  For example, if your DocumentRoot is
   /var/www/, do this:

   # cd /var/www
   # ln -s /path/to/PHP-OpenID-X.Y.Z/examples/server

2. Navigate to the server example.  You'll be redirected to
   server/setup.php where you can choose some configuration options to
   generate a configuration.  Once finished, you can download a file
   "config.php."  Save that file in the example server directory.

The example server has the following features:

 - It serves its own identity pages, whose URLs are of the form

   http://.../server/server.php/idpage?user=USERNAME

 - It does not require passwords.

 - It does not support a "trusted sites" page, as you pointed out.

In general, the example server is NOT supposed to be treated as a
fully-equiped OpenID server (i.e., with user accounts and other
state).  It is supposed to demonstrate how to write PHP applications
that use the library.

Upgrading from the 1.X.X example server
=======================================

The 2.X.X library's example server is different from the 1.X.X example
server in the following ways:

 - The new example server does not support authenticating arbitrary
   URLs.  It serves its own URLs.  This makes it easier to set up and
   test.

 - The new example server does not support password authentication.
   This makes it easier to set up and is not necessary for
   illustrating the use of the library.

 - The new example server does not have a "trusted sites" page.

server/ Files
=============

These files make up the server example code:

  config.php - The configuration file you'll need to customize to run
the example server.

  server.php - The PHP rendering script that takes care of handling
server requests from both regular user agents and consumers.

  lib/actions.php - Handles the various types of requests that the
server supports.

  lib/common.php - Supplies functions that wrap the OpenID API calls
to make them easier to use.

  lib/render.php - Miscellaneous page rendering code.

  lib/session.php - Code to handle session data for user settings.

  lib/render/*.php - Files for each page presented by the server.


code:
<?php

$path_extra = dirname(dirname(dirname(__FILE__)));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

function displayError($message) {
    $error = $message;
    include 'index.php';
    exit(0);
}

function doIncludes() {
    /**
     * Require the OpenID consumer code.
     */
    require_once "Auth/OpenID/Consumer.php";

    /**
     * Require the "file store" module, which we'll need to store
     * OpenID information.
     */
    require_once "Auth/OpenID/FileStore.php";

    /**
     * Require the Simple Registration extension API.
     */
    require_once "Auth/OpenID/SReg.php";

    /**
     * Require the PAPE extension module.
     */
    require_once "Auth/OpenID/PAPE.php";
}

doIncludes();

global $pape_policy_uris;
$pape_policy_uris = array(
			  PAPE_AUTH_MULTI_FACTOR_PHYSICAL,
			  PAPE_AUTH_MULTI_FACTOR,
			  PAPE_AUTH_PHISHING_RESISTANT
			  );

function &getStore() {
    /**
     * This is where the example will store its OpenID information.
     * You should change this path if you want the example store to be
     * created elsewhere.  After you're done playing with the example
     * script, you'll have to remove this directory manually.
     */
    $store_path = null;
    if (function_exists('sys_get_temp_dir')) {
        $store_path = sys_get_temp_dir();
    }
    else {
        if (strpos(PHP_OS, 'WIN') === 0) {
            $store_path = $_ENV['TMP'];
            if (!isset($store_path)) {
                $dir = 'C:\Windows\Temp';
            }
        }
        else {
            $store_path = @$_ENV['TMPDIR'];
            if (!isset($store_path)) {
                $store_path = '/tmp';
            }
        }
    }
    $store_path .= DIRECTORY_SEPARATOR . '_php_consumer_test';

    if (!file_exists($store_path) &&
        !mkdir($store_path)) {
        print "Could not create the FileStore directory '$store_path'. ".
            " Please check the effective permissions.";
        exit(0);
    }
	$r = new Auth_OpenID_FileStore($store_path);

    return $r;
}

function &getConsumer() {
    /**
     * Create a consumer object using the store object created
     * earlier.
     */
    $store = getStore();
	$r = new Auth_OpenID_Consumer($store);
    return $r;
}

function getScheme() {
    $scheme = 'http';
    if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
        $scheme .= 's';
    }
    return $scheme;
}

function getReturnTo() {
    return sprintf("%s://%s:%s%s/finish_auth.php",
                   getScheme(), $_SERVER['SERVER_NAME'],
                   $_SERVER['SERVER_PORT'],
                   dirname($_SERVER['PHP_SELF']));
}

function getTrustRoot() {
    return sprintf("%s://%s:%s%s/",
                   getScheme(), $_SERVER['SERVER_NAME'],
                   $_SERVER['SERVER_PORT'],
                   dirname($_SERVER['PHP_SELF']));
}

?>

repo_name: ksuudilla/gnu

license: mit


code:
<?php

require_once "common.php";
session_start();

function escape($thing) {
    return htmlentities($thing);
}

function run() {
    $consumer = getConsumer();

    // Complete the authentication process using the server's
    // response.
    $return_to = getReturnTo();
    $response = $consumer->complete($return_to);

    // Check the response status.
    if ($response->status == Auth_OpenID_CANCEL) {
        // This means the authentication was cancelled.
        $msg = 'Verification cancelled.';
    } else if ($response->status == Auth_OpenID_FAILURE) {
        // Authentication failed; display the error message.
        $msg = "OpenID authentication failed: " . $response->message;
    } else if ($response->status == Auth_OpenID_SUCCESS) {
        // This means the authentication succeeded; extract the
        // identity URL and Simple Registration data (if it was
        // returned).
        $openid = $response->getDisplayIdentifier();
        $esc_identity = escape($openid);

        $success = sprintf('You have successfully verified ' .
                           '%s as your identity.',
                           $esc_identity, $esc_identity);

        if ($response->endpoint->canonicalID) {
            $escaped_canonicalID = escape($response->endpoint->canonicalID);
            $success .= '  (XRI CanonicalID: '.$escaped_canonicalID.') ';
        }

        $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);

        $sreg = $sreg_resp->contents();

        if (@$sreg['email']) {
            $success .= "  You also returned '".escape($sreg['email']).
                "' as your email.";
        }

        if (@$sreg['nickname']) {
            $success .= "  Your nickname is '".escape($sreg['nickname']).
                "'.";
        }

        if (@$sreg['fullname']) {
            $success .= "  Your fullname is '".escape($sreg['fullname']).
                "'.";
        }

	$pape_resp = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);

	if ($pape_resp) {
            if ($pape_resp->auth_policies) {
                $success .= "
The following PAPE policies affected the authentication:

";

                foreach ($pape_resp->auth_policies as $uri) {
                    $escaped_uri = escape($uri);
                    $success .= "
<tt>$escaped_uri</tt>
";
                }

                $success .= "
";
            } else {
                $success .= "
No PAPE policies affected the authentication.
";
            }

            if ($pape_resp->auth_age) {
                $age = escape($pape_resp->auth_age);
                $success .= "
The authentication age returned by the " .
                    "server is: <tt>".$age."</tt>
";
            }

            if ($pape_resp->nist_auth_level) {
                $auth_level = escape($pape_resp->nist_auth_level);
                $success .= "
The NIST auth level returned by the " .
                    "server is: <tt>".$auth_level."</tt>
";
            }

	} else {
            $success .= "
No PAPE response was sent by the provider.
";
	}
    }

    include 'index.php';
}

run();

?>


code:
<?php
require_once "common.php";

global $pape_policy_uris;
?>

  <title>PHP OpenID Authentication Example</title>

PHP OpenID Authentication Example

      This example consumer uses the PHP
      OpenID library. It just verifies that the URL that you enter
      is your identity URL.

    <?php if (isset($msg)) { print "
$msg
"; } ?>
    <?php if (isset($error)) { print "
$error
"; } ?>
    <?php if (isset($success)) { print "
$success
"; } ?>

      <form method="get" action="try_auth.php">
        Identity URL:
        <input type="hidden" name="action" value="verify" />
        <input type="text" name="openid_identifier" value="" />

Optionally, request these PAPE policies:

        <?php foreach ($pape_policy_uris as $i => $uri) {
          print "<input type=\"checkbox\" name=\"policies[]\" value=\"$uri\" />";
          print "$uri
";
        } ?>

        <input type="submit" value="Verify" />
      </form>


code:
<?php

require_once "common.php";
session_start();

function getOpenIDURL() {
    // Render a default page if we got a submission without an openid
    // value.
    if (empty($_GET['openid_identifier'])) {
        $error = "Expected an OpenID URL.";
        include 'index.php';
        exit(0);
    }

    return $_GET['openid_identifier'];
}

function run() {
    $openid = getOpenIDURL();
    $consumer = getConsumer();

    // Begin the OpenID authentication process.
    $auth_request = $consumer->begin($openid);

    // No auth request means we can't begin OpenID.
    if (!$auth_request) {
        displayError("Authentication error; not a valid OpenID.");
    }

    $sreg_request = Auth_OpenID_SRegRequest::build(
                                     // Required
                                     array('nickname'),
                                     // Optional
                                     array('fullname', 'email'));

    if ($sreg_request) {
        $auth_request->addExtension($sreg_request);
    }

	$policy_uris = null;
	if (isset($_GET['policies'])) {
    	$policy_uris = $_GET['policies'];
	}

    $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
    if ($pape_request) {
        $auth_request->addExtension($pape_request);
    }

    // Redirect the user to the OpenID server for authentication.
    // Store the token for this authentication so we can verify the
    // response.

    // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
    // form to send a POST request to the server.
    if ($auth_request->shouldSendRedirect()) {
        $redirect_url = $auth_request->redirectURL(getTrustRoot(),
                                                   getReturnTo());

        // If the redirect URL can't be built, display an error
        // message.
        if (Auth_OpenID::isFailure($redirect_url)) {
            displayError("Could not redirect to server: " . $redirect_url->message);
        } else {
            // Send redirect.
            header("Location: ".$redirect_url);
        }
    } else {
        // Generate form markup and render it.
        $form_id = 'openid_message';
        $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
                                               false, array('id' => $form_id));

        // Display an error if the form markup couldn't be generated;
        // otherwise, render the HTML.
        if (Auth_OpenID::isFailure($form_html)) {
            displayError("Could not redirect to server: " . $form_html->message);
        } else {
            print $form_html;
        }
    }
}

run();

?>


code:
<?php

$path_extra = dirname(dirname(__FILE__));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

define('IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');

class PlainText {
    function start($title)
    {
        return '';
    }

    function tt($text)
    {
        return $text;
    }

    function link($href, $text=null)
    {
        if ($text) {
            return $text . ' <' . $href . '>';
        } else {
            return $href;
        }
    }

    function b($text)
    {
        return '*' . $text . '*';
    }

    function contentType()
    {
        return 'text/plain';
    }

    function p($text)
    {
        return wordwrap($text) . "\n\n";
    }

    function pre($text)
    {
        $out = '';
        $lines = array_map('trim', explode("\n", $text));
        foreach ($lines as $line) {
            $out .= '    ' . $line . "\n";
        }
        $out .= "\n";
        return $out;
    }

    function ol($items)
    {
        $out = '';
        $c = 1;
        foreach ($items as $item) {
            $item = wordwrap($item, 72);
            $lines = array_map('trim', explode("\n", $item));
            $out .= $c . '. ' . $lines[0] . "\n";
            unset($lines[0]);
            foreach ($lines as $line) {
                $out .= '   ' . $line . "\n";
            }
            $out .= "\n";
            $c += 1;
        }
        return $out;
    }

    function h2($text)
    {
        return $this->h($text, 2);
    }

    function h1($text)
    {
        return $this->h($text, 1);
    }

    function h($text, $n)
    {
        $chars = '#=+-.';
        $c = $chars[$n - 1];
        return "\n" . $text . "\n" . str_repeat($c, strlen($text)) . "\n\n";
    }

    function end()
    {
        return '';
    }
}

class HTML {
    function start($title)
    {
        return '<title>' . $title . '</title>' .
            $this->stylesheet().
            '' . "\n";
    }

    function stylesheet()
    {
        return "';
    }

    function tt($text)
    {
        return '' . $text . '';
    }

    function contentType()
    {
        return 'text/html';
    }

    function b($text)
    {
        return '' . $text . '';
    }

    function p($text)
    {
        return '
' . wordwrap($text) . "
\n";
    }

    function pre($text)
    {
        return '
' . $text . "
\n";
    }

    function ol($items)
    {
        $out = '
';
        foreach ($items as $item) {
            $out .= '
' . wordwrap($item) . "
\n";
        }
        $out .= "
\n";
        return $out;
    }

    function h($text, $n)
    {
        return "<h$n>$text</h$n>\n";
    }

    function h2($text)
    {
        return $this->h($text, 2);
    }

    function h1($text)
    {
        return $this->h($text, 1);
    }

    function link($href, $text=null)
    {
        return '' . ($text ? $text : $href) . '';
    }

    function end()
    {
        return "\n\n";
    }
}

if (isset($_SERVER['REQUEST_METHOD'])) {
    $r = new HTML();
} else {
    $r = new PlainText();
}

function detect_math($r, &$out)
{
    $out .= $r->h2('Math support');
    $ext = Auth_OpenID_detectMathLibrary(Auth_OpenID_math_extensions());
    if (!isset($ext['extension']) || !isset($ext['class'])) {
        $out .= $r->p(
            'Your PHP installation does not include big integer math ' .
            'support. This support is required if you wish to run a ' .
            'secure OpenID server without using SSL.');
        $out .= $r->p('To use this library, you have a few options:');

        $gmp_lnk = $r->link('http://www.php.net/manual/en/ref.gmp.php', 'GMP');
        $bc_lnk = $r->link('http://www.php.net/manual/en/ref.bc.php', 'bcmath');
        $out .= $r->ol(array(
            'Install the ' . $gmp_lnk . ' PHP extension',
            'Install the ' . $bc_lnk . ' PHP extension',
            'If your site is low-security, call ' .
            'Auth_OpenID_setNoMathSupport(), defined in Auth/OpenID/BigMath.php. ',
	    'The library will function, but ' .
            'the security of your OpenID server will depend on the ' .
            'security of the network links involved. If you are only ' .
            'using consumer support, you should still be able to operate ' .
            'securely when the users are communicating with a ' .
            'well-implemented server.'));
        return false;
    } else {
        switch ($ext['extension']) {
        case 'bcmath':
            $out .= $r->p('Your PHP installation has bcmath support. This is ' .
                  'adequate for small-scale use, but can be CPU-intensive. ' .
                  'You may want to look into installing the GMP extension.');
            $lnk = $r->link('http://www.php.net/manual/en/ref.gmp.php');
            $out .= $r->p('See ' . $lnk .' for more information ' .
                          'about the GMP extension.');
            break;
        case 'gmp':
            $out .= $r->p('Your PHP installation has gmp support. Good.');
            break;
        default:
            $class = $ext['class'];
            $lib = new $class();
            $one = $lib->init(1);
            $two = $lib->add($one, $one);
            $t = $lib->toString($two);
            $out .= $r->p('Uh-oh. I do not know about the ' .
                          $ext['extension'] . ' extension!');
            if ($t != '2') {
                $out .= $r->p('It looks like it is broken. 1 + 1 = ' .
                  var_export($t, false));
                return false;
            } else {
                $out .= $r->p('But it seems to be able to add one and one.');
            }
        }
        return true; // Math library is OK
    }
}

function detect_random($r, &$out)
{
    $out .= $r->h2('Cryptographic-quality randomness source');
    if (Auth_OpenID_RAND_SOURCE === null) {
        $out .= $r->p('Using (insecure) pseudorandom number source, because ' .
                      'Auth_OpenID_RAND_SOURCE has been defined as null.');
        return false;
    }

    $msg = 'The library will try to access ' . Auth_OpenID_RAND_SOURCE
        . ' as a source of random data. ';

    $numbytes = 6;

    $f = @fopen(Auth_OpenID_RAND_SOURCE, 'r');
    if ($f !== false) {
        $data = fread($f, $numbytes);
        $stat = fstat($f);
        $size = $stat['size'];
        fclose($f);
    } else {
        $data = null;
        $size = true;
    }

    if ($f !== false) {
        $dataok = (Auth_OpenID::bytes($data) == $numbytes);
        $ok = $dataok && !$size;
        $msg .= 'It seems to exist ';
        if ($dataok) {
            $msg .= 'and be readable. Here is some hex data: ' .
                bin2hex($data) . '.';
        } else {
            $msg .= 'but reading data failed.';
        }
        if ($size) {
            $msg .= ' This is a ' . $size . ' byte file. Unless you know ' .
                'what you are doing, it is likely that you are making a ' .
                'mistake by using a regular file as a randomness source.';
        }
    } else {
        $msg .= Auth_OpenID_RAND_SOURCE .
            ' could not be opened. This could be because of restrictions on' .
            ' your PHP environment or that randomness source may not exist' .
            ' on this platform.';
        if (IS_WINDOWS) {
            $msg .= ' You seem to be running Windows. This library does not' .
                ' have access to a good source of randomness on Windows.';
        }
        $ok = false;
    }

    $out .= $r->p($msg);

    if (!$ok) {
        $out .= $r->p(
            'To set a source of randomness, define Auth_OpenID_RAND_SOURCE ' .
            'to the path to the randomness source. If your platform does ' .
            'not provide a secure randomness source, the library can' .
            'operate in pseudorandom mode, but it is then vulnerable to ' .
            'theoretical attacks. If you wish to operate in pseudorandom ' .
            'mode, define Auth_OpenID_RAND_SOURCE to null.');
        $out .= $r->p('You are running on:');
        $out .= $r->pre(php_uname());
        $out .= $r->p('There does not seem to be an available source ' .
                      'of randomness. On a Unix-like platform ' .
                      '(including MacOS X), try /dev/random and ' .
                      '/dev/urandom.');
    }
    return $ok;
}

function detect_stores($r, &$out)
{
    $out .= $r->h2('Data storage');

    $found = array();
    foreach (array('sqlite', 'mysql', 'pgsql') as $dbext) {
        if (extension_loaded($dbext) || (function_exists('dl') && @dl($dbext . '.' . PHP_SHLIB_SUFFIX))) {
            $found[] = $dbext;
        }
    }
    if (count($found) == 0) {
        $text = 'No SQL database support was found in this PHP ' .
            'installation. See the PHP manual if you need to ' .
            'use an SQL database.';
    } else {
        $text = 'Support was found for ';
        if (count($found) == 1) {
            $text .= $found[0] . '.';
        } else {
            $last = array_pop($found);
            $text .= implode(', ', $found) . ' and ' . $last . '.';
        }
	$text = $r->b($text);
    }
    $text .= ' The library supports the MySQL, PostgreSQL, and SQLite ' .
        'database engines, as well as filesystem-based storage.  In ' .
        'addition, PEAR DB is required to use databases.';
    $out .= $r->p($text);

    if (function_exists('posix_getpwuid') &&
        function_exists('posix_geteuid')) {
        $processUser = posix_getpwuid(posix_geteuid());
        $web_user = $r->b($r->tt($processUser['name']));
    } else {
        $web_user = 'the PHP process';
    }

    if (in_array('sqlite', $found)) {
        $out .= $r->p('If you are using SQLite, your database must be ' .
                      'writable by ' . $web_user . ' and not available over' .
                      ' the web.');
    }

    $basedir_str = ini_get('open_basedir');
    if (gettype($basedir_str) == 'string' && $basedir_str) {
        $url = 'http://www.php.net/manual/en/features.safe-mode.php' .
            '#ini.open-basedir';
        $lnk = $r->link($url, 'open_basedir');
        $out .= $r->p('If you are using a filesystem-based store or SQLite, ' .
                      'be aware that ' . $lnk . ' is in effect. This means ' .
                      'that your data will have to be stored in one of the ' .
                      'following locations:');
        $out .= $r->pre(var_export($basedir_str, true));
    } else {
        $out .= $r->p('The ' . $r->b($r->tt('open_basedir')) . ' configuration restriction ' .
		      'is not in effect.');
    }

    $out .= $r->p('If you are using the filesystem store, your ' .
                  'data directory must be readable and writable by ' .
                  $web_user . ' and not available over the Web.');
    return true;
}

function detect_xml($r, &$out)
{
    global $__Auth_Yadis_xml_extensions;

    $out .= $r->h2('XML Support');

    // Try to get an XML extension.
    $ext = Auth_Yadis_getXMLParser();

    if ($ext !== null) {
        $out .= $r->p('XML parsing support is present using the '.
                      $r->b(get_class($ext)).' interface.');
        return true;
    } else {
        $out .= $r->p('XML parsing support is absent; please install one '.
                      'of the following PHP extensions:');
        foreach ($__Auth_Yadis_xml_extensions as $name => $cls) {
            $out .= "
" . $r->b($name) . "
";
        }
        return false;
    }
}

function detect_query_corruption($r, &$out)
{
    $out .= $r->h2('Query Corruption');
    if ($_SERVER["QUERY_STRING"]!="test_query=a%26b")
    {
        $out.=$r->p("Your web server seems to corrupt queries.  Received ".$_SERVER["QUERY_STRING"].", expected a=%26b. Check for mod_encoding.");
	    return false;
    }
    else
    {
        $out.=$r->p("Your web server does not corrupt queries.  Good.");
	    return true;
    }
}

function detect_fetcher($r, &$out)
{
    $out .= $r->h2('HTTP Fetching');

    $result = @include 'Auth/Yadis/Yadis.php';

    if (!$result) {
        $out .= $r->p('Yadis code unavailable; could not test fetcher support.');
	return false;
    }

    if (Auth_Yadis_Yadis::curlPresent()) {
        $out .= $r->p('This PHP installation has support for libcurl. Good.');
    } else {
        $out .= $r->p('This PHP installation does not have support for ' .
                      'libcurl. CURL is not required but is recommended. '.
                      'The OpenID library will use an fsockopen()-based fetcher.');
        $lnk = $r->link('http://us3.php.net/manual/en/ref.curl.php');
        $out .= $r->p('See ' . $lnk . ' about enabling the libcurl support ' .
                      'for PHP.');
    }

    $ok = true;
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    $fetch_url = 'https://gist.github.com/chuckpearce/6810258/raw/c57eff55ebc0c54973903af5f72bac72762cf4f4/gistfile1.txt';
    $expected_url = $fetch_url;// . '.txt';
    $result = $fetcher->get($fetch_url);

    if (isset($result)) {
        $parts = array('An HTTP request was completed.');
        // list ($code, $url, $data) = $result;
        if ($result->status != '200' && $result->status != '206') {
            $ok = false;
            $parts[] = $r->b(
                sprintf(
                    'Got %s instead of the expected HTTP status ' .
                    'code (200 or 206).', $result->status));
        }

        $url = $result->final_url;
        if ($url != $expected_url) {
            $ok = false;
            if ($url == $fetch_url) {
                $msg = 'The redirected URL was not returned.';
            } else {
                $msg = 'An unexpected URL was returned: ' . $url . '.';
            }
            $parts[] = $r->b($msg);
        }

        $data = $result->body;
        if ($data != 'Hello World!') {
            $ok = false;
            $parts[] = $r->b('Unexpected data was returned.');
        }
        $out .= $r->p(implode(' ', $parts));
    } else {
        $ok = false;
        $out .= $r->p('Fetching URL ' . $lnk . ' failed!');
    }

    if ($fetcher->supportsSSL()) {
        $out .= $r->p('Your PHP installation appears to support SSL, so it ' .
                      'will be able to process HTTPS identity URLs and server URLs.');
    } else {
        $out .= $r->p('Your PHP installation does not support SSL, so it ' .
                      'will NOT be able to process HTTPS identity URLs and server URLs.');
    }

    return $ok;
}

header('Content-Type: ' . $r->contentType() . '; charset=us-ascii');
if (empty($_GET["test_query"]))
{
    header("Location: ".$_SERVER['PHP_SELF']."?test_query=a%26b");
}

    $title = 'OpenID Library Support Report';
$out = $r->start($title) .
    $r->h1($title) .
    $r->p('This script checks your PHP installation to determine if you ' .
          'are set up to use the JanRain PHP OpenID library.');

$body = '';

$_include = include 'Auth/OpenID.php';

if (!$_include) {
    $path = ini_get('include_path');
    $body .= $r->p(
        'Cannot find the OpenID library. It must be in your PHP include ' .
        'path. Your PHP include path is currently:');
    $body .= $r->pre($path);
} else {
    $status = array();

    $status[] = detect_math($r, $body);
    $status[] = detect_random($r, $body);
    $status[] = detect_stores($r, $body);
    $status[] = detect_fetcher($r, $body);
    $status[] = detect_xml($r, $body);

    if (isset($_SERVER['REQUEST_METHOD'])) {
        $status[] = detect_query_corruption($r, $body);
    }

    $result = true;

    foreach ($status as $v) {
        if (!$v) {
            $result = false;
            break;
        }
    }

    if ($result) {
        $out .= $r->h2('Setup Complete!');
	$out .= $r->p('Your system should be ready to run the OpenID library.');
    } else {
        $out .= $r->h2('Setup Incomplete');
	$out .= $r->p('Your system needs a few changes before it will be ready to run the OpenID library.');
    }
}

$out .= $body . $r->end();
print $out;
?>


code:
<?php

require_once "consumer/common.php";

require_once "Auth/OpenID/Discover.php";
require_once "Auth/Yadis/Yadis.php";

function getOpenIDIdentifier()
{
    return $_GET['openid_identifier'];
}

function escape($x)
{
    return htmlentities($x);
}

$identifier = getOpenIDIdentifier();
?>

<title>OpenID discovery</title>

OpenID discovery tool

    Enter an OpenID URL to begin discovery:

  <form>
  <input type="text" name="openid_identifier" size="40" />
  <input type="submit" value="Begin" />
  </form>
<?php
if ($identifier) {

    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    list($normalized_identifier, $endpoints) = Auth_OpenID_discover(
        $identifier, $fetcher);

?>

Discovery Results for <?php echo escape($identifier) ?>

        Claimed Identifier
        <?php echo escape($normalized_identifier) ?>

<?php
if (!$endpoints) {
?>

      No OpenID services discovered.

<?php
} else {
?>

      Discovered OpenID services:

<?php
foreach ($endpoints as $endpoint) {
?>

      Server URL
      <tt><?php echo escape($endpoint->server_url) ?></tt>

      Local ID
      <tt><?php echo escape($endpoint->local_id) ?></tt>

Service types:

<?php
foreach ($endpoint->type_uris as $type_uri) {
?>

<tt><?php echo escape($type_uri) ?></tt>

<?php
}
?>

<?php
}
}
?>

<?php
}
?>


code:
<?php

header("Location: server.php");

?>


code:
<?php

require_once "lib/common.php";
require_once "lib/session.php";
require_once "lib/render.php";

require_once "lib/render/login.php";
require_once "lib/render/idpage.php";
require_once "lib/render/idpXrds.php";
require_once "lib/render/userXrds.php";

require_once "Auth/OpenID.php";

/**
 * Handle a standard OpenID server request
 */
function action_default()
{
    header('X-XRDS-Location: '.buildURL('idpXrds'));

    $server = getServer();
    $method = $_SERVER['REQUEST_METHOD'];
    $request = null;
    if ($method == 'GET') {
        $request = $_GET;
    } else {
        $request = $_POST;
    }

    $request = $server->decodeRequest();

    if (!$request) {
        return about_render();
    }

    setRequestInfo($request);

    if (in_array($request->mode,
                 array('checkid_immediate', 'checkid_setup'))) {

        if ($request->idSelect()) {
            // Perform IDP-driven identifier selection
            if ($request->mode == 'checkid_immediate') {
                $response = $request->answer(false);
            } else {
                return trust_render($request);
            }
        } else if ((!$request->identity) &&
                   (!$request->idSelect())) {
            // No identifier used or desired; display a page saying
            // so.
            return noIdentifier_render();
        } else if ($request->immediate) {
            $response = $request->answer(false, buildURL());
        } else {
            if (!getLoggedInUser()) {
                return login_render();
            }
            return trust_render($request);
        }
    } else {
        $response = $server->handleRequest($request);
    }

    $webresponse = $server->encodeResponse($response);

    if ($webresponse->code != AUTH_OPENID_HTTP_OK) {
        header(sprintf("HTTP/1.1 %d ", $webresponse->code),
               true, $webresponse->code);
    }

    foreach ($webresponse->headers as $k => $v) {
        header("$k: $v");
    }

    header(header_connection_close);
    print $webresponse->body;
    exit(0);
}

/**
 * Log out the currently logged in user
 */
function action_logout()
{
    setLoggedInUser(null);
    setRequestInfo(null);
    return authCancel(null);
}

/**
 * Check the input values for a login request
 */
function login_checkInput($input)
{
    $openid_url = false;
    $errors = array();

    if (!isset($input['openid_url'])) {
        $errors[] = 'Enter an OpenID URL to continue';
    }
    if (count($errors) == 0) {
        $openid_url = $input['openid_url'];
    }
    return array($errors, $openid_url);
}

/**
 * Log in a user and potentially continue the requested identity approval
 */
function action_login()
{
    $method = $_SERVER['REQUEST_METHOD'];
    switch ($method) {
    case 'GET':
        return login_render();
    case 'POST':
        $info = getRequestInfo();
        $fields = $_POST;
        if (isset($fields['cancel'])) {
            return authCancel($info);
        }

        list ($errors, $openid_url) = login_checkInput($fields);
        if (count($errors) || !$openid_url) {
            $needed = $info ? $info->identity : false;
            return login_render($errors, @$fields['openid_url'], $needed);
        } else {
            setLoggedInUser($openid_url);
            return doAuth($info);
        }
    default:
        return login_render(array('Unsupported HTTP method: $method'));
    }
}

/**
 * Ask the user whether he wants to trust this site
 */
function action_trust()
{
    $info = getRequestInfo();
    $trusted = isset($_POST['trust']);
    return doAuth($info, $trusted, true, @$_POST['idSelect']);
}

function action_idpage()
{
    $identity = $_GET['user'];
    return idpage_render($identity);
}

function action_idpXrds()
{
    return idpXrds_render();
}

function action_userXrds()
{
    $identity = $_GET['user'];
    return userXrds_render($identity);
}

?>


code:
<?php

require_once "lib/render.php";
require_once "lib/session.php";

require_once "lib/render/login.php";
require_once "lib/render/about.php";
require_once "lib/render/trust.php";

require_once "Auth/OpenID/Server.php";
require_once "Auth/OpenID/SReg.php";

function authCancel($info)
{
    if ($info) {
        setRequestInfo();
        $url = $info->getCancelURL();
    } else {
        $url = getServerURL();
    }
    return redirect_render($url);
}

function doAuth($info, $trusted=null, $fail_cancels=false,
                $idpSelect=null)
{
    if (!$info) {
        // There is no authentication information, so bail
        return authCancel(null);
    }

    if ($info->idSelect()) {
        if ($idpSelect) {
            $req_url = idURL($idpSelect);
        } else {
            $trusted = false;
        }
    } else {
        $req_url = $info->identity;
    }

    $user = getLoggedInUser();
    setRequestInfo($info);

    if ((!$info->idSelect()) && ($req_url != idURL($user))) {
        return login_render(array(), $req_url, $req_url);
    }

    $trust_root = $info->trust_root;

    if ($trusted) {
        setRequestInfo();
        $server = getServer();
        $response = $info->answer(true, null, $req_url);

        // Answer with some sample Simple Registration data.
        $sreg_data = array(
                           'fullname' => 'Example User',
                           'nickname' => 'example',
                           'dob' => '1970-01-01',
                           'email' => 'invalid@example.com',
                           'gender' => 'F',
                           'postcode' => '12345',
                           'country' => 'ES',
                           'language' => 'eu',
                           'timezone' => 'America/New_York');

        // Add the simple registration response values to the OpenID
        // response message.
        $sreg_request = Auth_OpenID_SRegRequest::fromOpenIDRequest(
                                              $info);

        $sreg_response = Auth_OpenID_SRegResponse::extractResponse(
                                              $sreg_request, $sreg_data);

        $sreg_response->toMessage($response->fields);

        // Generate a response to send to the user agent.
        $webresponse = $server->encodeResponse($response);

        $new_headers = array();

        foreach ($webresponse->headers as $k => $v) {
            $new_headers[] = $k.": ".$v;
        }

        return array($new_headers, $webresponse->body);
    } elseif ($fail_cancels) {
        return authCancel($info);
    } else {
        return trust_render($info);
    }
}

?>


code:
<?php

define('page_template',
'

    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <title>%s</title>
%s

    %s

%s

    %s

');

define('logged_in_pat', 'You are logged in as %s (URL: %s)');

/**
 * HTTP response line contstants
 */
define('http_bad_request', 'HTTP/1.1 400 Bad Request');
define('http_found', 'HTTP/1.1 302 Found');
define('http_ok', 'HTTP/1.1 200 OK');
define('http_internal_error', 'HTTP/1.1 500 Internal Error');

/**
 * HTTP header constants
 */
define('header_connection_close', 'Connection: close');
define('header_content_text', 'Content-Type: text/plain; charset=us-ascii');

define('redirect_message',
       'Please wait; you are being redirected to <%s>');

/**
 * Return a string containing an anchor tag containing the given URL
 *
 * The URL does not need to be quoted, but if text is passed in, then
 * it does.
 */
function link_render($url, $text=null) {
    $esc_url = htmlspecialchars($url, ENT_QUOTES);
    $text = ($text === null) ? $esc_url : $text;
    return sprintf('%s', $esc_url, $text);
}

/**
 * Return an HTTP redirect response
 */
function redirect_render($redir_url)
{
    $headers = array(http_found,
                     header_content_text,
                     header_connection_close,
                     'Location: ' . $redir_url,
                     );
    $body = sprintf(redirect_message, $redir_url);
    return array($headers, $body);
}

function navigation_render($msg, $items)
{
    $what = link_render(buildURL(), 'PHP OpenID Server');
    if ($msg) {
        $what .= ' — ' . $msg;
    }
    if ($items) {
        $s = '
' . $what . '

';
        foreach ($items as $action => $text) {
            $url = buildURL($action);
            $s .= sprintf('
%s
', link_render($url, $text));
        }
        $s .= '
';
    } else {
        $s = '
' . $what . '
';
    }
    return sprintf('
%s
', $s);
}

/**
 * Render an HTML page
 */
function page_render($body, $user, $title, $h1=null, $login=false)
{
    $h1 = $h1 ? $h1 : $title;

    if ($user) {
        $msg = sprintf(logged_in_pat, link_render(idURL($user), $user),
                       link_render(idURL($user)));
        $nav = array('logout' => 'Log Out');

        $navigation = navigation_render($msg, $nav);
    } else {
        if (!$login) {
            $msg = link_render(buildURL('login'), 'Log In');
            $navigation = navigation_render($msg, array());
        } else {
            $navigation = '';
        }
    }

    $style = getStyle();
    $text = sprintf(page_template, $title, $style, $navigation, $h1, $body);
    // No special headers here
    $headers = array();
    return array($headers, $text);
}

?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

define('about_error_template',
       '

An error occurred when processing your request:

%s

');

define('about_body',
       '

  This is an OpenID server
  endpoint. This server is built on the JanRain PHP OpenID
  library. Since OpenID consumer sites will need to directly contact this
  server, it must be accessible over the Internet (not behind a firewall).

  To use this server, you will have to set up a URL to use as an identifier.
  Insert the following markup into the <head> of the HTML
  document at that URL:

<link rel="openid.server" href="%s" />

  Then configure this server so that you can log in with that URL.

');

/**
 * Render the about page, potentially with an error message
 */
function about_render($error=false, $internal=true)
{
    $headers = array();
    $body = sprintf(about_body, buildURL());
    if ($error) {
        $headers[] = $internal ? http_internal_error : http_bad_request;
        $body .= sprintf(about_error_template, htmlspecialchars($error));
    }
    $current_user = getLoggedInUser();
    return page_render($body, $current_user, 'OpenID Server Endpoint');
}

?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

require_once "Auth/OpenID/Discover.php";

define('idp_xrds_pat', '<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS
    xmlns:xrds="xri://$xrds"
    xmlns="xri://$xrd*($v*2.0)">
  <XRD>
    <Service priority="0">
      <Type>%s</Type>
      <URI>%s</URI>
    </Service>
  </XRD>
</xrds:XRDS>
');

function idpXrds_render()
{
    $headers = array('Content-type: application/xrds+xml');

    $body = sprintf(idp_xrds_pat,
                    Auth_OpenID_TYPE_2_0_IDP,
                    buildURL());

    return array($headers, $body);
}

?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

define('idpage_pat',
       '<html>
<head>
  <link rel="openid2.provider openid.server" href="%s"/>
  <meta http-equiv="X-XRDS-Location" content="%s" />
</head>
<body>
  This is the identity page for users of this server.
</body>
</html>');

function idpage_render($identity)
{
    $xrdsurl = buildURL('userXrds')."?user=".urlencode($identity);

    $headers = array(
                     'X-XRDS-Location: '.$xrdsurl);

    $body = sprintf(idpage_pat,
                    buildURL(),
                    $xrdsurl);
    return array($headers, $body);
}

?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

define('login_form_pat',
       '

    Enter your username into this form to log in to this server.  It
    can be anything; this is just for demonstration purposes.  For
    example, entering USERNAME will give you the identity URL

%s

  <form method="post" action="%s">

        Name:
        <input type="text" name="openid_url"
                   value="%s" id="openid_url" />

          <input type="submit" value="Log in" />
          <input type="submit" name="cancel" value="Cancel" />

  </form>

');

define('login_needed_pat',
       'You must be logged in as %s to approve this request.');

function login_render($errors=null, $input=null, $needed=null)
{
    $current_user = getLoggedInUser();
    if ($input === null) {
        $input = $current_user;
    }
    if ($needed) {
        $errors[] = sprintf(login_needed_pat, link_render($needed));
    }

    $esc_input = htmlspecialchars($input, ENT_QUOTES);
    $login_url = buildURL('login', true);
    $body = sprintf(login_form_pat, idURL('USERNAME'), $login_url, $esc_input);
    if ($errors) {
        $body = loginError_render($errors) . $body;
    }
    return page_render($body, $current_user, 'Log In', null, true);
}

function loginError_render($errors)
{
    $text = '';
    foreach ($errors as $error) {
        $text .= sprintf("
%s
\n", $error);
    }
    return sprintf("
\n%s
\n", $text);
}
?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

define('trust_form_pat',
       '

  <form method="post" action="%s">
  %s
    <input type="submit" name="trust" value="Confirm" />
    <input type="submit" value="Do not confirm" />
  </form>

');

define('normal_pat',
       '
Do you wish to confirm your identity ' .
       '(%s) with %s?
');

define('id_select_pat',
       '
You entered the server URL at the RP.
Please choose the name you wish to use.  If you enter nothing, the request will be cancelled.

<input type="text" name="idSelect" />

');

define('no_id_pat',
'
You did not send an identifier with the request,
and it was not an identifier selection request.
Please return to the relying party and try again.
');

function trust_render($info)
{
    $current_user = getLoggedInUser();
    $lnk = link_render(idURL($current_user));
    $trust_root = htmlspecialchars($info->trust_root);
    $trust_url = buildURL('trust', true);

    if ($info->idSelect()) {
        $prompt = id_select_pat;
    } else {
        $prompt = sprintf(normal_pat, $lnk, $trust_root);
    }

    $form = sprintf(trust_form_pat, $trust_url, $prompt);

    return page_render($form, $current_user, 'Trust This Site');
}

function noIdentifier_render()
{
    return page_render(no_id_pat, null, 'No Identifier Sent');
}

?>


code:
<?php

require_once "lib/session.php";
require_once "lib/render.php";

require_once "Auth/OpenID/Discover.php";

define('user_xrds_pat', '<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS
    xmlns:xrds="xri://$xrds"
    xmlns="xri://$xrd*($v*2.0)">
  <XRD>
    <Service priority="0">
      <Type>%s</Type>
      <Type>%s</Type>
      <URI>%s</URI>
    </Service>
  </XRD>
</xrds:XRDS>
');

function userXrds_render($identity)
{
    $headers = array('Content-type: application/xrds+xml');

    $body = sprintf(user_xrds_pat,
                    Auth_OpenID_TYPE_2_0,
                    Auth_OpenID_TYPE_1_1,
                    buildURL());

    return array($headers, $body);
}

?>


code:
<?php

require_once "config.php";
require_once "lib/render.php";
require_once "Auth/OpenID/Server.php";

/**
 * Set up the session
 */
function init()
{
    session_name('openid_server');
    session_start();
}

/**
 * Get the style markup
 */
function getStyle()
{
    $parent = rtrim(dirname(getServerURL()), '/');
    $url = htmlspecialchars($parent . '/openid-server.css', ENT_QUOTES);
    return sprintf('<link rel="stylesheet" type="text/css" href="%s" />', $url);
}

/**
 * Get the URL of the current script
 */
function getServerURL()
{
    $path = $_SERVER['SCRIPT_NAME'];
    $host = $_SERVER['HTTP_HOST'];
    $port = $_SERVER['SERVER_PORT'];
    $s = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 's' : '';
    if (($s && $port == "443") || (!$s && $port == "80")) {
        $p = '';
    } else {
        $p = ':' . $port;
    }

    return "http$s://$host$p$path";
}

/**
 * Build a URL to a server action
 */
function buildURL($action=null, $escaped=true)
{
    $url = getServerURL();
    if ($action) {
        $url .= '/' . $action;
    }
    return $escaped ? htmlspecialchars($url, ENT_QUOTES) : $url;
}

/**
 * Extract the current action from the request
 */
function getAction()
{
    $path_info = @$_SERVER['PATH_INFO'];
    $action = ($path_info) ? substr($path_info, 1) : '';
    $function_name = 'action_' . $action;
    return $function_name;
}

/**
 * Write the response to the request
 */
function writeResponse($resp)
{
    list ($headers, $body) = $resp;
    array_walk($headers, 'header');
    header(header_connection_close);
    print $body;
}

/**
 * Instantiate a new OpenID server object
 */
function getServer()
{
    static $server = null;
    if (!isset($server)) {
        $server = new Auth_OpenID_Server(getOpenIDStore(),
                                         buildURL());
    }
    return $server;
}

/**
 * Return a hashed form of the user's password
 */
function hashPassword($password)
{
    return bin2hex(Auth_OpenID_SHA1($password));
}

/**
 * Get the openid_url out of the cookie
 *
 * @return mixed $openid_url The URL that was stored in the cookie or
 * false if there is none present or if the cookie is bad.
 */
function getLoggedInUser()
{
    return isset($_SESSION['openid_url'])
        ? $_SESSION['openid_url']
        : false;
}

/**
 * Set the openid_url in the cookie
 *
 * @param mixed $identity_url The URL to set. If set to null, the
 * value will be unset.
 */
function setLoggedInUser($identity_url=null)
{
    if (!isset($identity_url)) {
        unset($_SESSION['openid_url']);
    } else {
        $_SESSION['openid_url'] = $identity_url;
    }
}

function getRequestInfo()
{
    return isset($_SESSION['request'])
        ? unserialize($_SESSION['request'])
        : false;
}

function setRequestInfo($info=null)
{
    if (!isset($info)) {
        unset($_SESSION['request']);
    } else {
        $_SESSION['request'] = serialize($info);
    }
}

function getSreg($identity)
{
    // from config.php
    global $openid_sreg;

    if (!is_array($openid_sreg)) {
        return null;
    }

    return $openid_sreg[$identity];

}

function idURL($identity)
{
    return buildURL('idpage') . "?user=" . $identity;
}

function idFromURL($url)
{
    if (strpos($url, 'idpage') === false) {
        return null;
    }

    $parsed = parse_url($url);

    $q = $parsed['query'];

    $parts = array();
    parse_str($q, $parts);

    return @$parts['user'];
}

?>


code:
body {
    padding: 0;
    margin: 0;
}

#content {
    padding: 0.5em;
    max-width: 50em;
}

ul.error {
    background: #ffaaaa;
    border: 1px solid #ff0000;
    padding: 0.5em;
    padding-left: 1.5em;
}

.login th {
    text-align: left;
}

div.form {
    border: thin solid #777777;
    background: #dddddd;
    padding: 0.5em;
    margin-top: 1em;
}

div.navigation {
    border-bottom: thin solid #cccccc;
    background: #eeeeee;
    font-size: smaller;
    padding: 0.5em;
}

div.navigation h2 {
    margin-top: 0;
}

div.navigation p {
    margin: 0;
}

div.navigation ul {
    margin: 0;
}

div.login p {
    margin-top: 0;
}

h1 {
    margin-top: 0;
}

pre {
    padding: 1em;
    border: 1px solid black;
    background: #ffeebb;
}

#checkup {
    background: url('http://openid.net/favicon.ico') no-repeat;
    padding-left: 16px;
}

th {
    text-align: left;
}

table {
    border-collapse: collapse;
    margin-bottom: 1em;
}


code:
<?php

$path_extra = dirname(dirname(dirname(__FILE__)));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

$try_include = @include 'config.php';

if (!$try_include) {
    header("Location: setup.php");
}

header('Cache-Control: no-cache');
header('Pragma: no-cache');

if (function_exists('getOpenIDStore')) {
    require_once 'lib/session.php';
    require_once 'lib/actions.php';

    init();

    $action = getAction();
    if (!function_exists($action)) {
        $action = 'action_default';
    }

    $resp = $action();

    writeResponse($resp);
} else {
?>

    <title>PHP OpenID Server</title>

PHP OpenID Server

        This server needs to be configured before it can be used. Edit
        config.php to reflect your server's setup, then
        load this page again.

<?php
}
?>


code:
<?php

/**
 * OpenID server configuration script.
 *
 * This script generates a config.php file needed by the server
 * example.
 *
 * @package OpenID.Examples
 * @author JanRain, Inc. <openid@janrain.com>
 * @copyright 2005-2008 Janrain, Inc.
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
 */

$path_extra = dirname(dirname(dirname(__FILE__)));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);
require_once "Auth/OpenID.php";

/**
 * Data.
 */

$store_types = array("Filesystem" => "Auth_OpenID_FileStore",
                     "MySQL" => "Auth_OpenID_MySQLStore",
                     "PostgreSQL" => "Auth_OpenID_PostgreSQLStore",
                     "SQLite" => "Auth_OpenID_SQLiteStore");

/**
 * Main.
 */

$messages = array();

session_start();
init_session();

if (!check_session() ||
    isset($_GET['add_openid'])) {
    render_form();
} else {
    print generate_config(isset($_GET['download']));
}

/**
 * Functions.
 */

function check_url($url) {
    return (Auth_OpenID::normalizeUrl($url) !== null);
}

function build_url() {
    $port = (($_SERVER['SERVER_PORT'] == 80) ? null : $_SERVER['SERVER_PORT']);

    $parts = explode("/", $_SERVER['SERVER_PROTOCOL']);
    $scheme = strtolower($parts[0]);

    if ($port) {
        return sprintf("%s://%s:%s%s/server.php", $scheme, $_SERVER['SERVER_NAME'],
                       $port, dirname($_SERVER['PHP_SELF']));
    } else {
        return sprintf("%s://%s%s/server.php", $scheme, $_SERVER['SERVER_NAME'],
                       dirname($_SERVER['PHP_SELF']));
    }
}

function check_open_basedir($path) {
  if (ini_get('open_basedir')) {
    $parts = explode(PATH_SEPARATOR, ini_get('open_basedir'));

    $found = false;

    foreach ($parts as $p) {
      if (strpos($path, $p) === 0) {
        $found = true;
        break;
      }
    }

    return $found;
  } else {
    return true;
  }
}

function check_session() {

    global $messages;

    if ($_GET && isset($_GET['clear'])) {
        session_destroy();
        $_SESSION = array();
        init_session();
        return false;
    }

    $bad_path = false;

    if (isset($_GET['generate'])) {
        if (!$_SESSION['server_url']) {
            $messages[] = "Please enter a server URL.";
        }

        if (!isset($_SESSION['store_type'])) {
            $messages[] = "No store type chosen.";
        } else {
            switch ($_SESSION['store_type']) {
            case "Filesystem":
                if (!@$_SESSION['store_data']['fs_path']) {
                    $messages[] = "Please specify a filesystem store path.";
                } else {
                  if (!check_open_basedir($_SESSION['store_data']['fs_path'])) {
                    $messages[] = "The filesystem store path violates PHP's open_basedir setting.";
                    $bad_path = true;
                  }
                }
                break;

            case "SQLite":
                if (!@$_SESSION['store_data']['sqlite_path']) {
                    $messages[] = "Please specify a SQLite database path.";
                } else {
                  if (!check_open_basedir($_SESSION['store_data']['sqlite_path'])) {
                    $messages[] = "The SQLite store path violates PHP's open_basedir setting.";
                    $bad_path = true;
                  }
                }
                break;

            default:
                if (!($_SESSION['store_data']['host'] &&
                      $_SESSION['store_data']['database'] &&
                      $_SESSION['store_data']['username'] &&
                      $_SESSION['store_data']['password'])) {
                    $messages[] = "Please specify database connection details.";
                }
            }
        }
    }

    if ($_SESSION['store_type'] &&
        $_SESSION['server_url'] &&
        (parse_url($_SESSION['server_url']) !== false) &&
        ((($_SESSION['store_type'] == 'Filesystem') &&
          $_SESSION['store_data']['fs_path']) ||
         (($_SESSION['store_type'] == 'SQLite') &&
          $_SESSION['store_data']['sqlite_path']) ||
         ($_SESSION['store_data']['host'] &&
          $_SESSION['store_data']['username'] &&
          $_SESSION['store_data']['database'] &&
          $_SESSION['store_data']['password'])) &&
        !$bad_path) {

        return true;
    }

    return false;
}

function render_form() {

    global $store_types, $fields, $messages;

    $basedir_msg = "";

    if (ini_get('open_basedir')) {
        $basedir_msg = "
Note: Due to the ".
            "open_basedir php.ini setting, be sure to ".
            "choose a path in one of the following directories:

".
            implode("
",
                    explode(PATH_SEPARATOR, ini_get('open_basedir'))).
            "
";
    }

    $sqlite_found = false;
    if (extension_loaded('sqlite') ||
        (function_exists('dl') && @dl('sqlite.' . PHP_SHLIB_SUFFIX))) {
      $sqlite_found = true;
    }

    $mysql_found = false;
    if (extension_loaded('mysql') ||
        (function_exists('dl') && @dl('mysql.' . PHP_SHLIB_SUFFIX))) {
      $mysql_found = true;
    }

    $pgsql_found = false;
    if (extension_loaded('pgsql') ||
        (function_exists('dl') && @dl('pgsql.' . PHP_SHLIB_SUFFIX))) {
      $pgsql_found = true;
    }

?>

OpenID Example Server Configuration

<?php
if ($messages) {
    print "
";
    foreach ($messages as $m) {
        print "
$m
";
    }
    print "
";

}
?>

Your browser has been redirected to this page so you can configure the
server example.  This form will auto-generate an OpenID example server
configuration for use with the OpenID server example.

<form>

  The server URL is the URL that points to the "server.php" file.  It
  looks like your server URL should be <?php print build_url(); ?>.

  Server URL:

    <input type="text" id="i_server_url" size="35" name="server_url"
     value="<?php print $_SESSION['server_url'] ?>">

  If this package isn't installed in the PHP include path, the package's
  directory should be added.  For example, if the package is in
  /home/me/PHP-OpenID/, you should enter that directory here.

    Include path (optional):

    <input type="text" id="i_include_path" size="35" name="include_path"
     value="<?php print $_SESSION['include_path'] ?>">

  The server needs to store OpenID information in a "store".  The
  following store types are available on your PHP installation:

  Store method:

      <input type="radio" name="store_type" value="Filesystem"
       id="i_filesystem"<?php if ($_SESSION['store_type'] == 'Filesystem') { print " CHECKED"; } ?>>
      Filesystem

        Filesystem path:
        <input type="text" name="fs_path" id="i_fs_path"
         value="<?php print @$_SESSION['store_data']['fs_path']; ?>">
        <?php print $basedir_msg; ?>

<?php if ($sqlite_found) { ?>

      <input type="radio" name="store_type" value="SQLite"
       id="i_sqlite"<?php if ($_SESSION['store_type'] == 'SQLite') { print " CHECKED"; } ?>>
      SQLite

        SQLite database path:
        <input type="text" value="<?php print @$_SESSION['store_data']['sqlite_path']; ?>"
         name="sqlite_path" id="i_sqlite_path">
        <?php print $basedir_msg; ?>

<?php } ?>

<?php if ($mysql_found || $pgsql_found) { ?>

<?php if ($mysql_found) { ?>
      <input type="radio" name="store_type" value="MySQL"
       id="i_mysql"<?php if ($_SESSION['store_type'] == 'MySQL') { print " CHECKED"; } ?>>
      MySQL
<?php } ?>

<?php if ($pgsql_found) { ?>
      <input type="radio" name="store_type" value="PostgreSQL"
       id="i_pgsql"<?php if ($_SESSION['store_type'] == 'PostgreSQL') { print " CHECKED"; } ?>>
      PostgreSQL
<?php } ?>

        Host:
        <input type="text" value="<?php print @$_SESSION['store_data']['host']; ?>" name="host" id="i_m_host">

        Database:
        <input value="<?php print @$_SESSION['store_data']['database']; ?>" type="text" name="database" id="i_m_database">

        Username:
        <input type="text" name="username" id="i_m_username" value="<?php print @$_SESSION['store_data']['username']; ?>">

        Password:
        <input type="password" name="password" id="i_m_password" value="<?php print @$_SESSION['store_data']['password']; ?>">

<?php } ?>

<input type="submit" name="generate" value="Generate Configuration">
</form>

<?php
}

function init_session() {

    global $messages;

    // Set a guess value for the server url.
    if (!array_key_exists('server_url', $_SESSION)) {
        $_SESSION['server_url'] = build_url();
    }

    foreach (array('server_url', 'include_path', 'store_type') as $key) {
        if (!isset($_SESSION[$key])) {
            $_SESSION[$key] = "";
        }
    }

    if (!isset($_SESSION['store_data'])) {
        $_SESSION['store_data'] = array();
    }

    foreach (array('server_url', 'include_path', 'store_type') as $field) {
        if (array_key_exists($field, $_GET)) {
            $_SESSION[$field] = $_GET[$field];
        }
    }

    foreach (array('username', 'password', 'database', 'host', 'fs_path', 'sqlite_path') as $field) {
        if (array_key_exists($field, $_GET)) {
            $_SESSION['store_data'][$field] = $_GET[$field];
        }
    }
}

function generate_config($download = false) {

    if ($download) {
        // Emit headers to force browser download.
        header("Content-type: text/plain");
        header("Content-disposition: attachment; filename=config.php");
        print "<?php\n";
    } else {
?>

OpenID Example Server Configuration

Put the following text into <?php print dirname(__FILE__); print DIRECTORY_SEPARATOR; ?>config.php.

Back to form (resets settings)

Download this configuration

<?php
print "<?php\n";
}
?>
<?php if ($_SESSION['include_path']) { ?>
/**
 * Set any extra include paths needed to use the library
 */
set_include_path(get_include_path() . PATH_SEPARATOR . "<?php
print $_SESSION['include_path'];
?>");

<?php } ?>
/**
 * The URL for the server.
 *
 * This is the location of server.php. For example:
 *
 * $server_url = 'http://example.com/~user/server.php';
 *
 * This must be a full URL.
 */
$server_url = "<?php
print $_SESSION['server_url'];
?>";

/**
 * Initialize an OpenID store
 *
 * @return object $store an instance of OpenID store (see the
 * documentation for how to create one)
 */
function getOpenIDStore()
{
    <?php

    switch ($_SESSION['store_type']) {
    case "Filesystem":

        print "require_once \"Auth/OpenID/FileStore.php\";\n    ";
        print "return new Auth_OpenID_FileStore(\"".$_SESSION['store_data']['fs_path']."\");\n";
        break;

    case "SQLite":

        print "require_once \"Auth/OpenID/SQLiteStore.php\";\n    ";
        print "\$s = new Auth_OpenID_SQLiteStore(\"".$_SESSION['store_data']['sqlite_path']."\");\n    ";
        print "\$s->createTables();\n    ";
        print "return \$s;\n";
        break;

    case "MySQL":

        ?>require_once 'Auth/OpenID/MySQLStore.php';
    require_once 'DB.php';

    $dsn = array(
                 'phptype'  => 'mysql',
                 'username' => '<?php print $_SESSION['store_data']['username']; ?>',
                 'password' => '<?php print $_SESSION['store_data']['password']; ?>',
                 'hostspec' => '<?php print $_SESSION['store_data']['host']; ?>'
                 );

    $db = DB::connect($dsn);

    if (PEAR::isError($db)) {
        return null;
    }

    $db->query("USE <?php print $_SESSION['store_data']['database']; ?>");

    $s = new Auth_OpenID_MySQLStore($db);

    $s->createTables();

    return $s;
<?php
        break;

    case "PostgreSQL":

        ?>require_once 'Auth/OpenID/PostgreSQLStore.php';
    require_once 'DB.php';

    $dsn = array(
                 'phptype'  => 'pgsql',
                 'username' => '<?php print $_SESSION['store_data']['username']; ?>',
                 'password' => '<?php print $_SESSION['store_data']['password']; ?>',
                 'hostspec' => '<?php print $_SESSION['store_data']['host']; ?>',
                 'database' => '<?php print $_SESSION['store_data']['database']; ?>'
                 );

    $db = DB::connect($dsn);

    if (PEAR::isError($db)) {
        return null;
    }

    $s = new Auth_OpenID_PostgreSQLStore($db);

    $s->createTables();

    return $s;
<?php
        break;
    }

    ?>
}

<?php
    print "?>";
    if (!$download) {
?>

<?php
      }
    } // end function generate_config ()
?>


code:
language: php
sudo: false

php:
    - "7.2"
    - "7.1"
    - "7.0"
    - "5.6"
    - "hhvm"

matrix:
    fast_finish: true

install:
    - composer self-update
    - composer update

script:
    - vendor/bin/phpunit
    - vendor/bin/psalm


code:
# Constant-Time Encoding

[![Build Status](https://travis-ci.org/paragonie/constant_time_encoding.svg?branch=v1.x)](https://travis-ci.org/paragonie/constant_time_encoding)

Based on the [constant-time base64 implementation made by Steve "Sc00bz" Thomas](https://github.com/Sc00bz/ConstTimeEncoding),
this library aims to offer character encoding functions that do not leak
information about what you are encoding/decoding via processor cache
misses. Further reading on [cache-timing attacks](http://blog.ircmaxell.com/2014/11/its-all-about-time.html).

Our fork offers the following enchancements:

* `mbstring.func_overload` resistance
* Unit tests
* Composer- and Packagist-ready
* Base16 encoding
* Base32 encoding
* Uses `pack()` and `unpack()` instead of `chr()` and `ord()`

## PHP Version Requirements

This library should work on any [supported version of PHP](https://secure.php.net/supported-versions.php).
It *may* work on earlier versions, but we **do not** guarantee it. If it
doesn't, we **will not** fix it to work on earlier versions of PHP.

## How to Install

```sh
composer require paragonie/constant_time_encoding
```

## How to Use

```php
use \ParagonIE\ConstantTime\Encoding;

// possibly (if applicable):
// require 'vendor/autoload.php';

$data = random_bytes(32);
echo Encoding::base64Encode($data), "\n";
echo Encoding::base32EncodeUpper($data), "\n";
echo Encoding::base32Encode($data), "\n";
echo Encoding::hexEncode($data), "\n";
echo Encoding::hexEncodeUpper($data), "\n";
```

Example output:

```
1VilPkeVqirlPifk5scbzcTTbMT2clp+Zkyv9VFFasE=
2VMKKPSHSWVCVZJ6E7SONRY3ZXCNG3GE6ZZFU7TGJSX7KUKFNLAQ====
2vmkkpshswvcvzj6e7sonry3zxcng3ge6zzfu7tgjsx7kukfnlaq====
d558a53e4795aa2ae53e27e4e6c71bcdc4d36cc4f6725a7e664caff551456ac1
D558A53E4795AA2AE53E27E4E6C71BDCC4D36CC4F6725A7E664CAFF551456AC1
```

If you only need a particular variant, you can just reference the
required class like so:

```php
use \ParagonIE\ConstantTime\Base64;
use \ParagonIE\ConstantTime\Base32;

$data = random_bytes(32);
echo Base64::encode($data), "\n";
echo Base32::encode($data), "\n";
```

Example output:

```
1VilPkeVqirlPifk5scbzcTTbMT2clp+Zkyv9VFFasE=
2vmkkpshswvcvzj6e7sonry3zxcng3ge6zzfu7tgjsx7kukfnlaq====
```


description: Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)

license: MIT

type: library

Paragon Initiative Enterprises

role: Maintainer

Steve 'Sc00bz' Thomas

role: Original Developer

ParagonIE\ConstantTime\: src/


code:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="true"
         backupStaticAttributes="false"
         bootstrap="tests/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnError="false"
         stopOnFailure="false"
         syntaxCheck="true"
>
<testsuites>
    <testsuite name="Constant Time Encoding Test Suite">
        <directory suffix="Test.php">./tests</directory>
    </testsuite>
</testsuites>
<filter>
    <whitelist processUncoveredFilesFromWhitelist="true">
        <directory suffix=".php">./src</directory>
    </whitelist>
</filter>
</phpunit>


code:
<?xml version="1.0"?>
<psalm
    name="Example Psalm config with recommended defaults"
    stopOnFirstError="false"
    useDocblockTypes="true"
    totallyTyped="false"
>
    <projectFiles>
        <directory name="src" />
    </projectFiles>
</psalm>


code:
<?php
namespace ParagonIE\ConstantTime;

/**
 *  Copyright (c) 2016 - 2017 Paragon Initiative Enterprises.
 *  Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

/**
 * Class Base32
 * [A-Z][2-7]
 *
 * @package ParagonIE\ConstantTime
 */
abstract class Base32 implements EncoderInterface
{
    /**
     * Decode a Base32-encoded string into raw binary
     *
     * @param string $src
     * @param bool $strictPadding
     * @return string
     */
    public static function decode($src, $strictPadding = \false)
    {
        return static::doDecode($src, \false, $strictPadding);
    }

    /**
     * Decode an uppercase Base32-encoded string into raw binary
     *
     * @param string $src
     * @param bool $strictPadding
     * @return string
     */
    public static function decodeUpper($src, $strictPadding = \false)
    {
        return static::doDecode($src, \true, $strictPadding);
    }

    /**
     * Encode into Base32 (RFC 4648)
     *
     * @param string $src
     * @return string
     */
    public static function encode($src)
    {
        return static::doEncode($src, \false);
    }

    /**
     * Encode into Base32 (RFC 4648)
     *
     * @param string $src
     * @return string
     * @throws \TypeError
     */
    public static function encodeUnpadded($src)
    {
        return static::doEncode($src, false, false);
    }

    /**
     * Encode into uppercase Base32 (RFC 4648)
     *
     * @param string $src
     * @return string
     */
    public static function encodeUpper($src)
    {
        return static::doEncode($src, \true);
    }

    /**
     * Encode into uppercase Base32 (RFC 4648)
     *
     * @param string $src
     * @return string
     * @throws \TypeError
     */
    public static function encodeUpperUnpadded($src)
    {
        return static::doEncode($src, true, false);
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 5-bit integers
     * into 8-bit integers.
     *
     * @param int $src
     * @return int
     */
    protected static function decode5Bits($src)
    {
        $ret = -1;

        // if ($src > 96 && $src < 123) $ret += $src - 97 + 1; // -64
        $ret += (((0x60 - $src) & ($src - 0x7b)) >> 8) & ($src - 96);

        // if ($src > 0x31 && $src < 0x38) $ret += $src - 24 + 1; // -23
        $ret += (((0x31 - $src) & ($src - 0x38)) >> 8) & ($src - 23);

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 5-bit integers
     * into 8-bit integers.
     *
     * Uppercase variant.
     *
     * @param int $src
     * @return int
     */
    protected static function decode5BitsUpper($src)
    {
        $ret = -1;

        // if ($src > 64 && $src < 91) $ret += $src - 65 + 1; // -64
        $ret += (((0x40 - $src) & ($src - 0x5b)) >> 8) & ($src - 64);

        // if ($src > 0x31 && $src < 0x38) $ret += $src - 24 + 1; // -23
        $ret += (((0x31 - $src) & ($src - 0x38)) >> 8) & ($src - 23);

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 5-bit integers.
     *
     * @param int $src
     * @return string
     */
    protected static function encode5Bits($src)
    {
        $diff = 0x61;

        // if ($src > 25) $ret -= 72;
        $diff -= ((25 - $src) >> 8) & 73;

        return \pack('C', $src + $diff);
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 5-bit integers.
     *
     * Uppercase variant.
     *
     * @param int $src
     * @return string
     */
    protected static function encode5BitsUpper($src)
    {
        $diff = 0x41;

        // if ($src > 25) $ret -= 40;
        $diff -= ((25 - $src) >> 8) & 41;

        return \pack('C', $src + $diff);
    }

    /**
     * Base32 decoding
     *
     * @param string $src
     * @param bool $upper
     * @param bool $strictPadding
     * @return string
     */
    protected static function doDecode($src, $upper = \false, $strictPadding = \true)
    {
        // We do this to reduce code duplication:
        $method = $upper
            ? 'decode5BitsUpper'
            : 'decode5Bits';

        // Remove padding
        $srcLen = Binary::safeStrlen($src);
        if ($srcLen === 0) {
            return '';
        }
        if ($strictPadding) {
            if (($srcLen & 7) === 0) {
                for ($j = 0; $j < 7; ++$j) {
                    if ($src[$srcLen - 1] === '=') {
                        $srcLen--;
                    } else {
                        break;
                    }
                }
            }
            if (($srcLen & 7) === 1) {
                throw new \RangeException(
                    'Incorrect padding'
                );
            }
        } else {
            $src = \rtrim($src, '=');
            $srcLen = Binary::safeStrlen($src);
        }

        $err = 0;
        $dest = '';
        // Main loop (no padding):
        for ($i = 0; $i + 8 <= $srcLen; $i += 8) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, 8));
            $c0 = static::$method($chunk[1]);
            $c1 = static::$method($chunk[2]);
            $c2 = static::$method($chunk[3]);
            $c3 = static::$method($chunk[4]);
            $c4 = static::$method($chunk[5]);
            $c5 = static::$method($chunk[6]);
            $c6 = static::$method($chunk[7]);
            $c7 = static::$method($chunk[8]);

            $dest .= \pack(
                'CCCCC',
                (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                (($c1 << 6) | ($c2 << 1) | ($c3 >> 4)) & 0xff,
                (($c3 << 4) | ($c4 >> 1)             ) & 0xff,
                (($c4 << 7) | ($c5 << 2) | ($c6 >> 3)) & 0xff,
                (($c6 << 5) | ($c7     )             ) & 0xff
            );
            $err |= ($c0 | $c1 | $c2 | $c3 | $c4 | $c5 | $c6 | $c7) >> 8;
        }
        // The last chunk, which may have padding:
        if ($i < $srcLen) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, $srcLen - $i));
            $c0 = static::$method($chunk[1]);

            if ($i + 6 < $srcLen) {
                $c1 = static::$method($chunk[2]);
                $c2 = static::$method($chunk[3]);
                $c3 = static::$method($chunk[4]);
                $c4 = static::$method($chunk[5]);
                $c5 = static::$method($chunk[6]);
                $c6 = static::$method($chunk[7]);

                $dest .= \pack(
                    'CCCC',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                    (($c1 << 6) | ($c2 << 1) | ($c3 >> 4)) & 0xff,
                    (($c3 << 4) | ($c4 >> 1)             ) & 0xff,
                    (($c4 << 7) | ($c5 << 2) | ($c6 >> 3)) & 0xff
                );
                $err |= ($c0 | $c1 | $c2 | $c3 | $c4 | $c5 | $c6) >> 8;
            } elseif ($i + 5 < $srcLen) {
                $c1 = static::$method($chunk[2]);
                $c2 = static::$method($chunk[3]);
                $c3 = static::$method($chunk[4]);
                $c4 = static::$method($chunk[5]);
                $c5 = static::$method($chunk[6]);

                $dest .= \pack(
                    'CCCC',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                    (($c1 << 6) | ($c2 << 1) | ($c3 >> 4)) & 0xff,
                    (($c3 << 4) | ($c4 >> 1)             ) & 0xff,
                    (($c4 << 7) | ($c5 << 2)             ) & 0xff
                );
                $err |= ($c0 | $c1 | $c2 | $c3 | $c4 | $c5) >> 8;
            } elseif ($i + 4 < $srcLen) {
                $c1 = static::$method($chunk[2]);
                $c2 = static::$method($chunk[3]);
                $c3 = static::$method($chunk[4]);
                $c4 = static::$method($chunk[5]);

                $dest .= \pack(
                    'CCC',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                    (($c1 << 6) | ($c2 << 1) | ($c3 >> 4)) & 0xff,
                    (($c3 << 4) | ($c4 >> 1)             ) & 0xff
                );
                $err |= ($c0 | $c1 | $c2 | $c3 | $c4) >> 8;
            } elseif ($i + 3 < $srcLen) {
                $c1 = static::$method($chunk[2]);
                $c2 = static::$method($chunk[3]);
                $c3 = static::$method($chunk[4]);

                $dest .= \pack(
                    'CC',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                    (($c1 << 6) | ($c2 << 1) | ($c3 >> 4)) & 0xff
                );
                $err |= ($c0 | $c1 | $c2 | $c3) >> 8;
            } elseif ($i + 2 < $srcLen) {
                $c1 = static::$method($chunk[2]);
                $c2 = static::$method($chunk[3]);

                $dest .= \pack(
                    'CC',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff,
                    (($c1 << 6) | ($c2 << 1)             ) & 0xff
                );
                $err |= ($c0 | $c1 | $c2) >> 8;
            } elseif ($i + 1 < $srcLen) {
                $c1 = static::$method($chunk[2]);

                $dest .= \pack(
                    'C',
                    (($c0 << 3) | ($c1 >> 2)             ) & 0xff
                );
                $err |= ($c0 | $c1) >> 8;
            } else {
                $dest .= \pack(
                    'C',
                    (($c0 << 3)                          ) & 0xff
                );
                $err |= ($c0) >> 8;
            }
        }
        if ($err !== 0) {
            throw new \RangeException(
                'Base32::doDecode() only expects characters in the correct base32 alphabet'
            );
        }
        return $dest;
    }

    /**
     * Base32 Decoding
     *
     * @param string $src
     * @param bool $upper
     * @param bool $pad
     * @return string
     */
    protected static function doEncode($src, $upper = \false, $pad = \true)
    {
        // We do this to reduce code duplication:
        $method = $upper
            ? 'encode5BitsUpper'
            : 'encode5Bits';

        $dest = '';
        $srcLen = Binary::safeStrlen($src);

        // Main loop (no padding):
        for ($i = 0; $i + 5 <= $srcLen; $i += 5) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, 5));
            $b0 = $chunk[1];
            $b1 = $chunk[2];
            $b2 = $chunk[3];
            $b3 = $chunk[4];
            $b4 = $chunk[5];
            $dest .=
                static::$method(              ($b0 >> 3)  & 31) .
                static::$method((($b0 << 2) | ($b1 >> 6)) & 31) .
                static::$method((($b1 >> 1)             ) & 31) .
                static::$method((($b1 << 4) | ($b2 >> 4)) & 31) .
                static::$method((($b2 << 1) | ($b3 >> 7)) & 31) .
                static::$method((($b3 >> 2)             ) & 31) .
                static::$method((($b3 << 3) | ($b4 >> 5)) & 31) .
                static::$method(  $b4                     & 31);
        }
        // The last chunk, which may have padding:
        if ($i < $srcLen) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, $srcLen - $i));
            $b0 = $chunk[1];
            if ($i + 3 < $srcLen) {
                $b1 = $chunk[2];
                $b2 = $chunk[3];
                $b3 = $chunk[4];
                $dest .=
                    static::$method(              ($b0 >> 3)  & 31) .
                    static::$method((($b0 << 2) | ($b1 >> 6)) & 31) .
                    static::$method((($b1 >> 1)             ) & 31) .
                    static::$method((($b1 << 4) | ($b2 >> 4)) & 31) .
                    static::$method((($b2 << 1) | ($b3 >> 7)) & 31) .
                    static::$method((($b3 >> 2)             ) & 31) .
                    static::$method((($b3 << 3)             ) & 31);
                if ($pad) {
                    $dest .= '=';
                }
            } elseif ($i + 2 < $srcLen) {
                $b1 = $chunk[2];
                $b2 = $chunk[3];
                $dest .=
                    static::$method(              ($b0 >> 3)  & 31) .
                    static::$method((($b0 << 2) | ($b1 >> 6)) & 31) .
                    static::$method((($b1 >> 1)             ) & 31) .
                    static::$method((($b1 << 4) | ($b2 >> 4)) & 31) .
                    static::$method((($b2 << 1)             ) & 31);
                if ($pad) {
                    $dest .= '===';
                }
            } elseif ($i + 1 < $srcLen) {
                $b1 = $chunk[2];
                $dest .=
                    static::$method(              ($b0 >> 3)  & 31) .
                    static::$method((($b0 << 2) | ($b1 >> 6)) & 31) .
                    static::$method((($b1 >> 1)             ) & 31) .
                    static::$method((($b1 << 4)             ) & 31);
                if ($pad) {
                    $dest .= '====';
                }
            } else {
                $dest .=
                    static::$method(              ($b0 >> 3)  & 31) .
                    static::$method( ($b0 << 2)               & 31);
                if ($pad) {
                    $dest .= '======';
                }
            }
        }
        return $dest;
    }
}


code:
<?php
namespace ParagonIE\ConstantTime;

/**
 *  Copyright (c) 2016 - 2017 Paragon Initiative Enterprises.
 *  Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

/**
 * Class Base32Hex
 * [0-9][A-V]
 *
 * @package ParagonIE\ConstantTime
 */
abstract class Base32Hex extends Base32
{
    /**
     * Uses bitwise operators instead of table-lookups to turn 5-bit integers
     * into 8-bit integers.
     *
     * @param int $src
     * @return int
     */
    protected static function decode5Bits($src)
    {
        $ret = -1;

        // if ($src > 0x30 && $src < 0x3a) ret += $src - 0x2e + 1; // -47
        $ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src - 47);

        // if ($src > 0x60 && $src < 0x77) ret += $src - 0x61 + 10 + 1; // -86
        $ret += (((0x60 - $src) & ($src - 0x77)) >> 8) & ($src - 86);

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 5-bit integers
     * into 8-bit integers.
     *
     * @param int $src
     * @return int
     */
    protected static function decode5BitsUpper($src)
    {
        $ret = -1;

        // if ($src > 0x30 && $src < 0x3a) ret += $src - 0x2e + 1; // -47
        $ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src - 47);

        // if ($src > 0x40 && $src < 0x57) ret += $src - 0x41 + 10 + 1; // -54
        $ret += (((0x40 - $src) & ($src - 0x57)) >> 8) & ($src - 54);

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 5-bit integers.
     *
     * @param int $src
     * @return string
     */
    protected static function encode5Bits($src)
    {
        $src += 0x30;

        // if ($src > 0x39) $src += 0x61 - 0x3a; // 39
        $src += ((0x39 - $src) >> 8) & 39;

        return \pack('C', $src);
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 5-bit integers.
     *
     * Uppercase variant.
     *
     * @param int $src
     * @return string
     */
    protected static function encode5BitsUpper($src)
    {
        $src += 0x30;

        // if ($src > 0x39) $src += 0x41 - 0x3a; // 7
        $src += ((0x39 - $src) >> 8) & 7;

        return \pack('C', $src);
    }
}


code:
<?php
namespace ParagonIE\ConstantTime;

/**
 *  Copyright (c) 2016 - 2017 Paragon Initiative Enterprises.
 *  Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

/**
 * Class Base64
 * [A-Z][a-z][0-9]+/
 *
 * @package ParagonIE\ConstantTime
 */
abstract class Base64 implements EncoderInterface
{
    /**
     * Encode into Base64
     *
     * Base64 character set "[A-Z][a-z][0-9]+/"
     *
     * @param string $src
     * @return string
     */
    public static function encode($src)
    {
        return static::doEncode($src, \true);
    }

    /**
     * Encode into Base64, no = padding
     *
     * Base64 character set "[A-Z][a-z][0-9]+/"
     *
     * @param string $src
     * @return string
     */
    public static function encodeUnpadded($src)
    {
        return static::doEncode($src, \false);
    }

    /**
     * @param string $src
     * @param bool $pad   Include = padding?
     * @return string
     */
    protected static function doEncode($src, $pad = \true)
    {
        $dest = '';
        $srcLen = Binary::safeStrlen($src);
        // Main loop (no padding):
        for ($i = 0; $i + 3 <= $srcLen; $i += 3) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, 3));
            $b0 = $chunk[1];
            $b1 = $chunk[2];
            $b2 = $chunk[3];

            $dest .=
                static::encode6Bits(               $b0 >> 2       ) .
                static::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
                static::encode6Bits((($b1 << 2) | ($b2 >> 6)) & 63) .
                static::encode6Bits(  $b2                     & 63);
        }
        // The last chunk, which may have padding:
        if ($i < $srcLen) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, $srcLen - $i));
            $b0 = $chunk[1];
            if ($i + 1 < $srcLen) {
                $b1 = $chunk[2];
                $dest .=
                    static::encode6Bits(               $b0 >> 2       ) .
                    static::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
                    static::encode6Bits( ($b1 << 2)               & 63);
                if ($pad) {
                    $dest .= '=';
                }
            } else {
                $dest .=
                    static::encode6Bits( $b0 >> 2) .
                    static::encode6Bits(($b0 << 4) & 63);
                if ($pad) {
                    $dest .= '==';
                }
            }
        }
        return $dest;
    }

    /**
     * decode from base64 into binary
     *
     * Base64 character set "./[A-Z][a-z][0-9]"
     *
     * @param string $src
     * @param bool $strictPadding
     * @return string
     * @throws \RangeException
     */
    public static function decode($src, $strictPadding = \false)
    {
        // Remove padding
        $srcLen = Binary::safeStrlen($src);
        if ($srcLen === 0) {
            return '';
        }
        if ($strictPadding) {
            if (($srcLen & 3) === 0) {
                if ($src[$srcLen - 1] === '=') {
                    $srcLen--;
                    if ($src[$srcLen - 1] === '=') {
                        $srcLen--;
                    }
                }
            }
            if (($srcLen & 3) === 1) {
                throw new \RangeException(
                    'Incorrect padding'
                );
            }
        } else {
            $src = \rtrim($src, '=');
            $srcLen = Binary::safeStrlen($src);
        }

        $err = 0;
        $dest = '';
        // Main loop (no padding):
        for ($i = 0; $i + 4 <= $srcLen; $i += 4) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, 4));
            $c0 = static::decode6Bits($chunk[1]);
            $c1 = static::decode6Bits($chunk[2]);
            $c2 = static::decode6Bits($chunk[3]);
            $c3 = static::decode6Bits($chunk[4]);

            $dest .= \pack(
                'CCC',
                ((($c0 << 2) | ($c1 >> 4)) & 0xff),
                ((($c1 << 4) | ($c2 >> 2)) & 0xff),
                ((($c2 << 6) |  $c3      ) & 0xff)
            );
            $err |= ($c0 | $c1 | $c2 | $c3) >> 8;
        }
        // The last chunk, which may have padding:
        if ($i < $srcLen) {
            $chunk = \unpack('C*', Binary::safeSubstr($src, $i, $srcLen - $i));
            $c0 = static::decode6Bits($chunk[1]);
            if ($i + 2 < $srcLen) {
                $c1 = static::decode6Bits($chunk[2]);
                $c2 = static::decode6Bits($chunk[3]);
                $dest .= \pack(
                    'CC',
                    ((($c0 << 2) | ($c1 >> 4)) & 0xff),
                    ((($c1 << 4) | ($c2 >> 2)) & 0xff)
                );
                $err |= ($c0 | $c1 | $c2) >> 8;
            } elseif($i + 1 < $srcLen) {
                $c1 = static::decode6Bits($chunk[2]);
                $dest .= \pack(
                    'C',
                    ((($c0 << 2) | ($c1 >> 4)) & 0xff)
                );
                $err |= ($c0 | $c1) >> 8;
            } elseif ($i < $srcLen && $strictPadding) {
                $err |= 1;
            }
        }
        if ($err !== 0) {
            throw new \RangeException(
                'Base64::decode() only expects characters in the correct base64 alphabet'
            );
        }
        return $dest;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 6-bit integers
     * into 8-bit integers.
     *
     * Base64 character set:
     * [A-Z]      [a-z]      [0-9]      +     /
     * 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f
     *
     * @param int $src
     * @return int
     */
    protected static function decode6Bits($src)
    {
        $ret = -1;

        // if ($src > 0x40 && $src < 0x5b) $ret += $src - 0x41 + 1; // -64
        $ret += (((0x40 - $src) & ($src - 0x5b)) >> 8) & ($src - 64);

        // if ($src > 0x60 && $src < 0x7b) $ret += $src - 0x61 + 26 + 1; // -70
        $ret += (((0x60 - $src) & ($src - 0x7b)) >> 8) & ($src - 70);

        // if ($src > 0x2f && $src < 0x3a) $ret += $src - 0x30 + 52 + 1; // 5
        $ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src + 5);

        // if ($src == 0x2b) $ret += 62 + 1;
        $ret += (((0x2a - $src) & ($src - 0x2c)) >> 8) & 63;

        // if ($src == 0x2f) ret += 63 + 1;
        $ret += (((0x2e - $src) & ($src - 0x30)) >> 8) & 64;

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 6-bit integers.
     *
     * @param int $src
     * @return string
     */
    protected static function encode6Bits($src)
    {
        $diff = 0x41;

        // if ($src > 25) $diff += 0x61 - 0x41 - 26; // 6
        $diff += ((25 - $src) >> 8) & 6;

        // if ($src > 51) $diff += 0x30 - 0x61 - 26; // -75
        $diff -= ((51 - $src) >> 8) & 75;

        // if ($src > 61) $diff += 0x2b - 0x30 - 10; // -15
        $diff -= ((61 - $src) >> 8) & 15;

        // if ($src > 62) $diff += 0x2f - 0x2b - 1; // 3
        $diff += ((62 - $src) >> 8) & 3;

        return \pack('C', $src + $diff);
    }
}


code:
<?php
namespace ParagonIE\ConstantTime;

/**
 *  Copyright (c) 2016 - 2017 Paragon Initiative Enterprises.
 *  Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

/**
 * Class Base64DotSlash
 * ./[A-Z][a-z][0-9]
 *
 * @package ParagonIE\ConstantTime
 */
abstract class Base64DotSlash extends Base64
{
    /**
     * Uses bitwise operators instead of table-lookups to turn 6-bit integers
     * into 8-bit integers.
     *
     * Base64 character set:
     * ./         [A-Z]      [a-z]     [0-9]
     * 0x2e-0x2f, 0x41-0x5a, 0x61-0x7a, 0x30-0x39
     *
     * @param int $src
     * @return int
     */
    protected static function decode6Bits($src)
    {
        $ret = -1;

        // if ($src > 0x2d && $src < 0x30) ret += $src - 0x2e + 1; // -45
        $ret += (((0x2d - $src) & ($src - 0x30)) >> 8) & ($src - 45);

        // if ($src > 0x40 && $src < 0x5b) ret += $src - 0x41 + 2 + 1; // -62
        $ret += (((0x40 - $src) & ($src - 0x5b)) >> 8) & ($src - 62);

        // if ($src > 0x60 && $src < 0x7b) ret += $src - 0x61 + 28 + 1; // -68
        $ret += (((0x60 - $src) & ($src - 0x7b)) >> 8) & ($src - 68);

        // if ($src > 0x2f && $src < 0x3a) ret += $src - 0x30 + 54 + 1; // 7
        $ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src + 7);

        return $ret;
    }

    /**
     * Uses bitwise operators instead of table-lookups to turn 8-bit integers
     * into 6-bit integers.
     *
     * @param int $src
     * @return string
     */
    protected static function encode6Bits($src)
    {
        $src += 0x2e;

        // if ($src > 0x2f) $src += 0x41 - 0x30; // 17
        $src += ((0x2f - $src) >> 8) & 17;

        // if ($src > 0x5a) $src += 0x61 - 0x5b; // 6
        $src += ((0x5a - $src) >> 8) & 6;

        // if ($src > 0x7a) $src += 0x30 - 0x7b; // -75
        $src -= ((0x7a - $src) >> 8) & 75;

        return \pack('C', $src);
    }
}