<?PHP
#
#   FILE:  SubscribeComplete.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2015 Internet Scout Project
#   http://scout.wisc.edu/
#

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

# 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;
}

# pull out the requested list name
$ListName = GetArrayValue($_POST, "F_MailingList", NULL);

$FormPage = "index.php?P=P_MailingList_Subscribe";
$FTool = new FormTool(
    MailingList::GetSubscriptionFormFields()
    );

if (is_null($ListName))
{
    $FTool->SetAdditionalErrorCodes("E_NO_LIST_SPECIFIED");
    $GLOBALS["AF"]->SetJumpToPage(
        $FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# add the ListName to the form page if we had a valid one
$FormPage .= "&List=".$ListName;

$MyPlugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
if (!in_array($ListName, $MyPlugin->GetAllLists()))
{
    $FTool->SetAdditionalErrorCodes("E_NO_SUCH_LIST");
    $GLOBALS["AF"]->SetJumpToPage(
        $FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# generate a username and stuff it into $_POST
#   (if the EMail and EmailAgain don't match, we'll
#    catch that error in the next block)
$_POST["F_UserName"] =
    CWUserFactory::GenerateUniqueUsernameFromEmail(
    $_POST["F_EMail"]);
# generate a random password, so that the user will have
#   something
$RandomPass = GetRandomCharacters(8);
$_POST["F_Password"] = $RandomPass;
$_POST["F_PasswordAgain"] = $RandomPass;

# check and handle errors in the incoming values
$UserErrorCodes = UserEditingUI::TestUserValues($_POST);
if (UserEditingUI::UserFormHasErrors($FTool, $UserErrorCodes))
{
    $GLOBALS["AF"]->SetJumpToPage(
        $FTool->GetUrlWithValuesAndErrorCodes($FormPage));
    return;
}

# attempt to create the 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;
}

# convert message substitutions into the format that Mailer expects
$Substitutions = array();
foreach (UserEditingUI::GetActivationEmailSubstitutions($NewUser)
         as $Key => $Val)
{
    $Key = preg_replace("/X-([A-Z]+)-X/", "$1", $Key);
    $Substitutions[$Key] = $Val;
}
$Substitutions["ACTIVATIONCODE"] = $NewUser->GetActivationCode();

# and use Mailer to send the message
$Mailer = $GLOBALS["G_PluginManager"]->GetPlugin("Mailer");
$TemplateId = $MyPlugin->ConfigSetting("SubscriptionConfirmationTemplate");
$Mailer->SendEmail(
    $TemplateId,
    $NewUser,
    NULL,
    $Substitutions );

# save user attributes provided:
$UEUI = new UserEditingUI($NewUser);
$UEUI->UpdateUserAttributes($_POST, TRUE);

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

# edit the user to subscribe them to the given list
# these subscriptions won't be synced over to the backend until after
# the user verifies their account

$Schema = new MetadataSchema(MetadataSchema::SCHEMAID_USER);
$MLSubsField = $Schema->GetFieldByName("Mailing List Subscriptions");
$CNFactory = new ControlledNameFactory( $MLSubsField->Id() );

$CNameId = $CNFactory->GetItemIdByName($ListName);

$UserResource = $NewUser->GetResource();
$UserResource->Set( $MLSubsField, $CNameId );

# here, mark the user as needing a password entry
$UserResource->Set("Has No Password", TRUE);
