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

CheckAuthorization(PRIV_USERADMIN, PRIV_SYSADMIN);

PageTitle("Processing New User Registration");

if ($_POST["Submit"] == "Create Account")
{
    $FormPage = "index.php?P=P_UserCreator_NewUser&ResourceId=".$_GET["ResourceId"];
    $FTool = new FormTool("RequestAccount");

    # generate a random initial password
    $Password = md5(rand());

    # put generated password into form values
    $_POST["F_Password"] = $Password;
    $_POST["F_PasswordAgain"] = $Password;

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

    # check for and handle errors (by redirecting back to the form page)
    if (UserEditingUI::UserFormHasErrors($FTool, $UserErrorCodes))
    {
        $GLOBALS["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"],
        $Password, $Password,
        $_POST["F_EMail"], $_POST["F_EMailAgain"],
        array(U_ILLEGALPASSWORD, U_ILLEGALPASSWORDAGAIN));

    # 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($FormPage));
        return;
    }

    $UEUI = new UserEditingUI($NewUser);

    $UEUI->UpdateUserAttributes($_POST, TRUE);
    $UEUI->UpdateUserFields(CWUser::GetCustomUserFields());

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

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

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

    global $ActivationUrl;
    global $UserName;

    $UserName = $NewUser->Get("UserName");

    $Protocol = isset($_SERVER["HTTPS"]) ? "https://" : "http://";
    $ActivationUrl = $Protocol.$_SERVER["SERVER_NAME"]
        .dirname($_SERVER["SCRIPT_NAME"])
        ."/index.php?P=ResetPassword&UN=".urlencode($UserName)
        ."&RC=".urlencode($NewUser->GetResetCode());

    $TemplateId = $_POST["F_TemplateId"];
    if ($TemplateId != "-1" )
    {
        global $G_PluginManager;

        $MyResource = new Resource( $_GET["ResourceId"] );

        $MailerPlugin = $G_PluginManager->GetPlugin("Mailer");

        $MailerPlugin->SendEmail( $TemplateId,
                                  array($NewUser->Id()),
                                  array($MyResource),
                                  array("ACTIVATIONURL"=>$ActivationUrl) );

        $MyPlugin = $G_PluginManager->GetPlugin("UserCreator");
    }
}
elseif ($_POST["Submit"]=="Cancel")
{
    print "<script type='text/javascript'>"
        ."window.close();</script>";
}
