Inheritance: Universe.Framework.Modules.IDataTransferable
        public int CreateNewEstate(EstateSettings es)
        {
            object remoteValue = DoRemote(es.ToOSD());
            if (remoteValue != null || m_doRemoteOnly)
                return (int) remoteValue;

            int estateID = GetEstate(es.EstateOwner, es.EstateName);
            if (estateID > 0)
            {
                return estateID;
            }

            // check for system or user estates
            if ((es.EstateOwner == (UUID) Constants.GovernorUUID))                  // Mainland?
            {
                es.EstateID = Constants.MainlandEstateID;
            } else if ( (es.EstateOwner == (UUID) Constants.RealEstateOwnerUUID) )  // System Estate?
            {
                es.EstateID = (uint) Constants.SystemEstateID;
            } else                                                                  // must be a new user estate then
                es.EstateID = GetNewEstateID();

            SaveEstateSettings(es, true);
            return (int) es.EstateID;
        }
        public EstateSettings GetEstateSettings(UUID regionID)
        {
            EstateSettings settings = new EstateSettings () { EstateID = 0 };

            if (m_doRemoteOnly)
            {
                object remoteValue = DoRemote (regionID);
                return remoteValue != null ? (EstateSettings)remoteValue : settings;
            }

            int estateID = GetEstateID(regionID);
            if (estateID == 0)
                return settings;

            settings = GetEstate(estateID);
            return settings;
        }
        public int CreateNewEstate(EstateSettings es)
        {
            object remoteValue = DoRemote(es.ToOSD());
            if (remoteValue != null || m_doRemoteOnly)
                return (int) remoteValue;

            int estateID = GetEstate(es.EstateOwner, es.EstateName);
            if (estateID > 0)
            {
                return estateID;
            }

            // check for system user/estate
            if ( (es.EstateOwner == (UUID) Constants.RealEstateOwnerUUID) )           // We probably do not need to check both :)
            {
                es.EstateID = (uint) Constants.SystemEstateID;                        // Default Mainland estate  #
            } else
                es.EstateID = GetNewEstateID();

            SaveEstateSettings(es, true);
            return (int) es.EstateID;
        }
        public int CreateNewEstate(EstateSettings es, UUID RegionID)
        {
            object remoteValue = DoRemote(es.ToOSD(), RegionID);
            if (remoteValue != null || m_doRemoteOnly)
                return (int) remoteValue;

            int estateID = GetEstate(es.EstateOwner, es.EstateName);
            if (estateID > 0)
            {
                if (LinkRegion(RegionID, estateID))
                    return estateID;
                return 0;
            }
            es.EstateID = GetNewEstateID();
            SaveEstateSettings(es, true);
            LinkRegion(RegionID, (int) es.EstateID);
            return (int) es.EstateID;
        }
        EstateSettings GetEstate(int estateID)
        {
            QueryFilter filter = new QueryFilter();
            filter.andFilters["EstateID"] = estateID;
            List<string> retVals = GD.Query(new string[1] { "*" }, m_estateSettingsTable, filter, null, null, null);
            EstateSettings settings = new EstateSettings
                                          {
                                              EstateID = 0
                                          };
            if (retVals.Count > 0)
                settings.FromOSD((OSDMap) OSDParser.DeserializeJson(retVals[4]));

            return settings;
        }
        protected void SaveEstateSettings(EstateSettings es, bool doInsert)
        {
            Dictionary<string, object> values = new Dictionary<string, object>(5);
            values["EstateID"] = es.EstateID;
            values["EstateName"] = es.EstateName;
            values["EstateOwner"] = es.EstateOwner;
            values["ParentEstateID"] = es.ParentEstateID;
            values["Settings"] = OSDParser.SerializeJsonString(es.ToOSD());

            if (!doInsert)
            {
                QueryFilter filter = new QueryFilter();
                filter.andFilters["EstateID"] = es.EstateID;
                GD.Update(m_estateSettingsTable, values, null, filter, null, null);
            }
            else
            {
                GD.Insert(m_estateSettingsTable, values);
            }
        }
        public void SaveEstateSettings(EstateSettings es)
        {
            object remoteValue = DoRemote(es.ToOSD());
            if (remoteValue != null || m_doRemoteOnly)
                return;

            SaveEstateSettings(es, false);
        }
 bool CheckEstateGroups(EstateSettings ES, AgentCircuitData agent)
 {
     IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule> ();
     if (gm != null && ES.EstateGroups.Count > 0)
     {
         GroupMembershipData[] gmds = gm.GetMembershipData (agent.AgentID);
         return gmds.Any (gmd => ES.EstateGroups.Contains (gmd.GroupID));
     }
     return false;
 }
 /// <summary>
 /// Loads the estate settings from an archive.
 /// </summary>
 /// <param name="data">Data.</param>
 /// <param name="filePath">File path.</param>
 /// <param name="type">Type.</param>
 /// <param name="scene">Scene.</param>
 public void LoadModuleFromArchive(byte[] data, string filePath, TarArchiveReader.TarEntryType type, IScene scene)
 {
     if (filePath.StartsWith("estatesettings/"))
     {
         EstateSettings settings = new EstateSettings();
         settings.FromOSD((OSDMap) OSDParser.DeserializeLLSDBinary(data));
         scene.RegionInfo.EstateSettings = settings;
     }
     else if (filePath.StartsWith("regioninfo/"))
     {
         string m_merge =
             MainConsole.Instance.Prompt(
                 "Should we load the region information from the archive (region name, region position, etc)?",
                 "false");
         RegionInfo settings = new RegionInfo();
         settings.UnpackRegionInfoData((OSDMap) OSDParser.DeserializeLLSDBinary(data));
         if (m_merge == "false")
         {
             //Still load the region settings though
             scene.RegionInfo.RegionSettings = settings.RegionSettings;
             return;
         }
         settings.RegionSettings = scene.RegionInfo.RegionSettings;
         settings.EstateSettings = scene.RegionInfo.EstateSettings;
         scene.RegionInfo = settings;
     }
 }
        static void UpdateConsoleRegionEstate (string regionName, EstateSettings estateSettings)
        {
            for (int idx = 0; idx < MainConsole.Instance.ConsoleScenes.Count; idx++) {
                if (MainConsole.Instance.ConsoleScenes [idx].RegionInfo.RegionName == regionName)
                    MainConsole.Instance.ConsoleScenes [idx].RegionInfo.EstateSettings = estateSettings;
            }

        }
        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);
        }
        /// <summary>
        /// Correct the system estate ID and update any linked regions.
        /// </summary>
        /// <param name="estateConnector">Estate connector.</param>
        /// <param name="eS">E s.</param>
        /// <param name="newEstateID">New estate I.</param>
        static void UpdateSystemEstates (IEstateConnector estateConnector, EstateSettings eS, int newEstateID)
        {
            // this may be an ID correction or just an estate name change
            uint oldEstateID = eS.EstateID;

            // get existing linked regions
            var regions = estateConnector.GetRegions ((int)oldEstateID);

            // recreate the correct estate?
            if (oldEstateID != newEstateID) {
                estateConnector.DeleteEstate ((int)oldEstateID);
                newEstateID = estateConnector.CreateNewEstate (eS);
                MainConsole.Instance.Info ("System estate '" + eS.EstateName + "' is present but the ID was corrected.");
            }

            // re-link regions
            foreach (UUID regID in regions) {
                estateConnector.LinkRegion (regID, newEstateID);
            }
            if (regions.Count > 0)
                MainConsole.Instance.InfoFormat ("Relinked {0} regions", regions.Count);
        }
        /// <summary>
        /// Checks for a valid system estate. Adds or corrects if required
        /// </summary>
        /// <param name="estateID">Estate I.</param>
        /// <param name="estateName">Estate name.</param>
        /// <param name="ownerUUID">Owner UUI.</param>
        void CheckSystemEstateInfo (int estateID, string estateName, UUID ownerUUID)
        {
            // these should have already been checked but just make sure...
            if (m_estateConnector == null)
                return;

            if (m_estateConnector.RemoteCalls ())
                return;

            ISystemAccountService sysAccounts = m_registry.RequestModuleInterface<ISystemAccountService> ();
            EstateSettings ES;

            // check for existing estate name in case of estate ID change
            ES = m_estateConnector.GetEstateSettings (estateName);
            if (ES != null) {
                // ensure correct ID
                if (ES.EstateID != estateID)
                    UpdateSystemEstates (m_estateConnector, ES, estateID);
            }

            ES = m_estateConnector.GetEstateSettings (estateID);
            if ((ES != null) && (ES.EstateID != 0)) {

                // ensure correct owner
                if (ES.EstateOwner != ownerUUID) {
                    ES.EstateOwner = ownerUUID;
                    m_estateConnector.SaveEstateSettings (ES);
                    MainConsole.Instance.Info ("[EstateService]: The system Estate owner has been updated to " +
                        sysAccounts.GetSystemEstateOwnerName (estateID));
                }


                // in case of configuration changes
                if (ES.EstateName != estateName) {
                    ES.EstateName = estateName;
                    m_estateConnector.SaveEstateSettings (ES);
                    MainConsole.Instance.Info ("[EstateService]: The system Estate name has been updated to " + estateName);
                }

                return;
            }

            // Create a new estate

            ES = new EstateSettings ();
            ES.EstateName = estateName;
            ES.EstateOwner = ownerUUID;

            ES.EstateID = (uint)m_estateConnector.CreateNewEstate (ES);
            if (ES.EstateID == 0) {
                MainConsole.Instance.Warn ("There was an error in creating the system 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.",
                    ES.EstateName, sysAccounts.GetSystemEstateOwnerName (estateID));
            }
        }
        public void SaveEstateSettings(EstateSettings es)
        {
            if (m_doRemoteOnly) {
                DoRemote (es.ToOSD ());
                return;
            }

            SaveEstateSettings(es, false);
        }
        /// <summary>
        /// Checks for a valid system estate. Adds or corrects if required
        /// </summary>
        /// <param name="estateConnector">Estate connector.</param>
        private void CheckSystemEstateInfo()
        {
            // these should have already been checked but just make sure...
            if (m_estateConnector == null)
                return;

            if (m_estateConnector.RemoteCalls ())
                return;

            EstateSettings ES;
            ES = m_estateConnector.GetEstateSettings (Constants.SystemEstateID);
            if (ES != null)
            {
                // ensure correct ID
                if (ES.EstateID != Constants.SystemEstateID)
                    UpdateSystemEstates (m_estateConnector, ES);

                // in case of configuration changes
                if (ES.EstateName != SystemEstateName)
                {
                    ES.EstateName = SystemEstateName;
                    m_estateConnector.SaveEstateSettings (ES);
                    MainConsole.Instance.Info ("[EstateService]: The system Estate name has been updated to " + SystemEstateName);
                }

                return;
            }

            // Create a new estate
            ES = new EstateSettings();
            ES.EstateName = SystemEstateName;
            ES.EstateOwner = (UUID) Constants.RealEstateOwnerUUID;

            ES.EstateID = (uint) m_estateConnector.CreateNewEstate(ES);
            if (ES.EstateID == 0)
            {
                MainConsole.Instance.Warn ("There was an error in creating the system 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.",
                    SystemEstateName, SystemEstateOwnerName);
            }
        }
        public override void FinishedMigration(IDataConnector genericData)
        {
            if (!genericData.TableExists("estates")) return;
            DataReaderConnection dr = genericData.QueryData("WHERE `Key` = 'EstateID'", "estates",
                                                            "`ID`, `Key`, `Value`");

            if (dr != null)
            {
                try
                {
                    while (dr.DataReader.Read())
                    {
                        try
                        {
                            UUID ID = UUID.Parse(dr.DataReader["ID"].ToString());
                            string value = dr.DataReader["Value"].ToString();
                            QueryFilter filter = new QueryFilter();
                            filter.andFilters["`ID`"] = value;
                            filter.andFilters["`Key`"] = "EstateSettings";
                            List<string> results = genericData.Query(new string[1] {"`Value`"}, "estates", filter, null,
                                                                     null, null);
                            if ((results != null) && (results.Count >= 1))
                            {
                                EstateSettings es = new EstateSettings();
                                es.FromOSD((OSDMap) OSDParser.DeserializeLLSDXml(results[0]));
                                genericData.Insert("estateregions", new object[] {ID, value});

                                filter = new QueryFilter();
                                filter.andFilters["`EstateID`"] = value;

                                List<string> exist = genericData.Query(new string[1] {"`EstateID`"}, "estatesettings",
                                                                       filter, null, null, null);
                                if (exist == null || exist.Count == 0)
                                {
                                    genericData.Insert("estatesettings",
                                                       new object[]
                                                           {
                                                               value, es.EstateName, es.EstateOwner, es.ParentEstateID,
                                                               es.ToOSD()
                                                           });
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    dr.DataReader.Close();
                    genericData.CloseDatabase(dr);
                }
            }
        }