<?PHP

# This is the landing page on which OpenId responses will fall It
# needs to be its own page because (at least some) OID servers bork
# up the query string when they construct their response.  Bounce
# from this page back into CWIS, encoding the OID response in a friendly
# way.

/**
 * Get the base URL where PHP began execution.
 * @param $Path optional path to use instead of the base one
 * @return the base URL where PHP began execution
 */
function GetBaseUrl($Path=NULL)
{
    $Protocol = isset($_SERVER["HTTPS"]) ? "https://" : "http://";
    $Server = $_SERVER["SERVER_NAME"];
    $Port = $_SERVER["SERVER_PORT"];

    if (is_null($Path))
    {
        $Path = GetBasePath();
    }

    $Url = $Protocol . $Server;

    # only add the port number if it isn't implied
    if (!($Protocol == "http://" && $Port == 80)
        && !($Protocol == "https://" && $Port == 443))
    {
        $Url .= ":" . $Port;
    }

    $Url .= $Path;

    return $Url;
}

/**
 * Get the base path where PHP began execution.
 * @return the base path where PHP began execution
 */
function GetBasePath()
{
    $Self = $_SERVER["PHP_SELF"];
    $LongestValidPart = substr($Self, 0, strcspn($Self, "\r\n"));
    $Path = dirname(htmlentities($LongestValidPart, ENT_QUOTES));

    return $Path;
}


ob_start();
require_once("../../config.php");
require_once('../../lib/AxisPHP/Axis--Database.php');
require_once('../../lib/AxisPHP/Axis--Session.php');
Database::SetGlobalServerInfo($SPT_DBUserName, $SPT_DBPassword, $SPT_DBHost);
Database::SetGlobalDatabaseName($SPT_DBName);

$DB = new Database();
error_reporting(E_ALL);
ini_set('display_errors', '1');
# Pull in the php-openid components that I need.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR .
        dirname(__FILE__)."/php-openid");
require_once "Auth/Yadis/XML.php";
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/SReg.php";
require_once "OpenId_AxisDatabase.php" ;
require_once "OpenId_AxisDatabaseStore.php";

$XmlParser = Auth_Yadis_getXMLParser();

# if a built-in XML parser isn't available, use the custom one
if (FALSE === $XmlParser)
{
    require_once "Auth_Yadis_simplexml.php";
    global $__Auth_Yadis_defaultParser;
    $__Auth_Yadis_defaultParser = new Auth_Yadis_simplexml();
}

$store =  new Auth_OpenID_AxisDatabaseStore( new Auth_OpenId_AxisDatabase() );
$store->createTables();

$consumer = new Auth_OpenID_Consumer($store);

# Complete the authentication process using the server's
# response.
$TrustRoot = GetBaseUrl();
$LastChar = $TrustRoot{strlen($TrustRoot)-1};

if ($LastChar != "/")
{
    $TrustRoot .= "/";
}

$RedirectTo = $TrustRoot . "FinishAuthLanding.php";
$response = $consumer->complete($RedirectTo);

$OidData["Timestamp"] = time();

$OidData["Status"] = $response->status;
if ($response->status == Auth_OpenID_SUCCESS )
{
    $OidData["DisplayId"] = $response->getDisplayIdentifier();
    $OidData["CanonicalId"] = $response->endpoint->canonicalID;

    $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
    $sreg = $sreg_resp->contents();
    $OidData["ExtendedInfo"] = $sreg;
}

$DataSerial = base64_encode(gzdeflate(serialize($OidData)));
$CkSum = md5($DataSerial.$SPT_DBUserName.$SPT_DBPassword.$SPT_DBHost);

$AuthRedirect = GetBaseUrl(dirname(dirname(GetBasePath())));
$LastChar = $AuthRedirect{strlen($AuthRedirect)-1};

if ($LastChar != "/")
{
    $AuthRedirect .= "/";
}

header("Location: " . $AuthRedirect . "index.php?P=P_OpenId_FinishAuth"
       ."&D=".urlencode($DataSerial)."&C=".$CkSum);

ob_end_flush();
