private bool _readonly; // after prepared

    /// <summary>
    ///     Initializes a new instance of the <see cref="PublishedRequest" /> class.
    /// </summary>
    public PublishedRequestOld(IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, IOptions <WebRoutingSettings> webRoutingSettings, Uri?uri = null)
    {
        UmbracoContext      = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext));
        _publishedRouter    = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
        _webRoutingSettings = webRoutingSettings.Value;
        Uri = uri ?? umbracoContext.CleanedUmbracoUrl;
    }
Esempio n. 2
0
    private UmbracoRouteValueTransformer GetTransformer(
        IUmbracoContextAccessor ctx,
        IRuntimeState state,
        IRoutableDocumentFilter filter = null,
        IPublishedRouter router        = null,
        IUmbracoRouteValuesFactory routeValuesFactory = null)
    {
        var publicAccessRequestHandler = new Mock <IPublicAccessRequestHandler>();

        publicAccessRequestHandler.Setup(x =>
                                         x.RewriteForPublishedContentAccessAsync(It.IsAny <HttpContext>(), It.IsAny <UmbracoRouteValues>()))
        .Returns((HttpContext ctx, UmbracoRouteValues routeVals) => Task.FromResult(routeVals));

        var transformer = new UmbracoRouteValueTransformer(
            new NullLogger <UmbracoRouteValueTransformer>(),
            ctx,
            router ?? Mock.Of <IPublishedRouter>(),
            GetGlobalSettings(),
            TestHelper.GetHostingEnvironment(),
            state,
            routeValuesFactory ?? Mock.Of <IUmbracoRouteValuesFactory>(),
            filter ?? Mock.Of <IRoutableDocumentFilter>(x => x.IsDocumentRequest(It.IsAny <string>()) == true),
            Mock.Of <IDataProtectionProvider>(),
            Mock.Of <IControllerActionSearcher>(),
            Mock.Of <IEventAggregator>(),
            publicAccessRequestHandler.Object);

        return(transformer);
    }
    private static async Task <Attempt <UrlInfo?> > DetectCollisionAsync(
        ILogger logger,
        IContent content,
        string url,
        string culture,
        IUmbracoContext umbracoContext,
        IPublishedRouter publishedRouter,
        ILocalizedTextService textService,
        IVariationContextAccessor variationContextAccessor,
        UriUtility uriUtility)
    {
        // test for collisions on the 'main' URL
        var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute);

        if (uri.IsAbsoluteUri == false)
        {
            uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl);
        }

        uri = uriUtility.UriToUmbraco(uri);
        IPublishedRequestBuilder builder = await publishedRouter.CreateRequestAsync(uri);

        IPublishedRequest pcr =
            await publishedRouter.RouteRequestAsync(builder, new RouteRequestOptions(RouteDirection.Outbound));

        if (!pcr.HasPublishedContent())
        {
            const string logMsg = nameof(DetectCollisionAsync) +
                                  " did not resolve a content item for original url: {Url}, translated to {TranslatedUrl} and culture: {Culture}";
            logger.LogDebug(logMsg, url, uri, culture);

            var urlInfo = UrlInfo.Message(textService.Localize("content", "routeErrorCannotRoute"), culture);
            return(Attempt.Succeed(urlInfo));
        }

        if (pcr.IgnorePublishedContentCollisions)
        {
            return(Attempt <UrlInfo?> .Fail());
        }

        if (pcr.PublishedContent?.Id != content.Id)
        {
            IPublishedContent?o = pcr.PublishedContent;
            var l = new List <string>();
            while (o != null)
            {
                l.Add(o.Name(variationContextAccessor) !);
                o = o.Parent;
            }

            l.Reverse();
            var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent?.Id + ")";

            var urlInfo = UrlInfo.Message(textService.Localize("content", "routeError", new[] { s }), culture);
            return(Attempt.Succeed(urlInfo));
        }

        // no collision
        return(Attempt <UrlInfo?> .Fail());
    }
    public TemplateRenderer(
        IUmbracoContextAccessor umbracoContextAccessor,
        IPublishedRouter publishedRouter,
        IFileService fileService,
        ILocalizationService textService,
        IOptionsMonitor <WebRoutingSettings> webRoutingSettings,
        IHttpContextAccessor httpContextAccessor,
        ICompositeViewEngine viewEngine,
        IModelMetadataProvider modelMetadataProvider,
        ITempDataDictionaryFactory tempDataDictionaryFactory)
    {
        _umbracoContextAccessor =
            umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
        _publishedRouter    = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
        _fileService        = fileService ?? throw new ArgumentNullException(nameof(fileService));
        _languageService    = textService ?? throw new ArgumentNullException(nameof(textService));
        _webRoutingSettings = webRoutingSettings.CurrentValue ??
                              throw new ArgumentNullException(nameof(webRoutingSettings));
        _httpContextAccessor       = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        _viewEngine                = viewEngine ?? throw new ArgumentNullException(nameof(viewEngine));
        _modelMetadataProvider     = modelMetadataProvider;
        _tempDataDictionaryFactory = tempDataDictionaryFactory;

        webRoutingSettings.OnChange(x => _webRoutingSettings = x);
    }
        private async Task SetUmbracoRouteValues(ActionExecutingContext context, IPublishedContent content)
        {
            if (content != null)
            {
                IUmbracoContextAccessor umbracoContextAccessor = context.HttpContext.RequestServices.GetRequiredService <IUmbracoContextAccessor>();
                IPublishedRouter        router = context.HttpContext.RequestServices.GetRequiredService <IPublishedRouter>();

                var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();

                IPublishedRequestBuilder requestBuilder = await router.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl);

                requestBuilder.SetPublishedContent(content);
                IPublishedRequest publishedRequest = requestBuilder.Build();

                var routeValues = new UmbracoRouteValues(
                    publishedRequest,
                    (ControllerActionDescriptor)context.ActionDescriptor);

                context.HttpContext.Features.Set(routeValues);
            }
            else
            {
                // if there is no content then it should be a not found
                context.Result = new NotFoundResult();
            }
        }
Esempio n. 6
0
    /// <summary>
    ///     Initializes a new instance of the <see cref="UmbracoRouteValuesFactory" /> class.
    /// </summary>
    public UmbracoRouteValuesFactory(
        IOptions <UmbracoRenderingDefaultsOptions> renderingDefaults,
        IShortStringHelper shortStringHelper,
        UmbracoFeatures umbracoFeatures,
        IControllerActionSearcher controllerActionSearcher,
        IPublishedRouter publishedRouter)
    {
        _shortStringHelper        = shortStringHelper;
        _umbracoFeatures          = umbracoFeatures;
        _controllerActionSearcher = controllerActionSearcher;
        _publishedRouter          = publishedRouter;
        _defaultControllerName    = new Lazy <string>(() =>
                                                      ControllerExtensions.GetControllerName(renderingDefaults.Value.DefaultControllerType));
        _defaultControllerDescriptor = new Lazy <ControllerActionDescriptor>(() =>
        {
            ControllerActionDescriptor?descriptor = _controllerActionSearcher.Find <IRenderController>(
                new DefaultHttpContext(), // this actually makes no difference for this method
                DefaultControllerName,
                UmbracoRouteValues.DefaultActionName);

            if (descriptor == null)
            {
                throw new InvalidOperationException(
                    $"No controller/action found by name {DefaultControllerName}.{UmbracoRouteValues.DefaultActionName}");
            }

            return(descriptor);
        });
    }
        public UmbracoInjectedModule(
            IGlobalSettings globalSettings,
            IUmbracoContextAccessor umbracoContextAccessor,
            IPublishedSnapshotService publishedSnapshotService,
            IUserService userService,
            UrlProviderCollection urlProviders,
            IRuntimeState runtime,
            ILogger logger,
            IPublishedRouter publishedRouter,
            IVariationContextAccessor variationContextAccessor,
            IUmbracoContextFactory umbracoContextFactory)
        {
            _combinedRouteCollection = new Lazy <RouteCollection>(CreateRouteCollection);

            _globalSettings           = globalSettings;
            _umbracoContextAccessor   = umbracoContextAccessor;
            _publishedSnapshotService = publishedSnapshotService;
            _userService              = userService;
            _urlProviders             = urlProviders;
            _runtime                  = runtime;
            _logger                   = logger;
            _publishedRouter          = publishedRouter;
            _variationContextAccessor = variationContextAccessor;
            _umbracoContextFactory    = umbracoContextFactory;
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UmbracoRouteValueTransformer"/> class.
        /// </summary>
        public UmbracoRouteValueTransformer(
            ILogger <UmbracoRouteValueTransformer> logger,
            IUmbracoContextAccessor umbracoContextAccessor,
            IPublishedRouter publishedRouter,
            IOptions <GlobalSettings> globalSettings,
            IHostingEnvironment hostingEnvironment,
            IRuntimeState runtime,
            IUmbracoRouteValuesFactory routeValuesFactory,
            IRoutableDocumentFilter routableDocumentFilter,
            IDataProtectionProvider dataProtectionProvider,
            IControllerActionSearcher controllerActionSearcher,
            IEventAggregator eventAggregator,
            IPublicAccessRequestHandler publicAccessRequestHandler)
        {
            if (globalSettings is null)
            {
                throw new ArgumentNullException(nameof(globalSettings));
            }

            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
            _publishedRouter        = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
            _globalSettings         = globalSettings.Value;
            _hostingEnvironment     = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
            _runtime                    = runtime ?? throw new ArgumentNullException(nameof(runtime));
            _routeValuesFactory         = routeValuesFactory ?? throw new ArgumentNullException(nameof(routeValuesFactory));
            _routableDocumentFilter     = routableDocumentFilter ?? throw new ArgumentNullException(nameof(routableDocumentFilter));
            _dataProtectionProvider     = dataProtectionProvider;
            _controllerActionSearcher   = controllerActionSearcher;
            _eventAggregator            = eventAggregator;
            _publicAccessRequestHandler = publicAccessRequestHandler;
        }
Esempio n. 9
0
    private async Task SetUmbracoRouteValues(ActionExecutingContext context, IPublishedContent?content)
    {
        if (content != null)
        {
            UriUtility uriUtility = context.HttpContext.RequestServices.GetRequiredService <UriUtility>();

            var originalRequestUrl = new Uri(context.HttpContext.Request.GetEncodedUrl());
            Uri cleanedUrl         = uriUtility.UriToUmbraco(originalRequestUrl);

            IPublishedRouter router = context.HttpContext.RequestServices.GetRequiredService <IPublishedRouter>();

            IPublishedRequestBuilder requestBuilder = await router.CreateRequestAsync(cleanedUrl);

            requestBuilder.SetPublishedContent(content);
            IPublishedRequest publishedRequest = requestBuilder.Build();

            var routeValues = new UmbracoRouteValues(
                publishedRequest,
                (ControllerActionDescriptor)context.ActionDescriptor);

            context.HttpContext.Features.Set(routeValues);
        }
        else
        {
            // if there is no content then it should be a not found
            context.Result = new NotFoundResult();
        }
    }
Esempio n. 10
0
 public ContentMapDefinition(
     CommonMapper commonMapper,
     ILocalizedTextService localizedTextService,
     IContentService contentService,
     IContentTypeService contentTypeService,
     IFileService fileService,
     IUmbracoContextAccessor umbracoContextAccessor,
     IPublishedRouter publishedRouter,
     ILocalizationService localizationService,
     ILogger logger,
     IUserService userService,
     IEntityService entityService,
     AppCaches appCaches)
 {
     _commonMapper           = commonMapper;
     _localizedTextService   = localizedTextService;
     _contentService         = contentService;
     _contentTypeService     = contentTypeService;
     _fileService            = fileService;
     _umbracoContextAccessor = umbracoContextAccessor;
     _publishedRouter        = publishedRouter;
     _localizationService    = localizationService;
     _logger                  = logger;
     _userService             = userService;
     _entityService           = entityService;
     _appCaches               = appCaches;
     _tabsAndPropertiesMapper = new TabsAndPropertiesMapper <IContent>(localizedTextService);
     _stateMapper             = new ContentSavedStateMapper <ContentPropertyDisplay>();
     _basicStateMapper        = new ContentBasicSavedStateMapper <ContentPropertyBasic>();
     _contentVariantMapper    = new ContentVariantMapper(_localizationService, localizedTextService);
 }
Esempio n. 11
0
 public TemplateRenderer(IUmbracoContextAccessor umbracoContextAccessor, IPublishedRouter publishedRouter, IFileService fileService, ILocalizationService textService, IWebRoutingSection webRoutingSection)
 {
     _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
     _publishedRouter        = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
     _fileService            = fileService ?? throw new ArgumentNullException(nameof(fileService));
     _languageService        = textService ?? throw new ArgumentNullException(nameof(textService));
     _webRoutingSection      = webRoutingSection ?? throw new ArgumentNullException(nameof(webRoutingSection));
 }
Esempio n. 12
0
        /// <summary>
        /// Tries to return a <see cref="UrlInfo"/> for each culture for the content while detecting collisions/errors
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cultures"></param>
        /// <param name="publishedRouter"></param>
        /// <param name="umbracoContext"></param>
        /// <param name="contentService"></param>
        /// <param name="textService"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        private static IEnumerable <UrlInfo> GetContentUrlsByCulture(IContent content,
                                                                     IEnumerable <string> cultures,
                                                                     IPublishedRouter publishedRouter,
                                                                     UmbracoContext umbracoContext,
                                                                     IContentService contentService,
                                                                     ILocalizedTextService textService,
                                                                     ILogger logger)
        {
            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 = umbracoContext.UrlProvider.GetUrl(content.Id, culture: culture);
                }
                catch (Exception ex)
                {
                    logger.Error <UrlProvider>(ex, "GetUrl exception.");
                    url = "#ex";
                }

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

                    break;

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

                    break;

                // got a URL, deal with collisions, add URL
                default:
                    if (DetectCollision(content, url, culture, umbracoContext, publishedRouter, textService, out var urlInfo))     // detect collisions, etc
                    {
                        yield return(urlInfo);
                    }
                    else
                    {
                        yield return(UrlInfo.Url(url, culture));
                    }
                    break;
                }
            }
        }
 public ContentUrlResolver(
     IUmbracoContextAccessor umbracoContextAccessor,
     IPublishedRouter publishedRouter,
     ILocalizationService localizationService,
     ILocalizedTextService textService,
     IContentService contentService,
     ILogger logger)
 {
     _umbracoContextAccessor = umbracoContextAccessor ?? throw new System.ArgumentNullException(nameof(umbracoContextAccessor));
     _publishedRouter        = publishedRouter ?? throw new System.ArgumentNullException(nameof(publishedRouter));
     _localizationService    = localizationService ?? throw new System.ArgumentNullException(nameof(localizationService));
     _textService            = textService ?? throw new System.ArgumentNullException(nameof(textService));
     _contentService         = contentService ?? throw new System.ArgumentNullException(nameof(contentService));
     _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
 }
Esempio n. 14
0
 public UmbracoInjectedModule(
     IGlobalSettings globalSettings,
     IRuntimeState runtime,
     ILogger logger,
     IPublishedRouter publishedRouter,
     IUmbracoContextFactory umbracoContextFactory,
     RoutableDocumentFilter routableDocumentLookup)
 {
     _globalSettings         = globalSettings;
     _runtime                = runtime;
     _logger                 = logger;
     _publishedRouter        = publishedRouter;
     _umbracoContextFactory  = umbracoContextFactory;
     _routableDocumentLookup = routableDocumentLookup;
 }
 public PublicAccessRequestHandler(
     ILogger <PublicAccessRequestHandler> logger,
     IPublicAccessService publicAccessService,
     IPublicAccessChecker publicAccessChecker,
     IUmbracoContextAccessor umbracoContextAccessor,
     IUmbracoRouteValuesFactory umbracoRouteValuesFactory,
     IPublishedRouter publishedRouter)
 {
     _logger = logger;
     _publicAccessService       = publicAccessService;
     _publicAccessChecker       = publicAccessChecker;
     _umbracoContextAccessor    = umbracoContextAccessor;
     _umbracoRouteValuesFactory = umbracoRouteValuesFactory;
     _publishedRouter           = publishedRouter;
 }
Esempio n. 16
0
 public UmbracoRouteValueTransformer(
     ILogger <UmbracoRouteValueTransformer> logger,
     IUmbracoContextAccessor umbracoContextAccessor,
     IPublishedRouter publishedRouter,
     IOptions <GlobalSettings> globalSettings,
     IHostingEnvironment hostingEnvironment,
     IRuntimeState runtime,
     IUmbracoRouteValuesFactory routeValuesFactory,
     IRoutableDocumentFilter routableDocumentFilter,
     IDataProtectionProvider dataProtectionProvider,
     IControllerActionSearcher controllerActionSearcher,
     IEventAggregator eventAggregator,
     IPublicAccessRequestHandler publicAccessRequestHandler)
     : this(logger, umbracoContextAccessor, publishedRouter, runtime, routeValuesFactory, routableDocumentFilter, dataProtectionProvider, controllerActionSearcher, publicAccessRequestHandler)
 {
 }
Esempio n. 17
0
        public ContentMapDefinition(
            CommonMapper commonMapper,
            CommonTreeNodeMapper commonTreeNodeMapper,
            ICultureDictionary cultureDictionary,
            ILocalizedTextService localizedTextService,
            IContentService contentService,
            IContentTypeService contentTypeService,
            IFileService fileService,
            IUmbracoContextAccessor umbracoContextAccessor,
            IPublishedRouter publishedRouter,
            ILocalizationService localizationService,
            ILoggerFactory loggerFactory,
            IUserService userService,
            IVariationContextAccessor variationContextAccessor,
            IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
            UriUtility uriUtility,
            IPublishedUrlProvider publishedUrlProvider,
            IEntityService entityService,
            IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
            AppCaches appCaches)
        {
            _commonMapper               = commonMapper;
            _commonTreeNodeMapper       = commonTreeNodeMapper;
            _cultureDictionary          = cultureDictionary;
            _localizedTextService       = localizedTextService;
            _contentService             = contentService;
            _contentTypeService         = contentTypeService;
            _fileService                = fileService;
            _umbracoContextAccessor     = umbracoContextAccessor;
            _publishedRouter            = publishedRouter;
            _localizationService        = localizationService;
            _loggerFactory              = loggerFactory;
            _userService                = userService;
            _entityService              = entityService;
            _backOfficeSecurityAccessor = backOfficeSecurityAccessor;
            _variationContextAccessor   = variationContextAccessor;
            _uriUtility           = uriUtility;
            _publishedUrlProvider = publishedUrlProvider;
            _appCaches            = appCaches;

            _tabsAndPropertiesMapper = new TabsAndPropertiesMapper <IContent>(cultureDictionary, localizedTextService, contentTypeBaseServiceProvider);
            _stateMapper             = new ContentSavedStateMapper <ContentPropertyDisplay>();
            _basicStateMapper        = new ContentBasicSavedStateMapper <ContentPropertyBasic>();
            _contentVariantMapper    = new ContentVariantMapper(_localizationService, localizedTextService);
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewRenderer" /> class.
        /// </summary>
        /// <param name="publishedRouter">The published router.</param>
        /// <param name="umbracoContextAccessor">The umbraco context accessor.</param>
        public ViewRenderer(IPublishedRouter publishedRouter, IUmbracoContextAccessor umbracoContextAccessor)
        {
            var controller = new EmptyController();
            var wrapper    = new HttpContextWrapper(HttpContext.Current);
            var routeData  = new RouteData
            {
                Values = { { "controller", "empty" } },
            };

            this.context = controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
            var context = umbracoContextAccessor.UmbracoContext;

            if (context.PublishedRequest?.PublishedContent == null)
            {
                context.PublishedRequest = publishedRouter.CreateRequest(context);
                context.PublishedRequest.PublishedContent = context.Content.GetAtRoot().FirstOrDefault();
            }
        }
Esempio n. 19
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="UmbracoRouteValueTransformer" /> class.
 /// </summary>
 public UmbracoRouteValueTransformer(
     ILogger <UmbracoRouteValueTransformer> logger,
     IUmbracoContextAccessor umbracoContextAccessor,
     IPublishedRouter publishedRouter,
     IRuntimeState runtime,
     IUmbracoRouteValuesFactory routeValuesFactory,
     IRoutableDocumentFilter routableDocumentFilter,
     IDataProtectionProvider dataProtectionProvider,
     IControllerActionSearcher controllerActionSearcher,
     IPublicAccessRequestHandler publicAccessRequestHandler)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _umbracoContextAccessor =
         umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
     _publishedRouter        = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
     _runtime                = runtime ?? throw new ArgumentNullException(nameof(runtime));
     _routeValuesFactory     = routeValuesFactory ?? throw new ArgumentNullException(nameof(routeValuesFactory));
     _routableDocumentFilter =
         routableDocumentFilter ?? throw new ArgumentNullException(nameof(routableDocumentFilter));
     _dataProtectionProvider     = dataProtectionProvider;
     _controllerActionSearcher   = controllerActionSearcher;
     _publicAccessRequestHandler = publicAccessRequestHandler;
 }
Esempio n. 20
0
 public DocTypeGridEditorApiController(IUmbracoContextAccessor umbracoContext,
                                       IContentTypeService contentTypeService,
                                       IContentService contentService,
                                       IDataTypeService dataTypeService,
                                       IShortStringHelper shortStringHelper,
                                       IPublishedContentQuery contentQuery,
                                       IPublishedRouter router,
                                       ServiceContext serviceContext,
                                       IPublishedContentTypeFactory publishedContentTypeFactory,
                                       PropertyEditorCollection propertyEditorCollection,
                                       DocTypeGridEditorHelper dtgeHelper)
 {
     _umbracoContext              = umbracoContext;
     _contentTypeService          = contentTypeService;
     _contentService              = contentService;
     _dataTypeService             = dataTypeService;
     _shortStringHelper           = shortStringHelper;
     _contentQuery                = contentQuery;
     _router                      = router;
     _dtgeHelper                  = dtgeHelper;
     _serviceContext              = serviceContext;
     _publishedContentTypeFactory = publishedContentTypeFactory;
     _propertyEditorCollection    = propertyEditorCollection;
 }
Esempio n. 21
0
 private UmbracoRouteValueTransformer GetTransformerWithRunState(
     IUmbracoContextAccessor ctx,
     IRoutableDocumentFilter filter = null,
     IPublishedRouter router        = null,
     IUmbracoRouteValuesFactory routeValuesFactory = null)
 => GetTransformer(ctx, Mock.Of <IRuntimeState>(x => x.Level == RuntimeLevel.Run), filter, router, routeValuesFactory);
Esempio n. 22
0
        /// <summary>
        /// Gets the URLs of the content item.
        /// </summary>
        /// <remarks>
        /// <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para>
        /// <para>Contains all the URLs that we can figure out (based upon domains, etc).</para>
        /// </remarks>
        public static IEnumerable <UrlInfo> GetContentUrls(this IContent content,
                                                           IPublishedRouter publishedRouter,
                                                           UmbracoContext umbracoContext,
                                                           ILocalizationService localizationService,
                                                           ILocalizedTextService textService,
                                                           IContentService contentService,
                                                           ILogger logger)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (publishedRouter == null)
            {
                throw new ArgumentNullException(nameof(publishedRouter));
            }
            if (umbracoContext == null)
            {
                throw new ArgumentNullException(nameof(umbracoContext));
            }
            if (localizationService == null)
            {
                throw new ArgumentNullException(nameof(localizationService));
            }
            if (textService == null)
            {
                throw new ArgumentNullException(nameof(textService));
            }
            if (contentService == null)
            {
                throw new ArgumentNullException(nameof(contentService));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (content.Published == false)
            {
                yield return(UrlInfo.Message(textService.Localize("content/itemNotPublished")));

                yield break;
            }

            // build a list of URLs, for the back-office
            // which will contain
            // - the 'main' URLs, which is what .Url would return, for each culture
            // - the 'other' URLs we know (based upon domains, etc)
            //
            // need to work through each installed culture:
            // on invariant nodes, each culture returns the same URL segment but,
            // we don't know if the branch to this content is invariant, so we need to ask
            // for URLs for all cultures.
            // and, not only for those assigned to domains in the branch, because we want
            // to show what GetUrl() would return, for every culture.

            var urls     = new HashSet <UrlInfo>();
            var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList();

            //get all URLs for all cultures
            //in a HashSet, so de-duplicates too
            foreach (var cultureUrl in GetContentUrlsByCulture(content, cultures, publishedRouter, umbracoContext, contentService, textService, logger))
            {
                urls.Add(cultureUrl);
            }

            //return the real URLs first, then the messages
            foreach (var urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key))
            {
                //in some cases there will be the same URL for multiple cultures:
                // * The entire branch is invariant
                // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed

                foreach (var dUrl in urlGroup.DistinctBy(x => x.Text.ToUpperInvariant()).OrderBy(x => x.Text).ThenBy(x => x.Culture))
                {
                    yield return(dUrl);
                }
            }

            // get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless.
            // for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them.
            foreach (var otherUrl in umbracoContext.UrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text).ThenBy(x => x.Culture))
            {
                if (urls.Add(otherUrl)) //avoid duplicates
                {
                    yield return(otherUrl);
                }
            }
        }
Esempio n. 23
0
        private static bool DetectCollision(IContent content, string url, string culture, UmbracoContext umbracoContext, IPublishedRouter publishedRouter, ILocalizedTextService textService, out UrlInfo urlInfo)
        {
            // test for collisions on the 'main' URL
            var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute);

            if (uri.IsAbsoluteUri == false)
            {
                uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl);
            }
            uri = UriUtility.UriToUmbraco(uri);
            var pcr = publishedRouter.CreateRequest(umbracoContext, uri);

            publishedRouter.TryRouteRequest(pcr);

            urlInfo = null;

            if (pcr.HasPublishedContent == false)
            {
                urlInfo = UrlInfo.Message(textService.Localize("content/routeErrorCannotRoute"), culture);
                return(true);
            }

            if (pcr.IgnorePublishedContentCollisions)
            {
                return(false);
            }

            if (pcr.PublishedContent.Id != content.Id)
            {
                var o = pcr.PublishedContent;
                var l = new List <string>();
                while (o != null)
                {
                    l.Add(o.Name());
                    o = o.Parent;
                }
                l.Reverse();
                var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent.Id + ")";

                urlInfo = UrlInfo.Message(textService.Localize("content/routeError", new[] { s }), culture);
                return(true);
            }

            // no collision
            return(false);
        }
Esempio n. 24
0
        private PublishedContentHashtableConverter _umbracoPage; // legacy

        /// <summary>
        /// Initializes a new instance of the <see cref="PublishedRequest"/> class.
        /// </summary>
        /// <param name="publishedRouter">The published router.</param>
        /// <param name="umbracoContext">The Umbraco context.</param>
        /// <param name="uri">The request <c>Uri</c>.</param>
        internal PublishedRequest(IPublishedRouter publishedRouter, UmbracoContext umbracoContext, Uri uri = null)
        {
            UmbracoContext   = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext));
            _publishedRouter = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter));
            Uri = uri ?? umbracoContext.CleanedUmbracoUrl;
        }
Esempio n. 25
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);
        }
Esempio n. 26
0
        /// <summary>
        ///     Gets the URLs of the content item.
        /// </summary>
        /// <remarks>
        ///     <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para>
        ///     <para>Contains all the URLs that we can figure out (based upon domains, etc).</para>
        /// </remarks>
        public static async Task <IEnumerable <UrlInfo> > GetContentUrlsAsync(
            this IContent content,
            IPublishedRouter publishedRouter,
            IUmbracoContext umbracoContext,
            ILocalizationService localizationService,
            ILocalizedTextService textService,
            IContentService contentService,
            IVariationContextAccessor variationContextAccessor,
            ILogger <IContent> logger,
            UriUtility uriUtility,
            IPublishedUrlProvider publishedUrlProvider)
        {
            ArgumentNullException.ThrowIfNull(content);
            ArgumentNullException.ThrowIfNull(publishedRouter);
            ArgumentNullException.ThrowIfNull(umbracoContext);
            ArgumentNullException.ThrowIfNull(localizationService);
            ArgumentNullException.ThrowIfNull(textService);
            ArgumentNullException.ThrowIfNull(contentService);
            ArgumentNullException.ThrowIfNull(variationContextAccessor);
            ArgumentNullException.ThrowIfNull(logger);
            ArgumentNullException.ThrowIfNull(uriUtility);
            ArgumentNullException.ThrowIfNull(publishedUrlProvider);

            var result = new List <UrlInfo>();

            if (content.Published == false)
            {
                result.Add(UrlInfo.Message(textService.Localize("content", "itemNotPublished")));
                return(result);
            }

            // build a list of URLs, for the back-office
            // which will contain
            // - the 'main' URLs, which is what .Url would return, for each culture
            // - the 'other' URLs we know (based upon domains, etc)
            //
            // need to work through each installed culture:
            // on invariant nodes, each culture returns the same URL segment but,
            // we don't know if the branch to this content is invariant, so we need to ask
            // for URLs for all cultures.
            // and, not only for those assigned to domains in the branch, because we want
            // to show what GetUrl() would return, for every culture.
            var urls     = new HashSet <UrlInfo>();
            var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList();

            // get all URLs for all cultures
            // in a HashSet, so de-duplicates too
            foreach (UrlInfo cultureUrl in await GetContentUrlsByCultureAsync(content, cultures, publishedRouter, umbracoContext, contentService, textService, variationContextAccessor, logger, uriUtility, publishedUrlProvider))
            {
                urls.Add(cultureUrl);
            }

            // return the real URLs first, then the messages
            foreach (IGrouping <bool, UrlInfo> urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key))
            {
                // in some cases there will be the same URL for multiple cultures:
                // * The entire branch is invariant
                // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed
                if (urlGroup.Key)
                {
                    result.AddRange(urlGroup.DistinctBy(x => x.Text, StringComparer.OrdinalIgnoreCase).OrderBy(x => x.Text).ThenBy(x => x.Culture));
                }
                else
                {
                    result.AddRange(urlGroup);
                }
            }

            // get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless.
            // for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them.
            foreach (UrlInfo otherUrl in publishedUrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text).ThenBy(x => x.Culture))
            {
                // avoid duplicates
                if (urls.Add(otherUrl))
                {
                    result.Add(otherUrl);
                }
            }

            return(result);
        }