<?PHP
global $AF;
$AF->SuppressHTMLOutput();

// Add the OpenId library path to our includes and pull in the
// library components that we need.

ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR .
        dirname(__FILE__)."/php-openid");

require_once "Auth/Yadis/XML.php";
require_once "Auth_Yadis_simplexml.php";
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/SReg.php";
require_once "OpenId_AxisDatabase.php" ;
require_once "OpenId_AxisDatabaseStore.php";

global $SPT_DBHost, $SPT_DBUserName, $SPT_DBPassword, $SPT_DBName;

$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);
$TrustRoot = GetBaseUrl();
$LastChar = $TrustRoot{strlen($TrustRoot)-1};

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

$RedirectTo = $TrustRoot . "plugins/OpenId/FinishAuthLanding.php";

$openid = isset($_POST["F_OidDisplayed"]) ?
    $_POST["F_OpenId"] :
    $_POST["F_UserName"];
// Begin the OpenID authentication process.
$auth_request = $consumer->begin($openid);

// No auth request means we can't begin OpenID, so kick back to the
// regular user auth mechanism.
if (!$auth_request)
{
    global $Session;

    if ( ( isset($_POST["F_OidDisplayed"]) && strlen($_POST["F_OpenId"])>0 ) ||
         (!isset($_POST["F_OidDisplayed"]) && strpos($_POST["F_UserName"], ".") !== FALSE ))
    {
        global $Session;

        $OidLoginError = "It looks like you're trying to log in with an OpenId. "
            ."You entered '".$openid."', however this is not a valid OpenId";

        $Session->PassVariable("OidLoginError", $OidLoginError);
    }

    print(
        "<html><head><title>User Login in progress</title></head>"
        ."<body>"
        ."<form id=\"UserLogin\" method=\"POST\" action=\"index.php?P=UserLogin\">"
        ."<input type=\"hidden\" name=\"F_UserName\" value=\"".$_POST["F_UserName"]."\">"
        ."<input type=\"hidden\" name=\"F_Password\" value=\"".$_POST["F_Password"]."\">"
        ."<input type=\"hidden\" name=\"F_HashPassword\" value=\"".$_POST["F_HashPassword"]."\">"
        ."<input type=\"hidden\" name=\"Challenge\" value=\"".$_POST["Challenge"]."\">"
        ."<input type=\"hidden\" name=\"SkipOpenId\" value=\"1\">"
        ."<input type=\"submit\" value=\"Continue\">"
        ."</form>"
        ."<script type=\"text/javascript\">"
        ."document.forms[\"UserLogin\"].submit();"
        ."</script>"
        ."</body>"
        );
}
else
{
    // Ask for everything that the spec allows:
    $auth_request->addExtension(
        Auth_OpenID_SRegRequest::build(
            // Required
            array('nickname'),
            // Optional
            array('fullname','email','postcode',
                  'country','language')));

// 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($TrustRoot, $RedirectTo);

        // If the redirect URL can't be built, display an error
        // message.
        if (Auth_OpenID::isFailure($redirect_url)) {
            print("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($TrustRoot, $RedirectTo,
                                               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)) {
            print("Could not redirect to server: " . $form_html->message);
        }
        else
        {
            print $form_html;
        }
    }
}

/**
 * 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["HTTP"])) ? "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;
}
