Beispiel #1
0
        public ActionResult CreateAccount(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                Api.MembershipCreateStatus createStatus;
                string currentUser  = HttpContext.User.Identity.Name;
                int    companyID    = 0;
                int    departmentID = 0;

                _accountService.CreateUser(model.UserName, model.Password, model.Email, currentUser,
                                           model.Comment, companyID, departmentID, out createStatus);

                if (createStatus == Api.MembershipCreateStatus.Success)
                {
                    // FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    // return RedirectToAction("Index", "Home");
                    //new EmailService().SendMail(model.Email, model.UserName, "Authentication", "Welcome to app1");
                    ViewBag.SuccessMsg = "User created successfully!";
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #2
0
        /// <summary>
        /// Creates a new user account
        /// </summary>
        /// <param name="username">A unique username</param>
        /// <param name="password">A hopefully secure password</param>
        /// <param name="email">A unique email address</param>
        /// <param name="roles"></param>
        /// <returns></returns>
        public JsonResult CreateUser(string username, string password, string email)
        {
            MembershipCreateStatus status;
            MyJsonResult           result;

            //create user
            var user = _accountService.CreateUser(username, password, email, out status);

            if (status == MembershipCreateStatus.Success)
            {
                result      = MyJsonResult.CreateSuccess("The user account for " + username + " has been created.");
                result.data = CreateJsonUserObject(user);
            }
            else
            {
                result = MyJsonResult.CreateError(AccountValidation.ErrorCodeToString(status));
            }

            return(Json(result));
        }
        public async Task <IActionResult> Register(UserAccountVM user)
        {
            try
            {
                var result = await _userAccountService.CreateUser(user.FirstName, user.LastName, user.IdentificationNumber, user.Bank, user.BankAccountNumber, user.BankPin);

                //--> odavde ide redirekcija sa postavljenim pass-om na ChangePass sa userAcc modelom i setovanim passom!
                return(RedirectToAction("ChangePassword", new UserAccountChangePassVM()
                {
                    Id = user.Id
                }));
            }
            catch (NotValidParameterException e)
            {
                Logger.LogError(e, e.Message);
                return(RedirectToPage("Error"));
            }
            catch (Exception e)
            {
                Logger.LogError(e, e.Message);
                return(RedirectToPage("Error"));
            }
        }
        /// <summary>
        /// Creates a new estate.
        /// </summary>
        /// <param name="scene">Scene.</param>
        /// <param name="cmd">Cmd.</param>
        protected void CreateEstateCommand(IScene scene, string [] cmd)
        {
            IEstateConnector      estateConnector = Framework.Utilities.DataManager.RequestPlugin <IEstateConnector> ();
            IUserAccountService   accountService  = m_registry.RequestModuleInterface <IUserAccountService> ();
            ISystemAccountService sysAccounts     = m_registry.RequestModuleInterface <ISystemAccountService> ();

            string estateName  = "";
            string estateOwner = sysAccounts.SystemEstateOwnerName;

            // check for passed estate name
            estateName = (cmd.Length < 3)
                ? MainConsole.Instance.Prompt("Estate name", estateName)
                : cmd [2];
            if (estateName == "")
            {
                return;
            }

            // verify that the estate does not already exist
            if (estateConnector.EstateExists(estateName))
            {
                MainConsole.Instance.ErrorFormat("[EstateService]: The estate '{0}' already exists!", estateName);
                return;
            }

            // owner?
            estateOwner = (cmd.Length > 3)
                ? Util.CombineParams(cmd, 4)  // in case of spaces in the name eg Allan Allard
                : MainConsole.Instance.Prompt("Estate owner: ", estateOwner);
            if (estateOwner == "")
            {
                return;
            }


            // check to make sure the user exists
            UserAccount account = accountService.GetUserAccount(null, estateOwner);

            if (account == null)
            {
                MainConsole.Instance.WarnFormat("[User account service]: The user, '{0}' was not found!", estateOwner);

                // temporary fix until remote user creation can be implemented
                if (accountService.IsLocalConnector)
                {
                    string createUser = MainConsole.Instance.Prompt("Do you wish to create this user?  (yes/no)", "yes").ToLower();
                    if (!createUser.StartsWith("y", StringComparison.Ordinal))
                    {
                        return;
                    }

                    // Create a new account
                    string password = MainConsole.Instance.PasswordPrompt(estateOwner + "'s password");
                    string email    = MainConsole.Instance.Prompt(estateOwner + "'s email", "");

                    accountService.CreateUser(estateOwner, Util.Md5Hash(password), email);
                    // CreateUser will tell us success or problem
                    account = accountService.GetUserAccount(null, estateOwner);

                    if (account == null)
                    {
                        MainConsole.Instance.ErrorFormat(
                            "[EstateService]: Unable to store account details.\n   If this simulator is connected to a grid, create the estate owner account first at the grid level.");
                        return;
                    }
                }
                else
                {
                    MainConsole.Instance.WarnFormat("[User account service]: The user must be created on the Grid before assigning an estate!");
                    MainConsole.Instance.WarnFormat("[User account service]: Regions should be assigned to the system user estate until this can be corrected");

                    return;
                }
            }

            // check for bogies...
            if (Utilities.IsSystemUser(account.PrincipalID))
            {
                MainConsole.Instance.Info("[EstateService]: Tsk, tsk.  System users should not be used as estate managers!");
                return;
            }

            // we have an estate name and a user
            // Create a new estate
            var ES = new EstateSettings();

            ES.EstateName  = estateName;
            ES.EstateOwner = account.PrincipalID;

            ES.EstateID = (uint)estateConnector.CreateNewEstate(ES);
            if (ES.EstateID == 0)
            {
                MainConsole.Instance.Warn("There was an error in creating this estate: " + ES.EstateName);
                //EstateName holds the error. See LocalEstateConnector for more info.
            }
            else
            {
                MainConsole.Instance.InfoFormat("[EstateService]: The estate '{0}' owned by '{1}' has been created.", estateName, estateOwner);
            }
        }
        void VerifySystemUserInfo(string usrType, UUID usrUUID, string usrName, int usrLevel)
        {
            var userAccount  = m_accountService.GetUserAccount(null, usrUUID);
            var userPassword = Utilities.RandomPassword.Generate(2, 3, 0);

            if (userAccount == null)
            {
                MainConsole.Instance.WarnFormat("Creating the {0} user '{1}'", usrType, usrName);

                var error = m_accountService.CreateUser(
                    usrUUID,                                // user UUID
                    UUID.Zero,                              // scope
                    usrName,                                // name
                    Util.Md5Hash(userPassword),             // password
                    "");                                    // email

                if (error == "")
                {
                    SaveSystemUserPassword(usrType, usrName, userPassword);
                    MainConsole.Instance.InfoFormat(" The password for '{0}' is : {1}", usrName, userPassword);
                }
                else
                {
                    MainConsole.Instance.WarnFormat(" Unable to create the {0} user : {1}", usrType, error);
                    return;
                }

                //set  "God" level
                var account = m_accountService.GetUserAccount(null, usrUUID);
                account.UserLevel = usrLevel;
                account.UserFlags = Constants.USER_FLAG_CHARTERMEMBER;
                bool success = m_accountService.StoreUserAccount(account);

                if (success)
                {
                    MainConsole.Instance.InfoFormat(" The {0} user has been elevated to '{1}' level", usrType, m_accountService.UserGodLevel(usrLevel));
                }

                return;
            }

            // we already have the account.. verify details in case of a configuration change
            if (userAccount.Name != usrName)
            {
                IAuthenticationService authService = m_registry.RequestModuleInterface <IAuthenticationService> ();

                userAccount.Name = usrName;
                bool updatePass = authService.SetPassword(userAccount.PrincipalID, "UserAccount", userPassword);
                bool updateAcct = m_accountService.StoreUserAccount(userAccount);

                if (updatePass && updateAcct)
                {
                    SaveSystemUserPassword(usrType, usrName, userPassword);
                    MainConsole.Instance.InfoFormat(" The {0} user has been updated to '{1}'", usrType, usrName);
                }
                else
                {
                    MainConsole.Instance.WarnFormat(" There was a problem updating the {0} user", usrType);
                }
            }
        }
        OSDMap CreateAccount(OSDMap map)
        {
            bool   Verified = false;
            string Name     = map ["Name"].AsString();

            string Password = "";

            if (map.ContainsKey("Password"))
            {
                Password = map ["Password"].AsString();
            }
            else
            {
                Password = map ["PasswordHash"].AsString();  //is really plaintext password, the system hashes it later. Not sure why it was called PasswordHash to start with. I guess the original design was to have the PHP code generate the salt and password hash, then just simply store it here
            }

            //string PasswordSalt = map["PasswordSalt"].AsString(); //not being used
            string HomeRegion    = map ["HomeRegion"].AsString();
            string Email         = map ["Email"].AsString();
            string AvatarArchive = map ["AvatarArchive"].AsString();
            int    userLevel     = map ["UserLevel"].AsInteger();
            string UserTitle     = map ["UserTitle"].AsString();

            //server expects: 0 is PG, 1 is Mature, 2 is Adult - use this when setting MaxMaturity and MaturityRating
            //viewer expects: 13 is PG, 21 is Mature, 42 is Adult

            int MaxMaturity = 2;                //set to adult by default

            if (map.ContainsKey("MaxMaturity")) //MaxMaturity is the highest level that they can change the maturity rating to in the viewer
            {
                MaxMaturity = map ["MaxMaturity"].AsInteger();
            }

            int MaturityRating = MaxMaturity;      //set the default to whatever MaxMaturity was set tom incase they didn't define MaturityRating

            if (map.ContainsKey("MaturityRating")) //MaturityRating is the rating the user wants to be able to see
            {
                MaturityRating = map ["MaturityRating"].AsInteger();
            }

            bool activationRequired = map.ContainsKey("ActivationRequired") ? map ["ActivationRequired"].AsBoolean() : false;

            IUserAccountService accountService = m_registry.RequestModuleInterface <IUserAccountService> ();

            if (accountService == null)
            {
                return(null);
            }

            if (!Password.StartsWith("$1$", System.StringComparison.Ordinal))
            {
                Password = "******" + Util.Md5Hash(Password);
            }
            Password = Password.Remove(0, 3);  //remove $1$

            accountService.CreateUser(Name, Password, Email);
            UserAccount       user             = accountService.GetUserAccount(null, Name);
            IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService> ();
            IGridService      gridService      = m_registry.RequestModuleInterface <IGridService> ();

            if (agentInfoService != null && gridService != null)
            {
                GridRegion r = gridService.GetRegionByName(null, HomeRegion);
                if (r != null)
                {
                    agentInfoService.SetHomePosition(user.PrincipalID.ToString(), r.RegionID, new Vector3(r.RegionSizeX / 2, r.RegionSizeY / 2, 20), Vector3.Zero);
                }
                else
                {
                    MainConsole.Instance.DebugFormat("[API]: Could not set home position for user {0}, region \"{1}\" did not produce a result from the grid service", Name, HomeRegion);
                }
            }

            Verified = user != null;
            UUID userID = UUID.Zero;

            OSDMap resp = new OSDMap();

            resp ["Verified"] = OSD.FromBoolean(Verified);

            if (Verified)
            {
                userID         = user.PrincipalID;
                user.UserLevel = userLevel;

                // could not find a way to save this data here.
                DateTime RLDOB     = map ["RLDOB"].AsDate();
                string   RLGender  = map ["RLGender"].AsString();
                string   RLName    = map ["RLName"].AsString();
                string   RLAddress = map ["RLAddress"].AsString();
                string   RLCity    = map ["RLCity"].AsString();
                string   RLZip     = map ["RLZip"].AsString();
                string   RLCountry = map ["RLCountry"].AsString();
                string   RLIP      = map ["RLIP"].AsString();



                IAgentConnector con = DataPlugins.RequestPlugin <IAgentConnector> ();
                con.CreateNewAgent(userID);

                IAgentInfo agent = con.GetAgent(userID);

                agent.MaxMaturity    = MaxMaturity;
                agent.MaturityRating = MaturityRating;

                agent.OtherAgentInformation ["RLDOB"]     = RLDOB;
                agent.OtherAgentInformation ["RLGender"]  = RLGender;
                agent.OtherAgentInformation ["RLName"]    = RLName;
                agent.OtherAgentInformation ["RLAddress"] = RLAddress;
                agent.OtherAgentInformation ["RLCity"]    = RLCity;
                agent.OtherAgentInformation ["RLZip"]     = RLZip;
                agent.OtherAgentInformation ["RLCountry"] = RLCountry;
                agent.OtherAgentInformation ["RLIP"]      = RLIP;
                if (activationRequired)
                {
                    UUID activationToken = UUID.Random();
                    agent.OtherAgentInformation ["WebUIActivationToken"] = Util.Md5Hash(activationToken.ToString() + ":" + Password);
                    resp ["WebUIActivationToken"] = activationToken;
                }
                con.UpdateAgent(agent);

                accountService.StoreUserAccount(user);

                IProfileConnector profileData = DataPlugins.RequestPlugin <IProfileConnector> ();
                IUserProfileInfo  profile     = profileData.GetUserProfile(user.PrincipalID);
                if (profile == null)
                {
                    profileData.CreateNewProfile(user.PrincipalID);
                    profile = profileData.GetUserProfile(user.PrincipalID);
                }
                if (AvatarArchive.Length > 0)
                {
                    profile.AArchiveName = AvatarArchive;
                }
                //    MainConsole.Instance.InfoFormat("[WebUI] Triggered Archive load of " + profile.AArchiveName);
                profile.IsNewUser = true;

                profile.MembershipGroup = UserTitle;
                profile.CustomType      = UserTitle;

                profileData.UpdateUserProfile(profile);
                //   MainConsole.Instance.RunCommand("load avatar archive " + user.FirstName + " " + user.LastName + " Devil");
            }

            resp ["UUID"] = OSD.FromUUID(userID);
            return(resp);
        }
Beispiel #7
0
        public Dictionary <string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                                OSHttpResponse httpResponse, Dictionary <string, object> requestParameters,
                                                ITranslator translator, out string response)
        {
            response = null;
            var vars     = new Dictionary <string, object>();
            var settings = webInterface.GetWebUISettings();

            bool adminUser         = Authenticator.CheckAdminAuthentication(httpRequest, Constants.USER_GOD_CUSTOMER_SERVICE);
            bool allowRegistration = settings.WebRegistration;
            bool anonymousLogins;

            // allow configuration to override the web settings
            IConfig config = webInterface.Registry.RequestModuleInterface <ISimulationBase>().ConfigSource.Configs ["LoginService"];

            if (config != null)
            {
                anonymousLogins   = config.GetBoolean("AllowAnonymousLogin", allowRegistration);
                allowRegistration = (allowRegistration || anonymousLogins);
            }

            if (!adminUser && !allowRegistration)
            {
                vars.Add("ErrorMessage", "");
                vars.Add("RegistrationText", translator.GetTranslatedString("RegistrationText"));
                vars.Add("RegistrationsDisabled", translator.GetTranslatedString("RegistrationsDisabled"));
                vars.Add("Registrations", false);
                vars.Add("NoRegistrations", true);
                return(vars);
            }

            if (requestParameters.ContainsKey("Submit"))
            {
                string AvatarName          = requestParameters["AvatarName"].ToString();
                string AvatarPassword      = requestParameters["AvatarPassword"].ToString();
                string AvatarPasswordCheck = requestParameters["AvatarPassword2"].ToString();
                string FirstName           = requestParameters["FirstName"].ToString();
                string LastName            = requestParameters["LastName"].ToString();
                //removed - greythane - deemed not used
                //string UserAddress = requestParameters["UserAddress"].ToString();
                //string UserZip = requestParameters["UserZip"].ToString();
                string UserCity       = requestParameters["UserCity"].ToString();
                string UserEmail      = requestParameters["UserEmail"].ToString();
                string UserHomeRegion = requestParameters["UserHomeRegion"].ToString();
                string UserDOBMonth   = requestParameters["UserDOBMonth"].ToString();
                string UserDOBDay     = requestParameters["UserDOBDay"].ToString();
                string UserDOBYear    = requestParameters["UserDOBYear"].ToString();
                string AvatarArchive  = requestParameters.ContainsKey("AvatarArchive")
                                           ? requestParameters["AvatarArchive"].ToString()
                                           : "";
                bool ToSAccept = requestParameters.ContainsKey("ToSAccept") &&
                                 requestParameters["ToSAccept"].ToString() == "Accepted";

                string UserType = requestParameters.ContainsKey("UserType")         // only admins can set membership
                    ? requestParameters ["UserType"].ToString()
                    : "Resident";

                // revise UserDOBMonth to a number
                UserDOBMonth = ShortMonthToNumber(UserDOBMonth);

                // revise Type flags
                int UserFlags = webInterface.UserTypeToUserFlags(UserType);

                // a bit of idiot proofing
                if (AvatarName == "")
                {
                    response = "<h3>" + translator.GetTranslatedString("AvatarNameError") + "</h3>";
                    return(null);
                }
                if ((AvatarPassword == "") || (AvatarPassword != AvatarPasswordCheck))
                {
                    response = "<h3>" + translator.GetTranslatedString("AvatarPasswordError") + "</h3>";
                    return(null);
                }
                if (UserEmail == "")
                {
                    response = "<h3>" + translator.GetTranslatedString("AvatarEmailError") + "</h3>";
                    return(null);
                }

                // Thish -  Only one space is allowed in the name to seperate First and Last of the avatar name
                if (AvatarName.Split(' ').Length != 2)
                {
                    response = "<h3>" + translator.GetTranslatedString("AvatarNameSpacingError") + "</h3>";
                    return(null);
                }

                // so far so good...
                if (ToSAccept)
                {
                    AvatarPassword = Util.Md5Hash(AvatarPassword);

                    IUserAccountService accountService =
                        webInterface.Registry.RequestModuleInterface <IUserAccountService>();
                    UUID   userID = UUID.Random();
                    string error  = accountService.CreateUser(userID, settings.DefaultScopeID, AvatarName, AvatarPassword,
                                                              UserEmail);
                    if (error == "")
                    {
                        // set the user account type
                        UserAccount account = accountService.GetUserAccount(null, userID);
                        account.UserFlags = UserFlags;
                        accountService.StoreUserAccount(account);

                        // create and save agent info
                        IAgentConnector con = Framework.Utilities.DataManager.RequestPlugin <IAgentConnector> ();
                        con.CreateNewAgent(userID);
                        IAgentInfo agent = con.GetAgent(userID);
                        agent.OtherAgentInformation ["RLFirstName"] = FirstName;
                        agent.OtherAgentInformation ["RLLastName"]  = LastName;
                        //agent.OtherAgentInformation ["RLAddress"] = UserAddress;
                        agent.OtherAgentInformation ["RLCity"] = UserCity;
                        //agent.OtherAgentInformation ["RLZip"] = UserZip;
                        agent.OtherAgentInformation ["UserDOBMonth"] = UserDOBMonth;
                        agent.OtherAgentInformation ["UserDOBDay"]   = UserDOBDay;
                        agent.OtherAgentInformation ["UserDOBYear"]  = UserDOBYear;
                        agent.OtherAgentInformation ["UserFlags"]    = UserFlags;

                        /*if (activationRequired)
                         * {
                         *  UUID activationToken = UUID.Random();
                         *  agent.OtherAgentInformation["WebUIActivationToken"] = Util.Md5Hash(activationToken.ToString() + ":" + PasswordHash);
                         *  resp["WebUIActivationToken"] = activationToken;
                         * }*/
                        con.UpdateAgent(agent);

                        // create user profile details
                        IProfileConnector profileData =
                            Framework.Utilities.DataManager.RequestPlugin <IProfileConnector> ();
                        if (profileData != null)
                        {
                            IUserProfileInfo profile = profileData.GetUserProfile(userID);
                            if (profile == null)
                            {
                                profileData.CreateNewProfile(userID);
                                profile = profileData.GetUserProfile(userID);
                            }

                            if (AvatarArchive != "")
                            {
                                profile.AArchiveName = AvatarArchive;

                                List <AvatarArchive> avarchives = webInterface.Registry.RequestModuleInterface <IAvatarAppearanceArchiver>().GetAvatarArchives();
                                UUID snapshotUUID = UUID.Zero;
                                foreach (var archive in avarchives)
                                {
                                    if (archive.FolderName == AvatarArchive)
                                    {
                                        snapshotUUID = archive.Snapshot;
                                    }
                                }

                                if (snapshotUUID != UUID.Zero)
                                {
                                    profile.Image = snapshotUUID;
                                }
                            }
                            profile.MembershipGroup = webInterface.UserFlagToType(UserFlags, webInterface.EnglishTranslator);     // membership is english
                            profile.IsNewUser       = true;
                            profileData.UpdateUserProfile(profile);
                        }

                        IAgentInfoService agentInfoService = webInterface.Registry.RequestModuleInterface <IAgentInfoService> ();
                        Vector3           position         = new Vector3(128, 128, 25);
                        Vector3           lookAt           = new Vector3(0, 0, 22);

                        if (agentInfoService != null)
                        {
                            agentInfoService.SetHomePosition(userID.ToString(), (UUID)UserHomeRegion, position, lookAt);
                        }

                        vars.Add("ErrorMessage", "Successfully created account, redirecting to main page");
                        response = "<h3>Successfully created account, redirecting to main page</h3>" +
                                   "<script language=\"javascript\">" +
                                   "setTimeout(function() {window.location.href = \"index.html\";}, 3000);" +
                                   "</script>";
                    }
                    else
                    {
                        vars.Add("ErrorMessage", "<h3>" + error + "</h3>");
                        response = "<h3>" + error + "</h3>";
                    }
                }
                else
                {
                    response = "<h3>You did not accept the Terms of Service agreement.</h3>";
                }
                return(null);
            }

            List <Dictionary <string, object> > daysArgs = new List <Dictionary <string, object> >();

            for (int i = 1; i <= 31; i++)
            {
                daysArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            List <Dictionary <string, object> > monthsArgs = new List <Dictionary <string, object> >();

            //for (int i = 1; i <= 12; i++)
            //    monthsArgs.Add(new Dictionary<string, object> {{"Value", i}});

            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Jan_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Feb_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Mar_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Apr_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("May_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Jun_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Jul_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Aug_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Sep_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Oct_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Nov_Short") }
            });
            monthsArgs.Add(new Dictionary <string, object> {
                { "Value", translator.GetTranslatedString("Dec_Short") }
            });



            List <Dictionary <string, object> > yearsArgs = new List <Dictionary <string, object> >();

            for (int i = 1940; i <= 2013; i++)
            {
                yearsArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            vars.Add("Days", daysArgs);
            vars.Add("Months", monthsArgs);
            vars.Add("Years", yearsArgs);

            var sortBy = new Dictionary <string, bool>();

            sortBy.Add("RegionName", true);

            var RegionListVars = new List <Dictionary <string, object> >();
            var regions        = Framework.Utilities.DataManager.RequestPlugin <IRegionData>().Get((RegionFlags)0,
                                                                                                   RegionFlags.Hyperlink |
                                                                                                   RegionFlags.Foreign |
                                                                                                   RegionFlags.Hidden,
                                                                                                   null, null, sortBy);

            foreach (var region in regions)
            {
                RegionListVars.Add(new Dictionary <string, object> {
                    { "RegionName", region.RegionName },
                    { "RegionUUID", region.RegionID }
                });
            }

            vars.Add("RegionList", RegionListVars);
            vars.Add("UserHomeRegionText", translator.GetTranslatedString("UserHomeRegionText"));


            vars.Add("UserTypeText", translator.GetTranslatedString("UserTypeText"));
            vars.Add("UserType", webInterface.UserTypeArgs(translator));

            List <AvatarArchive> archives = webInterface.Registry.RequestModuleInterface <IAvatarAppearanceArchiver>().GetAvatarArchives();

            List <Dictionary <string, object> > avatarArchives = new List <Dictionary <string, object> >();
            IWebHttpTextureService webTextureService           = webInterface.Registry.
                                                                 RequestModuleInterface <IWebHttpTextureService>();

            foreach (var archive in archives)
            {
                avatarArchives.Add(new Dictionary <string, object>
                {
                    { "AvatarArchiveName", archive.FolderName },
                    { "AvatarArchiveSnapshotID", archive.Snapshot },
                    {
                        "AvatarArchiveSnapshotURL",
                        webTextureService.GetTextureURL(archive.Snapshot)
                    }
                });
            }

            vars.Add("AvatarArchive", avatarArchives);


            IConfig loginServerConfig =
                webInterface.Registry.RequestModuleInterface <ISimulationBase>().ConfigSource.Configs["LoginService"];
            string tosLocation = "";

            if (loginServerConfig != null && loginServerConfig.GetBoolean("UseTermsOfServiceOnFirstLogin", false))
            {
                tosLocation = loginServerConfig.GetString("FileNameOfTOS", "");
                tosLocation = PathHelpers.VerifyReadFile(tosLocation, ".txt", Constants.DEFAULT_DATA_DIR);
            }
            string ToS = "There are no Terms of Service currently. This may be changed at any point in the future.";

            if (tosLocation != "")
            {
                System.IO.StreamReader reader =
                    new System.IO.StreamReader(System.IO.Path.Combine(Environment.CurrentDirectory, tosLocation));
                ToS = reader.ReadToEnd();
                reader.Close();
            }

            // check for user name seed
            string[] m_userNameSeed = null;
            if (loginServerConfig != null)
            {
                string userNameSeed = loginServerConfig.GetString("UserNameSeed", "");
                if (userNameSeed != "")
                {
                    m_userNameSeed = userNameSeed.Split(',');
                }
            }

            Utilities.MarkovNameGenerator ufNames = new Utilities.MarkovNameGenerator();
            Utilities.MarkovNameGenerator ulNames = new Utilities.MarkovNameGenerator();
            string[] nameSeed = m_userNameSeed == null ? Utilities.UserNames : m_userNameSeed;

            string firstName   = ufNames.FirstName(nameSeed, 3, 4);
            string lastName    = ulNames.FirstName(nameSeed, 5, 6);
            string enteredName = firstName + " " + lastName;

            vars.Add("AvatarName", enteredName);
            vars.Add("ToSMessage", ToS);
            vars.Add("TermsOfServiceAccept", translator.GetTranslatedString("TermsOfServiceAccept"));
            vars.Add("TermsOfServiceText", translator.GetTranslatedString("TermsOfServiceText"));
            vars.Add("RegistrationsDisabled", "");
            //vars.Add("RegistrationsDisabled", translator.GetTranslatedString("RegistrationsDisabled"));
            vars.Add("RegistrationText", translator.GetTranslatedString("RegistrationText"));
            vars.Add("AvatarNameText", translator.GetTranslatedString("AvatarNameText"));
            vars.Add("AvatarPasswordText", translator.GetTranslatedString("Password"));
            vars.Add("AvatarPasswordConfirmationText", translator.GetTranslatedString("PasswordConfirmation"));
            vars.Add("AvatarScopeText", translator.GetTranslatedString("AvatarScopeText"));
            vars.Add("FirstNameText", translator.GetTranslatedString("FirstNameText"));
            vars.Add("LastNameText", translator.GetTranslatedString("LastNameText"));
            vars.Add("UserAddressText", translator.GetTranslatedString("UserAddressText"));
            vars.Add("UserZipText", translator.GetTranslatedString("UserZipText"));
            vars.Add("UserCityText", translator.GetTranslatedString("UserCityText"));
            vars.Add("UserCountryText", translator.GetTranslatedString("UserCountryText"));
            vars.Add("UserDOBText", translator.GetTranslatedString("UserDOBText"));
            vars.Add("UserEmailText", translator.GetTranslatedString("UserEmailText"));
            vars.Add("Accept", translator.GetTranslatedString("Accept"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));
            vars.Add("SubmitURL", "register.html");
            vars.Add("ErrorMessage", "");
            vars.Add("Registrations", true);
            vars.Add("NoRegistrations", false);

            return(vars);
        }
        private void CheckGovernorUserInfo()
        {
            UserAccount govInfo     = m_accountService.GetUserAccount(null, UUID.Parse(Constants.GovernorUUID));
            var         govPassword = Utilities.RandomPassword.Generate(2, 1, 0);

            if (govInfo == null)
            {
                MainConsole.Instance.Warn("Creating the Governor user '" + GovernorName + "'");

                var error = m_accountService.CreateUser(
                    (UUID)Constants.GovernorUUID,           // UUID
                    UUID.Zero,                              // ScopeID
                    GovernorName,                           // Name
                    Util.Md5Hash(govPassword),              // password
                    "");                                    // email

                if (error == "")
                {
                    SaveGovernorPassword(govPassword);
                    MainConsole.Instance.Info(" The password for '" + GovernorName + "' is : " + govPassword);
                }
                else
                {
                    MainConsole.Instance.Warn(" Unable to create the Governor user : "******"Maintenace" level
                var account = m_accountService.GetUserAccount(null, UUID.Parse(Constants.GovernorUUID));
                account.UserLevel = 250;
                account.UserFlags = Constants.USER_FLAG_CHARTERMEMBER;
                bool success = m_accountService.StoreUserAccount(account);

                if (success)
                {
                    MainConsole.Instance.Info(" The Governor user has been elevated to 'Maintenance' level");
                }

                return;
            }

            // we already have the Governor account.. verify details in case of a configuration change
            if (govInfo.Name != GovernorName)
            {
                IAuthenticationService authService = m_registry.RequestModuleInterface <IAuthenticationService> ();

                govInfo.Name = GovernorName;
                bool updatePass = authService.SetPassword(govInfo.PrincipalID, "UserAccount", govPassword);
                bool updateAcct = m_accountService.StoreUserAccount(govInfo);

                if (updatePass && updateAcct)
                {
                    SaveGovernorPassword(govPassword);
                    MainConsole.Instance.InfoFormat(" The Governor user has been updated to '{0}'", GovernorName);
                }
                else
                {
                    MainConsole.Instance.Warn(" There was a problem updating the Governor user");
                }
            }
        }
        public Dictionary <string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                                OSHttpResponse httpResponse, Dictionary <string, object> requestParameters, ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary <string, object>();

            if (requestParameters.ContainsKey("Submit"))
            {
                string AvatarName     = requestParameters["AvatarName"].ToString();
                string AvatarPassword = requestParameters["AvatarPassword"].ToString();
                string FirstName      = requestParameters["FirstName"].ToString();
                string LastName       = requestParameters["LastName"].ToString();
                string UserAddress    = requestParameters["UserAddress"].ToString();
                string UserZip        = requestParameters["UserZip"].ToString();
                string UserCity       = requestParameters["UserCity"].ToString();
                string UserEmail      = requestParameters["UserEmail"].ToString();
                string UserDOBMonth   = requestParameters["UserDOBMonth"].ToString();
                string UserDOBDay     = requestParameters["UserDOBDay"].ToString();
                string UserDOBYear    = requestParameters["UserDOBYear"].ToString();
                string AvatarArchive  = requestParameters.ContainsKey("AvatarArchive") ? requestParameters["AvatarArchive"].ToString() : "";
                bool   ToSAccept      = requestParameters.ContainsKey("ToSAccept") && requestParameters["ToSAccept"].ToString() == "Accepted";

                IGenericsConnector generics = Aurora.DataManager.DataManager.RequestPlugin <IGenericsConnector>();
                var settings = generics.GetGeneric <GridSettings>(UUID.Zero, "WebSettings", "Settings");

                if (ToSAccept)
                {
                    AvatarPassword = Util.Md5Hash(AvatarPassword);

                    IUserAccountService accountService = webInterface.Registry.RequestModuleInterface <IUserAccountService>();
                    UUID   userID = UUID.Random();
                    string error  = accountService.CreateUser(userID, settings.DefaultScopeID, AvatarName, AvatarPassword, UserEmail);
                    if (error == "")
                    {
                        IAgentConnector con = Aurora.DataManager.DataManager.RequestPlugin <IAgentConnector>();
                        con.CreateNewAgent(userID);
                        IAgentInfo agent = con.GetAgent(userID);
                        agent.OtherAgentInformation["RLFirstName"]  = FirstName;
                        agent.OtherAgentInformation["RLLastName"]   = LastName;
                        agent.OtherAgentInformation["RLAddress"]    = UserAddress;
                        agent.OtherAgentInformation["RLCity"]       = UserCity;
                        agent.OtherAgentInformation["RLZip"]        = UserZip;
                        agent.OtherAgentInformation["UserDOBMonth"] = UserDOBMonth;
                        agent.OtherAgentInformation["UserDOBDay"]   = UserDOBDay;
                        agent.OtherAgentInformation["UserDOBYear"]  = UserDOBYear;

                        /*if (activationRequired)
                         * {
                         *  UUID activationToken = UUID.Random();
                         *  agent.OtherAgentInformation["WebUIActivationToken"] = Util.Md5Hash(activationToken.ToString() + ":" + PasswordHash);
                         *  resp["WebUIActivationToken"] = activationToken;
                         * }*/
                        con.UpdateAgent(agent);

                        if (AvatarArchive != "")
                        {
                            IProfileConnector profileData = Aurora.DataManager.DataManager.RequestPlugin <IProfileConnector>();
                            profileData.CreateNewProfile(userID);

                            IUserProfileInfo profile = profileData.GetUserProfile(userID);
                            profile.AArchiveName = AvatarArchive + ".database";
                            profile.IsNewUser    = true;
                            profileData.UpdateUserProfile(profile);
                        }

                        response = "<h3>Successfully created account, redirecting to main page</h3>" +
                                   "<script language=\"javascript\">" +
                                   "setTimeout(function() {window.location.href = \"index.html\";}, 3000);" +
                                   "</script>";
                    }
                    else
                    {
                        response = "<h3>" + error + "</h3>";
                    }
                }
                else
                {
                    response = "<h3>You did not accept the Terms of Service agreement.</h3>";
                }
                return(null);
            }

            List <Dictionary <string, object> > daysArgs = new List <Dictionary <string, object> >();

            for (int i = 1; i <= 31; i++)
            {
                daysArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            List <Dictionary <string, object> > monthsArgs = new List <Dictionary <string, object> >();

            for (int i = 1; i <= 12; i++)
            {
                monthsArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            List <Dictionary <string, object> > yearsArgs = new List <Dictionary <string, object> >();

            for (int i = 1900; i <= 2013; i++)
            {
                yearsArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            vars.Add("Days", daysArgs);
            vars.Add("Months", monthsArgs);
            vars.Add("Years", yearsArgs);

            List <AvatarArchive> archives = Aurora.DataManager.DataManager.RequestPlugin <IAvatarArchiverConnector>().GetAvatarArchives(true);

            List <Dictionary <string, object> > avatarArchives = new List <Dictionary <string, object> >();
            IWebHttpTextureService webTextureService           = webInterface.Registry.
                                                                 RequestModuleInterface <IWebHttpTextureService>();

            foreach (var archive in archives)
            {
                avatarArchives.Add(new Dictionary <string, object> {
                    { "AvatarArchiveName", archive.Name },
                    { "AvatarArchiveSnapshotID", archive.Snapshot },
                    { "AvatarArchiveSnapshotURL", webTextureService.GetTextureURL(UUID.Parse(archive.Snapshot)) }
                });
            }

            vars.Add("AvatarArchive", avatarArchives);


            IConfig loginServerConfig = webInterface.Registry.RequestModuleInterface <ISimulationBase>().ConfigSource.Configs["LoginService"];
            string  tosLocation       = "";

            if (loginServerConfig != null && loginServerConfig.GetBoolean("UseTermsOfServiceOnFirstLogin", false))
            {
                tosLocation = loginServerConfig.GetString("FileNameOfTOS", "");
            }
            string ToS = "There are no Terms of Service currently. This may be changed at any point in the future.";

            if (tosLocation != "")
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(System.IO.Path.Combine(Environment.CurrentDirectory, tosLocation));
                ToS = reader.ReadToEnd();
                reader.Close();
            }
            vars.Add("ToSMessage", ToS);
            vars.Add("TermsOfServiceAccept", translator.GetTranslatedString("TermsOfServiceAccept"));
            vars.Add("TermsOfServiceText", translator.GetTranslatedString("TermsOfServiceText"));
            vars.Add("RegistrationsDisabled", translator.GetTranslatedString("RegistrationsDisabled"));
            vars.Add("RegistrationText", translator.GetTranslatedString("RegistrationText"));
            vars.Add("AvatarNameText", translator.GetTranslatedString("AvatarNameText"));
            vars.Add("AvatarPasswordText", translator.GetTranslatedString("Password"));
            vars.Add("AvatarPasswordConfirmationText", translator.GetTranslatedString("PasswordConfirmation"));
            vars.Add("AvatarScopeText", translator.GetTranslatedString("AvatarScopeText"));
            vars.Add("FirstNameText", translator.GetTranslatedString("FirstNameText"));
            vars.Add("LastNameText", translator.GetTranslatedString("LastNameText"));
            vars.Add("UserAddressText", translator.GetTranslatedString("UserAddressText"));
            vars.Add("UserZipText", translator.GetTranslatedString("UserZipText"));
            vars.Add("UserCityText", translator.GetTranslatedString("UserCityText"));
            vars.Add("UserCountryText", translator.GetTranslatedString("UserCountryText"));
            vars.Add("UserDOBText", translator.GetTranslatedString("UserDOBText"));
            vars.Add("UserEmailText", translator.GetTranslatedString("UserEmailText"));
            vars.Add("Accept", translator.GetTranslatedString("Accept"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));
            vars.Add("SubmitURL", "register.html");

            return(vars);
        }
        /// <summary>
        /// This method will produce a random city with the central region of the city being
        /// specified as a parameter. More parameters need to be made available for this method
        /// to produce a better quality city, note for now the minimum area for a city is a
        /// 3x3 grid of regions. This code is based on the original C++ version called pixel city.
        /// </summary>
        /// <param name="seed_value">Random integer seed value.</param>
        /// <returns>true / false indicator of success or failure.</returns>
        private bool doGenerate(int seed_value)
        {
            int rx, ry;

            //  Based on the initial seed value populate the regions that this shared module
            // is connected to, this means first get a list of the region, determine which
            // region is in the center of all the regions and set this as the hotzone, or
            // central part of the city (this is where the tallest/largest buildings will
            // be created) and will extend out to cover virtually all of the connected
            // regions if desired. No support for aging of the buildings or the city exists
            // yet it is a possible course for the future of this module.

            //  First quick check to see if the module is enabled or not.
            if (!m_fEnabled)
            {
                m_log.Info("[CITY BUILDER]: Disabled, aborting auto generation.");
                return(false);
            }

            m_log.Info("[CITY BUILDER]: Auto generating the city.");

            //  Now we need to ask some basic values for the city generation, we already have
            // the base seed value as this is part of the 'city generate' command, now what
            // about a name, position, size, densities etc. Some of this can be generated
            // based on the seed value, but then, it would need to be confirmed by the user
            // or allow them to change it. TODO move all requested data into the configuration file.
            if (m_UserAccountService == null)
            {
                m_UserAccountService = simulationBase.ApplicationRegistry.RequestModuleInterface <IUserAccountService>();
            }

            //  Decide where the city is to be placed within the server instance.
            int r = this.randomValue(10);

            string regionCount = MainConsole.Instance.CmdPrompt("Region Count ", r.ToString());

            r = Convert.ToInt32(regionCount);
            m_log.InfoFormat("[CITY BUILDER]: City area {0} x {1} regions ", r, r);

            cityName          = MainConsole.Instance.CmdPrompt("City Name ", cityName);
            cityOwner         = MainConsole.Instance.CmdPrompt("City Owner ", cityOwner);
            m_DefaultUserName = cityOwner;

            //  Make sure that the user and estate information specified in the configuration file
            // have been loaded and the information has either been found or has been created.
            m_DefaultUserAccount = m_UserAccountService.GetUserAccount(UUID.Zero, cityOwner);
            if (m_DefaultUserAccount == null)
            {
                m_log.InfoFormat("[CITY BUILDER]: Creating default account {0}", m_DefaultUserName);
                m_UserAccountService.CreateUser(m_DefaultUserName, Util.Md5Hash(m_DefaultUserPword), m_DefaultUserEmail);
                m_DefaultUserAccount = m_UserAccountService.GetUserAccount(UUID.Zero, m_DefaultUserName);
                cityOwner            = m_DefaultUserName;
            }
            else
            {
                m_log.InfoFormat("[CITY BUILDER]: Account found for {0}", m_DefaultUserName);
            }

            // Obtain the scene manager that the server instance is using.
            sceneManager = simulationBase.ApplicationRegistry.RequestModuleInterface <SceneManager>();

            //  Construct the data instance for a city map to hold the total regions in the simulation.
            cityMap               = new CityMap();
            citySeed              = seed_value;
            cityMap.cityRegions   = new Scene[r, r];
            cityMap.cityPlots     = new List <BuildingPlot>();
            cityMap.cityBuildings = new List <CityBuilding>();

            //  Construct land and estate data and update to reflect the found user or the newly created one.
            cityLandData = new LandData();
            RegionInfo regionInfo = new RegionInfo();

            regionInfo.RegionID = UUID.Random();

            //Create an estate
            m_DefaultEstate = new EstateSettings();

            m_log.InfoFormat("[CITY BUILDER]: No estates found for user {0}, constructing default estate.", m_DefaultUserAccount.Name);

            m_DefaultEstate.EstateOwner = m_DefaultUserAccount.PrincipalID;
            m_DefaultEstate.EstateName  = m_DefaultEstateName;
            m_DefaultEstate.EstatePass  = Util.Md5Hash(Util.Md5Hash(m_DefaultEstatePassword));
            m_DefaultEstate.EstateID    = (uint)this.randomValue(1000);

            regionInfo.EstateSettings = m_DefaultEstate; //Just set the estate, this module took care of the loading and the rest will leave it alone

            cityLandData.OwnerID  = m_DefaultUserAccount.PrincipalID;
            cityLandData.Name     = m_DefaultEstateName;
            cityLandData.GlobalID = UUID.Random();
            cityLandData.GroupID  = UUID.Zero;

            int regionPort = startPort;

            //  Construct the region.
            regionInfo.RegionSizeX    = cityConfig.GetInt("DefaultRegionSize", 256);
            regionInfo.RegionSizeY    = regionInfo.RegionSizeX;
            regionInfo.RegionType     = "Mainland";
            regionInfo.ObjectCapacity = 100000;
            regionInfo.Startup        = StartupType.Normal;
            regionInfo.ScopeID        = UUID.Zero;

            IParcelServiceConnector parcelService = Aurora.DataManager.DataManager.RequestPlugin <IParcelServiceConnector>();

            if (r == 1)
            {
                m_log.Info("[CITY BUILDER]: Single region city.");
                IPAddress address = IPAddress.Parse("0.0.0.0");
                regionInfo.ExternalHostName          = Aurora.Framework.Utilities.GetExternalIp();
                regionInfo.FindExternalAutomatically = true;
                regionInfo.InternalEndPoint          = new IPEndPoint(address, regionPort++);
                cityLandData.RegionID = regionInfo.RegionID;
                if (parcelService != null)
                {
                    parcelService.StoreLandObject(cityLandData.LandData);
                }
                regionInfo.RegionName = "Region00";
                regionInfo.RegionLocX = (int)m_DefaultStartLocation.X;
                regionInfo.RegionLocY = (int)m_DefaultStartLocation.Y;
                if (!createRegion(0, 0, regionInfo))
                {
                    m_log.Info("[CITY BUILDER]: Failed to construct region.");
                    return(false);
                }
            }
            else if (r > 1)
            {
                m_log.Info("[CITY BUILDER]: Multi-region city.");
                IPAddress address = IPAddress.Parse("0.0.0.0");
                regionInfo.ExternalHostName          = Aurora.Framework.Utilities.GetExternalIp();
                regionInfo.FindExternalAutomatically = true;
                //  Construct the regions for the city.
                regionPort = startPort;
                for (rx = 0; rx < r; rx++)
                {
                    for (ry = 0; ry < r; ry++)
                    {
                        regionInfo.InternalEndPoint = new IPEndPoint(address, regionPort++);
                        cityLandData.RegionID       = regionInfo.RegionID;
                        if (parcelService != null)
                        {
                            parcelService.StoreLandObject(cityLandData.LandData);
                        }
                        regionInfo.RegionName = "Region" + rx + ry;
                        regionInfo.RegionLocX = (int)(m_DefaultStartLocation.X + rx);
                        regionInfo.RegionLocY = (int)(m_DefaultStartLocation.Y + ry);
                        m_log.InfoFormat("[CITY BUILDER]: '{0}' @ {1},{2}, http://{3}/", regionInfo.RegionName,
                                         regionInfo.RegionLocX, regionInfo.RegionLocY, regionInfo.InternalEndPoint);
                        //We already set the estate before, we don't need to deal with linking it or anything
                        //EstateConnector.LinkRegion(regionInfo.RegionID, (int)m_DefaultEstate.EstateID, m_DefaultEstate.EstatePass);
                        if (!createRegion(rx, ry, regionInfo))
                        {
                            m_log.InfoFormat("[CITY BUILDER]: Failed to construct region at {0},{1}", rx, ry);
                            return(false);
                        }
                    }
                }
            }

            //  Either generate the terrain or loading from an existing file, DEM for example.
            m_log.Info("[CITY BUILDER]: [TERRAIN]");

            //  For each region, just fill the terrain to be 21. This is just above the default
            // water level for Aurora.
            float[,] tHeight = new float[256, 256];
            for (rx = 0; rx < 256; rx++)
            {
                for (ry = 0; ry < 256; ry++)
                {
                    tHeight[rx, ry] = 21.0f;
                }
            }
            //  Construct the new terrain for each region and pass the height map to it.
            for (rx = 0; rx < r; rx++)
            {
                for (ry = 0; ry < r; ry++)
                {
                    Scene           region   = cityMap.cityRegions[rx, ry];
                    ITerrainChannel tChannel = new TerrainChannel(true, region);
                    ITerrain        terrain  = null;
                    try
                    {
                        region.TryRequestModuleInterface <ITerrain>(out terrain);
                        terrain.SetHeights2D(tHeight);
                    }
                    catch
                    {
                    }
                }
            }

            //  Rivers and other waterways.

            //  From the total number of regions pick a number of regions that will be 'centers'
            // for the entire city, record these in the centralRegions list.
            m_log.Info("[CITY BUILDER]: [CENTERS]");
            //  ( region count * region count ) / 3
            int aNum = this.randomValue((cityMap.cityRegions.GetUpperBound(0) * cityMap.cityRegions.GetUpperBound(1)) / 3);

            if (aNum == 0)
            {
                aNum = 1;
            }
            m_log.InfoFormat("[CITY BUILDER]: Total regions {0}, selecting {1} regions for centers.", (r * r), aNum);
            int prevRegionX = 0;
            int prevRegionY = 0;

            while (aNum > 0)
            {
                int currRegionX = randomValue(cityMap.cityRegions.GetUpperBound(0)) / 2;
                int currRegionY = randomValue(cityMap.cityRegions.GetUpperBound(1)) / 2;

                // If the location selected is the same as the previous location try again.
                if (currRegionX == prevRegionX && currRegionY == prevRegionY)
                {
                    aNum--;
                    continue;
                }

                m_log.InfoFormat("[CITY BUILDER]: Region {0}, located {1},{2}", aNum, prevRegionX, prevRegionY);

                try
                {
                    Scene region = cityMap.centralRegions[(prevRegionX * cityMap.cityRegions.GetUpperBound(0)) + prevRegionY];
                    if (region != null)
                    {
                        cityMap.centralRegions.Add(region);
                    }
                }
                catch
                {
                }
                aNum--;
                prevRegionX = currRegionX;
                prevRegionY = currRegionY;
            }

            m_log.Info("[CITY BUILDER]: [DENSITY]");
            float avgDensity = 0.0f;

            avgDensity += cityDensities[0];
            avgDensity += cityDensities[1];
            avgDensity += cityDensities[2];
            avgDensity += cityDensities[3];
            avgDensity /= 4;

            //  Before ANYTHING else is created construct the transport systems, priority is given
            // to the road network before the rail network, perhaps a configuration option to allow
            // for the prioritisation value of the transport system is possible.
            m_log.Info("[CITY BUILDER]: [FREEWAYS]");
            m_log.Info("[CITY BUILDER]: [HIGHWAYS]");
            m_log.Info("[CITY BUILDER]: [STREETS]");
            m_log.Info("[CITY BUILDER]: [RAILWAYS]");

            m_log.InfoFormat("[CITY BUILDER]: [RESIDENTIAL DENSITY] {0}%", cityDensities[0] * 100);
            m_log.InfoFormat("[CITY BUILDER]: [COMMERCIAL DENSITY] {0}%", cityDensities[1] * 100);
            m_log.InfoFormat("[CITY BUILDER]: [CORPORATE DENSITY] {0}%", cityDensities[2] * 100);
            m_log.InfoFormat("[CITY BUILDER]: [INDUSTRIAL DENISTY] {0}%", cityDensities[3] * 100);
            m_log.InfoFormat("[CITY BUILDER]: [AVERAGE DENSITY] {0}%", avgDensity);

            m_log.Info("[CITY BUILDER]: [BLOCKS]");
            m_log.Info("[CITY BUILDER]: [ALLOTMENT PLOTS]");
            m_log.Info("[CITY BUILDER]: [BUILDINGS]");

            return(true);
        }
Beispiel #11
0
        private byte[] ProcessCreateAccount(OSDMap map)
        {
            bool   Verified     = false;
            string Name         = map["Name"].AsString();
            string PasswordHash = map["PasswordHash"].AsString();
            //string PasswordSalt = map["PasswordSalt"].AsString();
            string HomeRegion    = map["HomeRegion"].AsString();
            string Email         = map["Email"].AsString();
            string AvatarArchive = map["AvatarArchive"].AsString();



            IUserAccountService accountService = m_registry.RequestModuleInterface <IUserAccountService>();

            if (accountService == null)
            {
                return(null);
            }

            if (!PasswordHash.StartsWith("$1$"))
            {
                PasswordHash = "$1$" + Util.Md5Hash(PasswordHash);
            }
            PasswordHash = PasswordHash.Remove(0, 3); //remove $1$

            accountService.CreateUser(Name, PasswordHash, Email);
            UserAccount       user             = accountService.GetUserAccount(UUID.Zero, Name);
            IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService> ();
            IGridService      gridService      = m_registry.RequestModuleInterface <IGridService> ();

            if (agentInfoService != null && gridService != null)
            {
                GridRegion r = gridService.GetRegionByName(UUID.Zero, HomeRegion);
                agentInfoService.SetHomePosition(user.PrincipalID.ToString(), r.RegionID, new Vector3(r.RegionSizeX / 2, r.RegionSizeY / 2, 20), Vector3.Zero);
            }

            Verified = user != null;
            UUID userID = UUID.Zero;

            if (Verified)
            {
                // could not find a way to save this data here.

                /*DateTime RLDOB = map["RLDOB"].AsDate();
                 * string RLFirstName = map["RLFisrtName"].AsString();
                 * string RLLastName = map["RLLastName"].AsString();
                 * string RLAdress = map["RLAdress"].AsString();
                 * string RLCity = map["RLCity"].AsString();
                 * string RLZip = map["RLZip"].AsString();
                 * string RLCountry = map["RLCountry"].AsString();
                 * string RLIP = map["RLIP"].AsString();*/
                // could not find a way to save this data here.


                userID         = user.PrincipalID;
                user.UserLevel = -1;

                accountService.StoreUserAccount(user);

                IProfileConnector profileData = DataManager.RequestPlugin <IProfileConnector>();
                IUserProfileInfo  profile     = profileData.GetUserProfile(user.PrincipalID);
                if (profile == null)
                {
                    profileData.CreateNewProfile(user.PrincipalID);
                    profile = profileData.GetUserProfile(user.PrincipalID);
                }
                if (AvatarArchive.Length > 0)
                {
                    profile.AArchiveName = AvatarArchive + ".database";
                }

                profile.IsNewUser = true;
                profileData.UpdateUserProfile(profile);
            }

            OSDMap resp = new OSDMap();

            resp["Verified"] = OSD.FromBoolean(Verified);
            resp["UUID"]     = OSD.FromUUID(userID);
            string       xmlString = OSDParser.SerializeJsonString(resp);
            UTF8Encoding encoding  = new UTF8Encoding();

            return(encoding.GetBytes(xmlString));
        }
        /// <summary>
        /// Creates a user
        /// TODO: Does not implement the restrict to estate option
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        private OSD CreateUser(OSDMap map)
        {
            //Required params
            string username     = map["username"];
            int    last_name_id = map["last_name_id"];
            string email        = map["email"];
            string password     = map["password"];
            string dob          = map["dob"];

            //Optional params
            int    limited_to_estate = map["limited_to_estate"];
            string start_region_name = map["start_region_name"];
            float  start_local_x     = map["start_local_x"];
            float  start_local_y     = map["start_local_y"];
            float  start_local_z     = map["start_local_z"];
            float  start_look_at_x   = map["start_look_at_x"];
            float  start_look_at_y   = map["start_look_at_y"];
            float  start_look_at_z   = map["start_look_at_z"];
            OSD    resp = null;

            if (username != "" && last_name_id != 0 && email != "" &&
                password != "" && dob != "")
            {
                IUserAccountService accountService = m_registry.RequestModuleInterface <IUserAccountService>();
                if (m_lastNameRegistry.ContainsKey(last_name_id))
                {
                    string      lastName = m_lastNameRegistry[last_name_id];
                    UserAccount user     = accountService.GetUserAccount(null, username, lastName);
                    if (user == null)
                    {
                        //The pass is in plain text... so put it in and create the account
                        accountService.CreateUser(username + " " + lastName, password, email);
                        DateTime time = DateTime.ParseExact(dob, "YYYY-MM-DD", System.Globalization.CultureInfo.InvariantCulture);
                        user = accountService.GetUserAccount(null, username, lastName);
                        //Update the dob
                        user.Created = Util.ToUnixTime(time);
                        accountService.StoreUserAccount(user);

                        IAgentConnector agentConnector = Aurora.Framework.Utilities.DataManager.RequestPlugin <IAgentConnector>();
                        if (agentConnector != null)
                        {
                            agentConnector.CreateNewAgent(user.PrincipalID);
                            if (map.ContainsKey("limited_to_estate"))
                            {
                                IAgentInfo agentInfo = agentConnector.GetAgent(user.PrincipalID);
                                agentInfo.OtherAgentInformation["LimitedToEstate"] = limited_to_estate;
                                agentConnector.UpdateAgent(agentInfo);
                            }
                        }

                        MainConsole.Instance.Info("[RegApi]: Created new user " + user.Name);
                        try
                        {
                            if (start_region_name != "")
                            {
                                IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService>();
                                if (agentInfoService != null)
                                {
                                    agentInfoService.SetHomePosition(user.PrincipalID.ToString(),
                                                                     m_registry.RequestModuleInterface <IGridService>().GetRegionByName
                                                                         (null, start_region_name).RegionID,
                                                                     new Vector3(start_local_x,
                                                                                 start_local_y,
                                                                                 start_local_z),
                                                                     new Vector3(start_look_at_x,
                                                                                 start_look_at_y,
                                                                                 start_look_at_z));
                                }
                            }
                        }
                        catch
                        {
                            MainConsole.Instance.Warn("[RegApi]: Encountered an error when setting the home position of a new user");
                        }
                        OSDMap r = new OSDMap();
                        r["agent_id"] = user.PrincipalID;
                        resp          = r;
                    }
                    else //Already exists
                    {
                        resp = false;
                    }
                }
                else //Could not find last name
                {
                    resp = false;
                }
            }
            else //Not enough params
            {
                resp = false;
            }

            return(resp);
        }