Exemple #1
0
    /// <inheritdoc />
    public virtual UrlInfo?GetMediaUrl(
        IPublishedContent content,
        string propertyAlias,
        UrlMode mode,
        string?culture,
        Uri current)
    {
        IPublishedProperty?prop = content.GetProperty(propertyAlias);

        // get the raw source value since this is what is used by IDataEditorWithMediaPath for processing
        var value = prop?.GetSourceValue(culture);

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

        IPublishedPropertyType?propType = prop?.PropertyType;

        if (_mediaPathGenerators.TryGetMediaPath(propType?.EditorAlias, value, out var path))
        {
            Uri url = AssembleUrl(path !, current, mode);
            return(UrlInfo.Url(url.ToString(), culture));
        }

        return(null);
    }
        public override UrlInfo GetUrl(UmbracoContext umbracoContext, IPublishedContent content, UrlMode mode, string culture, Uri current)
        {
            if (content != null && (content.ContentType.Alias == "ArticulateRichText" || content.ContentType.Alias == "ArticulateMarkdown") && content.Parent != null)
            {
                if (content.Parent.Parent != null)
                {
                    var useDateFormat = content.Parent.Parent.Value <bool>("useDateFormatForUrl");
                    if (!useDateFormat)
                    {
                        return(null);
                    }
                }

                var date = content.Value <DateTime>("publishedDate");
                if (date != null)
                {
                    var parentPath = base.GetUrl(umbracoContext, content, mode, culture, current);
                    var urlFolder  = string.Format("{0}/{1:d2}/{2:d2}", date.Year, date.Month, date.Day);
                    var newUrl     = parentPath.Text.EnsureEndsWith("/") + urlFolder + "/" + content.Url;

                    return(UrlInfo.Url(newUrl, culture));
                }
            }

            return(null);
        }
Exemple #3
0
        public void Ensure_Image_Sources()
        {
            // setup a mock URL provider which we'll use for testing
            var mediaType = new PublishedContentType(Guid.NewGuid(), 777, "image", PublishedItemType.Media, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var media     = new Mock <IPublishedContent>();

            media.Setup(x => x.ContentType).Returns(mediaType);
            var mediaUrlProvider = new Mock <IMediaUrlProvider>();

            mediaUrlProvider.Setup(x => x.GetMediaUrl(It.IsAny <IPublishedContent>(), It.IsAny <string>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/media/1001/my-image.jpg"));

            var umbracoContextAccessor = new TestUmbracoContextAccessor();

            IUmbracoContextFactory umbracoContextFactory = TestUmbracoContextFactory.Create(
                umbracoContextAccessor: umbracoContextAccessor);

            var webRoutingSettings   = new WebRoutingSettings();
            var publishedUrlProvider = new UrlProvider(
                umbracoContextAccessor,
                Options.Create(webRoutingSettings),
                new UrlProviderCollection(() => Enumerable.Empty <IUrlProvider>()),
                new MediaUrlProviderCollection(() => new[] { mediaUrlProvider.Object }),
                Mock.Of <IVariationContextAccessor>());

            using (UmbracoContextReference reference = umbracoContextFactory.EnsureUmbracoContext())
            {
                var mediaCache = Mock.Get(reference.UmbracoContext.Media);
                mediaCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media.Object);

                var imageSourceParser = new HtmlImageSourceParser(publishedUrlProvider);

                var result = imageSourceParser.EnsureImageSources(@"<p>
<div>
    <img src="""" />
</div></p>
<p>
    <div><img src="""" data-udi=""umb://media/81BB2036-034F-418B-B61F-C7160D68DCD4"" /></div>
</p>
<p>
    <div><img src=""?width=100"" data-udi=""umb://media/81BB2036-034F-418B-B61F-C7160D68DCD4"" /></div>
</p>");

                Assert.AreEqual(
                    @"<p>
<div>
    <img src="""" />
</div></p>
<p>
    <div><img src=""/media/1001/my-image.jpg"" data-udi=""umb://media/81BB2036-034F-418B-B61F-C7160D68DCD4"" /></div>
</p>
<p>
    <div><img src=""/media/1001/my-image.jpg?width=100"" data-udi=""umb://media/81BB2036-034F-418B-B61F-C7160D68DCD4"" /></div>
</p>", result);
            }
        }
        public void ParseLocalLinks(string input, string result)
        {
            // setup a mock URL provider which we'll use for testing
            var contentUrlProvider = new Mock <IUrlProvider>();

            contentUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/my-test-url"));
            var contentType      = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = new Mock <IPublishedContent>();

            publishedContent.Setup(x => x.Id).Returns(1234);
            publishedContent.Setup(x => x.ContentType).Returns(contentType);

            var mediaType = new PublishedContentType(Guid.NewGuid(), 777, "image", PublishedItemType.Media, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var media     = new Mock <IPublishedContent>();

            media.Setup(x => x.ContentType).Returns(mediaType);
            var mediaUrlProvider = new Mock <IMediaUrlProvider>();

            mediaUrlProvider.Setup(x => x.GetMediaUrl(It.IsAny <IPublishedContent>(), It.IsAny <string>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/media/1001/my-image.jpg"));

            var umbracoContextAccessor = new TestUmbracoContextAccessor();

            IUmbracoContextFactory umbracoContextFactory = TestUmbracoContextFactory.Create(
                umbracoContextAccessor: umbracoContextAccessor);

            var webRoutingSettings   = new WebRoutingSettings();
            var publishedUrlProvider = new UrlProvider(
                umbracoContextAccessor,
                Microsoft.Extensions.Options.Options.Create(webRoutingSettings),
                new UrlProviderCollection(() => new[] { contentUrlProvider.Object }),
                new MediaUrlProviderCollection(() => new[] { mediaUrlProvider.Object }),
                Mock.Of <IVariationContextAccessor>());

            using (UmbracoContextReference reference = umbracoContextFactory.EnsureUmbracoContext())
            {
                var contentCache = Mock.Get(reference.UmbracoContext.Content);
                contentCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent.Object);
                contentCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent.Object);

                var mediaCache = Mock.Get(reference.UmbracoContext.Media);
                mediaCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(media.Object);
                mediaCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media.Object);

                var linkParser = new HtmlLocalLinkParser(umbracoContextAccessor, publishedUrlProvider);

                var output = linkParser.EnsureInternalLinks(input);

                Assert.AreEqual(result, output);
            }
        }
Exemple #5
0
    /// <summary>
    ///     Gets the other URLs of a published content.
    /// </summary>
    /// <param name="umbracoContextAccessor">The Umbraco context.</param>
    /// <param name="id">The published content id.</param>
    /// <param name="current">The current absolute URL.</param>
    /// <returns>The other URLs for the published content.</returns>
    /// <remarks>
    ///     <para>
    ///         Other URLs are those that <c>GetUrl</c> would not return in the current context, but would be valid
    ///         URLs for the node in other contexts (different domain for current request, umbracoUrlAlias...).
    ///     </para>
    /// </remarks>
    public virtual IEnumerable <UrlInfo> GetOtherUrls(int id, Uri current)
    {
        IUmbracoContext   umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
        IPublishedContent?node           = umbracoContext.Content?.GetById(id);

        if (node == null)
        {
            yield break;
        }

        // look for domains, walking up the tree
        IPublishedContent?         n          = node;
        IEnumerable <DomainAndUri>?domainUris =
            DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current, false);

        // n is null at root
        while (domainUris == null && n != null)
        {
            n          = n.Parent; // move to parent node
            domainUris = n == null
                ? null
                : DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current);
        }

        // no domains = exit
        if (domainUris == null)
        {
            yield break;
        }

        foreach (DomainAndUri d in domainUris)
        {
            var culture = d.Culture;

            // although we are passing in culture here, if any node in this path is invariant, it ignores the culture anyways so this is ok
            var route = umbracoContext.Content?.GetRouteById(id, culture);
            if (route == null)
            {
                continue;
            }

            // need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned)
            var pos  = route.IndexOf('/');
            var path = pos == 0 ? route : route.Substring(pos);

            var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path));
            uri = _uriUtility.UriFromUmbraco(uri, _requestSettings);
            yield return(UrlInfo.Url(uri.ToString(), culture));
        }
    }
Exemple #6
0
        public void ParseLocalLinks(string input, string result)
        {
            //setup a mock url provider which we'll use for testing
            var contentUrlProvider = new Mock <IUrlProvider>();

            contentUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/my-test-url"));
            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = new Mock <IPublishedContent>();

            publishedContent.Setup(x => x.Id).Returns(1234);
            publishedContent.Setup(x => x.ContentType).Returns(contentType);

            var mediaType = new PublishedContentType(777, "image", PublishedItemType.Media, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var media     = new Mock <IPublishedContent>();

            media.Setup(x => x.ContentType).Returns(mediaType);
            var mediaUrlProvider = new Mock <IMediaUrlProvider>();

            mediaUrlProvider.Setup(x => x.GetMediaUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <string>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/media/1001/my-image.jpg"));

            var umbracoContextAccessor = new TestUmbracoContextAccessor();

            var umbracoContextFactory = TestUmbracoContextFactory.Create(
                urlProvider: contentUrlProvider.Object,
                mediaUrlProvider: mediaUrlProvider.Object,
                umbracoContextAccessor: umbracoContextAccessor);

            using (var reference = umbracoContextFactory.EnsureUmbracoContext(Mock.Of <HttpContextBase>()))
            {
                var contentCache = Mock.Get(reference.UmbracoContext.Content);
                contentCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent.Object);
                contentCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent.Object);

                var mediaCache = Mock.Get(reference.UmbracoContext.Media);
                mediaCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(media.Object);
                mediaCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media.Object);

                var linkParser = new HtmlLocalLinkParser(umbracoContextAccessor);

                var output = linkParser.EnsureInternalLinks(input);

                Assert.AreEqual(result, output);
            }
        }
Exemple #7
0
        public void Can_Mock_UrlProvider()
        {
            var umbracoContext = TestObjects.GetUmbracoContextMock();

            var urlProviderMock = new Mock <IUrlProvider>();

            urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/hello/world/1234"));
            var urlProvider = urlProviderMock.Object;

            var theUrlProvider = new UrlProvider(umbracoContext, new [] { urlProvider }, Enumerable.Empty <IMediaUrlProvider>(), umbracoContext.VariationContextAccessor);

            var contentType      = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);

            Assert.AreEqual("/hello/world/1234", theUrlProvider.GetUrl(publishedContent));
        }
Exemple #8
0
        /// <inheritdoc />
        public UrlInfo GetUrl(UmbracoContext umbracoContext, IPublishedContent content, UrlMode mode, string culture, Uri current)
        {
            string url;

            switch (content.ContentType.Alias)
            {
            case "robotsTxt":
                url = "/robots.txt";
                break;

            case "sitemapXml":
                url = $"/sitemap-{culture}.xml";
                break;

            default:
                return(null);
            }

            return(UrlInfo.Url(mode == UrlMode.Absolute ? new Uri(current, url).ToString() : url));
        }
Exemple #9
0
        /// <summary>
        /// Gets the nice url of a custom routed published content item
        /// </summary>
        public UrlInfo GetUrl(UmbracoContext umbracoContext, IPublishedContent content, UrlProviderMode mode, string culture, Uri current)
        {
            if (umbracoContext.PublishedRequest == null)
            {
                return(null);
            }
            if (umbracoContext.PublishedRequest.PublishedContent == null)
            {
                return(null);
            }
            var virtualPage = umbracoContext.PublishedRequest.PublishedContent as ArticulateVirtualPage;

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

            //if the ids match, then return the assigned url
            return(content.Id == virtualPage.Id ? UrlInfo.Url(virtualPage.Url, culture) : null);
        }
Exemple #10
0
        protected UrlInfo GetHeadRestUrl(UmbracoContext umbracoContext, int id, string culture, HeadRestEndpointMode endpointMode)
        {
            var content = umbracoContext.Content.GetById(id);

            foreach (var headRestConfig in HeadRest.Configs.Values.Where(x => x.Mode == endpointMode))
            {
                var rootNode = umbracoContext.Content.GetSingleByXPath(headRestConfig.RootNodeXPath);
                if (content.Path.StartsWith(rootNode.Path))
                {
                    var subUrl = string.Join("/", content.AncestorsOrSelf(true, x => x.Level > rootNode.Level)
                                             .Select(x => x.UrlSegment)
                                             .Reverse());

                    var url = (headRestConfig.BasePath
                               .EnsureStartsWith("/")
                               .EnsureEndsWith("/") + subUrl).EnsureEndsWith('/');

                    return(UrlInfo.Url(url, culture));;
                }
            }

            return(null);
        }
Exemple #11
0
        /// <summary>
        ///     Tries to return a <see cref="UrlInfo" /> for each culture for the content while detecting collisions/errors
        /// </summary>
        private static async Task <IEnumerable <UrlInfo> > GetContentUrlsByCultureAsync(
            IContent content,
            IEnumerable <string> cultures,
            IPublishedRouter publishedRouter,
            IUmbracoContext umbracoContext,
            IContentService contentService,
            ILocalizedTextService textService,
            IVariationContextAccessor variationContextAccessor,
            ILogger logger,
            UriUtility uriUtility,
            IPublishedUrlProvider publishedUrlProvider)
        {
            var result = new List <UrlInfo>();

            foreach (var culture in cultures)
            {
                // if content is variant, and culture is not published, skip
                if (content.ContentType.VariesByCulture() && !content.IsCulturePublished(culture))
                {
                    continue;
                }

                // if it's variant and culture is published, or if it's invariant, proceed
                string url;
                try
                {
                    url = publishedUrlProvider.GetUrl(content.Id, culture: culture);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "GetUrl exception.");
                    url = "#ex";
                }

                switch (url)
                {
                // deal with 'could not get the URL'
                case "#":
                    result.Add(HandleCouldNotGetUrl(content, culture, contentService, textService));
                    break;

                // deal with exceptions
                case "#ex":
                    result.Add(UrlInfo.Message(textService.Localize("content", "getUrlException"), culture));
                    break;

                // got a URL, deal with collisions, add URL
                default:
                    // detect collisions, etc
                    Attempt <UrlInfo?> hasCollision = await DetectCollisionAsync(logger, content, url, culture, umbracoContext, publishedRouter, textService, variationContextAccessor, uriUtility);

                    if (hasCollision.Success && hasCollision.Result is not null)
                    {
                        result.Add(hasCollision.Result);
                    }
                    else
                    {
                        result.Add(UrlInfo.Url(url, culture));
                    }

                    break;
                }
            }

            return(result);
        }
Exemple #12
0
        IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            // default
            if (!typeof(UmbracoApiControllerBase).IsAssignableFrom(controllerType))
            {
                return(base.Create(request, controllerDescriptor, controllerType));
            }

            var owinContext = request.TryGetOwinContext().Result;

            var mockedUserService        = Mock.Of <IUserService>();
            var mockedContentService     = Mock.Of <IContentService>();
            var mockedMediaService       = Mock.Of <IMediaService>();
            var mockedEntityService      = Mock.Of <IEntityService>();
            var mockedMemberService      = Mock.Of <IMemberService>();
            var mockedMemberTypeService  = Mock.Of <IMemberTypeService>();
            var mockedDataTypeService    = Mock.Of <IDataTypeService>();
            var mockedContentTypeService = Mock.Of <IContentTypeService>();

            var serviceContext = ServiceContext.CreatePartial(
                userService: mockedUserService,
                contentService: mockedContentService,
                mediaService: mockedMediaService,
                entityService: mockedEntityService,
                memberService: mockedMemberService,
                memberTypeService: mockedMemberTypeService,
                dataTypeService: mockedDataTypeService,
                contentTypeService: mockedContentTypeService,
                localizedTextService: Mock.Of <ILocalizedTextService>());

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            // FIXME: v8?
            ////new app context
            //var dbCtx = new Mock<DatabaseContext>(Mock.Of<IDatabaseFactory>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test");
            ////ensure these are set so that the appctx is 'Configured'
            //dbCtx.Setup(x => x.CanConnect).Returns(true);
            //dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
            //var appCtx = ApplicationContext.EnsureContext(
            //    dbCtx.Object,
            //    //pass in mocked services
            //    serviceContext,
            //    CacheHelper.CreateDisabledCacheHelper(),
            //    new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()),
            //    true);

            var httpContextItems = new Dictionary <string, object>
            {
                //add the special owin environment to the httpcontext items, this is how the GetOwinContext works
                ["owin.Environment"] = new Dictionary <string, object>()
            };

            //httpcontext with an auth'd user
            var httpContext = Mock.Of <HttpContextBase>(
                http => http.User == owinContext.Authentication.User
                //ensure the request exists with a cookies collection
                && http.Request == Mock.Of <HttpRequestBase>(r => r.Cookies == new HttpCookieCollection() &&
                                                             r.RequestContext == new System.Web.Routing.RequestContext
            {
                RouteData = new System.Web.Routing.RouteData()
            })
                //ensure the request exists with an items collection
                && http.Items == httpContextItems);

            //chuck it into the props since this is what MS does when hosted and it's needed there
            request.Properties["MS_HttpContext"] = httpContext;

            var backofficeIdentity = (UmbracoBackOfficeIdentity)owinContext.Authentication.User.Identity;

            var webSecurity = new Mock <WebSecurity>(null, null, globalSettings);

            //mock CurrentUser
            var groups = new List <ReadOnlyUserGroup>();

            for (var index = 0; index < backofficeIdentity.Roles.Length; index++)
            {
                var role = backofficeIdentity.Roles[index];
                groups.Add(new ReadOnlyUserGroup(index + 1, role, "icon-user", null, null, role, new string[0], new string[0]));
            }
            webSecurity.Setup(x => x.CurrentUser)
            .Returns(Mock.Of <IUser>(u => u.IsApproved == true &&
                                     u.IsLockedOut == false &&
                                     u.AllowedSections == backofficeIdentity.AllowedApplications &&
                                     u.Groups == groups &&
                                     u.Email == "*****@*****.**" &&
                                     u.Id == (int)backofficeIdentity.Id &&
                                     u.Language == "en" &&
                                     u.Name == backofficeIdentity.RealName &&
                                     u.StartContentIds == backofficeIdentity.StartContentNodes &&
                                     u.StartMediaIds == backofficeIdentity.StartMediaNodes &&
                                     u.Username == backofficeIdentity.Username));

            //mock Validate
            webSecurity.Setup(x => x.ValidateCurrentUser())
            .Returns(() => true);
            webSecurity.Setup(x => x.UserHasSectionAccess(It.IsAny <string>(), It.IsAny <IUser>()))
            .Returns(() => true);

            var publishedSnapshot = new Mock <IPublishedSnapshot>();

            publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of <IPublishedMemberCache>());
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedSnapshot.Object);

            var umbracoContextAccessor = Umbraco.Web.Composing.Current.UmbracoContextAccessor;

            var umbCtx = new UmbracoContext(httpContext,
                                            publishedSnapshotService.Object,
                                            webSecurity.Object,
                                            Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "Auto")),
                                            Enumerable.Empty <IUrlProvider>(),
                                            Enumerable.Empty <IMediaUrlProvider>(),
                                            globalSettings,
                                            new TestVariationContextAccessor());

            //replace it
            umbracoContextAccessor.UmbracoContext = umbCtx;

            var urlHelper = new Mock <IUrlProvider>();

            urlHelper.Setup(provider => provider.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlProviderMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/hello/world/1234"));

            var membershipHelper = new MembershipHelper(umbCtx.HttpContext, Mock.Of <IPublishedMemberCache>(), Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>(), Mock.Of <IMemberService>(), Mock.Of <IMemberTypeService>(), Mock.Of <IUserService>(), Mock.Of <IPublicAccessService>(), Mock.Of <AppCaches>(), Mock.Of <ILogger>());

            var umbHelper = new UmbracoHelper(Mock.Of <IPublishedContent>(),
                                              Mock.Of <ITagQuery>(),
                                              Mock.Of <ICultureDictionaryFactory>(),
                                              Mock.Of <IUmbracoComponentRenderer>(),
                                              Mock.Of <IPublishedContentQuery>(),
                                              membershipHelper);

            return(CreateController(controllerType, request, umbracoContextAccessor, umbHelper));
        }
        public void ParseLocalLinks(string input, string result)
        {
            var serviceCtxMock = new TestObjects(null).GetServiceContextMock();

            //setup a mock entity service from the service context to return an integer for a GUID
            var entityService = Mock.Get(serviceCtxMock.EntityService);
            //entityService.Setup(x => x.GetId(It.IsAny<Guid>(), It.IsAny<UmbracoObjectTypes>()))
            //    .Returns((Guid id, UmbracoObjectTypes objType) =>
            //    {
            //        return Attempt.Succeed(1234);
            //    });

            //setup a mock url provider which we'll use fo rtesting
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlProviderMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns((UmbracoContext umbCtx, IPublishedContent content, UrlProviderMode mode, string culture, Uri url) => UrlInfo.Url("/my-test-url"));

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.Id).Returns(1234);
            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);
            var contentCache = Mock.Of <IPublishedContentCache>();

            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent);
            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent);
            var snapshot = Mock.Of <IPublishedSnapshot>();

            Mock.Get(snapshot).Setup(x => x.Content).Returns(contentCache);
            var snapshotService = Mock.Of <IPublishedSnapshotService>();

            Mock.Get(snapshotService).Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(snapshot);

            var umbracoContextFactory = new UmbracoContextFactory(
                Umbraco.Web.Composing.Current.UmbracoContextAccessor,
                snapshotService,
                new TestVariationContextAccessor(),
                new TestDefaultCultureAccessor(),
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "Auto")),
                globalSettings,
                new UrlProviderCollection(new[] { testUrlProvider.Object }),
                Mock.Of <IUserService>());

            using (var reference = umbracoContextFactory.EnsureUmbracoContext(Mock.Of <HttpContextBase>()))
            {
                var output = TemplateUtilities.ParseInternalLinks(input, reference.UmbracoContext.UrlProvider);

                Assert.AreEqual(result, output);
            }
        }
Exemple #14
0
        public void ParseLocalLinks(string input, string result)
        {
            //setup a mock url provider which we'll use for testing
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns((UmbracoContext umbCtx, IPublishedContent content, UrlMode mode, string culture, Uri url) => UrlInfo.Url("/my-test-url"));

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.Id).Returns(1234);
            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);
            var contentCache = Mock.Of <IPublishedContentCache>();

            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent);
            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent);
            var snapshot = Mock.Of <IPublishedSnapshot>();

            Mock.Get(snapshot).Setup(x => x.Content).Returns(contentCache);
            var snapshotService = Mock.Of <IPublishedSnapshotService>();

            Mock.Get(snapshotService).Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(snapshot);
            var media = Mock.Of <IPublishedContent>();

            Mock.Get(media).Setup(x => x.Url).Returns("/media/1001/my-image.jpg");
            var mediaCache = Mock.Of <IPublishedMediaCache>();

            Mock.Get(mediaCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media);

            var umbracoContextAccessor = new TestUmbracoContextAccessor();
            var umbracoContextFactory  = new UmbracoContextFactory(
                umbracoContextAccessor,
                snapshotService,
                new TestVariationContextAccessor(),
                new TestDefaultCultureAccessor(),
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "Auto")),
                globalSettings,
                new UrlProviderCollection(new[] { testUrlProvider.Object }),
                new MediaUrlProviderCollection(Enumerable.Empty <IMediaUrlProvider>()),
                Mock.Of <IUserService>());

            using (var reference = umbracoContextFactory.EnsureUmbracoContext(Mock.Of <HttpContextBase>()))
            {
                var output = TemplateUtilities.ParseInternalLinks(input, reference.UmbracoContext.UrlProvider, mediaCache);

                Assert.AreEqual(result, output);
            }
        }
    null;     // we have nothing to say

    #endregion

    #region GetOtherUrls

    /// <summary>
    ///     Gets the other URLs of a published content.
    /// </summary>
    /// <param name="id">The published content id.</param>
    /// <param name="current">The current absolute URL.</param>
    /// <returns>The other URLs for the published content.</returns>
    /// <remarks>
    ///     <para>
    ///         Other URLs are those that <c>GetUrl</c> would not return in the current context, but would be valid
    ///         URLs for the node in other contexts (different domain for current request, umbracoUrlAlias...).
    ///     </para>
    /// </remarks>
    public IEnumerable <UrlInfo> GetOtherUrls(int id, Uri current)
    {
        IUmbracoContext   umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
        IPublishedContent?node           = umbracoContext.Content?.GetById(id);

        if (node == null)
        {
            yield break;
        }

        if (!node.HasProperty(Constants.Conventions.Content.UrlAlias))
        {
            yield break;
        }

        // look for domains, walking up the tree
        IPublishedContent?         n          = node;
        IEnumerable <DomainAndUri>?domainUris = DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current, false);

        // n is null at root
        while (domainUris == null && n != null)
        {
            // move to parent node
            n          = n.Parent;
            domainUris = n == null
                ? null
                : DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current, false);
        }

        // determine whether the alias property varies
        var varies = node.GetProperty(Constants.Conventions.Content.UrlAlias) !.PropertyType.VariesByCulture();

        if (domainUris == null)
        {
            // no domain
            // if the property is invariant, then URL "/<alias>" is ok
            // if the property varies, then what are we supposed to do?
            //  the content finder may work, depending on the 'current' culture,
            //  but there's no way we can return something meaningful here
            if (varies)
            {
                yield break;
            }

            var umbracoUrlName = node.Value <string>(_publishedValueFallback, Constants.Conventions.Content.UrlAlias);
            var aliases        = umbracoUrlName?.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries);

            if (aliases == null || aliases.Any() == false)
            {
                yield break;
            }

            foreach (var alias in aliases.Distinct())
            {
                var path = "/" + alias;
                var uri  = new Uri(path, UriKind.Relative);
                yield return(UrlInfo.Url(_uriUtility.UriFromUmbraco(uri, _requestConfig).ToString()));
            }
        }
        else
        {
            // some domains: one URL per domain, which is "<domain>/<alias>"
            foreach (DomainAndUri domainUri in domainUris)
            {
                // if the property is invariant, get the invariant value, URL is "<domain>/<invariant-alias>"
                // if the property varies, get the variant value, URL is "<domain>/<variant-alias>"

                // but! only if the culture is published, else ignore
                if (varies && !node.HasCulture(domainUri.Culture))
                {
                    continue;
                }

                var umbracoUrlName = varies
                    ? node.Value <string>(_publishedValueFallback, Constants.Conventions.Content.UrlAlias, domainUri.Culture)
                    : node.Value <string>(_publishedValueFallback, Constants.Conventions.Content.UrlAlias);

                var aliases = umbracoUrlName?.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries);

                if (aliases == null || aliases.Any() == false)
                {
                    continue;
                }

                foreach (var alias in aliases.Distinct())
                {
                    var path = "/" + alias;
                    var uri  = new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path));
                    yield return(UrlInfo.Url(
                                     _uriUtility.UriFromUmbraco(uri, _requestConfig).ToString(),
                                     domainUri.Culture));
                }
            }
        }
    }