<?php

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

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

# Check to see if the data in "D" has a proper checksum.
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 CWUserFactory();
            $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 CWUser($UserName);

            # Some previous versions of this plugin were creating users without
            # setting IsActivated.  Check for and fix that here:
            if (! $TmpUser->IsActivated())
                $TmpUser->IsActivated(TRUE);

            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);

            # signal successful user login
            $AF->SignalEvent("EVENT_USER_LOGIN", array(
                                 "UserId" => $G_User->Id(), "Password" => "" ));



            # This is borrowed from pages/UserLogin.php, and
            # should be kept in sync with that source.

            # list of pages we do not want to return to
            $DoNotReturnToPages = array(
                "Login",
                "UserLogin",
                "LoginError",
                "ForgottenPasswordComplete",
                "RequestAccount",
                "RequestAccountComplete",
                "ActivateAccount",
                "ResendAccountActivation",
                "ResetPassword",
                "ForgottenPasswordComplete",
                "EditResourceComplete"
                );

            # add in any locally-defined pages not to return to
            if (function_exists("Local_GetDoNotReturnToPages"))
            {
                $DoNotReturnToPages = array_merge($DoNotReturnToPages,
                                                  Local_GetDoNotReturnToPages());
            }

            # if originating page looks like a valid destination
            #  When referer isn't set, redirect to front page.
            $OrigPage = isset($_SESSION["ReturnToPage"]) ?
                $_SESSION["ReturnToPage"] : "Home";
            $OrigPagePieces = explode("?", basename($OrigPage), 2);
            $OrigPageFile = array_shift($OrigPagePieces);
            if (($OrigPageFile == "index.php") &&
                (!count($OrigPagePieces)       ||
                 preg_match("/P=([a-zA-Z_-]+)/", $OrigPagePieces[0], $OrigParams)))
            {
                $OrigPageFile = isset($OrigParams) ? $OrigParams[1] : "Home";
            }
            if (!in_array($OrigPageFile, $DoNotReturnToPages))
            {
                if (substr($OrigPage, -1) == "/")
                {
                    $OrigPage .= "index.php";
                }
                elseif ($OrigPageFile == "AdvancedSearch")
                {
                    # If we're going back to a search result, strip out the results per page
                    # so as not to overwrite the users's prefs.
                    $OrigPage = preg_replace('/\&(amp;)?RP=[0-9]+/', '', $OrigPage);
                }

                # head to originating page
                $ReturnPage = $OrigPage;
            }
            else
            {
                # head to home page
                $ReturnPage = "Home";
            }

            # pass login return address through any hooked filters via signal
            $SignalResult = $AF->SignalEvent("EVENT_USER_LOGIN_RETURN",
                                             array("ReturnPage" => $ReturnPage));
            $ReturnPage = $SignalResult["ReturnPage"];


            $AF->SetJumpToPage($ReturnPage);
            if (isset($_SESSION["ReturnToPage"]))
                unset($_SESSION["ReturnToPage"]);
        }
    }
}
