public bool TryFindContent(PublishedContentRequest docRequest)
		{
			int pageId;
			if (int.TryParse(docRequest.RoutingContext.UmbracoContext.HttpContext.Request["umbPageID"], out pageId))
			{
				var doc = docRequest.RoutingContext.UmbracoContext.ContentCache.GetById(pageId);

				if (doc != null)
				{
					docRequest.PublishedContent = doc;
					return true;
				}
			}
			return false;
		}
 public static PublishedContentRequest SetPublishedContentRequest(UmbracoContext context = null, PublishedContentRequest request = null)
 {
     return((context ?? UmbracoContext.Current).PublishedContentRequest = request ?? GetPublishedContentRequest());
 }
        public static ControllerContext GetControllerContext(UmbracoContext context, Controller controller, PublishedContentRequest publishedContentRequest = null, RouteData routeData = null)
        {
            var contextBase = context.HttpContext;

            var pcr = publishedContentRequest ?? GetPublishedContentRequest(context);

            var routeDefinition = new RouteDefinition
            {
                PublishedContentRequest = pcr
            };

            var rd = routeData ?? new RouteData();

            rd.DataTokens.Add("umbraco-route-def", routeDefinition);
            return(new ControllerContext(contextBase, rd, controller));
        }
示例#4
0
        /// <summary>
        /// this will determine the controller and set the values in the route data
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="publishedContentRequest"></param>
        internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
        {
            var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);

            //Need to check for a special case if there is form data being posted back to an Umbraco URL
            var postedInfo = GetPostedFormInfo(requestContext);

            if (postedInfo != null)
            {
                return(HandlePostedValues(requestContext, postedInfo));
            }

            //here we need to check if there is no hijacked route and no template assigned, if this is the case
            //we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
            if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
            {
                publishedContentRequest.UpdateOnMissingTemplate();                 // will go 404

                // HandleHttpResponseStatus returns a value indicating that the request should
                // not be processed any further, eg because it has been redirect. then, exit.
                if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
                {
                    return(null);
                }

                var handler = GetHandlerOnMissingTemplate(publishedContentRequest);

                // if it's not null it can be either the PublishedContentNotFoundHandler (no document was
                // found to handle 404, or document with no template was found) or the WebForms handler
                // (a document was found and its template is WebForms)

                // if it's null it means that a document was found and its template is Mvc

                // if we have a handler, return now
                if (handler != null)
                {
                    return(handler);
                }

                // else we are running Mvc
                // update the route data - because the PublishedContent has changed
                UpdateRouteDataForRequest(
                    new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
                    requestContext);
                // update the route definition
                routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
            }

            //no post values, just route to the controller/action requried (local)

            requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
            if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
            {
                requestContext.RouteData.Values["action"] = routeDef.ActionName;
            }

            // Set the session state requirements
            requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));

            // reset the friendly path so in the controllers and anything occuring after this point in time,
            //the URL is reset back to the original request.
            requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);

            return(new UmbracoMvcHandler(requestContext));
        }
示例#5
0
        /// <summary>
        /// Returns a RouteDefinition object based on the current renderModel
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="publishedContentRequest"></param>
        /// <returns></returns>
        internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
        {
            var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
            var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
            //creates the default route definition which maps to the 'UmbracoController' controller
            var def = new RouteDefinition
            {
                ControllerName          = defaultControllerName,
                ControllerType          = defaultControllerType,
                PublishedContentRequest = publishedContentRequest,
                ActionName       = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
                HasHijackedRoute = false
            };

            //check that a template is defined), if it doesn't and there is a hijacked route it will just route
            // to the index Action
            if (publishedContentRequest.HasTemplate)
            {
                //the template Alias should always be already saved with a safe name.
                //if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
                // with the action name attribute.
                var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
                def.ActionName = templateName;
            }

            //check if there's a custom controller assigned, base on the document type alias.
            var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);

            //check if that controller exists
            if (controllerType != null)
            {
                //ensure the controller is of type 'IRenderMvcController' and ControllerBase
                if (TypeHelper.IsTypeAssignableFrom <IRenderMvcController>(controllerType) &&
                    TypeHelper.IsTypeAssignableFrom <ControllerBase>(controllerType))
                {
                    //set the controller and name to the custom one
                    def.ControllerType = controllerType;
                    def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
                    if (def.ControllerName != defaultControllerName)
                    {
                        def.HasHijackedRoute = true;
                    }
                }
                else
                {
                    LogHelper.Warn <RenderRouteHandler>(
                        "The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
                        () => publishedContentRequest.PublishedContent.DocumentTypeAlias,
                        () => controllerType.FullName,
                        () => typeof(IRenderMvcController).FullName,
                        () => typeof(ControllerBase).FullName);
                    //exit as we cannnot route to the custom controller, just route to the standard one.
                    return(def);
                }
            }

            //store the route definition
            requestContext.RouteData.DataTokens["umbraco-route-def"] = def;

            return(def);
        }
 /// <summary>
 /// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
 /// </summary>
 /// <param name="renderModel"></param>
 /// <param name="requestContext"></param>
 /// <param name="docRequest"></param>
 internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
 {
     //put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
     requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, renderModel);                 //required for the RenderModelBinder and view engine
     requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, docRequest); //required for RenderMvcController
     requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, UmbracoContext);       //required for UmbracoTemplatePage
 }
示例#7
0
 public bool TryFindContent(PublishedContentRequest docRequest)
 {
     return(false);
 }
        public void Render(StringWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            // instanciate a request a process
            // important to use CleanedUmbracoUrl - lowercase path-only version of the current url, though this isn't going to matter
            // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually.
            var contentRequest = new PublishedContentRequest(_umbracoContext.CleanedUmbracoUrl, _umbracoContext.RoutingContext);

            var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(PageId);

            if (doc == null)
            {
                writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", PageId);
                return;
            }

            //in some cases the UmbracoContext will not have a PublishedContentRequest assigned to it if we are not in the
            //execution of a front-end rendered page. In this case set the culture to the default.
            //set the culture to the same as is currently rendering
            if (_umbracoContext.PublishedContentRequest == null)
            {
                var defaultLanguage = Language.GetAllAsList().FirstOrDefault();
                contentRequest.Culture = defaultLanguage == null
                    ? CultureInfo.CurrentUICulture
                    : new CultureInfo(defaultLanguage.CultureAlias);
            }
            else
            {
                contentRequest.Culture = _umbracoContext.PublishedContentRequest.Culture;
            }

            //set the doc that was found by id
            contentRequest.PublishedContent = doc;
            //set the template, either based on the AltTemplate found or the standard template of the doc
            contentRequest.TemplateModel = UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates || AltTemplate.HasValue == false
                ? _umbracoContext.Application.Services.FileService.GetTemplate(doc.TemplateId)
                : _umbracoContext.Application.Services.FileService.GetTemplate(AltTemplate.Value);

            //if there is not template then exit
            if (!contentRequest.HasTemplate)
            {
                if (!AltTemplate.HasValue)
                {
                    writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId);
                }
                else
                {
                    writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", AltTemplate);
                }
                return;
            }

            //First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these
            //after this page has rendered.
            SaveExistingItems();

            try
            {
                //set the new items on context objects for this templates execution
                SetNewItemsOnContextObjects(contentRequest);

                //Render the template
                ExecuteTemplateRendering(writer, contentRequest);
            }
            finally
            {
                //restore items on context objects to continuing rendering the parent template
                RestoreItems();
            }
        }
示例#9
0
        /// <inheritdoc/>
        public virtual bool TryFindContent(PublishedContentRequest contentRequest)
        {
            IPublishedContent content = null;

            if (contentRequest.RoutingContext.UmbracoContext == null)
            {
                LogHelper.Error <DocumentTypeUrlNodeRouteHandler>(
                    "umbraco context is null! for url: " + contentRequest.Uri,
                    new ArgumentNullException(nameof(contentRequest.RoutingContext.UmbracoContext)));
                return(false);
            }

            try
            {
                if (contentRequest.RoutingContext.UmbracoContext.HttpContext.Request.Url != null)
                {
                    var path = contentRequest.RoutingContext.UmbracoContext.HttpContext.Request.Url
                               .GetAbsolutePathDecoded();
                    var parts  = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    var tmpUrl = "/";

                    // Lets try to get the content by using parts of the url until we find it.
                    for (var index = 0; index < parts.Length; index++)
                    {
                        tmpUrl += parts[index] + "/";

                        try
                        {
                            // Try to resolve it as a route.
                            content = UmbracoContext.Current.ContentCache.GetByRoute(tmpUrl);
                            if (content != null)
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            // ignored
                        }
                    }

                    if (content == null)
                    {
                        var rootNodes = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot();
                        content = rootNodes.DescendantsOrSelf(DocumentTypeAlias)
                                  .FirstOrDefault(x => x.UrlName == parts.First());
                    }
                }
            }
            catch (Exception ex)
            {
                // ignored
            }

            if (content != null && content.DocumentTypeAlias.Equals(DocumentTypeAlias))
            {
                var template = ApplicationContext.Current.Services.FileService.GetTemplate(content.TemplateId);
                if (template != null)
                {
                    contentRequest.PublishedContent = content;
                    contentRequest.TrySetTemplate(template.Alias);
                    return(true);
                }
            }

            return(false);
        }
示例#10
0
 public bool TrySetDocument(PublishedContentRequest docRequest)
 {
     return(false);
 }
示例#11
0
 public bool TryFindContent(PublishedContentRequest contentRequest)
 {
     EnsureDictionaryLoaded(contentRequest);
     return(TryRedirect(contentRequest, true) || TryRedirect(contentRequest, false));
 }
示例#12
0
        /// <summary>
        /// Processses the Umbraco Request
        /// </summary>
        /// <param name="httpContext"></param>
        /// <remarks>
        ///
        /// This will check if we are trying to route to the default back office page (i.e. ~/Umbraco/ or ~/Umbraco or ~/Umbraco/Default )
        /// and ensure that the MVC handler executes for that. This is required because the route for /Umbraco will never execute because
        /// files/folders exist there and we cannot set the RouteCollection.RouteExistingFiles = true since that will muck a lot of other things up.
        /// So we handle it here and explicitly execute the MVC controller.
        ///
        /// </remarks>
        void ProcessRequest(HttpContextBase httpContext)
        {
            // do not process if client-side request
            if (httpContext.Request.Url.IsClientSideRequest())
            {
                return;
            }

            if (UmbracoContext.Current == null)
            {
                throw new InvalidOperationException("The UmbracoContext.Current is null, ProcessRequest cannot proceed unless there is a current UmbracoContext");
            }
            if (UmbracoContext.Current.RoutingContext == null)
            {
                throw new InvalidOperationException("The UmbracoContext.RoutingContext has not been assigned, ProcessRequest cannot proceed unless there is a RoutingContext assigned to the UmbracoContext");
            }

            var umbracoContext = UmbracoContext.Current;

            //re-write for the default back office path
            if (httpContext.Request.Url.IsDefaultBackOfficeRequest())
            {
                if (EnsureIsConfigured(httpContext, umbracoContext.OriginalRequestUrl))
                {
                    RewriteToBackOfficeHandler(httpContext);
                }
                return;
            }

            // do not process but remap to handler if it is a base rest request
            if (BaseRest.BaseRestHandler.IsBaseRestRequest(umbracoContext.OriginalRequestUrl))
            {
                httpContext.RemapHandler(new BaseRest.BaseRestHandler());
                return;
            }

            // do not process if this request is not a front-end routable page
            var isRoutableAttempt = EnsureUmbracoRoutablePage(umbracoContext, httpContext);

            //raise event here
            OnRouteAttempt(new RoutableAttemptEventArgs(isRoutableAttempt.Result, umbracoContext, httpContext));
            if (!isRoutableAttempt.Success)
            {
                return;
            }


            httpContext.Trace.Write("UmbracoModule", "Umbraco request confirmed");

            // ok, process

            // note: requestModule.UmbracoRewrite also did some stripping of &umbPage
            // from the querystring... that was in v3.x to fix some issues with pre-forms
            // auth. Paul Sterling confirmed in jan. 2013 that we can get rid of it.

            // instanciate, prepare and process the published content request
            // important to use CleanedUmbracoUrl - lowercase path-only version of the current url
            var pcr = new PublishedContentRequest(umbracoContext.CleanedUmbracoUrl, umbracoContext.RoutingContext);

            umbracoContext.PublishedContentRequest = pcr;
            pcr.Prepare();

            // HandleHttpResponseStatus returns a value indicating that the request should
            // not be processed any further, eg because it has been redirect. then, exit.
            if (HandleHttpResponseStatus(httpContext, pcr))
            {
                return;
            }

            if (!pcr.HasPublishedContent)
            {
                httpContext.RemapHandler(new PublishedContentNotFoundHandler());
            }
            else
            {
                RewriteToUmbracoHandler(httpContext, pcr);
            }
        }
        // returns a value indicating whether redirection took place and the request has
        // been completed - because we don't want to Response.End() here to terminate
        // everything properly.
        internal static bool HandleHttpResponseStatus(HttpContextBase context, PublishedContentRequest pcr)
        {
            var end      = false;
            var response = context.Response;

            LogHelper.Debug <UmbracoModule>("Response status: Redirect={0}, Is404={1}, StatusCode={2}",
                                            () => pcr.IsRedirect ? (pcr.IsRedirectPermanent ? "permanent" : "redirect") : "none",
                                            () => pcr.Is404 ? "true" : "false", () => pcr.ResponseStatusCode);

            if (pcr.Cacheability != default(HttpCacheability))
            {
                response.Cache.SetCacheability(pcr.Cacheability);
            }

            foreach (var cacheExtension in pcr.CacheExtensions)
            {
                response.Cache.AppendCacheExtension(cacheExtension);
            }

            foreach (var header in pcr.Headers)
            {
                response.AppendHeader(header.Key, header.Value);
            }

            if (pcr.IsRedirect)
            {
                if (pcr.IsRedirectPermanent)
                {
                    response.RedirectPermanent(pcr.RedirectUrl, false); // do not end response
                }
                else
                {
                    response.Redirect(pcr.RedirectUrl, false); // do not end response
                }
                end = true;
            }
            else if (pcr.Is404)
            {
                response.StatusCode             = 404;
                response.TrySkipIisCustomErrors = UmbracoConfig.For.UmbracoSettings().WebRouting.TrySkipIisCustomErrors;

                if (response.TrySkipIisCustomErrors == false)
                {
                    LogHelper.Warn <UmbracoModule>("Status code is 404 yet TrySkipIisCustomErrors is false - IIS will take over.");
                }
            }

            if (pcr.ResponseStatusCode > 0)
            {
                // set status code -- even for redirects
                response.StatusCode        = pcr.ResponseStatusCode;
                response.StatusDescription = pcr.ResponseStatusDescription;
            }
            //if (pcr.IsRedirect)
            //    response.End(); // end response -- kills the thread and does not return!

            if (pcr.IsRedirect)
            {
                response.Flush();
                // bypass everything and directly execute EndRequest event -- but returns
                context.ApplicationInstance.CompleteRequest();
                // though some say that .CompleteRequest() does not properly shutdown the response
                // and the request will hang until the whole code has run... would need to test?
                LogHelper.Debug <UmbracoModule>("Response status: redirecting, complete request now.");
            }

            return(end);
        }
示例#14
0
 /// <summary>
 /// Gets the page model.
 /// </summary>
 /// <returns></returns>
 public static PageModel GetPageModel(PublishedContentRequest request)
 {
     return(new PageModel(request.PublishedContent));
 }
        /// <summary>
        /// The try find content.
        /// </summary>
        /// <param name="contentRequest">
        /// The content request.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool TryFindContent(PublishedContentRequest contentRequest)
        {
            if (contentRequest == null)
            {
                return(false);
            }

            try
            {
                using (
                    ApplicationContext.Current.ProfilingLogger.TraceDuration <MultilingualContentFinder>(
                        "Started TryFindContent",
                        "Completed TryFindContent"))
                {
                    var helper = new UmbracoHelper(UmbracoContext.Current);

                    var urls = UmbracoContext.Current.Application.ApplicationCache.RuntimeCache.GetCacheItem <List <Tuple <int, string> > >(
                        "MultilingualContentFinder-Urls",
                        () =>
                    {
                        var contentUrls = new List <Tuple <int, string> >();

                        // Get all the nodes in the website.
                        var allNodes = helper.TypedContentAtRoot().DescendantsOrSelf <UmbMaster>().ToList();

                        foreach (var node in allNodes)
                        {
                            // Get all the urls in the website.
                            // With UrlProvider.GetOtherUrls we also get the urls of the other languages.
                            contentUrls.Add(new Tuple <int, string>(node.Id, node.Url));
                            contentUrls.AddRange(UmbracoContext.Current.UrlProvider.GetOtherUrls(node.Id).Select(x => new Tuple <int, string>(node.Id, x)));
                        }

                        return(contentUrls);
                    });

                    if (urls.Any())
                    {
                        // Get the current url without querystring.
                        var url = this.RemoveQueryFromUrl(contentRequest.Uri.ToString()).EnsureEndsWith("/");

                        var currentUrlItem = urls.FirstOrDefault(x => url.InvariantEquals(x.Item2));

                        if (currentUrlItem != null)
                        {
                            var contentItem = UmbracoContext.Current.ContentCache.GetById(currentUrlItem.Item1);

                            if (contentItem != null)
                            {
                                contentRequest.PublishedContent = contentItem;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <MultilingualContentFinder>("Error in contenfinder MultilingualContentFinder", ex);
            }

            return(contentRequest.PublishedContent != null);
        }
示例#16
0
        public override bool TryFindContent(PublishedContentRequest contentRequest)
        {
            // eg / or /path/to/whatever
            var url = contentRequest.Uri.GetAbsolutePathDecoded();

            var mdRoot = "/" + MarkdownLogic.BaseUrl;

            if (url.StartsWith("/projects/umbraco-pro/contour/documentation"))
            {
                mdRoot = "/projects";
            }

            // ensure it's a md url
            if (url.StartsWith(mdRoot) == false)
            {
                return(false); // not for us
            }
            // find the root content
            var node = FindContent(contentRequest, mdRoot);

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

            // kill those old urls
            foreach (var s in new[] { "master", "v480" })
            {
                if (url.StartsWith(mdRoot + "/" + s))
                {
                    url = url.Replace(mdRoot + "/" + s, mdRoot);
                    contentRequest.SetRedirectPermanent(url);
                    return(true);
                }
            }

            // find the md file
            var mdFilepath = FindMarkdownFile(url);

            //return the broken link doc page
            var is404 = false;

            if (mdFilepath == null)
            {
                mdFilepath = FindMarkdownFile("/documentation/broken-link");
                is404      = true;
            }
            if (mdFilepath == null)
            {
                // clear the published content (that was set by FindContent) to cause a 404, and in
                // both case return 'true' because there's no point other finders try to handle the request
                contentRequest.PublishedContent = null;
                return(true);
            }

            if (is404)
            {
                contentRequest.SetIs404();
            }

            // set the context vars
            var httpContext = contentRequest.RoutingContext.UmbracoContext.HttpContext;

            httpContext.Items[MarkdownLogic.MarkdownPathKey] = mdFilepath;
            httpContext.Items["topicTitle"] = string.Join(" - ", httpContext.Request.RawUrl
                                                          .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
                                                          .Skip(1)
                                                          .Reverse());

            // override the template
            const string altTemplate   = "DocumentationSubpage";
            var          templateIsSet = contentRequest.TrySetTemplate(altTemplate);

            //httpContext.Trace.Write("Markdown Files Handler",
            //    string.Format("Template changed to: '{0}' is {1}", altTemplate, templateIsSet));

            // be happy
            return(true);
        }
        public bool TryFindContent(PublishedContentRequest contentRequest)
        {
            var stores = StoreHelper.GetAllStores();

            if (!stores.Any())
            {
                return(false);
            }

            var uwebshopRequest = UwebshopRequest.Current;
            var content         = uwebshopRequest.Product ?? uwebshopRequest.Category ?? uwebshopRequest.PaymentProvider ??     // in case ResolveUwebshopEntityUrl was already called from the module
                                  IO.Container.Resolve <IUrlRewritingService>().ResolveUwebshopEntityUrl().Entity;

            if (content is PaymentProvider)
            {
                var paymentProvider = content as PaymentProvider;

                Log.Instance.LogDebug("UmbracoDefaultAfterRequestInit paymentProvider: " + paymentProvider.Name);

                new PaymentRequestHandler().HandleuWebshopPaymentRequest(paymentProvider);

                var publishedContent = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(paymentProvider.Id);
                if (publishedContent == null)
                {
                    return(false);
                }
                contentRequest.PublishedContent = publishedContent;

                SetRequestCulture(contentRequest);
                return(true);
            }

            if (content is Category)
            {
                var categoryFromUrl = content as Category;

                if (categoryFromUrl.Disabled)
                {
                    return(false);
                }

                if (Access.HasAccess(categoryFromUrl.Id, categoryFromUrl.Path, Membership.GetUser()))
                {
                    var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id);
                    if (doc != null)
                    {
                        contentRequest.PublishedContent = doc;
                        var altTemplate = HttpContext.Current.Request["altTemplate"];
                        contentRequest.TrySetTemplate(altTemplate);

                        SetRequestCulture(contentRequest);
                        return(true);
                    }
                }
                else
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(categoryFromUrl.Path)));
                    }
                    contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(categoryFromUrl.Path)));
                    return(true);
                }
            }

            else if (content is Product)
            {
                var productFromUrl = content as Product;
                if (productFromUrl.Disabled)
                {
                    return(false);
                }

                if (Access.HasAccess(productFromUrl.Id, productFromUrl.Path, Membership.GetUser()))
                {
                    var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id);
                    if (doc != null)
                    {
                        contentRequest.PublishedContent = doc;
                        var altTemplate = HttpContext.Current.Request["altTemplate"];
                        contentRequest.TrySetTemplate(altTemplate);

                        SetRequestCulture(contentRequest);
                        return(true);
                    }
                }
                else
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(productFromUrl.Path)));
                    }
                    contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(productFromUrl.Path)));
                    return(true);
                }
            }
            return(false);
        }
示例#18
0
        private void Process(PublishedContentRequest request)
        {
            //Are we rendering a published content (sanity check)?
            if (request?.PublishedContent == null)
            {
                return;
            }

            //Are there any experiments running
            var experiments = new GetApplicableCachedExperiments
            {
                ContentId = request.PublishedContent.Id
            }.ExecuteAsync().Result;

            //variations of the same content will be applied in the order the experiments were created,
            //if they override the same property variation of the newest experiment wins
            var variationsToApply = new List <IPublishedContentVariation>();

            foreach (var experiment in experiments)
            {
                var experimentId = experiment.GoogleExperiment.Id;

                //Has the user been previously exposed to this experiment?
                var assignedVariationId = GetAssignedVariation(request, experiment.Id);
                if (assignedVariationId != null)
                {
                    var variation = GetVariation(request, experiment, assignedVariationId.Value);
                    if (variation != null)
                    {
                        variationsToApply.Add(new PublishedContentVariation(variation, experimentId, assignedVariationId.Value));
                    }
                }
                //Should the user be included in the experiment?
                else if (ShouldVisitorParticipate(experiment))
                {
                    //Choose a variation for the user
                    var variationId = SelectVariation(experiment);
                    var variation   = GetVariation(request, experiment, variationId);
                    if (variation != null)
                    {
                        variationsToApply.Add(new PublishedContentVariation(variation, experimentId, variationId));
                    }
                }
                else
                {
                    //should we assign -1 as variation (remember we showed nothing? - maybe in case we decide to exclude if say only 60% traffic is covered)
                }
            }

            //the visitor is excluded or we didn't find the content needed for variations, just show original
            if (variationsToApply.Count <= 0)
            {
                return;
            }

            var variedContent = new VariedContent(request.PublishedContent, variationsToApply.ToArray());

            request.PublishedContent = variedContent;
            request.SetIsInitialPublishedContent();

            //Reset the published content now we have set the initial content
            request.PublishedContent = PublishedContentModelFactoryResolver.Current.Factory.CreateModel(variedContent);

            request.TrySetTemplate(variedContent.GetTemplateAlias());
        }
示例#19
0
 protected virtual void PreparePublishedContentRequest(PublishedContentRequest publishedContentRequest)
 {
     publishedContentRequest.Prepare();
 }
示例#20
0
 /// <summary>
 /// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
 /// </summary>
 /// <param name="renderModel"></param>
 /// <param name="requestContext"></param>
 /// <param name="docRequest"></param>
 internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
 {
     //put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
     requestContext.RouteData.DataTokens.Add("umbraco", renderModel);             //required for the RenderModelBinder and view engine
     requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest);  //required for RenderMvcController
     requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext);  //required for UmbracoTemplatePage
 }
        public bool TryFindContent(PublishedContentRequest contentRequest)
        {
            var uri = contentRequest.Uri.GetAbsolutePathDecoded();
            // a route is "/path/to/page" when there is no domain, and "123/path/to/page" when there is a domain, and then 123 is the ID of the node which is the root of the domain
            //get domain name from Uri
            // find umbraco home node for uri's domain, and get the id of the node it is set on
            var ds                  = ApplicationContext.Current.Services.DomainService;
            var domains             = ds.GetAll(true) as IList <IDomain> ?? ds.GetAll(true).ToList();
            var domainRoutePrefixId = String.Empty;

            if (domains.Any())
            {
                // a domain is set, so I think we need to prefix the request to GetByRoute by the id of the node it is attached to.
                // I guess if the Uri contains one of these, lets use it's RootContentid as a prefix for the subsequent calls to GetByRoute...

                //A domain can be defined with or without http(s) so we neet to check for both cases.
                IDomain domain = null;
                foreach (IDomain currentDomain in domains)
                {
                    if (currentDomain.DomainName.ToLower().StartsWith("http") && contentRequest.Uri.AbsoluteUri.ToLower().StartsWith(currentDomain.DomainName.ToLower()))
                    {
                        domain = currentDomain;
                        break;
                    }
                    else if ((contentRequest.Uri.Authority.ToLower() + contentRequest.Uri.AbsolutePath.ToLower()).StartsWith(currentDomain.DomainName.ToLower()))
                    {
                        domain = currentDomain;
                        break;
                    }
                }

                if (domain != null)
                {
                    // the domain has a RootContentId that we can use as the prefix.
                    domainRoutePrefixId = domain.RootContentId.ToString();
                }
            }
            var closestContent = UmbracoContext.Current.ContentCache.GetByRoute(domainRoutePrefixId + uri.ToString(), false);

            while (closestContent == null)
            {
                uri            = uri.Remove(uri.Length - 1, 1);
                closestContent = UmbracoContext.Current.ContentCache.GetByRoute(domainRoutePrefixId + uri.ToString(), false);
            }
            var nfp = Config.GetNotFoundPage(closestContent.Id);

            while (nfp == 0)
            {
                closestContent = closestContent.Parent;

                if (closestContent == null)
                {
                    return(false);
                }

                nfp = Config.GetNotFoundPage(closestContent.Id);
            }

            var content = UmbracoContext.Current.ContentCache.GetById(nfp);

            if (content == null)
            {
                return(false);
            }

            contentRequest.PublishedContent = content;
            return(true);
        }