/// <summary>
        ///     Deserialize item
        /// </summary>
        /// <param name="serialization"></param>
        /// <returns></returns>
        /// <exception cref="System.Xml.XmlException"></exception>
        public static InventoryItemBase Deserialize(byte[] serialization)
        {
            InventoryItemBase item = new InventoryItemBase();

            StringReader reader = new StringReader(Encoding.ASCII.GetString(serialization, 0, serialization.Length));
            XmlReader xtr = XmlReader.Create(reader);
            //Uses byte[] directly... should be used once issues with it are fixed
            //MemoryStream mr = new MemoryStream (serialization);
            //StreamReader sr = new StreamReader (mr, Encoding.ASCII);
            //XmlReader xtr = XmlTextReader.Create (sr);
            xtr.ReadStartElement("InventoryItem");

            item.Name = xtr.ReadElementString("Name");
            item.ID = UUID.Parse(xtr.ReadElementString("ID"));
            item.InvType = Convert.ToInt32(xtr.ReadElementString("InvType"));
            item.CreatorId = xtr.ReadElementString("CreatorUUID");
            try
            {
                item.CreatorData = xtr.ReadElementString("CreatorData");
            }
            catch
            {
            }
            item.CreationDate = Convert.ToInt32(xtr.ReadElementString("CreationDate"));
            item.Owner = UUID.Parse(xtr.ReadElementString("Owner"));
            item.Description = xtr.ReadElementString("Description");
            item.AssetType = Convert.ToInt32(xtr.ReadElementString("AssetType"));
            item.AssetID = UUID.Parse(xtr.ReadElementString("AssetID"));
            item.SaleType = Convert.ToByte(xtr.ReadElementString("SaleType"));
            item.SalePrice = Convert.ToInt32(xtr.ReadElementString("SalePrice"));
            item.BasePermissions = Convert.ToUInt32(xtr.ReadElementString("BasePermissions"));
            item.CurrentPermissions = Convert.ToUInt32(xtr.ReadElementString("CurrentPermissions"));
            item.EveryOnePermissions = Convert.ToUInt32(xtr.ReadElementString("EveryOnePermissions"));
            item.NextPermissions = Convert.ToUInt32(xtr.ReadElementString("NextPermissions"));
            item.Flags = Convert.ToUInt32(xtr.ReadElementString("Flags"));
            item.GroupID = UUID.Parse(xtr.ReadElementString("GroupID"));
            item.GroupOwned = Convert.ToBoolean(xtr.ReadElementString("GroupOwned"));

            xtr.ReadEndElement();

            xtr.Close();

            return item;
        }
 public override void FromOSD(OSDMap map)
 {
     OSDArray items = (OSDArray) map["Items"];
     Items = items.ConvertAll<InventoryItemBase>((osd) =>
                                                     {
                                                         InventoryItemBase item = new InventoryItemBase();
                                                         item.FromOSD((OSDMap) osd);
                                                         return item;
                                                     }
         );
     OSDArray folders = (OSDArray) map["Folders"];
     Folders = folders.ConvertAll<InventoryFolderBase>((osd) =>
                                                           {
                                                               InventoryFolderBase folder =
                                                                   new InventoryFolderBase();
                                                               folder.FromOSD((OSDMap) osd);
                                                               return folder;
                                                           }
         );
     UserID = map["UserID"];
     FolderID = map["FolderID"];
 }
        /// <summary>
        ///     Update what the avatar is wearing using an item from their inventory.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        public void AvatarIsWearing(IClientAPI client, AvatarWearingArgs e)
        {
            IScenePresence sp = m_scene.GetScenePresence(client.AgentId);
            if (sp == null)
            {
                MainConsole.Instance.WarnFormat("[AvatarFactory]: AvatarIsWearing unable to find presence for {0}",
                                                client.AgentId);
                return;
            }

            MainConsole.Instance.DebugFormat("[AvatarFactory]: AvatarIsWearing called for {0}", client.AgentId);

            // operate on a copy of the appearance so we don't have to lock anything
            IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>();
            AvatarAppearance avatAppearance = new AvatarAppearance(appearance.Appearance, false);

            #region Teen Mode Stuff

            IOpenRegionSettingsModule module = m_scene.RequestModuleInterface<IOpenRegionSettingsModule>();

            bool NeedsRebake = false;
            if (module != null && module.EnableTeenMode)
            {
                foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
                {
                    if (wear.Type == 10 & wear.ItemID == UUID.Zero && module.DefaultUnderpants != UUID.Zero)
                    {
                        NeedsRebake = true;
                        wear.ItemID = module.DefaultUnderpants;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Underpants",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0,
                            CreatorId = UUID.Zero.ToString(),
                            AssetID = module.DefaultUnderpants
                        };
                        //Locked
                        client.SendInventoryItemCreateUpdate(item, 0);
                    }
                    else if (wear.Type == 10 & wear.ItemID == UUID.Zero)
                    {
                        NeedsRebake = true;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Underpants",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0
                        };
                        //Locked
                        if (m_underPantsUUID == UUID.Zero)
                        {
                            m_underPantsUUID = UUID.Random();
                            AssetBase asset = new AssetBase(m_underPantsUUID, "Default Underpants", AssetType.Clothing,
                                                            UUID.Zero) { Data = Utils.StringToBytes(m_defaultUnderPants) };
                            asset.ID = m_scene.AssetService.Store(asset);
                            m_underPantsUUID = asset.ID;
                        }
                        item.CreatorId = UUID.Zero.ToString();
                        item.AssetID = m_underPantsUUID;
                        m_scene.InventoryService.AddItemAsync(item, null);
                        client.SendInventoryItemCreateUpdate(item, 0);
                        wear.ItemID = item.ID;
                    }
                    if (wear.Type == 11 && wear.ItemID == UUID.Zero && module.DefaultUndershirt != UUID.Zero)
                    {
                        NeedsRebake = true;
                        wear.ItemID = module.DefaultUndershirt;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Undershirt",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0,
                            CreatorId = UUID.Zero.ToString(),
                            AssetID = module.DefaultUndershirt
                        };
                        //Locked
                        client.SendInventoryItemCreateUpdate(item, 0);
                    }
                    else if (wear.Type == 11 & wear.ItemID == UUID.Zero)
                    {
                        NeedsRebake = true;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Undershirt",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0
                        };
                        //Locked
                        if (m_underShirtUUID == UUID.Zero)
                        {
                            m_underShirtUUID = UUID.Random();
                            AssetBase asset = new AssetBase(m_underShirtUUID, "Default Undershirt", AssetType.Clothing,
                                                            UUID.Zero) { Data = Utils.StringToBytes(m_defaultUnderShirt) };
                            asset.ID = m_scene.AssetService.Store(asset);
                            m_underShirtUUID = asset.ID;
                        }
                        item.CreatorId = UUID.Zero.ToString();
                        item.AssetID = m_underShirtUUID;
                        m_scene.InventoryService.AddItemAsync(item, null);
                        client.SendInventoryItemCreateUpdate(item, 0);
                        wear.ItemID = item.ID;
                    }
                }
            }

            #endregion

            foreach (
                AvatarWearingArgs.Wearable wear in e.NowWearing.Where(wear => wear.Type < AvatarWearable.MAX_WEARABLES))
            {
                avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
            }

            avatAppearance.GetAssetsFrom(appearance.Appearance);

            // This could take awhile since it needs to pull inventory
            SetAppearanceAssets(sp.UUID, e.NowWearing, appearance.Appearance, ref avatAppearance);

            // could get fancier with the locks here, but in the spirit of "last write wins"
            // this should work correctly, also, we don't need to send the appearance here
            // since the "iswearing" will trigger a new set of visual param and baked texture changes
            // when those complete, the new appearance will be sent
            appearance.Appearance = avatAppearance;

            //This only occurs if something has been forced on afterwards (teen mode stuff)
            if (NeedsRebake)
            {
                //Tell the client about the new things it is wearing
                sp.ControllingClient.SendWearables(appearance.Appearance.Wearables, appearance.Appearance.Serial);
                //Then forcefully tell it to rebake
                foreach (
                    Primitive.TextureEntryFace face in
                        appearance.Appearance.Texture.FaceTextures.Select(t => (t)).Where(face => face != null))
                {
                    sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
                }
            }

            QueueAppearanceSave(sp.UUID);
            //Send the wearables HERE so that the client knows what it is wearing
            //sp.ControllingClient.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial);
            //Do not save or send the appearance! The client loops back and sends a bunch of SetAppearance
            //  (handled above) and that takes care of it
        }
        public InventoryItemBase InnerGiveInventoryItem(
            UUID recipient, UUID senderId, InventoryItemBase item, UUID recipientFolderId, bool doOwnerCheck, bool checkTransferPermission)
        {
            if (item == null)
            {
                MainConsole.Instance.Info("[InventoryService]: Could not find item to give to " + recipient);
                return null;
            }
            if (!doOwnerCheck || item.Owner == senderId)
            {
                if (checkTransferPermission)
                {
                    if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
                        return null;
                }

                // Insert a copy of the item into the recipient
                InventoryItemBase itemCopy = new InventoryItemBase
                                                 {
                                                     Owner = recipient,
                                                     CreatorId = item.CreatorId,
                                                     CreatorData = item.CreatorData,
                                                     ID = UUID.Random(),
                                                     AssetID = item.AssetID,
                                                     Description = item.Description,
                                                     Name = item.Name,
                                                     AssetType = item.AssetType,
                                                     InvType = item.InvType,
                                                     Folder = recipientFolderId
                                                 };

                if (recipient != senderId)
                {
                    // Trying to do this right this time. This is evil. If
                    // you believe in Good, go elsewhere. Vampires and other
                    // evil creatores only beyond this point. You have been
                    // warned.

                    // We're going to mask a lot of things by the next perms
                    // Tweak the next perms to be nicer to our data
                    //
                    // In this mask, all the bits we do NOT want to mess
                    // with are set. These are:
                    //
                    // Transfer
                    // Copy
                    // Modufy
                    const uint permsMask = ~((uint) PermissionMask.Copy |
                                             (uint) PermissionMask.Transfer |
                                             (uint) PermissionMask.Modify);

                    // Now, reduce the next perms to the mask bits
                    // relevant to the operation
                    uint nextPerms = permsMask | (item.NextPermissions &
                                                  ((uint) PermissionMask.Copy |
                                                   (uint) PermissionMask.Transfer |
                                                   (uint) PermissionMask.Modify));

                    // nextPerms now has all bits set, except for the actual
                    // next permission bits.

                    // This checks for no mod, no copy, no trans.
                    // This indicates an error or messed up item. Do it like
                    // SL and assume trans
                    if (nextPerms == permsMask)
                        nextPerms |= (uint) PermissionMask.Transfer;

                    // Inventory owner perms are the logical AND of the
                    // folded perms and the root prim perms, however, if
                    // the root prim is mod, the inventory perms will be
                    // mod. This happens on "take" and is of little concern
                    // here, save for preventing escalation

                    // This hack ensures that items previously permalocked
                    // get unlocked when they're passed or rezzed
                    uint basePerms = item.BasePermissions |
                                     (uint) PermissionMask.Move;
                    uint ownerPerms = item.CurrentPermissions;

                    // If this is an object, root prim perms may be more
                    // permissive than folded perms. Use folded perms as
                    // a mask
                    if (item.InvType == (int) InventoryType.Object)
                    {
                        // Create a safe mask for the current perms
                        uint foldedPerms = (item.CurrentPermissions & 7) << 13;
                        foldedPerms |= permsMask;

                        bool isRootMod = (item.CurrentPermissions &
                                          (uint) PermissionMask.Modify) != 0;

                        // Mask the owner perms to the folded perms
                        ownerPerms &= foldedPerms;
                        basePerms &= foldedPerms;

                        // If the root was mod, let the mask reflect that
                        // We also need to adjust the base here, because
                        // we should be able to edit in-inventory perms
                        // for the root prim, if it's mod.
                        if (isRootMod)
                        {
                            ownerPerms |= (uint) PermissionMask.Modify;
                            basePerms |= (uint) PermissionMask.Modify;
                        }
                    }

                    // These will be applied to the root prim at next rez.
                    // The slam bit (bit 3) and folded permission (bits 0-2)
                    // are preserved due to the above mangling
                    ownerPerms &= nextPerms;

                    // Mask the base permissions. This is a conservative
                    // approach altering only the three main perms
                    basePerms &= nextPerms;

                    // Assign to the actual item. Make sure the slam bit is
                    // set, if it wasn't set before.
                    itemCopy.BasePermissions = basePerms;
                    itemCopy.CurrentPermissions = ownerPerms | 16; // Slam

                    itemCopy.NextPermissions = item.NextPermissions;

                    // This preserves "everyone can move"
                    itemCopy.EveryOnePermissions = item.EveryOnePermissions &
                                                   nextPerms;

                    // Intentionally killing "share with group" here, as
                    // the recipient will not have the group this is
                    // set to
                    itemCopy.GroupPermissions = 0;
                }
                else
                {
                    itemCopy.CurrentPermissions = item.CurrentPermissions;
                    itemCopy.NextPermissions = item.NextPermissions;
                    itemCopy.EveryOnePermissions = item.EveryOnePermissions & item.NextPermissions;
                    itemCopy.GroupPermissions = item.GroupPermissions & item.NextPermissions;
                    itemCopy.BasePermissions = item.BasePermissions;
                }

                if (itemCopy.Folder == UUID.Zero)
                {
                    InventoryFolderBase folder = GetFolderForType(recipient,
                                                                  (InventoryType) itemCopy.InvType,
                                                                  (AssetType) itemCopy.AssetType);

                    if (folder != null)
                        itemCopy.Folder = folder.ID;
                }

                itemCopy.GroupID = UUID.Zero;
                itemCopy.GroupOwned = false;
                itemCopy.Flags = item.Flags;
                itemCopy.SalePrice = item.SalePrice;
                itemCopy.SaleType = item.SaleType;

                AddItem(itemCopy);

                if ((item.CurrentPermissions & (uint) PermissionMask.Copy) == 0)
                    DeleteItems(senderId, new List<UUID> {item.ID});

                return itemCopy;
            }
            MainConsole.Instance.WarnFormat(
                "[InventoryService]: Failed to give item {0} as item does not belong to giver", item.ID.ToString());
            return null;
        }
        /// <summary>
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetDescription"></param>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="parentFolder"></param>
        /// <param name="data"></param>
        /// <param name="inventoryType"></param>
        /// <param name="assetType"></param>
        /// <param name="everyone_mask"></param>
        /// <param name="group_mask"></param>
        /// <param name="next_owner_mask"></param>
        public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask)
        {
            sbyte assType = 0;
            sbyte inType = 0;

            switch (inventoryType)
            {
                case "sound":
                    inType = 1;
                    assType = 1;
                    break;
                case "animation":
                    inType = 19;
                    assType = 20;
                    break;
                case "snapshot":
                    inType = 15;
                    assType = 0;
                    break;
                case "wearable":
                    inType = 18;
                    switch (assetType)
                    {
                        case "bodypart":
                            assType = 13;
                            break;
                        case "clothing":
                            assType = 5;
                            break;
                    }
                    break;
                case "object":
                    {
                        inType = (sbyte) InventoryType.Object;
                        assType = (sbyte) AssetType.Object;

                        List<Vector3> positions = new List<Vector3>();
                        List<Quaternion> rotations = new List<Quaternion>();
                        OSDMap request = (OSDMap) OSDParser.DeserializeLLSDXml(data);
                        OSDArray instance_list = (OSDArray) request["instance_list"];
                        OSDArray mesh_list = (OSDArray) request["mesh_list"];
                        OSDArray texture_list = (OSDArray) request["texture_list"];
                        SceneObjectGroup grp = null;

                        List<UUID> textures = new List<UUID>();
                        foreach (
                            AssetBase textureAsset in
                                texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture,
                                                                       m_agentID) { Data = t.AsBinary() }))
                        {
                            textureAsset.ID = m_assetService.Store(textureAsset);
                            textures.Add(textureAsset.ID);
                        }

                        InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_agentID,
                                                                                             InventoryType.Mesh,
                                                                                             AssetType.Mesh);
                        for (int i = 0; i < mesh_list.Count; i++)
                        {
                            PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                            Primitive.TextureEntry textureEntry =
                                new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                            OSDMap inner_instance_list = (OSDMap) instance_list[i];

                            OSDArray face_list = (OSDArray) inner_instance_list["face_list"];
                            for (uint face = 0; face < face_list.Count; face++)
                            {
                                OSDMap faceMap = (OSDMap) face_list[(int) face];
                                Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                                if (faceMap.ContainsKey("fullbright"))
                                    f.Fullbright = faceMap["fullbright"].AsBoolean();
                                if (faceMap.ContainsKey("diffuse_color"))
                                    f.RGBA = faceMap["diffuse_color"].AsColor4();

                                int textureNum = faceMap["image"].AsInteger();
                                float imagerot = faceMap["imagerot"].AsInteger();
                                float offsets = (float) faceMap["offsets"].AsReal();
                                float offsett = (float) faceMap["offsett"].AsReal();
                                float scales = (float) faceMap["scales"].AsReal();
                                float scalet = (float) faceMap["scalet"].AsReal();

                                if (imagerot != 0)
                                    f.Rotation = imagerot;
                                if (offsets != 0)
                                    f.OffsetU = offsets;
                                if (offsett != 0)
                                    f.OffsetV = offsett;
                                if (scales != 0)
                                    f.RepeatU = scales;
                                if (scalet != 0)
                                    f.RepeatV = scalet;
                                f.TextureID = textures.Count > textureNum
                                                  ? textures[textureNum]
                                                  : Primitive.TextureEntry.WHITE_TEXTURE;
                                textureEntry.FaceTextures[face] = f;
                            }
                            pbs.TextureEntry = textureEntry.GetBytes();

                            AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_agentID)
                                                      {Data = mesh_list[i].AsBinary()};
                            meshAsset.ID = m_assetService.Store(meshAsset);

                            if (meshFolder == null)
                            {
                                m_inventoryService.CreateUserInventory(m_agentID, false);
                                meshFolder = m_inventoryService.GetFolderForType(m_agentID, InventoryType.Mesh,
                                                                                 AssetType.Mesh);
                            }

                            InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_agentID)
                                                             {
                                                                 AssetType = (sbyte) AssetType.Mesh,
                                                                 AssetID = meshAsset.ID,
                                                                 CreatorId = m_agentID.ToString(),
                                                                 Folder = meshFolder.ID,
                                                                 InvType = (int) InventoryType.Texture,
                                                                 Name = "(Mesh) - " + assetName,
                                                                 CurrentPermissions = (uint) PermissionMask.All,
                                                                 BasePermissions = (uint) PermissionMask.All,
                                                                 EveryOnePermissions = everyone_mask,
                                                                 GroupPermissions = group_mask,
                                                                 NextPermissions = next_owner_mask
                                                             };
                            //Bad... but whatever
                            m_inventoryService.AddItem(itemBase);

                            pbs.SculptEntry = true;
                            pbs.SculptTexture = meshAsset.ID;
                            pbs.SculptType = (byte) SculptType.Mesh;
                            pbs.SculptData = meshAsset.Data;

                            Vector3 position = inner_instance_list["position"].AsVector3();
                            Vector3 scale = inner_instance_list["scale"].AsVector3();
                            Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                            int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                            int material = inner_instance_list["material"].AsInteger();
                            int mesh = inner_instance_list["mesh"].AsInteger();

                            SceneObjectPart prim = new SceneObjectPart(m_agentID, pbs, position, Quaternion.Identity,
                                                                       Vector3.Zero, assetName)
                                                       {Scale = scale, AbsolutePosition = position};

                            rotations.Add(rotation);
                            positions.Add(position);
                            prim.UUID = UUID.Random();
                            prim.CreatorID = m_agentID;
                            prim.OwnerID = m_agentID;
                            prim.GroupID = UUID.Zero;
                            prim.LastOwnerID = m_agentID;
                            prim.CreationDate = Util.UnixTimeSinceEpoch();
                            prim.Name = assetName;
                            prim.Description = "";
                            prim.PhysicsType = (byte) physicsShapeType;

                            prim.BaseMask = (uint) PermissionMask.All;
                            prim.EveryoneMask = everyone_mask;
                            prim.NextOwnerMask = next_owner_mask;
                            prim.GroupMask = group_mask;
                            prim.OwnerMask = (uint) PermissionMask.All;

                            if (grp == null)
                                grp = new SceneObjectGroup(prim, null);
                            else
                                grp.AddChild(prim, i + 1);
                            grp.RootPart.IsAttachment = false;
                        }
                        if (grp.ChildrenList.Count > 1) //Fix first link #
                            grp.RootPart.LinkNum++;

                        Vector3 rootPos = positions[0];
                        grp.SetAbsolutePosition(false, rootPos);
                        for (int i = 0; i < positions.Count; i++)
                        {
                            Vector3 offset = positions[i] - rootPos;
                            grp.ChildrenList[i].SetOffsetPosition(offset);
                        }
                        //grp.Rotation = rotations[0];
                        for (int i = 0; i < rotations.Count; i++)
                        {
                            if (i != 0)
                                grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false);
                        }
                        grp.UpdateGroupRotationR(rotations[0]);
                        data = Encoding.ASCII.GetBytes(grp.ToXml2());
                    }
                    break;
            }
            AssetBase asset = new AssetBase(assetID, assetName, (AssetType)assType, m_agentID) { Data = data };
            asset.ID = m_assetService.Store(asset);
            assetID = asset.ID;

            InventoryItemBase item = new InventoryItemBase
                                         {
                                             Owner = m_agentID,
                                             CreatorId = m_agentID.ToString(),
                                             ID = inventoryItem,
                                             AssetID = asset.ID,
                                             Description = assetDescription,
                                             Name = assetName,
                                             AssetType = assType,
                                             InvType = inType,
                                             Folder = parentFolder,
                                             CurrentPermissions = (uint) PermissionMask.All,
                                             BasePermissions = (uint) PermissionMask.All,
                                             EveryOnePermissions = everyone_mask,
                                             NextPermissions = next_owner_mask,
                                             GroupPermissions = group_mask,
                                             CreationDate = Util.UnixTimeSinceEpoch()
                                         };

            m_inventoryService.AddItem(item);

            return assetID;
        }
        /// <summary>
        ///     Change a task inventory item to a user inventory item
        /// </summary>
        /// <param name="destAgent">The agent who will own the inventory item</param>
        /// <param name="part">The object that the item is in</param>
        /// <param name="itemId">The item to convert</param>
        /// <returns></returns>
        private InventoryItemBase CreateAgentInventoryItemFromTask(UUID destAgent, ISceneChildEntity part, UUID itemId)
        {
            TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(itemId);

            if (null == taskItem)
            {
                MainConsole.Instance.ErrorFormat(
                    "[PRIM INVENTORY]: Tried to retrieve item ID {0} from prim {1}, {2} for creating an avatar"
                    + " inventory item from a prim's inventory item "
                    + " but the required item does not exist in the prim's inventory",
                    itemId, part.Name, part.UUID);

                return null;
            }

            if ((destAgent != taskItem.OwnerID) && ((taskItem.CurrentPermissions & (uint) PermissionMask.Transfer) == 0))
            {
                return null;
            }

            InventoryItemBase agentItem = new InventoryItemBase
                                              {
                                                  ID = UUID.Random(),
                                                  CreatorId = taskItem.CreatorID.ToString(),
                                                  CreatorData = taskItem.CreatorData,
                                                  Owner = destAgent,
                                                  AssetID = taskItem.AssetID,
                                                  Description = taskItem.Description,
                                                  Name = taskItem.Name,
                                                  AssetType = taskItem.Type,
                                                  InvType = taskItem.InvType,
                                                  Flags = taskItem.Flags,
                                                  SalePrice = taskItem.SalePrice,
                                                  SaleType = taskItem.SaleType
                                              };

            if ((part.OwnerID != destAgent) && m_scene.Permissions.PropagatePermissions())
            {
                agentItem.BasePermissions = taskItem.BasePermissions &
                                            (taskItem.NextPermissions | (uint) PermissionMask.Move);
                if (taskItem.InvType == (int) InventoryType.Object)
                    agentItem.CurrentPermissions = agentItem.BasePermissions &
                                                   (((taskItem.CurrentPermissions & 7) << 13) |
                                                    (taskItem.CurrentPermissions & (uint) PermissionMask.Move));
                else
                    agentItem.CurrentPermissions = agentItem.BasePermissions & taskItem.CurrentPermissions;

                agentItem.CurrentPermissions |= 16; // Slam
                agentItem.NextPermissions = taskItem.NextPermissions;
                agentItem.EveryOnePermissions = taskItem.EveryonePermissions &
                                                (taskItem.NextPermissions | (uint) PermissionMask.Move);
                agentItem.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions;
            }
            else
            {
                agentItem.BasePermissions = taskItem.BasePermissions;
                agentItem.CurrentPermissions = taskItem.CurrentPermissions;
                agentItem.NextPermissions = taskItem.NextPermissions;
                agentItem.EveryOnePermissions = taskItem.EveryonePermissions;
                agentItem.GroupPermissions = taskItem.GroupPermissions;
            }

            if (!m_scene.Permissions.BypassPermissions())
            {
                if ((taskItem.CurrentPermissions & (uint) PermissionMask.Copy) == 0)
                    part.Inventory.RemoveInventoryItem(itemId);
            }

            return agentItem;
        }
 /// <summary>
 ///     Create a new Inventory Item
 /// </summary>
 /// <param name="remoteClient"></param>
 /// <param name="creatorData"></param>
 /// <param name="folderID"></param>
 /// <param name="flags"></param>
 /// <param name="callbackID"></param>
 /// <param name="asset"></param>
 /// <param name="invType"></param>
 /// <param name="everyoneMask"></param>
 /// <param name="nextOwnerMask"></param>
 /// <param name="groupMask"></param>
 /// <param name="creationDate"></param>
 /// <param name="creatorID"></param>
 /// <param name="name"></param>
 /// <param name="baseMask"></param>
 /// <param name="currentMask"></param>
 protected void CreateNewInventoryItem(
     IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, string name, uint flags,
     uint callbackID, AssetBase asset, sbyte invType,
     uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate)
 {
     InventoryItemBase item = new InventoryItemBase
                                  {
                                      Owner = remoteClient.AgentId,
                                      CreatorId = creatorID,
                                      CreatorData = creatorData,
                                      ID = UUID.Random(),
                                      AssetID = asset.ID,
                                      Description = asset.Description,
                                      Name = name,
                                      Flags = flags,
                                      AssetType = asset.Type == -1 ? -1 : asset.Type,
                                      InvType = invType,
                                      Folder = folderID,
                                      CurrentPermissions = currentMask,
                                      NextPermissions = nextOwnerMask,
                                      EveryOnePermissions = everyoneMask,
                                      GroupPermissions = groupMask,
                                      BasePermissions = baseMask,
                                      CreationDate = creationDate
                                  };
     m_scene.InventoryService.AddItemAsync(item,
                                           (itm) =>
                                               { remoteClient.SendInventoryItemCreateUpdate(itm, callbackID); });
 }
 /// <summary>
 ///     Add the given inventory item to a user's inventory.
 /// </summary>
 /// <param name="item">The item to add</param>
 public void AddInventoryItemAsync(InventoryItemBase item)
 {
     m_scene.InventoryService.AddItemAsync(item, null);
 }
        /// <summary>
        ///     Rez a script into a prim's inventory, either ex nihilo or from an existing avatar inventory
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transactionID"></param>
        /// <param name="localID"></param>
        /// <param name="itemBase"></param>
        protected void RezScript(IClientAPI remoteClient, InventoryItemBase itemBase, UUID transactionID, uint localID)
        {
            UUID itemID = itemBase.ID;
            UUID copyID = UUID.Random();

            if (itemID != UUID.Zero) // transferred from an avatar inventory to the prim's inventory
            {
                //Might be a library item, use UUID.Zero
                InventoryItemBase item = m_scene.InventoryService.GetItem(UUID.Zero, itemID);

                if (item != null)
                {
                    ISceneChildEntity part = m_scene.GetSceneObjectPart(localID);
                    if (part != null)
                    {
                        if (!m_scene.Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
                            return;

                        part.ParentEntity.AddInventoryItem(remoteClient, localID, item, copyID);
                        part.Inventory.CreateScriptInstance(copyID, 0, false, 0);

                        //                        MainConsole.Instance.InfoFormat("[PRIMINVENTORY]: " +
                        //                                         "Rezzed script {0} into prim local ID {1} for user {2}",
                        //                                         item.inventoryName, localID, remoteClient.Name);
                        part.GetProperties(remoteClient);
                    }
                    else
                    {
                        MainConsole.Instance.ErrorFormat(
                            "[PRIM INVENTORY]: " +
                            "Could not rez script {0} into prim local ID {1} for user {2}"
                            + " because the prim could not be found in the region!",
                            item.Name, localID, remoteClient.Name);
                    }
                }
                else
                {
                    MainConsole.Instance.ErrorFormat(
                        "[PRIM INVENTORY]: Could not find script inventory item {0} to rez for {1}!",
                        itemID, remoteClient.Name);
                }
            }
            else // script has been rezzed directly into a prim's inventory
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(itemBase.Folder);
                if (part == null)
                    return;

                if (!m_scene.Permissions.CanCreateObjectInventory(
                    itemBase.InvType, part.UUID, remoteClient.AgentId))
                    return;

                AssetBase asset = new AssetBase(UUID.Random(), itemBase.Name, (AssetType) itemBase.AssetType,
                                                remoteClient.AgentId)
                                      {
                                          Description = itemBase.Description,
                                          Data = Encoding.ASCII.GetBytes(DefaultLSLScript)
                                      };
                asset.ID = m_scene.AssetService.Store(asset);

                TaskInventoryItem taskItem = new TaskInventoryItem();

                taskItem.ResetIDs(itemBase.Folder);
                taskItem.ParentID = itemBase.Folder;
                taskItem.CreationDate = (uint) itemBase.CreationDate;
                taskItem.Name = itemBase.Name;
                taskItem.Description = itemBase.Description;
                taskItem.Type = itemBase.AssetType;
                taskItem.InvType = itemBase.InvType;
                taskItem.OwnerID = itemBase.Owner;
                taskItem.CreatorID = itemBase.CreatorIdAsUuid;
                taskItem.CreatorData = itemBase.CreatorData;
                taskItem.BasePermissions = itemBase.BasePermissions;
                taskItem.CurrentPermissions = itemBase.CurrentPermissions;
                taskItem.EveryonePermissions = itemBase.EveryOnePermissions;
                taskItem.GroupPermissions = itemBase.GroupPermissions;
                taskItem.NextPermissions = itemBase.NextPermissions;
                taskItem.GroupID = itemBase.GroupID;
                taskItem.GroupPermissions = 0;
                taskItem.Flags = itemBase.Flags;
                taskItem.PermsGranter = UUID.Zero;
                taskItem.PermsMask = 0;
                taskItem.AssetID = asset.ID;
                taskItem.SalePrice = itemBase.SalePrice;
                taskItem.SaleType = itemBase.SaleType;

                part.Inventory.AddInventoryItem(taskItem, false);
                part.GetProperties(remoteClient);

                part.Inventory.CreateScriptInstance(taskItem, 0, false, StateSource.NewRez);
            }
        }
        /// <summary>
        ///     Delete a scene object from a scene and place in the given avatar's inventory.
        ///     Returns the UUID of the newly created asset.
        /// </summary>
        /// <param name="action"></param>
        /// <param name="folderID"></param>
        /// <param name="objectGroups"></param>
        /// <param name="agentId"></param>
        /// <param name="itemID"></param>
        public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID,
                                              List<ISceneEntity> objectGroups, UUID agentId, out UUID itemID)
        {
            itemID = UUID.Zero;
            if (objectGroups.Count == 0)
                return UUID.Zero;

            // Get the user info of the item destination
            //
            IScenePresence SP = m_scene.GetScenePresence(agentId);
            UUID userID = UUID.Zero;

            if (action == DeRezAction.Take || action == DeRezAction.AcquireToUserInventory ||
                action == DeRezAction.SaveToExistingUserInventoryItem)
            {
                // Take or take copy require a taker
                // Saving changes requires a local user
                //
                if (SP == null || SP.ControllingClient == null)
                    return UUID.Zero;

                userID = agentId;
            }
            else
            {
                // All returns / deletes go to the object owner
                //

                userID = objectGroups[0].OwnerID;
            }

            if (userID == UUID.Zero) // Can't proceed
            {
                return UUID.Zero;
            }

            // If we're returning someone's item, it goes back to the
            // owner's Lost And Found folder.
            // Delete is treated like return in this case
            // Deleting your own items makes them go to trash
            //

            InventoryFolderBase folder = null;
            InventoryItemBase item = null;

            if (DeRezAction.SaveToExistingUserInventoryItem == action)
            {
                item = m_scene.InventoryService.GetItem(userID, objectGroups[0].RootChild.FromUserInventoryItemID);

                //item = userInfo.RootFolder.FindItem(
                //        objectGroup.RootPart.FromUserInventoryItemID);

                if (null == item)
                {
                    MainConsole.Instance.DebugFormat(
                        "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.",
                        objectGroups[0].Name, objectGroups[0].UUID);
                    return UUID.Zero;
                }
            }
            else
            {
                // Folder magic
                //
                if (action == DeRezAction.Delete)
                {
                    // Deleting someone else's item
                    //

                    if (SP == null || SP.ControllingClient == null ||
                        objectGroups[0].OwnerID != agentId)
                    {
                        folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                           AssetType.LostAndFoundFolder);
                    }
                    else
                    {
                        folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                           AssetType.TrashFolder);
                    }
                }
                else if (action == DeRezAction.Return)
                {
                    // Dump to lost + found unconditionally
                    //
                    folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                       AssetType.LostAndFoundFolder);
                }

                if (folderID == UUID.Zero && folder == null)
                {
                    if (action == DeRezAction.Delete)
                    {
                        // Deletes go to trash by default
                        //
                        folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                           AssetType.TrashFolder);
                    }
                    else
                    {
                        if (SP == null || SP.ControllingClient == null ||
                            objectGroups[0].OwnerID != agentId)
                        {
                            folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                               AssetType.LostAndFoundFolder);
                        }
                        else
                        {
                            folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Unknown,
                                                                               AssetType.TrashFolder);
                        }
                    }
                }

                // Override and put into where it came from, if it came
                // from anywhere in inventory
                //
                if (action == DeRezAction.Attachment || action == DeRezAction.Take ||
                    action == DeRezAction.AcquireToUserInventory)
                {
                    if (objectGroups[0].RootChild.FromUserInventoryItemID != UUID.Zero)
                    {
                        InventoryFolderBase f =
                            new InventoryFolderBase(objectGroups[0].RootChild.FromUserInventoryItemID, userID);
                        folder = m_scene.InventoryService.GetFolder(f);
                    }
                    else
                    {
                        folder = m_scene.InventoryService.GetFolderForType(userID, InventoryType.Object,
                                                                           AssetType.Object);
                    }
                }

                if (folder == null) // None of the above
                {
                    folder = new InventoryFolderBase(folderID);
                }

                item = new InventoryItemBase
                           {
                               CreatorId = objectGroups[0].RootChild.CreatorID.ToString(),
                               ID = UUID.Random(),
                               InvType = (int) InventoryType.Object,
                               Folder = folder.ID,
                               Owner = userID
                           };
            }

            AssetBase asset;
            UUID assetID = SaveAsAsset(objectGroups, out asset);
            item.AssetID = assetID;
            if (DeRezAction.SaveToExistingUserInventoryItem != action)
            {
                item.Description = asset.Description;
                item.Name = asset.Name;
                item.AssetType = asset.Type;
            }

            if (DeRezAction.SaveToExistingUserInventoryItem == action)
            {
                m_scene.InventoryService.UpdateItem(item);
            }
            else
            {
                if (SP != null && SP.ControllingClient != null &&
                    (SP.ControllingClient.AgentId != objectGroups[0].OwnerID) &&
                    m_scene.Permissions.PropagatePermissions())
                {
                    foreach (ISceneEntity group in objectGroups)
                    {
                        uint perms = group.GetEffectivePermissions();
                        uint nextPerms = (perms & 7) << 13;
                        if ((nextPerms & (uint) PermissionMask.Copy) == 0)
                            perms &= ~(uint) PermissionMask.Copy;
                        if ((nextPerms & (uint) PermissionMask.Transfer) == 0)
                            perms &= ~(uint) PermissionMask.Transfer;
                        if ((nextPerms & (uint) PermissionMask.Modify) == 0)
                            perms &= ~(uint) PermissionMask.Modify;

                        // Make sure all bits but the ones we want are clear
                        // on take.
                        // This will be applied to the current perms, so
                        // it will do what we want.
                        group.RootChild.NextOwnerMask &=
                            ((uint) PermissionMask.Copy |
                             (uint) PermissionMask.Transfer |
                             (uint) PermissionMask.Modify);
                        group.RootChild.NextOwnerMask |=
                            (uint) PermissionMask.Move;

                        item.BasePermissions = perms & group.RootChild.NextOwnerMask;
                        item.CurrentPermissions = item.BasePermissions;
                        item.NextPermissions = group.RootChild.NextOwnerMask;
                        item.EveryOnePermissions = group.RootChild.EveryoneMask & group.RootChild.NextOwnerMask;
                        item.GroupPermissions = group.RootChild.GroupMask & group.RootChild.NextOwnerMask;

                        // Magic number badness. Maybe this deserves an enum.
                        // bit 4 (16) is the "Slam" bit, it means treat as passed
                        // and apply next owner perms on rez
                        item.CurrentPermissions |= 16; // Slam!

                        item.SalePrice = group.RootChild.SalePrice;
                        item.SaleType = group.RootChild.ObjectSaleType;
                    }
                }
                else
                {
                    foreach (ISceneEntity group in objectGroups)
                    {
                        item.BasePermissions = group.GetEffectivePermissions();
                        item.CurrentPermissions = group.GetEffectivePermissions();
                        item.NextPermissions = group.RootChild.NextOwnerMask;
                        item.EveryOnePermissions = group.RootChild.EveryoneMask;
                        item.GroupPermissions = group.RootChild.GroupMask;

                        item.SalePrice = group.RootChild.SalePrice;
                        item.SaleType = group.RootChild.ObjectSaleType;

                        item.CurrentPermissions &=
                            ((uint) PermissionMask.Copy |
                             (uint) PermissionMask.Transfer |
                             (uint) PermissionMask.Modify |
                             (uint) PermissionMask.Move |
                             7); // Preserve folded permissions
                    }
                }

                if (objectGroups.Count != 1)
                    item.Flags |= (uint) InventoryItemFlags.ObjectHasMultipleItems;
                item.CreationDate = Util.UnixTimeSinceEpoch();

                m_LLCLientInventoryModule.AddInventoryItem(item);

                if (SP != null && SP.ControllingClient != null && item.Owner == SP.ControllingClient.AgentId)
                {
                    SP.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
                }
                else
                {
                    IScenePresence notifyUser = m_scene.GetScenePresence(item.Owner);
                    if (notifyUser != null)
                    {
                        notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
                    }
                }
            }
            itemID = item.ID;
            return assetID;
        }
        /// <summary>
        ///     Rez an object into the scene from the user's inventory
        /// </summary>
        /// FIXME: It would be really nice if inventory access modules didn't also actually do the work of rezzing
        /// things to the scene.  The caller should be doing that, I think.
        /// <param name="remoteClient"></param>
        /// <param name="itemID"></param>
        /// <param name="RayEnd"></param>
        /// <param name="RayStart"></param>
        /// <param name="RayTargetID"></param>
        /// <param name="BypassRayCast"></param>
        /// <param name="RayEndIsIntersection"></param>
        /// <param name="RezSelected"></param>
        /// <param name="RemoveItem"></param>
        /// <param name="fromTaskID"></param>
        /// <returns>The SceneObjectGroup rezzed or null if rez was unsuccessful.</returns>
        public virtual ISceneEntity RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
                                              UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
                                              bool RezSelected, bool RemoveItem, UUID fromTaskID)
        {
            // Work out position details
            byte bRayEndIsIntersection = (byte) 0;

            bRayEndIsIntersection = (byte) (RayEndIsIntersection ? 1 : 0);

            XmlDocument doc;
            //It might be a library item, send UUID.Zero
            InventoryItemBase item = m_scene.InventoryService.GetItem(UUID.Zero, itemID);
            if (item == null)
            {
                remoteClient.SendAlertMessage("Failed to find the item you requested.");
                return null;
            }
            ISceneEntity group = CreateObjectFromInventory(item, remoteClient, itemID, out doc);

            Vector3 pos = m_scene.SceneGraph.GetNewRezLocation(
                RayStart, RayEnd, RayTargetID, Quaternion.Identity,
                BypassRayCast, bRayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);

            if (doc == null)
            {
                //No asset, check task inventory
                IEntity e;
                m_scene.SceneGraph.TryGetEntity(fromTaskID, out e);
                if (e != null && e is ISceneEntity)
                {
                    ISceneEntity grp = (ISceneEntity) e;
                    TaskInventoryItem taskItem = grp.RootChild.Inventory.GetInventoryItem(itemID);
                    item = new InventoryItemBase
                               {
                                   ID = UUID.Random(),
                                   CreatorId = taskItem.CreatorID.ToString(),
                                   Owner = remoteClient.AgentId,
                                   AssetID = taskItem.AssetID,
                                   Description = taskItem.Description,
                                   Name = taskItem.Name,
                                   AssetType = taskItem.Type,
                                   InvType = taskItem.InvType,
                                   Flags = taskItem.Flags,
                                   SalePrice = taskItem.SalePrice,
                                   SaleType = taskItem.SaleType
                               };

                    if (m_scene.Permissions.PropagatePermissions())
                    {
                        item.BasePermissions = taskItem.BasePermissions &
                                               (taskItem.NextPermissions | (uint) PermissionMask.Move);
                        if (taskItem.InvType == (int) InventoryType.Object)
                            item.CurrentPermissions = item.BasePermissions &
                                                      (((taskItem.CurrentPermissions & 7) << 13) |
                                                       (taskItem.CurrentPermissions & (uint) PermissionMask.Move));
                        else
                            item.CurrentPermissions = item.BasePermissions & taskItem.CurrentPermissions;

                        item.CurrentPermissions |= 16; // Slam
                        item.NextPermissions = taskItem.NextPermissions;
                        item.EveryOnePermissions = taskItem.EveryonePermissions &
                                                   (taskItem.NextPermissions | (uint) PermissionMask.Move);
                        item.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions;
                    }
                    else
                    {
                        item.BasePermissions = taskItem.BasePermissions;
                        item.CurrentPermissions = taskItem.CurrentPermissions;
                        item.NextPermissions = taskItem.NextPermissions;
                        item.EveryOnePermissions = taskItem.EveryonePermissions;
                        item.GroupPermissions = taskItem.GroupPermissions;
                    }
                    group = CreateObjectFromInventory(item, remoteClient, itemID, out doc);
                }
            }
            if (group == null && doc != null && doc.FirstChild != null &&
                (doc.FirstChild.OuterXml.StartsWith("<groups>") ||
                 (doc.FirstChild.NextSibling != null &&
                  doc.FirstChild.NextSibling.OuterXml.StartsWith("<groups>"))))
            {
                XmlNodeList nodes;
                if (doc.FirstChild.OuterXml.StartsWith("<groups>")) nodes = doc.FirstChild.ChildNodes;
                else if (doc.FirstChild.NextSibling != null) nodes = doc.FirstChild.NextSibling.ChildNodes;
                else
                {
                    remoteClient.SendAlertMessage("Failed to find the item you requested.");
                    return null;
                }
                List<ISceneEntity> Groups = RezMultipleObjectsFromInventory(nodes, itemID, remoteClient, pos,
                                                                            RezSelected, item, RayTargetID,
                                                                            BypassRayCast, RayEndIsIntersection, RayEnd,
                                                                            RayStart, bRayEndIsIntersection);
                if (Groups.Count != 0)
                    return Groups[0];
                remoteClient.SendAlertMessage("Failed to rez the item you requested.");
                return null;
            }
            if (group == null)
            {
                remoteClient.SendAlertMessage("Failed to find the item you requested.");
                return null;
            }

            string reason;
            if (!m_scene.Permissions.CanRezObject(
                group.ChildrenEntities().Count, remoteClient.AgentId, pos, out reason))
            {
                // The client operates in no fail mode. It will
                // have already removed the item from the folder
                // if it's no copy.
                // Put it back if it's not an attachment
                //
                if ((item.CurrentPermissions & (uint) PermissionMask.Copy) == 0)
                    remoteClient.SendBulkUpdateInventory(item);
                remoteClient.SendAlertMessage("You do not have permission to rez objects here.");
                return null;
            }

            if (RezSelected)
                group.RootChild.AddFlag(PrimFlags.CreateSelected);
            // If we're rezzing an attachment then don't ask AddNewSceneObject() to update the client since
            // we'll be doing that later on.  Scheduling more than one full update during the attachment
            // process causes some clients to fail to display the attachment properly.
            m_scene.SceneGraph.AddPrimToScene(group);

            //  MainConsole.Instance.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z);
            //  Set it's position in world.
            const float offsetHeight = 0;
            //The OOBsize is only half the size, x2
            Vector3 newSize = (group.OOBsize*2)*Quaternion.Inverse(group.GroupRotation);
            pos = m_scene.SceneGraph.GetNewRezLocation(
                RayStart, RayEnd, RayTargetID, Quaternion.Identity,
                BypassRayCast, bRayEndIsIntersection, true, newSize, false);
            pos.Z += offsetHeight;
            group.AbsolutePosition = pos;
            //   MainConsole.Instance.InfoFormat("rezx point for inventory rezz is {0} {1} {2}  and offsetheight was {3}", pos.X, pos.Y, pos.Z, offsetHeight);

            ISceneChildEntity rootPart = group.GetChildPart(group.UUID);
            if (rootPart == null)
            {
                MainConsole.Instance.Error("[AGENT INVENTORY]: Error rezzing ItemID: " + itemID +
                                           " object has no rootpart.");
                return null;
            }

            // Since renaming the item in the inventory does not affect the name stored
            // in the serialization, transfer the correct name from the inventory to the
            // object itself before we rez.
            rootPart.Name = item.Name;
            rootPart.Description = item.Description;

            List<ISceneChildEntity> partList = group.ChildrenEntities();

            group.SetGroup(remoteClient.ActiveGroupId, remoteClient.AgentId, false);
            item.Owner = remoteClient.AgentId;
            if (rootPart.OwnerID != item.Owner)
            {
                //Need to kill the for sale here
                rootPart.ObjectSaleType = 0;
                rootPart.SalePrice = 10;

                if (m_scene.Permissions.PropagatePermissions())
                {
                    if ((item.CurrentPermissions & 8) != 0)
                    {
                        foreach (ISceneChildEntity part in partList)
                        {
                            part.EveryoneMask = item.EveryOnePermissions;
                            part.NextOwnerMask = item.NextPermissions;
                            part.GroupMask = 0; // DO NOT propagate here
                        }
                    }

                    group.ApplyNextOwnerPermissions();
                }
            }

            foreach (ISceneChildEntity part in partList)
            {
                if (part.OwnerID != item.Owner)
                {
                    part.LastOwnerID = part.OwnerID;
                    part.OwnerID = item.Owner;
                    part.Inventory.ChangeInventoryOwner(item.Owner);
                }
                else if ((item.CurrentPermissions & 8) != 0) // Slam!
                {
                    part.EveryoneMask = item.EveryOnePermissions;
                    part.NextOwnerMask = item.NextPermissions;

                    part.GroupMask = 0; // DO NOT propagate here
                }
            }

            rootPart.TrimPermissions();

            if (group.RootChild.Shape.PCode == (byte) PCode.Prim)
            {
                group.ClearPartAttachmentData();
            }

            // Fire on_rez
            group.CreateScriptInstances(0, true, StateSource.NewRez, UUID.Zero, false);

            group.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
            if (!m_scene.Permissions.BypassPermissions())
            {
                if ((item.CurrentPermissions & (uint) PermissionMask.Copy) == 0)
                {
                    List<UUID> uuids = new List<UUID> {item.ID};
                    m_scene.InventoryService.DeleteItems(item.Owner, uuids);
                }
            }
            return group;
        }
        public virtual bool AddItem(InventoryItemBase item)
        {
            object remoteValue = DoRemoteByURL("InventoryServerURI", item);
            if (remoteValue != null || m_doRemoteOnly)
                return remoteValue == null ? false : (bool) remoteValue;

            return AddItem(item, true);
        }
 public virtual ISceneEntity CreateObjectFromInventory(IClientAPI remoteClient, UUID itemID, UUID assetID, InventoryItemBase item)
 {
     XmlDocument doc;
     return CreateObjectFromInventory(remoteClient, itemID, assetID, out doc, item);
 }
 public AddInventoryItemStore(InventoryItemBase item, Action<InventoryItemBase> success)
 {
     Item = item;
     Complete = success;
 }
        public virtual bool UpdateItem(InventoryItemBase item)
        {
            object remoteValue = DoRemoteByURL("InventoryServerURI", item);
            if (remoteValue != null || m_doRemoteOnly)
                return remoteValue == null ? false : (bool) remoteValue;

            if (!m_AllowDelete) //Initial item MUST be created as a link or link folder
                if (item.AssetType == (sbyte) AssetType.Link || item.AssetType == (sbyte) AssetType.LinkFolder)
                    return false;
            m_Database.IncrementFolder(item.Folder);
            return m_Database.StoreItem(item);
        }
        public virtual bool CreateUserInventory(UUID principalID, bool createDefaultItems,
                                                out List<InventoryItemBase> defaultItems)
        {
            // This is braindeaad. We can't ever communicate that we fixed
            // an existing inventory. Well, just return root folder status,
            // but check sanity anyway.
            //
            bool result = false;

            InventoryFolderBase rootFolder = GetRootFolder(principalID);

            if (rootFolder == null)
            {
                rootFolder = CreateFolder(principalID, UUID.Zero, (int) AssetType.RootFolder, "My Inventory");
                result = true;
            }

            InventoryFolderBase[] sysFolders = GetSystemFolders(principalID);

            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Animation) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Animation, "Animations");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Bodypart) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Bodypart, "Body Parts");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.CallingCard) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.CallingCard, "Calling Cards");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Clothing) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Clothing, "Clothing");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Gesture) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Gesture, "Gestures");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Landmark) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Landmark, "Landmarks");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.LostAndFoundFolder) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.LostAndFoundFolder, "Lost And Found");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Notecard) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Notecard, "Notecards");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Object) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Object, "Objects");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.SnapshotFolder) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.SnapshotFolder, "Photo Album");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.LSLText) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.LSLText, "Scripts");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Sound) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Sound, "Sounds");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Texture) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Texture, "Textures");
            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.TrashFolder) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.TrashFolder, "Trash");

            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Mesh) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Mesh, "Mesh");

            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Inbox) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Inbox, "Received Items");

            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.Outbox) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.Outbox, "Merchant Outbox");

            if (!Array.Exists(sysFolders, delegate(InventoryFolderBase f)
                                              {
                                                  if (f.Type == (short) AssetType.CurrentOutfitFolder) return true;
                                                  return false;
                                              }))
                CreateFolder(principalID, rootFolder.ID, (int) AssetType.CurrentOutfitFolder, "Current Outfit");

            if (createDefaultItems && m_LibraryService != null)
            {
                defaultItems = new List<InventoryItemBase>();
                InventoryFolderBase bodypartFolder = GetFolderForType(principalID, InventoryType.Unknown,
                                                                      AssetType.Bodypart);
                InventoryFolderBase clothingFolder = GetFolderForType(principalID, InventoryType.Unknown,
                                                                      AssetType.Clothing);

                // Default items
                InventoryItemBase defaultShape = new InventoryItemBase
                                                     {
                                                         Name = "Default shape",
                                                         Description = "Default shape description",
                                                         AssetType = (int) AssetType.Bodypart,
                                                         InvType = (int) InventoryType.Wearable,
                                                         Flags = (uint) WearableType.Shape,
                                                         ID = UUID.Random()
                                                     };
                //Give a new copy to every person
                AssetBase asset = m_AssetService.Get(AvatarWearable.DEFAULT_BODY_ASSET.ToString());
                if (asset != null)
                {
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultShape.AssetID = asset.ID;
                    defaultShape.Folder = bodypartFolder.ID;
                    defaultShape.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultShape.Owner = principalID;
                    defaultShape.BasePermissions = (uint) PermissionMask.All;
                    defaultShape.CurrentPermissions = (uint) PermissionMask.All;
                    defaultShape.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultShape.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultShape, false);
                    defaultItems.Add(defaultShape);
                }

                InventoryItemBase defaultSkin = new InventoryItemBase
                                                    {
                                                        Name = "Default skin",
                                                        Description = "Default skin description",
                                                        AssetType = (int) AssetType.Bodypart,
                                                        InvType = (int) InventoryType.Wearable,
                                                        Flags = (uint) WearableType.Skin,
                                                        ID = UUID.Random()
                                                    };
                //Give a new copy to every person
                asset = m_AssetService.Get(AvatarWearable.DEFAULT_SKIN_ASSET.ToString());
                if (asset != null)
                {
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultSkin.AssetID = asset.ID;
                    defaultSkin.Folder = bodypartFolder.ID;
                    defaultSkin.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultSkin.Owner = principalID;
                    defaultSkin.BasePermissions = (uint) PermissionMask.All;
                    defaultSkin.CurrentPermissions = (uint) PermissionMask.All;
                    defaultSkin.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultSkin.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultSkin, false);
                    defaultItems.Add(defaultSkin);
                }

                InventoryItemBase defaultHair = new InventoryItemBase
                                                    {
                                                        Name = "Default hair",
                                                        Description = "Default hair description",
                                                        AssetType = (int) AssetType.Bodypart,
                                                        InvType = (int) InventoryType.Wearable,
                                                        Flags = (uint) WearableType.Hair,
                                                        ID = UUID.Random()
                                                    };
                //Give a new copy to every person
                asset = m_AssetService.Get(AvatarWearable.DEFAULT_HAIR_ASSET.ToString());
                if (asset != null)
                {
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultHair.AssetID = asset.ID;
                    defaultHair.Folder = bodypartFolder.ID;
                    defaultHair.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultHair.Owner = principalID;
                    defaultHair.BasePermissions = (uint) PermissionMask.All;
                    defaultHair.CurrentPermissions = (uint) PermissionMask.All;
                    defaultHair.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultHair.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultHair, false);
                    defaultItems.Add(defaultHair);
                }

                InventoryItemBase defaultEyes = new InventoryItemBase
                                                    {
                                                        Name = "Default eyes",
                                                        Description = "Default eyes description",
                                                        AssetType = (int) AssetType.Bodypart,
                                                        InvType = (int) InventoryType.Wearable,
                                                        Flags = (uint) WearableType.Eyes,
                                                        ID = UUID.Random()
                                                    };
                //Give a new copy to every person
                asset = m_AssetService.Get(AvatarWearable.DEFAULT_EYES_ASSET.ToString());
                if (asset != null)
                {
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultEyes.AssetID = asset.ID;
                    defaultEyes.Folder = bodypartFolder.ID;
                    defaultEyes.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultEyes.Owner = principalID;
                    defaultEyes.BasePermissions = (uint) PermissionMask.All;
                    defaultEyes.CurrentPermissions = (uint) PermissionMask.All;
                    defaultEyes.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultEyes.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultEyes, false);
                    defaultItems.Add(defaultEyes);
                }

                InventoryItemBase defaultShirt = new InventoryItemBase
                                                     {
                                                         Name = "Default shirt",
                                                         Description = "Default shirt description",
                                                         AssetType = (int) AssetType.Clothing,
                                                         InvType = (int) InventoryType.Wearable,
                                                         Flags = (uint) WearableType.Shirt,
                                                         ID = UUID.Random()
                                                     };
                //Give a new copy to every person
                asset = m_AssetService.Get(AvatarWearable.DEFAULT_SHIRT_ASSET.ToString());
                if (asset != null)
                {
                    OpenMetaverse.Assets.AssetClothing clothing = new OpenMetaverse.Assets.AssetClothing()
                                                                      {
                                                                          Creator = m_LibraryService.LibraryOwner,
                                                                          Name = "Default shirt",
                                                                          Owner = principalID,
                                                                          Permissions =
                                                                              new Permissions(
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All),
                                                                          WearableType = WearableType.Shirt,
                                                                          Textures =
                                                                              new Dictionary<AvatarTextureIndex, UUID>()
                                                                                  {
                                                                                      {
                                                                                          AvatarTextureIndex
                                                                                          .UpperShirt
                                                                                          ,
                                                                                          UUID
                                                                                          .Parse
                                                                                          ("5748decc-f629-461c-9a36-a35a221fe21f")
                                                                                      }
                                                                                  }
                                                                      };
                    clothing.Encode();
                    asset.Data = clothing.AssetData;
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultShirt.AssetID = asset.ID;
                    defaultShirt.Folder = clothingFolder.ID;
                    defaultShirt.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultShirt.Owner = principalID;
                    defaultShirt.BasePermissions = (uint) PermissionMask.All;
                    defaultShirt.CurrentPermissions = (uint) PermissionMask.All;
                    defaultShirt.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultShirt.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultShirt, false);
                    defaultItems.Add(defaultShirt);
                }

                InventoryItemBase defaultPants = new InventoryItemBase
                                                     {
                                                         Name = "Default pants",
                                                         Description = "Default pants description",
                                                         AssetType = (int) AssetType.Clothing,
                                                         InvType = (int) InventoryType.Wearable,
                                                         Flags = (uint) WearableType.Pants,
                                                         ID = UUID.Random()
                                                     };
                //Give a new copy to every person
                asset = m_AssetService.Get(AvatarWearable.DEFAULT_PANTS_ASSET.ToString());
                if (asset != null)
                {
                    OpenMetaverse.Assets.AssetClothing clothing = new OpenMetaverse.Assets.AssetClothing()
                                                                      {
                                                                          Creator = m_LibraryService.LibraryOwner,
                                                                          Name = "Default pants",
                                                                          Owner = principalID,
                                                                          Permissions =
                                                                              new Permissions(
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All,
                                                                              (uint) PermissionMask.All),
                                                                          WearableType = WearableType.Pants,
                                                                          Textures =
                                                                              new Dictionary<AvatarTextureIndex, UUID>()
                                                                                  {
                                                                                      {
                                                                                          AvatarTextureIndex
                                                                                          .LowerPants
                                                                                          ,
                                                                                          UUID
                                                                                          .Parse
                                                                                          ("5748decc-f629-461c-9a36-a35a221fe21f")
                                                                                      }
                                                                                  }
                                                                      };
                    clothing.Encode();
                    asset.Data = clothing.AssetData;
                    asset.ID = UUID.Random();
                    asset.ID = m_AssetService.Store(asset);
                    defaultPants.AssetID = asset.ID;
                    defaultPants.Folder = clothingFolder.ID;
                    defaultPants.CreatorId = m_LibraryService.LibraryOwner.ToString();
                    defaultPants.Owner = principalID;
                    defaultPants.BasePermissions = (uint) PermissionMask.All;
                    defaultPants.CurrentPermissions = (uint) PermissionMask.All;
                    defaultPants.EveryOnePermissions = (uint) PermissionMask.None;
                    defaultPants.NextPermissions = (uint) PermissionMask.All;
                    AddItem(defaultPants, false);
                    defaultItems.Add(defaultPants);
                }
            }
            else
                defaultItems = new List<InventoryItemBase>();

            return result;
        }
        /// <summary>
        ///     Update an inventory item with data that has been received through a transaction.
        ///     This is called when clothing or body parts are updated (for instance, with new textures or
        ///     colours).  It may also be called in other situations.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transactionID"></param>
        /// <param name="item"></param>
        public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, UUID transactionID,
                                                    InventoryItemBase item)
        {
            //            MainConsole.Instance.DebugFormat(
            //                "[TRANSACTIONS MANAGER] Called HandleItemUpdateFromTransaction with item {0}",
            //                item.Name);

            AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);

            IMonitorModule monitorModule = m_scene.RequestModuleInterface<IMonitorModule>();
            if (monitorModule != null)
            {
                INetworkMonitor networkMonitor = monitorModule.GetMonitor<INetworkMonitor>(m_scene);
                networkMonitor.AddPendingUploads(1);
            }

            transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item);
        }
        protected virtual ISceneEntity CreateObjectFromInventory(InventoryItemBase item, IClientAPI remoteClient,
                                                                 UUID itemID, out XmlDocument doc)
        {
            UUID itemId = UUID.Zero;

            // If we have permission to copy then link the rezzed object back to the user inventory
            // item that it came from.  This allows us to enable 'save object to inventory'
            if (!m_scene.Permissions.BypassPermissions())
            {
                if ((item.CurrentPermissions & (uint) PermissionMask.Copy) == (uint) PermissionMask.Copy)
                {
                    itemId = item.ID;
                }
            }
            else
            {
                // Brave new fullperm world
                //
                itemId = item.ID;
            }
            return CreateObjectFromInventory(remoteClient, itemId, item.AssetID, out doc, item);
        }
 /// <summary>
 ///     Add the given inventory item to a user's inventory.
 /// </summary>
 /// <param name="item">The item to add</param>
 public void AddInventoryItem(InventoryItemBase item)
 {
     m_scene.InventoryService.AddItem(item);
 }
        protected virtual ISceneEntity CreateObjectFromInventory(IClientAPI remoteClient, UUID itemID, UUID assetID,
                                                                 out XmlDocument doc, InventoryItemBase item)
        {
            byte[] rezAsset = m_scene.AssetService.GetData(assetID.ToString());

            if (rezAsset != null)
            {
                string xmlData = Utils.BytesToString(rezAsset);
                doc = new XmlDocument();
                try
                {
                    doc.LoadXml(xmlData);
                }
                catch
                {
                    return null;
                }

                if (doc.FirstChild.OuterXml.StartsWith("<groups>") ||
                    (doc.FirstChild.NextSibling != null &&
                     doc.FirstChild.NextSibling.OuterXml.StartsWith("<groups>")))
                {
                    //We don't do multiple objects here
                    return null;
                }
                string xml = "";
                if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                {
                    if (doc.FirstChild.NextSibling != null) xml = doc.FirstChild.NextSibling.OuterXml;
                }
                else
                    xml = doc.FirstChild.OuterXml;
                ISceneEntity group
                    = SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat(itemID, xml, m_scene);
                if (group == null)
                    return null;

                group.IsDeleted = false;
                foreach (ISceneChildEntity part in group.ChildrenEntities())
                {
                    //AR: Could be changed by user in inventory, so restore from inventory not asset on rez
                    if (item != null)
                    {
                        part.EveryoneMask = item.EveryOnePermissions;
                        part.GroupMask = item.GroupPermissions;
                        part.NextOwnerMask = item.NextPermissions;
                    }

                    part.IsLoading = false;
                }
                return group;
            }
            doc = null;
            return null;
        }
 /// <summary>
 ///     Add an inventory item to an avatar's inventory.
 /// </summary>
 /// <param name="remoteClient">The remote client controlling the avatar</param>
 /// <param name="item">
 ///     The item.  This structure contains all the item metadata, including the folder
 ///     in which the item is to be placed.
 /// </param>
 public void AddInventoryItemAsync(IClientAPI remoteClient, InventoryItemBase item)
 {
     m_scene.InventoryService.AddItemAsync(item,
                                           (itm) => remoteClient.SendInventoryItemCreateUpdate(itm, 0));
 }
        private List<ISceneEntity> RezMultipleObjectsFromInventory(XmlNodeList nodes, UUID itemId,
                                                                   IClientAPI remoteClient, Vector3 pos,
                                                                   bool RezSelected,
                                                                   InventoryItemBase item, UUID RayTargetID,
                                                                   byte BypassRayCast, bool RayEndIsIntersection,
                                                                   Vector3 RayEnd, Vector3 RayStart,
                                                                   byte bRayEndIsIntersection)
        {
            Vector3 OldMiddlePos = Vector3.Zero;
            List<ISceneEntity> NewGroup = new List<ISceneEntity>();

            foreach (XmlNode aPrimNode in nodes)
            {
                if (aPrimNode.OuterXml.StartsWith("<middle>"))
                {
                    string Position = aPrimNode.OuterXml.Remove(0, 13);
                    Position = Position.Remove(Position.Length - 16, 16);
                    string[] XYZ = Position.Split(' ');
                    OldMiddlePos = new Vector3(float.Parse(XYZ[0]), float.Parse(XYZ[1]), float.Parse(XYZ[2]));
                    continue;
                }
                ISceneEntity group
                    = SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml, m_scene);
                if (group == null)
                    return null;

                group.IsDeleted = false;
                foreach (ISceneChildEntity part in group.ChildrenEntities())
                {
                    part.IsLoading = false;
                }
                NewGroup.Add(group);

                string reason;
                if (!m_scene.Permissions.CanRezObject(
                    group.ChildrenEntities().Count, remoteClient.AgentId, pos, out reason))
                {
                    // The client operates in no fail mode. It will
                    // have already removed the item from the folder
                    // if it's no copy.
                    // Put it back if it's not an attachment
                    //
                    if (((item.CurrentPermissions & (uint) PermissionMask.Copy) == 0))
                        remoteClient.SendBulkUpdateInventory(item);
                    return null;
                }

                if (RezSelected)
                    group.RootChild.AddFlag(PrimFlags.CreateSelected);
                // If we're rezzing an attachment then don't ask AddNewSceneObject() to update the client since
                // we'll be doing that later on.  Scheduling more than one full update during the attachment
                // process causes some clients to fail to display the attachment properly.
                m_scene.SceneGraph.AddPrimToScene(group);

                //  MainConsole.Instance.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z);
                // if attachment we set it's asset id so object updates can reflect that
                // if not, we set it's position in world.
                float offsetHeight = 0;
                pos = m_scene.SceneGraph.GetNewRezLocation(
                    RayStart, RayEnd, RayTargetID, Quaternion.Identity,
                    BypassRayCast, bRayEndIsIntersection, true, group.GetAxisAlignedBoundingBox(out offsetHeight), false);
                pos.Z += offsetHeight;
                //group.AbsolutePosition = pos;
                //   MainConsole.Instance.InfoFormat("rezx point for inventory rezz is {0} {1} {2}  and offsetheight was {3}", pos.X, pos.Y, pos.Z, offsetHeight);

                ISceneChildEntity rootPart = group.GetChildPart(group.UUID);

                // Since renaming the item in the inventory does not affect the name stored
                // in the serialization, transfer the correct name from the inventory to the
                // object itself before we rez.
                if (NewGroup.Count == 1)
                {
                    //Only do this to the first object, as it is the only one that will need to be renamed
                    rootPart.Name = item.Name;
                    rootPart.Description = item.Description;
                }

                List<ISceneChildEntity> partList = group.ChildrenEntities();

                group.SetGroup(remoteClient.ActiveGroupId, remoteClient.AgentId, false);
                item.Owner = remoteClient.AgentId;
                if (rootPart.OwnerID != item.Owner)
                {
                    //Need to kill the for sale here
                    rootPart.ObjectSaleType = 0;
                    rootPart.SalePrice = 10;

                    if (m_scene.Permissions.PropagatePermissions())
                    {
                        if ((item.CurrentPermissions & 8) != 0)
                        {
                            foreach (ISceneChildEntity part in partList)
                            {
                                part.EveryoneMask = item.EveryOnePermissions;
                                part.NextOwnerMask = item.NextPermissions;
                                part.GroupMask = 0; // DO NOT propagate here
                            }
                        }

                        group.ApplyNextOwnerPermissions();
                    }
                }

                foreach (ISceneChildEntity part in partList)
                {
                    if (part.OwnerID != item.Owner)
                    {
                        part.LastOwnerID = part.OwnerID;
                        part.OwnerID = item.Owner;
                        part.Inventory.ChangeInventoryOwner(item.Owner);
                    }
                    else if ((item.CurrentPermissions & 8) != 0) // Slam!
                    {
                        part.EveryoneMask = item.EveryOnePermissions;
                        part.NextOwnerMask = item.NextPermissions;

                        part.GroupMask = 0; // DO NOT propagate here
                    }
                }

                rootPart.TrimPermissions();

                if (group.RootChild.Shape.PCode == (byte) PCode.Prim)
                    group.ClearPartAttachmentData();

                // Fire on_rez
                group.CreateScriptInstances(0, true, StateSource.NewRez, UUID.Zero, false);

                if (!m_scene.Permissions.BypassPermissions())
                {
                    if ((item.CurrentPermissions & (uint) PermissionMask.Copy) == 0)
                    {
                        // If this is done on attachments, no
                        // copy ones will be lost, so avoid it
                        //
                        List<UUID> uuids = new List<UUID> {item.ID};
                        m_scene.InventoryService.DeleteItems(item.Owner, uuids);
                    }
                }
            }
            foreach (ISceneEntity group in NewGroup)
            {
                if (OldMiddlePos != Vector3.Zero)
                {
                    Vector3 NewPosOffset = Vector3.Zero;
                    NewPosOffset.X = group.AbsolutePosition.X - OldMiddlePos.X;
                    NewPosOffset.Y = group.AbsolutePosition.Y - OldMiddlePos.Y;
                    NewPosOffset.Z = group.AbsolutePosition.Z - OldMiddlePos.Z;
                    group.AbsolutePosition = pos + NewPosOffset;
                }
                group.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
            }
            return NewGroup;
        }
        /// <summary>
        ///     Update an item which is either already in the client's inventory or is within
        ///     a transaction
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transactionID">
        ///     The transaction ID.  If this is UUID.Zero we will
        ///     assume that we are not in a transaction
        /// </param>
        /// <param name="itemID">The ID of the updated item</param>
        /// <param name="itemUpd"></param>
        protected void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID,
                                                UUID itemID, InventoryItemBase itemUpd)
        {
            // This one will let people set next perms on items in agent
            // inventory. Rut-Roh. Whatever. Make this secure. Yeah.
            //
            // Passing something to another avatar or a an object will already
            InventoryItemBase item = m_scene.InventoryService.GetItem(remoteClient.AgentId, itemID);

            if (item != null)
            {
                if (UUID.Zero == transactionID)
                {
                    uint oldnextperms = item.NextPermissions;
                    bool hasPermissionsChanged = item.NextPermissions !=
                                                 (itemUpd.NextPermissions & item.BasePermissions);
                    item.Name = itemUpd.Name;
                    item.Description = itemUpd.Description;
                    item.NextPermissions = itemUpd.NextPermissions & item.BasePermissions;
                    item.EveryOnePermissions = itemUpd.EveryOnePermissions & item.BasePermissions;
                    item.GroupPermissions = itemUpd.GroupPermissions & item.BasePermissions;
                    item.GroupID = itemUpd.GroupID;
                    item.GroupOwned = itemUpd.GroupOwned;
                    item.CreationDate = itemUpd.CreationDate;
                    // The client sends zero if its newly created?

                    item.CreationDate = itemUpd.CreationDate == 0 ? Util.UnixTimeSinceEpoch() : itemUpd.CreationDate;

                    // TODO: Check if folder changed and move item
                    //item.NextPermissions = itemUpd.Folder;
                    item.InvType = itemUpd.InvType;
                    item.SalePrice = itemUpd.SalePrice;
                    item.SaleType = itemUpd.SaleType;
                    item.Flags = itemUpd.Flags;

                    if ((hasPermissionsChanged) && (item.AssetType == (int) InventoryType.Object))
                    {
                        AssetBase asset = m_scene.AssetService.Get(item.AssetID.ToString());
                        if (asset != null)
                        {
                            ISceneEntity group =
                                SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat(
                                    Utils.BytesToString(asset.Data), m_scene);

                            bool didchange = false;
                            //copy
                            if ((((PermissionMask) oldnextperms & PermissionMask.Copy) == PermissionMask.Copy) &&
                                (((PermissionMask) item.NextPermissions & PermissionMask.Copy) != PermissionMask.Copy))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Copy, 0);
                            }
                            else if ((((PermissionMask) oldnextperms & PermissionMask.Copy) != PermissionMask.Copy) &&
                                     (((PermissionMask) item.NextPermissions & PermissionMask.Copy) ==
                                      PermissionMask.Copy))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Copy, 1);
                            }

                            //mod
                            if ((((PermissionMask) oldnextperms & PermissionMask.Modify) == PermissionMask.Modify) &&
                                (((PermissionMask) item.NextPermissions & PermissionMask.Modify) !=
                                 PermissionMask.Modify))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Modify, 0);
                            }
                            else if ((((PermissionMask) oldnextperms & PermissionMask.Modify) != PermissionMask.Modify) &&
                                     (((PermissionMask) item.NextPermissions & PermissionMask.Modify) ==
                                      PermissionMask.Modify))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Modify, 1);
                            }

                            //trans
                            if ((((PermissionMask) oldnextperms & PermissionMask.Transfer) == PermissionMask.Transfer) &&
                                (((PermissionMask) item.NextPermissions & PermissionMask.Transfer) !=
                                 PermissionMask.Transfer))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Transfer, 0);
                            }
                            else if ((((PermissionMask) oldnextperms & PermissionMask.Transfer) !=
                                      PermissionMask.Transfer) &&
                                     (((PermissionMask) item.NextPermissions & PermissionMask.Transfer) ==
                                      PermissionMask.Transfer))
                            {
                                didchange = true;
                                group.UpdatePermissions(remoteClient.AgentId, 16, 1, (uint) PermissionMask.Transfer,
                                                        1);
                            }

                            if (didchange)
                            {
                                asset.Data = Encoding.ASCII.GetBytes(group.ToXml2());
                                asset.ID = m_scene.AssetService.Store(asset);
                                item.AssetID = asset.ID;
                            }
                        }
                    }
                    m_scene.InventoryService.UpdateItem(item);
                }
                else
                {
                    IAgentAssetTransactions agentTransactions =
                        m_scene.RequestModuleInterface<IAgentAssetTransactions>();
                    if (agentTransactions != null)
                    {
                        agentTransactions.HandleItemUpdateFromTransaction(
                            remoteClient, transactionID, item);
                    }
                }
            }
            else
            {
                MainConsole.Instance.Error(
                    "[AGENTINVENTORY]: Item ID " + itemID + " not found for an inventory item update.");
            }
        }
 public virtual bool StoreItem(InventoryItemBase item)
 {
     QueryFilter filter = new QueryFilter();
     filter.andFilters["inventoryID"] = item.ID;
     GD.Delete(m_itemsrealm, filter);
     Dictionary<string, object> row = new Dictionary<string, object>(20);
     row["assetID"] = item.AssetID;
     row["assetType"] = item.AssetType;
     row["inventoryName"] = item.Name;
     row["inventoryDescription"] = item.Description;
     row["inventoryNextPermissions"] = item.NextPermissions;
     row["inventoryCurrentPermissions"] = item.CurrentPermissions;
     row["invType"] = item.InvType;
     row["creatorID"] = item.CreatorIdentification;
     row["inventoryBasePermissions"] = item.BasePermissions;
     row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
     row["salePrice"] = item.SalePrice;
     row["saleType"] = item.SaleType;
     row["creationDate"] = item.CreationDate;
     row["groupID"] = item.GroupID;
     row["groupOwned"] = item.GroupOwned ? "1" : "0";
     row["flags"] = item.Flags;
     row["inventoryID"] = item.ID;
     row["avatarID"] = item.Owner;
     row["parentFolderID"] = item.Folder;
     row["inventoryGroupPermissions"] = item.GroupPermissions;
     return GD.Insert(m_itemsrealm, row);
 }
        /// <summary>
        /// Handle a fetch inventory request from the client
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="itemID"></param>
        /// <param name="ownerID"></param>
        protected void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID)
        {
            //MainConsole.Instance.Warn("[Scene.PacketHandler]: Depriated UDP Inventory request!");
            InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
            item = m_scene.InventoryService.GetItem(item);

            if (item != null)
            {
                remoteClient.SendInventoryItemDetails(ownerID, item);
            }
            // else shouldn't we send an alert message?
        }
        public virtual bool AddItem(InventoryItemBase item, bool doParentFolderCheck)
        {
            if (doParentFolderCheck)
            {
                InventoryFolderBase folder = GetFolder(new InventoryFolderBase(item.Folder));

                if (folder == null || folder.Owner != item.Owner)
                    return false;
            }
            m_Database.IncrementFolder(item.Folder);
            return m_Database.StoreItem(item);
        }
        /// <summary>
        ///     Add an inventory item to a prim in this group.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="localID"></param>
        /// <param name="item"></param>
        /// <param name="copyItemID">The item UUID that should be used by the new item.</param>
        /// <returns></returns>
        public bool AddInventoryItem(IClientAPI remoteClient, uint localID,
                                     InventoryItemBase item, UUID copyItemID)
        {
            UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;

            SceneObjectPart part = (SceneObjectPart) GetChildPart(localID);
            if (part != null)
            {
                TaskInventoryItem taskItem = new TaskInventoryItem
                                                 {
                                                     ItemID = newItemId,
                                                     AssetID = item.AssetID,
                                                     Name = item.Name,
                                                     Description = item.Description,
                                                     OwnerID = part.OwnerID,
                                                     CreatorID = item.CreatorIdAsUuid,
                                                     Type = item.AssetType,
                                                     InvType = item.InvType
                                                 };

                // Transfer ownership

                if (remoteClient != null &&
                    remoteClient.AgentId != part.OwnerID &&
                    m_scene.Permissions.PropagatePermissions())
                {
                    taskItem.BasePermissions = item.BasePermissions &
                                               item.NextPermissions;
                    taskItem.CurrentPermissions = item.CurrentPermissions &
                                                  item.NextPermissions;
                    taskItem.EveryonePermissions = item.EveryOnePermissions &
                                                   item.NextPermissions;
                    taskItem.GroupPermissions = item.GroupPermissions &
                                                item.NextPermissions;
                    taskItem.NextPermissions = item.NextPermissions;
                    // We're adding this to a prim we don't own. Force
                    // owner change
                    taskItem.CurrentPermissions |= 16; // Slam
                }
                else
                {
                    taskItem.BasePermissions = item.BasePermissions;
                    taskItem.CurrentPermissions = item.CurrentPermissions;
                    taskItem.EveryonePermissions = item.EveryOnePermissions;
                    taskItem.GroupPermissions = item.GroupPermissions;
                    taskItem.NextPermissions = item.NextPermissions;
                }

                taskItem.Flags = item.Flags;
                taskItem.SalePrice = item.SalePrice;
                taskItem.SaleType = item.SaleType;
                taskItem.CreationDate = (uint) item.CreationDate;

                bool addFromAllowedDrop = false;
                if (remoteClient != null)
                {
                    addFromAllowedDrop = remoteClient.AgentId != part.OwnerID;
                }

                part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);

                return true;
            }
            MainConsole.Instance.ErrorFormat(
                "[PRIM INVENTORY]: " +
                "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
                localID, Name, UUID, newItemId);

            return false;
        }
 public void AddItemAsync(InventoryItemBase item, Action<InventoryItemBase> success)
 {
     if (item == null)
         return;
     lock (_tempItemCache)
     {
         if (!_tempItemCache.ContainsKey(item.ID))
             _tempItemCache.Add(item.ID, item);
     }
     _addInventoryItemQueue.Add(item.Owner, new AddInventoryItemStore(item, success));
 }
 private List<InventoryItemBase> ParseInventoryItems(IDataReader retVal)
 {
     List<InventoryItemBase> items = new List<InventoryItemBase>();
     while (retVal.Read())
     {
         InventoryItemBase item = new InventoryItemBase
                                      {
                                          AssetID = UUID.Parse(retVal["assetID"].ToString()),
                                          AssetType = int.Parse(retVal["assetType"].ToString()),
                                          Name = retVal["inventoryName"].ToString(),
                                          Description = retVal["inventoryDescription"].ToString(),
                                          NextPermissions =
                                              uint.Parse(retVal["inventoryNextPermissions"].ToString()),
                                          CurrentPermissions =
                                              uint.Parse(retVal["inventoryCurrentPermissions"].ToString()),
                                          InvType = int.Parse(retVal["invType"].ToString()),
                                          CreatorIdentification = retVal["creatorID"].ToString(),
                                          BasePermissions =
                                              uint.Parse(retVal["inventoryBasePermissions"].ToString()),
                                          EveryOnePermissions =
                                              uint.Parse(retVal["inventoryEveryOnePermissions"].ToString()),
                                          SalePrice = int.Parse(retVal["salePrice"].ToString()),
                                          SaleType = byte.Parse(retVal["saleType"].ToString()),
                                          CreationDate = int.Parse(retVal["creationDate"].ToString()),
                                          GroupID = UUID.Parse(retVal["groupID"].ToString()),
                                          GroupOwned = int.Parse(retVal["groupOwned"].ToString()) == 1,
                                          Flags = uint.Parse(retVal["flags"].ToString()),
                                          ID = UUID.Parse(retVal["inventoryID"].ToString()),
                                          Owner = UUID.Parse(retVal["avatarID"].ToString()),
                                          Folder = UUID.Parse(retVal["parentFolderID"].ToString()),
                                          GroupPermissions =
                                              uint.Parse(retVal["inventoryGroupPermissions"].ToString())
                                      };
         if (item.InvType == -1)
         {
             //Fix the bad invType
             item.InvType = 0;
             StoreItem(item);
         }
         items.Add(item);
     }
     return items;
 }
        /// <summary>
        ///     Create the calling card inventory item in the user's inventory
        /// </summary>
        /// <param name="client"></param>
        /// <param name="creator"></param>
        /// <param name="folder"></param>
        /// <param name="name"></param>
        public void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name)
        {
            MainConsole.Instance.Debug("[AURORA CALLING CARD MODULE]: Creating calling card for " + client.Name);
            InventoryItemBase item = new InventoryItemBase
                                         {
                                             AssetID = UUID.Zero,
                                             AssetType = (int) AssetType.CallingCard,
                                             BasePermissions = (uint) (PermissionMask.Copy | PermissionMask.Modify),
                                             CurrentPermissions = (uint) (PermissionMask.Copy | PermissionMask.Modify),
                                             NextPermissions = (uint) PermissionMask.None,
                                             CreationDate = Util.UnixTimeSinceEpoch(),
                                             CreatorId = creator.ToString(),
                                             Description = "",
                                             EveryOnePermissions = (uint) PermissionMask.None,
                                             Flags = 0,
                                             Folder = folder,
                                             GroupID = UUID.Zero,
                                             GroupOwned = false,
                                             ID = UUID.Random(),
                                             InvType = (int) InventoryType.CallingCard,
                                             Name = name,
                                             Owner = client.AgentId,
                                             SalePrice = 10,
                                             SaleType = (byte) SaleType.Not
                                         };

            ILLClientInventory inventory = client.Scene.RequestModuleInterface<ILLClientInventory>();
            if (inventory != null)
                inventory.AddInventoryItemAsync(client, item);
        }