<?php

global $AF, $DB, $G_User;
global $SPT_DBUserName, $SPT_DBPassword, $SPT_DBHost;

# By default, just return home:
$AF->SetJumpToPage("Home");

if (isset($_GET["D"]) && isset($_GET["C"]) &&
    md5($_GET["D"].$SPT_DBUserName.$SPT_DBPassword.$SPT_DBHost) == $_GET["C"])
{
    $Response = unserialize( gzinflate( base64_decode( $_GET["D"] )));

    if ($Response["Status"] == "success" && time() - $Response["Timestamp"] < 600 )
    {
        $EscapedDisplayId = addslashes($Response["DisplayId"]);

        $UserName = $DB->Query(
            "SELECT UserName FROM OpenId_UserMap "
            ."WHERE DisplayId='".$EscapedDisplayId."'",
            "UserName");

        $ExtInfo = $Response["ExtendedInfo"];

        # display ID to user name mapping exists
        if (!is_null($UserName))
        {
            $UserFactory = new UserFactory($Session);
            $UserExists = $UserFactory->UserNameExists($UserName);

            # the mapping is invalid
            if (!$UserExists)
            {
                # unset the user name and delete the invalid mappin
                $UserName = NULL;
                $DB->Query("
                    DELETE FROM OpenId_UserMap
                    WHERE DisplayId = '".$EscapedDisplayId."'");
            }
        }

        if ($UserName===NULL)
        {
            if (isset($ExtInfo["email"]))
            {
                $AF->SetJumpToPage("P_OpenId_CreateUser&D=".urlencode($_GET["D"])."&C=".$_GET["C"]);
            }
            else
            {
                $Response["ErrorMessage"] =
                    "We were unable to obtain an email address from your OpenID provider, ".
                    "however one is required for several CWIS features (feedback and saved ".
                    "searches, to name a few). ";

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

                $AF->SetJumpToPage("P_OpenId_GetUserEmail&D=".urlencode($DataSerial)."&C=".$CkSum);
            }
        }
        else
        {
            $TmpUser = new SPTUser($UserName);

            if (isset($ExtInfo["fullname"]))
                $TmpUser->Set("RealName", $ExtInfo["fullname"]);
            if (isset($ExtInfo["postcode"]))
                $TmpUser->Set("ZipCode", $ExtInfo["postcode"]);
            if (isset($ExtInfo["country"]))
                $TmpUser->Set("Country", $ExtInfo["country"]);

            if (isset($ExtInfo["email"]) &&
                $ExtInfo["email"] !==  $TmpUser->Get("EMail"))
            {
                $OldEmail = $TmpUser->Get("EMail");
                $NewEmail = $ExtInfo["email"];
                $TmpUser->Set("EMail", $NewEmail);
                $AF->SignalEvent("EVENT_USER_EMAIL_CHANGED", array(
                                     "UserId" => $TmpUser->Id(),
                                     "OldEmail" => $OldEmail,
                                     "NewEmail" => $NewEmail));
            }

            $G_User->Login($TmpUser->Name(), "", TRUE);
        }
    }
}
