Example #1
0
    /// <summary>
    ///     Searches Examine for results based on the entity type
    /// </summary>
    /// <param name="query"></param>
    /// <param name="entityType"></param>
    /// <param name="culture"></param>
    /// <param name="totalFound"></param>
    /// <param name="searchFrom">
    ///     A starting point for the search, generally a node id, but for members this is a member type alias
    /// </param>
    /// <param name="pageSize"></param>
    /// <param name="pageIndex"></param>
    /// <param name="ignoreUserStartNodes">If set to true, user and group start node permissions will be ignored.</param>
    /// <returns></returns>
    public IEnumerable <SearchResultEntity> ExamineSearch(
        string query,
        UmbracoEntityTypes entityType,
        int pageSize,
        long pageIndex,
        out long totalFound,
        string?culture            = null,
        string?searchFrom         = null,
        bool ignoreUserStartNodes = false)
    {
        IEnumerable <ISearchResult> pagedResult = _backOfficeExamineSearcher.Search(query, entityType, pageSize, pageIndex, out totalFound, searchFrom, ignoreUserStartNodes);

        switch (entityType)
        {
        case UmbracoEntityTypes.Member:
            return(MemberFromSearchResults(pagedResult.ToArray()));

        case UmbracoEntityTypes.Media:
            return(MediaFromSearchResults(pagedResult));

        case UmbracoEntityTypes.Document:
            return(ContentFromSearchResults(pagedResult, culture));

        default:
            throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) +
                                            " currently does not support searching against object type " +
                                            entityType);
        }
    }
Example #2
0
        private IEnumerable <EntityBasic> GetResultForAncestors(int id, UmbracoEntityTypes entityType)
        {
            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                //TODO: Need to check for Object types that support hierarchic here, some might not.

                var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse).Distinct().ToArray();

                return(Services.EntityService.GetAll(objectType.Value, ids)
                       .WhereNotNull()
                       .OrderBy(x => x.Level)
                       .Select(Mapper.Map <EntityBasic>));
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.PropertyType:
            case UmbracoEntityTypes.PropertyGroup:
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #3
0
        private EntityBasic GetResultForId(int id, UmbracoEntityTypes entityType)
        {
            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                var found = Services.EntityService.Get(id, objectType.Value);
                if (found == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return(MapEntity(found));
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.PropertyType:

            case UmbracoEntityTypes.PropertyGroup:

            case UmbracoEntityTypes.Domain:

            case UmbracoEntityTypes.Language:

            case UmbracoEntityTypes.User:

            case UmbracoEntityTypes.Macro:

            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #4
0
        private IEnumerable <EntityBasic> GetResultForIds(int[] ids, UmbracoEntityTypes entityType)
        {
            if (ids.Length == 0)
            {
                return(Enumerable.Empty <EntityBasic>());
            }

            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                var entities = Services.EntityService.GetAll(objectType.Value, ids)
                               .WhereNotNull()
                               .Select(MapEntities());

                // entities are in "some" order, put them back in order
                var xref   = entities.ToDictionary(x => x.Id);
                var result = ids.Select(x => xref.ContainsKey(x) ? xref[x] : null).Where(x => x != null);

                return(result);
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.PropertyType:
            case UmbracoEntityTypes.PropertyGroup:
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #5
0
        private static UmbracoObjectTypes?ConvertToObjectType(UmbracoEntityTypes entityType)
        {
            switch (entityType)
            {
            case UmbracoEntityTypes.Document:
                return(UmbracoObjectTypes.Document);

            case UmbracoEntityTypes.Media:
                return(UmbracoObjectTypes.Media);

            case UmbracoEntityTypes.MemberType:
                return(UmbracoObjectTypes.MediaType);

            case UmbracoEntityTypes.MemberGroup:
                return(UmbracoObjectTypes.MemberGroup);

            case UmbracoEntityTypes.MediaType:
                return(UmbracoObjectTypes.MediaType);

            case UmbracoEntityTypes.DocumentType:
                return(UmbracoObjectTypes.DocumentType);

            case UmbracoEntityTypes.Member:
                return(UmbracoObjectTypes.Member);

            case UmbracoEntityTypes.DataType:
                return(UmbracoObjectTypes.DataType);

            default:
                //There is no UmbracoEntity conversion (things like Macros, Users, etc...)
                return(null);
            }
        }
Example #6
0
        /// <summary>
        /// Gets the url of an entity
        /// </summary>
        /// <param name="id">Int id of the entity to fetch URL for</param>
        /// <param name="type">The type of entity such as Document, Media, Member</param>
        /// <returns>The URL or path to the item</returns>
        public HttpResponseMessage GetUrl(int id, UmbracoEntityTypes type)
        {
            var returnUrl = string.Empty;

            if (type == UmbracoEntityTypes.Document)
            {
                var foundUrl = UmbracoContext.Url(id);
                if (string.IsNullOrEmpty(foundUrl) == false && foundUrl != "#")
                {
                    returnUrl = foundUrl;

                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(returnUrl)
                    });
                }
            }

            var ancestors = GetResultForAncestors(id, type);

            //if content, skip the first node for replicating NiceUrl defaults
            if (type == UmbracoEntityTypes.Document)
            {
                ancestors = ancestors.Skip(1);
            }

            returnUrl = "/" + string.Join("/", ancestors.Select(x => x.Name));

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(returnUrl)
            });
        }
Example #7
0
        /// <summary>
        /// Gets the result for the entity list based on the type
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="postFilter">A string where filter that will filter the results dynamically with linq - optional</param>
        /// <param name="postFilterParams">the parameters to fill in the string where filter - optional</param>
        /// <returns></returns>
        private IEnumerable <EntityBasic> GetResultForAll(UmbracoEntityTypes entityType, string postFilter = null, IDictionary <string, object> postFilterParams = null)
        {
            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                //TODO: Should we order this by something ?
                var entities = Services.EntityService.GetAll(objectType.Value).WhereNotNull().Select(Mapper.Map <EntityBasic>);
                return(ExecutePostFilter(entities, postFilter, postFilterParams));
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.Template:
                var templates         = Services.FileService.GetTemplates();
                var filteredTemplates = ExecutePostFilter(templates, postFilter, postFilterParams);
                return(filteredTemplates.Select(Mapper.Map <EntityBasic>));

            case UmbracoEntityTypes.Macro:
                //Get all macros from the macro service
                var macros         = Services.MacroService.GetAll().WhereNotNull().OrderBy(x => x.Name);
                var filteredMacros = ExecutePostFilter(macros, postFilter, postFilterParams);
                return(filteredMacros.Select(Mapper.Map <EntityBasic>));

            case UmbracoEntityTypes.PropertyType:

                //get all document types, then combine all property types into one list
                var propertyTypes = Services.ContentTypeService.GetAll().Cast <IContentTypeComposition>()
                                    .Concat(Services.MediaTypeService.GetAll())
                                    .ToArray()
                                    .SelectMany(x => x.PropertyTypes)
                                    .DistinctBy(composition => composition.Alias);
                var filteredPropertyTypes = ExecutePostFilter(propertyTypes, postFilter, postFilterParams);
                return(Mapper.Map <IEnumerable <PropertyType>, IEnumerable <EntityBasic> >(filteredPropertyTypes));

            case UmbracoEntityTypes.PropertyGroup:

                //get all document types, then combine all property types into one list
                var propertyGroups = Services.ContentTypeService.GetAll().Cast <IContentTypeComposition>()
                                     .Concat(Services.MediaTypeService.GetAll())
                                     .ToArray()
                                     .SelectMany(x => x.PropertyGroups)
                                     .DistinctBy(composition => composition.Name);
                var filteredpropertyGroups = ExecutePostFilter(propertyGroups, postFilter, postFilterParams);
                return(Mapper.Map <IEnumerable <PropertyGroup>, IEnumerable <EntityBasic> >(filteredpropertyGroups));

            case UmbracoEntityTypes.User:

                long total;
                var  users         = Services.UserService.GetAll(0, int.MaxValue, out total);
                var  filteredUsers = ExecutePostFilter(users, postFilter, postFilterParams);
                return(Mapper.Map <IEnumerable <IUser>, IEnumerable <EntityBasic> >(filteredUsers));

            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #8
0
 public IEnumerable <EntityBasic> GetByIds([FromJsonPath] Guid[] ids, UmbracoEntityTypes type)
 {
     if (ids == null)
     {
         throw new HttpResponseException(HttpStatusCode.NotFound);
     }
     return(GetResultForKeys(ids, type));
 }
Example #9
0
 /// <summary>
 /// Searches Examine for results based on the entity type
 /// </summary>
 /// <param name="query"></param>
 /// <param name="entityType"></param>
 /// <param name="totalFound"></param>
 /// <param name="searchFrom">
 /// A starting point for the search, generally a node id, but for members this is a member type alias
 /// </param>
 /// <param name="pageSize"></param>
 /// <param name="pageIndex"></param>
 /// <param name="ignoreUserStartNodes">If set to true, user and group start node permissions will be ignored.</param>
 /// <returns></returns>
 public IEnumerable <SearchResultEntity> ExamineSearch(
     string query,
     UmbracoEntityTypes entityType,
     int pageSize,
     long pageIndex, out long totalFound, string searchFrom = null, bool ignoreUserStartNodes = false)
 {
     return(ExamineSearch(query, entityType, pageSize, pageIndex, culture: null, out totalFound, searchFrom, ignoreUserStartNodes));
 }
Example #10
0
        /// <summary>
        /// Get paged child entities by id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderDirection"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PagedResult <EntityBasic> GetPagedChildren(
            int id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "")
        {
            if (pageNumber <= 0)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            if (pageSize <= 0)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var objectType = ConvertToObjectType(type);

            if (objectType.HasValue)
            {
                var entities = Services.EntityService.GetPagedChildren(id, objectType.Value, pageNumber - 1, pageSize, out var totalRecords,
                                                                       filter.IsNullOrWhiteSpace()
                        ? null
                        : SqlContext.Query <IUmbracoEntity>().Where(x => x.Name.Contains(filter)),
                                                                       Ordering.By(orderBy, orderDirection));

                if (totalRecords == 0)
                {
                    return(new PagedResult <EntityBasic>(0, 0, 0));
                }

                var pagedResult = new PagedResult <EntityBasic>(totalRecords, pageNumber, pageSize)
                {
                    Items = entities.Select(entity => Mapper.Map <IEntitySlim, EntityBasic>(entity, options =>
                                                                                            options.AfterMap((src, dest) => { dest.AdditionalData["hasChildren"] = src.HasChildren; })
                                                                                            )
                                            )
                };

                return(pagedResult);
            }

            //now we need to convert the unknown ones
            switch (type)
            {
            case UmbracoEntityTypes.PropertyType:
            case UmbracoEntityTypes.PropertyGroup:
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + type);
            }
        }
Example #11
0
        /// <summary>
        /// Gets the path for a given node ID
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public IEnumerable <int> GetPath(Udi id, UmbracoEntityTypes type)
        {
            var guidUdi = id as GuidUdi;

            if (guidUdi != null)
            {
                return(GetPath(guidUdi.Guid, type));
            }
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
Example #12
0
        /// <summary>
        /// Gets an entity by it's UDI
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public EntityBasic GetById(Udi id, UmbracoEntityTypes type)
        {
            var guidUdi = id as GuidUdi;

            if (guidUdi != null)
            {
                return(GetResultForKey(guidUdi.Guid, type));
            }
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
Example #13
0
        public PagedResult <EntityBasic> GetPagedDescendants(
            int id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "")
        {
            if (pageNumber <= 0)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            if (pageSize <= 0)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var objectType = ConvertToObjectType(type);

            if (objectType.HasValue)
            {
                long totalRecords;
                //if it's from root, don't return recycled
                var entities = id == Constants.System.Root
                    ? Services.EntityService.GetPagedDescendantsFromRoot(objectType.Value, pageNumber - 1, pageSize, out totalRecords, orderBy, orderDirection, filter, includeTrashed: false)
                    : Services.EntityService.GetPagedDescendants(id, objectType.Value, pageNumber - 1, pageSize, out totalRecords, orderBy, orderDirection, filter);

                if (totalRecords == 0)
                {
                    return(new PagedResult <EntityBasic>(0, 0, 0));
                }

                var pagedResult = new PagedResult <EntityBasic>(totalRecords, pageNumber, pageSize)
                {
                    Items = entities.Select(Mapper.Map <EntityBasic>)
                };

                return(pagedResult);
            }

            //now we need to convert the unknown ones
            switch (type)
            {
            case UmbracoEntityTypes.PropertyType:
            case UmbracoEntityTypes.PropertyGroup:
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + type);
            }
        }
Example #14
0
        public IEnumerable <EntityBasic> Search(string query, UmbracoEntityTypes type, string searchFrom = null)
        {
            //TODO: Should we restrict search results based on what app the user has access to?
            // - Theoretically you shouldn't be able to see member data if you don't have access to members right?

            if (string.IsNullOrEmpty(query))
            {
                return(Enumerable.Empty <EntityBasic>());
            }

            return(ExamineSearch(query, type, searchFrom));
        }
        /// <summary>
        /// Get paged child entities by id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderDirection"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PagedResult <EntityBasic> GetPagedChildren(
            string id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "",
            Guid?dataTypeId          = null)
        {
            int intId;

            if (int.TryParse(id, out intId))
            {
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            Guid guidId;

            if (Guid.TryParse(id, out guidId))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            Udi udiId;

            if (Udi.TryParse(id, out udiId))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //so we don't have an INT, GUID or UDI, it's just a string, so now need to check if it's a special id or a member type
            if (id == Constants.Conventions.MemberTypes.AllMembersListId)
            {
                //the EntityService can search paged members from the root

                intId = -1;
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter, dataTypeId));
            }

            //the EntityService cannot search members of a certain type, this is currently not supported and would require
            //quite a bit of plumbing to do in the Services/Repository, we'll revert to a paged search

            long total;
            var  searchResult = _treeSearcher.ExamineSearch(Umbraco, filter ?? "", type, pageSize, pageNumber - 1, out total, id);

            return(new PagedResult <EntityBasic>(total, pageNumber, pageSize)
            {
                Items = searchResult
            });
        }
Example #16
0
 public IEnumerable <ISearchResult> Search(
     string query,
     UmbracoEntityTypes entityType,
     int pageSize,
     long pageIndex,
     out long totalFound,
     string?searchFrom         = null,
     bool ignoreUserStartNodes = false)
 {
     totalFound = 0;
     return(Enumerable.Empty <ISearchResult>());
 }
Example #17
0
 public PagedResult <EntityBasic> GetPagedDescendants(
     int id,
     UmbracoEntityTypes type,
     int pageNumber,
     int pageSize,
     string orderBy           = "SortOrder",
     Direction orderDirection = Direction.Ascending,
     string filter            = "")
 {
     return(GetPagedDescendants(id, type, pageNumber, pageSize,
                                ignoreUserStartNodes: false, orderBy, orderDirection, filter));
 }
        public IEnumerable <EntityBasic> Search(string query, UmbracoEntityTypes type, string searchFrom = null, Guid?dataTypeId = null)
        {
            // NOTE: Theoretically you shouldn't be able to see member data if you don't have access to members right? ... but there is a member picker, so can't really do that

            if (string.IsNullOrEmpty(query))
            {
                return(Enumerable.Empty <EntityBasic>());
            }

            var ignoreUserStartNodes = dataTypeId.HasValue && Services.DataTypeService.IsDataTypeIgnoringUserStartNodes(dataTypeId.Value);

            return(ExamineSearch(query, type, searchFrom, ignoreUserStartNodes));
        }
        private int[] GetStartNodes(UmbracoEntityTypes type)
        {
            switch (type)
            {
            case UmbracoEntityTypes.Document:
                return(Security.CurrentUser.CalculateContentStartNodeIds(Services.EntityService));

            case UmbracoEntityTypes.Media:
                return(Security.CurrentUser.CalculateMediaStartNodeIds(Services.EntityService));

            default:
                return(new int[0]);
            }
        }
Example #20
0
        public IEnumerable <EntityBasic> Search(string query, UmbracoEntityTypes type, bool?ignoreUserStartNodes, string searchFrom = null)
        {
            // TODO: Should we restrict search results based on what app the user has access to?
            // - Theoretically you shouldn't be able to see member data if you don't have access to members right?

            if (string.IsNullOrEmpty(query))
            {
                return(Enumerable.Empty <EntityBasic>());
            }

            //TODO: This uses the internal UmbracoTreeSearcher, this instead should delgate to the ISearchableTree implementation for the type

            return(ExamineSearch(query, type, searchFrom, ignoreUserStartNodes != null && ignoreUserStartNodes.Value));
        }
Example #21
0
        /// <summary>
        /// Get paged child entities by id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderDirection"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PagedResult <EntityBasic> GetPagedChildren(
            string id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "")
        {
            if (int.TryParse(id, out var intId))
            {
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            if (Guid.TryParse(id, out _))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (Udi.TryParse(id, out _))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //so we don't have an INT, GUID or UDI, it's just a string, so now need to check if it's a special id or a member type
            if (id == Constants.Conventions.MemberTypes.AllMembersListId)
            {
                //the EntityService can search paged members from the root

                intId = -1;
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            //the EntityService cannot search members of a certain type, this is currently not supported and would require
            //quite a bit of plumbing to do in the Services/Repository, we'll revert to a paged search

            //TODO: We should really fix this in the EntityService but if we don't we should allow the ISearchableTree for the members controller
            // to be used for this search instead of the built in/internal searcher

            var searchResult = _treeSearcher.ExamineSearch(filter ?? "", type, pageSize, pageNumber - 1, out long total, id);

            return(new PagedResult <EntityBasic>(total, pageNumber, pageSize)
            {
                Items = searchResult
            });
        }
        public IEnumerable <EntityBasic> GetChildren(int id, UmbracoEntityTypes type, Guid?dataTypeId = null)
        {
            var objectType = ConvertToObjectType(type);

            if (objectType.HasValue)
            {
                //TODO: Need to check for Object types that support hierarchy here, some might not.

                var startNodes = GetStartNodes(type);

                var ignoreUserStartNodes = IsDataTypeIgnoringUserStartNodes(dataTypeId);

                // root is special: we reduce it to start nodes if the user's start node is not the default, then we need to return their start nodes
                if (id == Constants.System.Root && startNodes.Length > 0 && startNodes.Contains(Constants.System.Root) == false && !ignoreUserStartNodes)
                {
                    var nodes = Services.EntityService.GetAll(objectType.Value, startNodes).ToArray();
                    if (nodes.Length == 0)
                    {
                        return(Enumerable.Empty <EntityBasic>());
                    }
                    var pr = new List <EntityBasic>(nodes.Select(Mapper.Map <EntityBasic>));
                    return(pr);
                }

                // else proceed as usual

                return(Services.EntityService.GetChildren(id, objectType.Value)
                       .WhereNotNull()
                       .Select(Mapper.Map <EntityBasic>));
            }
            //now we need to convert the unknown ones
            switch (type)
            {
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + type);
            }
        }
Example #23
0
        /// <summary>
        /// Gets an entity by a xpath query
        /// </summary>
        /// <param name="query"></param>
        /// <param name="nodeContextId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public EntityBasic GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type)
        {
            // TODO: Rename this!!! It's misleading, it should be GetByXPath


            if (type != UmbracoEntityTypes.Document)
            {
                throw new ArgumentException("Get by query is only compatible with entities of type Document");
            }


            var q    = ParseXPathQuery(query, nodeContextId);
            var node = Umbraco.ContentSingleAtXPath(q);

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

            return(GetById(node.Id, type));
        }
Example #24
0
        private IEnumerable <EntityBasic> GetResultForChildren(int id, UmbracoEntityTypes entityType)
        {
            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                // TODO: Need to check for Object types that support hierarchic here, some might not.

                return(Services.EntityService.GetChildren(id, objectType.Value)
                       .WhereNotNull()
                       .Select(MapEntities()));
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #25
0
        public IEnumerable <EntityBasic> GetByIds([FromJsonPath] Udi[] ids, [FromUri] UmbracoEntityTypes type)
        {
            if (ids == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (ids.Length == 0)
            {
                return(Enumerable.Empty <EntityBasic>());
            }

            //all udi types will need to be the same in this list so we'll determine by the first
            //currently we only support GuidIdi for this method

            var guidUdi = ids[0] as GuidUdi;

            if (guidUdi != null)
            {
                return(GetResultForKeys(ids.Select(x => ((GuidUdi)x).Guid).ToArray(), type));
            }

            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
Example #26
0
        /// <summary>
        /// Searches Examine for results based on the entity type
        /// </summary>
        /// <param name="query"></param>
        /// <param name="entityType"></param>
        /// <param name="totalFound"></param>
        /// <param name="searchFrom">
        /// A starting point for the search, generally a node id, but for members this is a member type alias
        /// </param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="ignoreUserStartNodes">If set to true, user and group start node permissions will be ignored.</param>
        /// <returns></returns>
        public IEnumerable <SearchResultEntity> ExamineSearch(
            string query,
            UmbracoEntityTypes entityType,
            int pageSize,
            long pageIndex, out long totalFound, string searchFrom = null, bool ignoreUserStartNodes = false)
        {
            var sb = new StringBuilder();

            string type;
            var    indexName = Constants.UmbracoIndexes.InternalIndexName;
            var    fields    = new List <string> {
                "id", "__NodeId", "__Key"
            };

            // TODO: WE should try to allow passing in a lucene raw query, however we will still need to do some manual string
            // manipulation for things like start paths, member types, etc...
            //if (Examine.ExamineExtensions.TryParseLuceneQuery(query))
            //{

            //}

            //special GUID check since if a user searches on one specifically we need to escape it
            if (Guid.TryParse(query, out var g))
            {
                query = "\"" + g.ToString() + "\"";
            }

            switch (entityType)
            {
            case UmbracoEntityTypes.Member:
                indexName = Constants.UmbracoIndexes.MembersIndexName;
                type      = "member";
                fields.AddRange(new[] { "email", "loginName" });
                if (searchFrom != null && searchFrom != Constants.Conventions.MemberTypes.AllMembersListId && searchFrom.Trim() != "-1")
                {
                    sb.Append("+__NodeTypeAlias:");
                    sb.Append(searchFrom);
                    sb.Append(" ");
                }
                break;

            case UmbracoEntityTypes.Media:
                type = "media";
                fields.AddRange(new[] { UmbracoExamineIndex.UmbracoFileFieldName });
                var allMediaStartNodes = _umbracoContext.Security.CurrentUser.CalculateMediaStartNodeIds(_entityService);
                AppendPath(sb, UmbracoObjectTypes.Media, allMediaStartNodes, searchFrom, ignoreUserStartNodes, _entityService);
                break;

            case UmbracoEntityTypes.Document:
                type = "content";
                var allContentStartNodes = _umbracoContext.Security.CurrentUser.CalculateContentStartNodeIds(_entityService);
                AppendPath(sb, UmbracoObjectTypes.Document, allContentStartNodes, searchFrom, ignoreUserStartNodes, _entityService);
                break;

            default:
                throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
            }

            if (!_examineManager.TryGetIndex(indexName, out var index))
            {
                throw new InvalidOperationException("No index found by name " + indexName);
            }

            var internalSearcher = index.GetSearcher();

            if (!BuildQuery(sb, query, searchFrom, fields, type))
            {
                totalFound = 0;
                return(Enumerable.Empty <SearchResultEntity>());
            }

            var result = internalSearcher.CreateQuery().NativeQuery(sb.ToString())
                         //only return the number of items specified to read up to the amount of records to fill from 0 -> the number of items on the page requested
                         .Execute(Convert.ToInt32(pageSize * (pageIndex + 1)));

            totalFound = result.TotalItemCount;

            var pagedResult = result.Skip(Convert.ToInt32(pageIndex));

            switch (entityType)
            {
            case UmbracoEntityTypes.Member:
                return(MemberFromSearchResults(pagedResult.ToArray()));

            case UmbracoEntityTypes.Media:
                return(MediaFromSearchResults(pagedResult));

            case UmbracoEntityTypes.Document:
                return(ContentFromSearchResults(pagedResult));

            default:
                throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
            }
        }
        /// <summary>
        /// Searches for results based on the entity type
        /// </summary>
        /// <param name="umbracoHelper"></param>
        /// <param name="query"></param>
        /// <param name="entityType"></param>
        /// <param name="totalFound"></param>
        /// <param name="searchFrom">
        /// A starting point for the search, generally a node id, but for members this is a member type alias
        /// </param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="ignoreUserStartNodes">If set to true, user and group start node permissions will be ignored.</param>
        /// <returns></returns>
        public IEnumerable <SearchResultItem> ExamineSearch(
            UmbracoHelper umbracoHelper,
            string query,
            UmbracoEntityTypes entityType,
            int pageSize,
            long pageIndex, out long totalFound, string searchFrom = null, bool ignoreUserStartNodes = false)
        {
            var sb = new StringBuilder();

            string type;
            var    searcher = Constants.Examine.InternalSearcher;
            var    fields   = new[] { "id", "__NodeId" };

            var umbracoContext = umbracoHelper.UmbracoContext;
            var appContext     = umbracoContext.Application;

            //TODO: WE should really just allow passing in a lucene raw query
            switch (entityType)
            {
            case UmbracoEntityTypes.Member:
                searcher = Constants.Examine.InternalMemberSearcher;
                type     = "member";
                fields   = new[] { "id", "__NodeId", "email", "loginName" };
                if (searchFrom != null && searchFrom != Constants.Conventions.MemberTypes.AllMembersListId && searchFrom.Trim() != "-1")
                {
                    sb.Append("+__NodeTypeAlias:");
                    sb.Append(searchFrom);
                    sb.Append(" ");
                }
                break;

            case UmbracoEntityTypes.Media:
                type = "media";
                var allMediaStartNodes = umbracoContext.Security.CurrentUser.CalculateMediaStartNodeIds(appContext.Services.EntityService);
                AppendPath(sb, UmbracoObjectTypes.Media, allMediaStartNodes, searchFrom, ignoreUserStartNodes, appContext.Services.EntityService);
                break;

            case UmbracoEntityTypes.Document:
                type = "content";
                var allContentStartNodes = umbracoContext.Security.CurrentUser.CalculateContentStartNodeIds(appContext.Services.EntityService);
                AppendPath(sb, UmbracoObjectTypes.Document, allContentStartNodes, searchFrom, ignoreUserStartNodes, appContext.Services.EntityService);
                break;

            default:
                throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
            }

            var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher];

            //build a lucene query:
            // the __nodeName will be boosted 10x without wildcards
            // then __nodeName will be matched normally with wildcards
            // the rest will be normal without wildcards


            //check if text is surrounded by single or double quotes, if so, then exact match
            var surroundedByQuotes = Regex.IsMatch(query, "^\".*?\"$") ||
                                     Regex.IsMatch(query, "^\'.*?\'$");

            if (surroundedByQuotes)
            {
                //strip quotes, escape string, the replace again
                query = query.Trim(new[] { '\"', '\'' });

                query = Lucene.Net.QueryParsers.QueryParser.Escape(query);

                //nothing to search
                if (searchFrom.IsNullOrWhiteSpace() && query.IsNullOrWhiteSpace())
                {
                    totalFound = 0;
                    return(new List <SearchResultItem>());
                }

                //update the query with the query term
                if (query.IsNullOrWhiteSpace() == false)
                {
                    //add back the surrounding quotes
                    query = string.Format("{0}{1}{0}", "\"", query);

                    //node name exactly boost x 10
                    sb.Append("+(__nodeName: (");
                    sb.Append(query.ToLower());
                    sb.Append(")^10.0 ");

                    foreach (var f in fields)
                    {
                        //additional fields normally
                        sb.Append(f);
                        sb.Append(": (");
                        sb.Append(query);
                        sb.Append(") ");
                    }

                    sb.Append(") ");
                }
            }
            else
            {
                var trimmed = query.Trim(new[] { '\"', '\'' });

                //nothing to search
                if (searchFrom.IsNullOrWhiteSpace() && trimmed.IsNullOrWhiteSpace())
                {
                    totalFound = 0;
                    return(new List <SearchResultItem>());
                }

                //update the query with the query term
                if (trimmed.IsNullOrWhiteSpace() == false)
                {
                    query = Lucene.Net.QueryParsers.QueryParser.Escape(query);

                    var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    //node name exactly boost x 10
                    sb.Append("+(__nodeName:");
                    sb.Append("\"");
                    sb.Append(query.ToLower());
                    sb.Append("\"");
                    sb.Append("^10.0 ");

                    //node name normally with wildcards
                    sb.Append(" __nodeName:");
                    sb.Append("(");
                    foreach (var w in querywords)
                    {
                        sb.Append(w.ToLower());
                        sb.Append("* ");
                    }
                    sb.Append(") ");


                    foreach (var f in fields)
                    {
                        //additional fields normally
                        sb.Append(f);
                        sb.Append(":");
                        sb.Append("(");
                        foreach (var w in querywords)
                        {
                            sb.Append(w.ToLower());
                            sb.Append("* ");
                        }
                        sb.Append(")");
                        sb.Append(" ");
                    }

                    sb.Append(") ");
                }
            }

            //must match index type
            sb.Append("+__IndexType:");
            sb.Append(type);

            var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString());

            var result = internalSearcher
                         //only return the number of items specified to read up to the amount of records to fill from 0 -> the number of items on the page requested
                         .Search(raw, Convert.ToInt32(pageSize * (pageIndex + 1)));

            totalFound = result.TotalItemCount;

            var pagedResult = result.Skip(Convert.ToInt32(pageIndex));

            switch (entityType)
            {
            case UmbracoEntityTypes.Member:
                return(MemberFromSearchResults(pagedResult.ToArray()));

            case UmbracoEntityTypes.Media:
                return(MediaFromSearchResults(pagedResult));

            case UmbracoEntityTypes.Document:
                return(ContentFromSearchResults(umbracoHelper, pagedResult));

            default:
                throw new NotSupportedException("The " + typeof(UmbracoTreeSearcher) + " currently does not support searching against object type " + entityType);
            }
        }
Example #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="type">The type of entity.</param>
 /// <param name="postFilter">Optional filter - Format like: "BoolVariable==true&IntVariable>=6". Invalid filters are ignored.</param>
 /// <returns></returns>
 public IEnumerable <EntityBasic> GetAll(UmbracoEntityTypes type, string postFilter)
 {
     return(GetResultForAll(type, postFilter));
 }
Example #29
0
        private IEnumerable <EntityBasic> GetResultForAncestors(int id, UmbracoEntityTypes entityType, FormDataCollection queryStrings = null, bool ignoreUserStartNodes = false)
        {
            var objectType = ConvertToObjectType(entityType);

            if (objectType.HasValue)
            {
                // TODO: Need to check for Object types that support hierarchic here, some might not.

                var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse).Distinct().ToArray();

                if (ignoreUserStartNodes == false)
                {
                    int[] aids = null;
                    switch (entityType)
                    {
                    case UmbracoEntityTypes.Document:
                        aids = Security.CurrentUser.CalculateContentStartNodeIds(Services.EntityService);
                        break;

                    case UmbracoEntityTypes.Media:
                        aids = Security.CurrentUser.CalculateMediaStartNodeIds(Services.EntityService);
                        break;
                    }

                    if (aids != null)
                    {
                        var lids = new List <int>();
                        var ok   = false;
                        foreach (var i in ids)
                        {
                            if (ok)
                            {
                                lids.Add(i);
                                continue;
                            }
                            if (aids.Contains(i))
                            {
                                lids.Add(i);
                                ok = true;
                            }
                        }
                        ids = lids.ToArray();
                    }
                }

                var culture = queryStrings?.GetValue <string>("culture");

                return(ids.Length == 0
                    ? Enumerable.Empty <EntityBasic>()
                    : Services.EntityService.GetAll(objectType.Value, ids)
                       .WhereNotNull()
                       .OrderBy(x => x.Level)
                       .Select(MapEntities(culture)));
            }
            //now we need to convert the unknown ones
            switch (entityType)
            {
            case UmbracoEntityTypes.PropertyType:
            case UmbracoEntityTypes.PropertyGroup:
            case UmbracoEntityTypes.Domain:
            case UmbracoEntityTypes.Language:
            case UmbracoEntityTypes.User:
            case UmbracoEntityTypes.Macro:
            default:
                throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
            }
        }
Example #30
0
 /// <summary>
 /// Searches for results based on the entity type
 /// </summary>
 /// <param name="query"></param>
 /// <param name="entityType"></param>
 /// <param name="searchFrom"></param>
 /// <param name="ignoreUserStartNodes">If set to true, user and group start node permissions will be ignored.</param>
 /// <returns></returns>
 private IEnumerable <SearchResultEntity> ExamineSearch(string query, UmbracoEntityTypes entityType, string searchFrom = null, bool ignoreUserStartNodes = false)
 {
     return(_treeSearcher.ExamineSearch(query, entityType, 200, 0, out _, ignoreUserStartNodes, searchFrom));
 }
        public static IEnumerable<EntityBasic> ExamineSearchRaw(this EntityController controller, string query, UmbracoEntityTypes entityType)
        {
            string type;
            var searcher = Constants.Examine.InternalSearcher;            
            var fields = new[] { "id", "bodyText" };
            
            //TODO: WE should really just allow passing in a lucene raw query
            switch (entityType)
            {
                case UmbracoEntityTypes.Member:
                    searcher = Constants.Examine.InternalMemberSearcher;
                    type = "member";
                    fields = new[] { "id", "email", "loginName"};
                    break;
                case UmbracoEntityTypes.Media:
                    type = "media";
                    break;
                case UmbracoEntityTypes.Document:
                    type = "content";
                    break;
                default:
                    throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType);                    
            }

            var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher];

            //build a lucene query:
            // the __nodeName will be boosted 10x without wildcards
            // then __nodeName will be matched normally with wildcards
            // the rest will be normal without wildcards
            var sb = new StringBuilder();
            
            //node name exactly boost x 10
            sb.Append("+(__nodeName:");
            sb.Append(query.ToLower());
            sb.Append("^10.0 ");

            //node name normally with wildcards
            sb.Append(" __nodeName:");            
            sb.Append(query.ToLower());
            sb.Append("* ");

            foreach (var f in fields)
            {
                //additional fields normally
                sb.Append(f);
                sb.Append(":");
                sb.Append(query);
                sb.Append(" ");
            }

            //must match index type
            sb.Append(") +__IndexType:");
            sb.Append(type);

            var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString());
            
            var result = internalSearcher.Search(raw);

            switch (entityType)
            {
                case UmbracoEntityTypes.Member:
                    return MemberFromSearchResults(result);
                case UmbracoEntityTypes.Media:
                    return MediaFromSearchResults(result);                    
                case UmbracoEntityTypes.Document:
                    return ContentFromSearchResults(result);
                default:
                    throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType);
            }
        }