public void AddCacheItemAsync(InventoryItemBase item)
 {
     if (item == null)
         return;
     lock (_tempItemCache)
     {
         if (!_tempItemCache.ContainsKey(item.ID))
             _tempItemCache.Add(item.ID, item);
     }
     //_addInventoryItemQueue.Add(item.Owner, new AddInventoryItemStore(item, success));
 }
        /// <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"];
 }
        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 static string Serialize(InventoryItemBase inventoryItem)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(sw) {Formatting = Formatting.Indented};
            writer.WriteStartDocument();

            writer.WriteStartElement("InventoryItem");

            writer.WriteStartElement("Name");
            writer.WriteString(inventoryItem.Name);
            writer.WriteEndElement();
            writer.WriteStartElement("ID");
            writer.WriteString(inventoryItem.ID.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("InvType");
            writer.WriteString(inventoryItem.InvType.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("CreatorUUID");
            writer.WriteString(inventoryItem.CreatorId);
            writer.WriteEndElement();
            writer.WriteStartElement("CreatorData");
            writer.WriteString(inventoryItem.CreatorData);
            writer.WriteEndElement();
            writer.WriteStartElement("CreationDate");
            writer.WriteString(inventoryItem.CreationDate.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("Owner");
            writer.WriteString(inventoryItem.Owner.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("Description");
            writer.WriteString(inventoryItem.Description);
            writer.WriteEndElement();
            writer.WriteStartElement("AssetType");
            writer.WriteString(inventoryItem.AssetType.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("AssetID");
            writer.WriteString(inventoryItem.AssetID.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("SaleType");
            writer.WriteString(inventoryItem.SaleType.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("SalePrice");
            writer.WriteString(inventoryItem.SalePrice.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("BasePermissions");
            writer.WriteString(inventoryItem.BasePermissions.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("CurrentPermissions");
            writer.WriteString(inventoryItem.CurrentPermissions.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("EveryOnePermissions");
            writer.WriteString(inventoryItem.EveryOnePermissions.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("NextPermissions");
            writer.WriteString(inventoryItem.NextPermissions.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("Flags");
            writer.WriteString(inventoryItem.Flags.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("GroupID");
            writer.WriteString(inventoryItem.GroupID.ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("GroupOwned");
            writer.WriteString(inventoryItem.GroupOwned.ToString());
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.Close();

            return sw.ToString();
        }
    /// <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]: Deprecated 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?
        }
        AvatarAppearance CopyWearablesAndAttachments (UUID destination, UUID source,
                                                             AvatarAppearance avatarAppearance,
                                                             InventoryFolderBase destinationFolder, UUID agentid,
                                                             OSDMap itemsMap,
                                                             out List<InventoryItemBase> items)
        {
            items = new List<InventoryItemBase> ();

            if (destinationFolder == null) {
                MainConsole.Instance.Error ("[Avatar Archiver]: Cannot locate folder(s) for copying wearables!");
                return avatarAppearance;
            }

            List<InventoryItemBase> litems = new List<InventoryItemBase> ();
            foreach (KeyValuePair<string, OSD> kvp in itemsMap) {
                InventoryItemBase item = new InventoryItemBase ();
                item.FromOSD ((OSDMap)kvp.Value);
                MainConsole.Instance.Info ("[Avatar Archiver]: Loading item " + item.ID);
                litems.Add (item);
            }

            // Wearables
            AvatarWearable [] wearables = avatarAppearance.Wearables;
            MainConsole.Instance.InfoFormat ("[Avatar Archiver] Adding {0} wearables", wearables.Length);

            for (int i = 0; i < wearables.Length; i++) {
                AvatarWearable wearable = wearables [i];
                for (int ii = 0; ii < wearable.Count; ii++) {
                    if (wearable [ii].ItemID != UUID.Zero) {
                        // Get inventory item and copy it
                        InventoryItemBase item = inventoryService.GetItem (UUID.Zero, wearable [ii].ItemID);

                        if (item == null) {
                            //Attempt to get from the map if it doesn't already exist on the grid
                            item = litems.First ((itm) => itm.ID == wearable [ii].ItemID);
                        }
                        if (item != null) {
                            InventoryItemBase destinationItem = inventoryService.InnerGiveInventoryItem (destination,
                                                                                                        destination,
                                                                                                        item,
                                                                                                        destinationFolder
                                                                                                            .ID,
                                                                                                        false, false);
                            items.Add (destinationItem);
                            MainConsole.Instance.DebugFormat ("[Avatar Archiver]: Added item {0} to folder {1}",
                                                             destinationItem.ID, destinationFolder.ID);

                            // Wear item
                            AvatarWearable newWearable = new AvatarWearable ();
                            newWearable.Wear (destinationItem.ID, destinationItem.AssetID);
                            avatarAppearance.SetWearable (i, newWearable);
                        } else {
                            MainConsole.Instance.WarnFormat ("[Avatar Archiver]: Unable to transfer {0} to folder {1}",
                                                            wearable [ii].ItemID, destinationFolder.ID);
                        }
                    }
                }
            }

            // Attachments
            List<AvatarAttachment> attachments = avatarAppearance.GetAttachments ();
            MainConsole.Instance.InfoFormat ("[Avatar Archiver] Adding {0} attachments", attachments.Count);

            foreach (AvatarAttachment attachment in attachments) {
                int attachpoint = attachment.AttachPoint;
                UUID itemID = attachment.ItemID;

                if (itemID != UUID.Zero) {

                    // Get inventory item and copy it
                    InventoryItemBase item = inventoryService.GetItem (UUID.Zero, itemID);

                    if (item == null) {
                        //Attempt to get from the map if it doesn't already exist on the grid
                        item = litems.First ((itm) => itm.ID == itemID);
                    }

                    if (item != null) {
                        InventoryItemBase destinationItem = inventoryService.InnerGiveInventoryItem (destination,
                                                                                                    destination, item,
                                                                                                    destinationFolder.ID,
                                                                                                    false, false);
                        items.Add (destinationItem);
                        MainConsole.Instance.DebugFormat ("[Avatar Archiver]: Added item {0} to folder {1}", destinationItem.ID,
                                                         destinationFolder.ID);

                        // Attach item
                        avatarAppearance.SetAttachment (attachpoint, destinationItem.ID, destinationItem.AssetID);
                        MainConsole.Instance.DebugFormat ("[Avatar Archiver]: Attached {0}", destinationItem.ID);
                    } else {
                        MainConsole.Instance.WarnFormat ("[Avatar Archiver]: Error transferring {0} to folder {1}", itemID,
                                                        destinationFolder.ID);
                    }
                }
            }
            return avatarAppearance;
        }
        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;
        }
        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>
        ///     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>
        ///     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 virtual bool AddItem(InventoryItemBase item, bool doParentFolderCheck)
        {
            if (doParentFolderCheck)
            {
                InventoryFolderBase folder = GetFolder(new InventoryFolderBase(item.Folder));

                if (folder == null || folder.Owner != item.Owner)
                {
                    MainConsole.Instance.DebugFormat ("[InventoryService]: Aborting adding item as folder {0} does not exist or is not the owner's",folder);
                    return false;
                }
            }
            m_Database.IncrementFolder(item.Folder);
            bool success = m_Database.StoreItem(item);
            if (!success)
                MainConsole.Instance.DebugFormat ("[InventoryService]: Failed to save item {0} in folder {1}",item.Name,item.Folder);
            else
                MainConsole.Instance.DebugFormat ("[InventoryService]: Saved item {0} in folder {1}",item.Name,item.Folder);

            return success;
        }
        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)
                    {
                        MainConsole.Instance.WarnFormat (
                            "[InventoryService]: Inventory copy of {0} aborted due to permissions: Sender {1}, recipient {2}",
                            item.AssetID, senderId, recipient);
                        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;

                    MainConsole.Instance.Debug ("[InventoryService]: Updated item permissions for new user");
                }
                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;

                if (! AddItem(itemCopy))
                    MainConsole.Instance.Warn ("[InventoryService]: Failed to insert inventory item copyinto database");

                if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
                {
                    DeleteItems (senderId, new List<UUID> { item.ID });
                    MainConsole.Instance.Debug ("[InventoryService]: Deleting new item as permissions prevent copying");
                }

                return itemCopy;
            }
            MainConsole.Instance.WarnFormat(
                "[InventoryService]: Failed to give item {0} as item does not belong to giver", item.ID.ToString());
            return null;
        }
        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);
        }
        /// <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
        }
Ejemplo n.º 16
0
        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>
        ///     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.");
            }
        }
 /// <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); });
 }
Ejemplo n.º 19
0
        /// <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="everyoneMask"></param>
        /// <param name="groupMask"></param>
        /// <param name="nextOwnerMask"></param>
        public UUID UploadCompleteHandler (string assetName, string assetDescription, UUID assetID,
                                           UUID inventoryItem, UUID parentFolder, byte [] data, string inventoryType,
                                           string assetType, uint everyoneMask, uint groupMask, uint nextOwnerMask)
        {
            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, FolderType.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, FolderType.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 = everyoneMask,
                            GroupPermissions = groupMask,
                            NextPermissions = nextOwnerMask
                        };
                        //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 ();
                        // not currently used                        int material = inner_instance_list["material"].AsInteger();
                        // not currently used                        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 = everyoneMask;
                        prim.NextOwnerMask = nextOwnerMask;
                        prim.GroupMask = groupMask;
                        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 != null) {              // unlikely not to have anything but itis possible
                        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 = everyoneMask,
                NextPermissions = nextOwnerMask,
                GroupPermissions = groupMask,
                CreationDate = Util.UnixTimeSinceEpoch ()
            };

            m_inventoryService.AddItem (item);

            return assetID;
        }
        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_SHAPE_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)
                {
                    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)
                {
                    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;
        }
 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;
 }
        /// <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;
        }
 /// <summary>
 /// Create the archive name for a particular item.
 /// </summary>
 ///
 /// These names are prepended with an inventory item's UUID so that more than one item can have the
 /// same name
 /// 
 /// <param name="item"></param>
 /// <returns></returns>
 public static string CreateArchiveItemName(InventoryItemBase item)
 {
     return CreateArchiveItemName (item.Name, item.ID);
 }
        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;
        }
        protected void SaveInvItem(InventoryItemBase inventoryItem, string path)
        {
            string filename = path + CreateArchiveItemName (inventoryItem);

            InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone ();

            string serialization = UserInventoryItemSerializer.Serialize (saveItem);
            m_archiveWriter.WriteFile (filename, serialization);
        }
        InventoryItemBase GiveInventoryItem (UUID senderId, UUID recipient, InventoryItemBase item,
                                                    InventoryFolderBase parentFolder)
        {
            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 = UUID.Zero,
                NextPermissions = (uint)PermissionMask.All,
                GroupPermissions = (uint)PermissionMask.All,
                EveryOnePermissions = (uint)PermissionMask.All,
                CurrentPermissions = (uint)PermissionMask.All
            };

            //Give full permissions for them

            if (parentFolder == null) {
                InventoryFolderBase folder = inventoryService.GetFolderForType (recipient, InventoryType.Unknown,
                                                                               (FolderType)itemCopy.AssetType);

                if (folder != null)
                    itemCopy.Folder = folder.ID;
                else {
                    InventoryFolderBase root = inventoryService.GetRootFolder (recipient);

                    if (root != null)
                        itemCopy.Folder = root.ID;
                    else
                        return null; // No destination
                }
            } else
                itemCopy.Folder = parentFolder.ID; //We already have a folder to put it in

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

            inventoryService.AddItem (itemCopy);
            return itemCopy;
        }
        /// <summary>
        ///     Deserialize settings
        /// </summary>
        /// <param name="serialization"></param>
        /// <returns></returns>
        /// <exception cref="System.Xml.XmlException"></exception>
        public static InventoryItemBase Deserialize(string serialization)
        {
            InventoryItemBase item = new InventoryItemBase();

            StringReader sr = new StringReader(serialization);
            XmlTextReader xtr = new XmlTextReader(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");
            item.CreatorData = xtr.ReadElementString("CreatorData");
            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 bool AddInventoryItem(InventoryItemBase item)
        {
            if (UUID.Zero == item.Folder)
            {
                InventoryFolderBase f = m_inventoryService.GetFolderForType(
                    item.Owner,
                    (InventoryType) item.InvType,
                    (AssetType) item.AssetType);

                if (f != null)
                {
                    //                    MainConsole.Instance.DebugFormat(
                    //                        "[LOCAL INVENTORY SERVICES CONNECTOR]: Found folder {0} type {1} for item {2}",
                    //                        f.Name, (AssetType)f.Type, item.Name);

                    item.Folder = f.ID;
                }
                else
                {
                    f = m_inventoryService.GetRootFolder(item.Owner);
                    if (f != null)
                    {
                        item.Folder = f.ID;
                    }
                    else
                    {
                        MainConsole.Instance.WarnFormat(
                            "[AGENT INVENTORY]: Could not find root folder for {0} when trying to add item {1} with no parent folder specified",
                            item.Owner, item.Name);
                        return false;
                    }
                }
            }

            // check if the folder item exists
            if (!m_inventoryService.FolderItemExists (item.Folder, item.ID))
            {
                if (m_inventoryService.ItemExists (item.ID))
                {
                    // Don't use this item ID as it probably belongs to another local user's folder
                    item.ID = UUID.Random();
                }

                if (!m_inventoryService.AddItem (item))
                {
                    MainConsole.Instance.WarnFormat (
                        "[AGENT INVENTORY]: Agent {0} could not add item {1} {2}",
                        item.Owner, item.Name, item.ID);
                    return false;
                }
            }
            return true;
        }
 /// <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));
 }