<?php

function GenerateUsername($BaseName)
{
    global $DB;

    $DB->Query("SELECT UserName FROM APUsers");

    $Names = array();
    while ($Row = $DB->FetchRow())
    {
        $Names []= $Row["UserName"];
    }

    $Str="";
    while (in_array($BaseName.$Str, $Names) )
    {
        $Str = ($Str==="")? 1 : $Str+1;
    }

    return $BaseName.$Str;
}

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

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 )
    {
        $UserName = $DB->Query(
            "SELECT UserName FROM OpenId_UserMap "
            ."WHERE DisplayId='".addslashes($Response["DisplayId"])."'",
            "UserName");
        $ExtInfo = $Response["ExtendedInfo"];

        if ($UserName === NULL && isset($ExtInfo["email"]) )
        {
            $UserFactory = new SPTUserFactory($Session);

            // Now the most exciting part: trying to map the OpenID into a username:

            // If the user gave us a nickname, try to use that plus an
            // optional sequence number
            if (isset($ExtInfo["nickname"]))
            {
                $UserName = GenerateUsername($ExtInfo["nickname"]);
            }
            // If we have no nickname, but we have a full name, smash all the
            // alphabetic characters in it goether, and try to use that plus
            // an optional sequence number.
            elseif (isset($ExtInfo["fullname"]))
            {
                $FnMunge = preg_replace("/[^A-Za-z]/", "", $ExtInfo["fullname"]);
                $UserName = GenerateUsername($FnMunge);
            }
            // If all that fails, use the local part on someone's email
            else
            {
                $TmpName = array_shift(explode('@', $ExtInfo["email"]));

                $UserName = GenerateUsername($TmpName);
            }

            $UserPassword = md5(time());

            $TmpUser = $UserFactory->CreateNewUser(
                $UserName,
                $UserPassword, $UserPassword,
                $ExtInfo["email"], $ExtInfo["email"],
                array(U_ILLEGALPASSWORD, U_ILLEGALPASSWORDAGAIN,
                      U_ILLEGALEMAIL, U_ILLEGALEMAILAGAIN,
                      U_ILLEGALUSERNAME, U_DUPLICATEEMAIL));
            $TmpUser->GivePriv(PRIV_POSTTOFORUMS);
            $TmpUser->GivePriv(PRIV_POSTCOMMENTS);

            $DB->Query(
                "INSERT INTO OpenId_UserMap (DisplayId, UserName) "
                ."VALUES ('".addslashes($Response["DisplayId"])."',"
                ."'".addslashes($TmpUser->Name())."')");

            $AF->SetJumpToPage("P_OpenId_FinishAuth&D=".urlencode($_GET["D"])."&C=".$_GET["C"]);
        }
    }
}