<?PHP
#
#   FILE:  RequestAccountComplete.php
#
#   FUNCTIONS PROVIDED:
#       GetUserCreationResultText()
#           -
#       UserCreationSucceeded()
#           -
#
#   FUNCTIONS EXPECTED:
#       (none)
#
#   OPTIONAL FUNCTIONS:
#       (none)
#
#   FORM FIELDS EXPECTED:
#       F_UserName
#       F_EMail
#       F_EMailAgain
#       F_RealName
#       F_WebSite
#       F_AddressLineOne
#       F_AddressLineTwo
#       F_City
#       F_State
#       F_ZipCode
#       F_Country
#           - user account attributes
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- MAIN -----------------------------------------------------------------

# set up expectations for incoming form

PageTitle("Processing New User Registration");

#$FormPage = "SPT--RequestAccount.php";
$FormPage = "index.php?P=RequestAccount";
$FTool = new FormTool("RequestAccount");

# check incoming values for errors
$OurDB = new SPTDatabase();
$UserFactory = new UserFactory($OurDB);
$UserErrorCodes = $UserFactory->TestNewUserValues($_POST["F_UserName"],
            $_POST["F_Password"], $_POST["F_PasswordAgain"],
            $_POST["F_EMail"], $_POST["F_EMailAgain"]);

$SignupStatus = $AF->SignalEvent("EVENT_USER_SIGNUP_VERIFY",
                                 array(
                                     "UserName" => $_POST["F_UserName"],
                                     "Password" => $_POST["F_Password"],
                                     "EMail"    => $_POST["F_EMail"],
                                     "Status" => U_OKAY ));

if ($SignupStatus["Status"] !== U_OKAY)
{
    $UserErrorCodes[]= $SignupStatus["Status"];
}

# if errors were found in incoming values
if ($FTool->IncomingFieldValuesHaveErrors() || count($UserErrorCodes))
{
    # make form fields based on error codes
    $CodeToFieldMap = array(
            U_DUPLICATEUSERNAME => "F_UserName",
            U_ILLEGALUSERNAME => "F_UserName",
            U_PASSWORDSDONTMATCH => array("F_Password", "F_PasswordAgain"),
            U_EMAILSDONTMATCH => array("F_EMail", "F_EMailAgain"),
            U_ILLEGALPASSWORD => "F_Password",
            U_ILLEGALPASSWORDAGAIN => "F_PasswordAgain",
            U_ILLEGALEMAIL => "F_EMail",
            U_ILLEGALEMAILAGAIN => "F_EMailAgain",
            U_EMPTYPASSWORD => "F_Password",
            U_EMPTYPASSWORDAGAIN => "F_PasswordAgain",
            U_EMPTYEMAIL => "F_EMail",
            U_EMPTYEMAILAGAIN => "F_EMailAgain",
            U_DUPLICATEEMAIL => array("F_EMail", "F_EMailAgain"),
            );

    foreach ($UserErrorCodes as $Code)
    {
        if (isset($CodeToFieldMap[$Code]))
        {
            if (is_array(isset($CodeToFieldMap[$Code])))
            {
                foreach ($CodeToFieldMap[$Code] as $FieldName)
                {
                    $FTool->SetAdditionalErrorFields($FieldName);
                }
            }
            else
            {
                $FTool->SetAdditionalErrorFields($CodeToFieldMap[$Code]);
            }
        }
    }

    $FTool->SetAdditionalErrorCodes($UserErrorCodes);
    $AF->SetJumpToPage($FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# retrieve form values for account creation
$UserName = $_POST["F_UserName"];

# create new user
$NewUser = $UserFactory->CreateNewUser($_POST["F_UserName"],
            $_POST["F_Password"], $_POST["F_PasswordAgain"],
            $_POST["F_EMail"], $_POST["F_EMailAgain"]);

# if user creation failed
if (!is_object($NewUser) || ($NewUser->Status() != U_OKAY))
{
    # return to calling page with error code
    foreach ($NewUser as $ErrorCode)
    {
        $FTool->SetAdditionalErrorCodes($ErrorCode);
    }
    $AF->SetJumpToPage($FTool->GetUrlWithValuesAndErrorCodes("SPT--RequestAccount.php"));
    return;
}

# send confirmation e-mail
$ActivationUrlParameters = "?UN=".urlencode($NewUser->Get("UserName"))
        ."&AC=".$NewUser->GetActivationCode();
$ActivationUrl = "http://".$_SERVER["SERVER_NAME"]
        .dirname($_SERVER["SCRIPT_NAME"])
        ."/index.php".$ActivationUrlParameters."&P=ActivateAccount";
$ManualActivationUrl = "http://".$_SERVER["SERVER_NAME"]
        .dirname($_SERVER["SCRIPT_NAME"])
        ."/index.php?P=ManuallyActivateAccount";
$OurSubstitutions = array(
        "X-PORTALNAME-X" => $SysConfig->PortalName(),
        "X-ACTIVATIONURL-X" => $ActivationUrl,
        "X-ACTIVATIONPARAMETERS-X" => $ActivationUrlParameters,
        "X-MANUALACTIVATIONURL-X" => $ManualActivationUrl,
        );
$MailTemplate = $SysConfig->PasswordMailSubject()."\n"
        .$SysConfig->PasswordMailBody();
$FromAddress = $SysConfig->PortalName()." <".$SysConfig->AdminEmail().">";
$NewUser->SendEMail($MailTemplate, $FromAddress, $OurSubstitutions);

# save other user information
$UserFields = array(
        "RealName",
        "WebSite",
        "AddressLineOne",
        "AddressLineTwo",
        "City",
        "State",
        "ZipCode",
        "Country",
        );
foreach ($UserFields as $VarName)
{
    $FormVarName = "F_".$VarName;
    if (isset($_POST[$FormVarName]) && strlen($_POST[$FormVarName]))
    {
        $NewUser->Set($VarName, $_POST[$FormVarName]);
    }
}

# set up initial UI setting
$NewUser->Set("ActiveUI", $SysConfig->DefaultActiveUI());

# set up initial privileges
foreach ($SysConfig->DefaultUserPrivs() as $Privilege)
{
    $NewUser->GivePriv($Privilege);
}

# always disable account until activated via confirmation e-mail
$NewUser->GivePriv(PRIV_USERDISABLED);

# set e-mail address and user name for use in page display
$G_EMailAddress = User::NormalizeEMailAddress($_POST["F_EMail"]);
$G_UserName = User::NormalizeUserName($_POST["F_UserName"]);

# signal that user has been added
$AF->SignalEvent("EVENT_USER_ADDED", array(
        "UserId" => $NewUser->Id(), "Password" => $_POST["F_Password"]));
