<?PHP
#
#   FILE:  RequestAccountComplete.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#


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

# set up expectations for incoming form

PageTitle("Processing New User Registration");

# Don't allow new user signups from spambots:
if ($GLOBALS["G_PluginManager"]->PluginEnabled("BotDetector") &&
    $GLOBALS["G_PluginManager"]->GetPlugin("BotDetector")->CheckForSpamBot())
{
    $GLOBALS["AF"]->SetJumpToPage("UnauthorizedAccess");
    return;
}

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

# check incoming values for errors
$UserErrorCodes = UserEditingUI::TestUserValues($_POST);

# check for and handle errors (by redirecting back to the form page)
if (UserEditingUI::UserFormHasErrors($FTool, $UserErrorCodes))
{
    $GLOBALS["AF"]->SetJumpToPage(
        $FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# create new user
$UserFactory = new CWUserFactory();
$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);
    }
    $GLOBALS["AF"]->SetJumpToPage(
        $FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# send confirmation e-mail
$MailTemplate = $SysConfig->PasswordMailSubject()."\n"
        .$SysConfig->PasswordMailBody();
$FromAddress = $SysConfig->PortalName()." <".$SysConfig->AdminEmail().">";
$NewUser->SendEMail($MailTemplate, $FromAddress,
        UserEditingUI::GetActivationEmailSubstitutions(
                $NewUser));

# save provided attributes and values
$UEUI = new UserEditingUI($NewUser);
$UEUI->UpdateUserAttributes($_POST, TRUE);
$UEUI->UpdateUserFields(CWUser::GetCustomUserFields());

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

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

# 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"]);
