<?PHP

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());

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

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

            if ($Code == U_DUPLICATEEMAIL)
            {
                $OurDB = new Database();
                $ExistingUserName = $OurDB->Query(
                    "SELECT UserName FROM APUsers WHERE EMail='".addslashes($_POST["F_EMail"])."'",
                    "UserName");
                $FormPage .= "&ExistingUserName=".$ExistingUserName ;
            }
        }

        $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"],
        $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;
    }

    # save other user information
    $UserFields = array(
        "RealName",
        );
    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);
    }

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

    # Check if there's a default mailing list set up:
    if (isset($_POST["F_SubscribeToDefaultList"]) &&
        $AF->IsRegisteredEvent("MAILMAN_SUBSCRIBE_TO_DEFAULT_LIST") )
    {
        $AF->SignalEvent("MAILMAN_SUBSCRIBE_TO_DEFAULT_LIST",
                         array( "User" => $NewUser ) );
    }

    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")
{
?>
<script type='text/javascript'>
    window.close();
</script>

<?PHP
}
?>
