コード例 #1
0
        public ActionResult Edit(string path)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage aliases")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (path == "/")
            {
                path = String.Empty;
            }

            var routeValues = _aliasService.Get(path);

            if (routeValues == null)
            {
                return(HttpNotFound());
            }

            var virtualPaths = _aliasService.LookupVirtualPaths(routeValues, HttpContext)
                               .Select(vpd => vpd.VirtualPath);

            ViewBag.AliasPath = path;
            ViewBag.RoutePath = virtualPaths.FirstOrDefault();

            return(View("Edit"));
        }
コード例 #2
0
        private IContent GetContentItemForCurrentRequest()
        {
            var requestUrl       = _workContextAccessor.GetContext().HttpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(1).Trim('/');
            var requestItemRoute = _aliasService.Get(requestUrl);

            return(requestItemRoute == null?_contentManager.New("Dummy") : _contentManager.Get(Convert.ToInt32(requestItemRoute["Id"])));
        }
コード例 #3
0
        private bool IsHomePage(IContent content)
        {
            var homePageRoute = _aliasService.Get("");
            var homePageId    = homePageRoute.ContainsKey("id") ? XmlHelper.Parse <int>((string)homePageRoute["id"]) : default(int?);

            return(content.Id == homePageId);
        }
コード例 #4
0
        private bool IsHomePage(IContent content)
        {
            var homepage           = _aliasService.Get(String.Empty);
            var displayRouteValues = _contentManager.GetItemMetadata(content).DisplayRouteValues;

            return(homepage.Match(displayRouteValues));
        }
コード例 #5
0
        private ContentTreeItem GetHomepageTreeItem()
        {
            var homepage = _homeAliasService.GetHomePage();

            if (homepage == null)
            {
                var routeValues = _aliasService.Get("");
                if (routeValues == null)
                {
                    throw new InvalidOperationException("Homepage content item was not found.");
                }

                int id;
                if (!int.TryParse((string)routeValues["id"], out id))
                {
                    throw new InvalidOperationException("Homepage content item was not found.");
                }

                homepage = _contentManager.Get(id);
            }

            return(new ContentTreeItem
            {
                Content = homepage.As <ContentPart>(),
                Path = "",
                Name = "",
                Title = homepage.As <TitlePart>().Title,
                Children = new List <ContentTreeItem>(),
            });
        }
コード例 #6
0
        public RouteValueDictionary GetHomeRoute()
        {
            if (_homeAliasRoute == null)
            {
                _homeAliasRoute = _aliasService.Get(HomeAlias);
            }

            return(_homeAliasRoute);
        }
コード例 #7
0
        void RemoveAlias(AutoroutePart part)
        {
            // Is this the current home page?
            var homePageRoute = _aliasService.Get("");
            var homePageId    = homePageRoute.ContainsKey("id") ? int.Parse(homePageRoute["id"].ToString()) : default(int);

            if (part.ContentItem.Id == homePageId)
            {
                _orchardServices.Notifier.Warning(T("You removed the content item that served as the site\'s home page. \nMost possibly this means that instead of the home page a \"404 Not Found\" error page will be displayed without a link to log in or access the dashboard. \n\nTo prevent this you can e.g. publish a content item that has the \"Set as home page\" checkbox ticked."));
            }
            _autorouteService.Value.RemoveAliases(part);
        }
コード例 #8
0
        public ActionResult Index()
        {
            HttpContextBase httpContext = _orchardServices.WorkContext.HttpContext;

            RouteValueDictionary homepageRouteValueDictionary = _aliasService.Get(string.Empty);
            int routeId = Convert.ToInt32(homepageRouteValueDictionary["Id"]);

            ContentItem content = _orchardServices.ContentManager.Get(routeId, VersionOptions.Published);

            if (content == null)
            {
                return(new HttpNotFoundResult());
            }

            string        currentCultureName = _cultureManager.GetCurrentCulture(httpContext);
            AutoroutePart localizedRoutePart;

            //content may not have localized version and we use "Try" approach
            if (_localizableContentService.TryFindLocalizedRoute(content, currentCultureName, out localizedRoutePart))
            {
                string returnUrl = localizedRoutePart.Path;

                //support for Orchard < 1.6
                //TODO: discontinue in 2013 Q2
                Version orchardVersion = Utils.GetOrchardVersion();
                if (orchardVersion < new Version(1, 6))
                {
                    returnUrl = Url.Encode(returnUrl);
                }
                else
                {
                    if (!returnUrl.StartsWith("~/"))
                    {
                        returnUrl = "~/" + returnUrl;
                    }
                }

                return(this.RedirectLocal(returnUrl, (Func <ActionResult>)null));
            }

            dynamic model = _orchardServices.ContentManager.BuildDisplay(content);

            return(new ShapeResult(this, model));
        }
コード例 #9
0
        public IContent GetByPath(string aliasPath)
        {
            var contentRouting = _aliasService.Get(aliasPath);

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

            object id;

            if (contentRouting.TryGetValue("id", out id))
            {
                int contentId;
                if (int.TryParse(id as string, out contentId))
                {
                    return(_contentManager.Get(contentId));
                }
            }
            return(null);
        }
コード例 #10
0
        //Finds route part for the specified URL
        //Returns true if specified url corresponds to some content and route exists; otherwise - false

        #region ILocalizableContentService Members

        public bool TryGetRouteForUrl(string url, out AutoroutePart route)
        {
            if (string.IsNullOrWhiteSpace(url))   //look for homepage
            {
                var routeValues = _aliasService.Get(string.Empty);
                var homeCI      = _contentManager.Get(int.Parse(routeValues["Id"].ToString()));

                route = homeCI.As <AutoroutePart>();
            }
            else
            {
                //first check for route (fast, case sensitive, not precise)
                route = _contentManager.Query <AutoroutePart, AutoroutePartRecord>()
                        .ForVersion(VersionOptions.Published)
                        .Where(r => r.DisplayAlias == url)
                        .List()
                        .FirstOrDefault();
            }

            return(route != null);
        }
コード例 #11
0
        public int GetCurrentContentId()
        {
            var currentContentItemId = 0;
            var request = _hca.Current().Request;
            var path    = request.AppRelativeCurrentExecutionFilePath.Substring(1).Trim('/');

            var itemRoute = _aliasService.Get(path);

            if (itemRoute != null)
            {
                currentContentItemId = Convert.ToInt32(itemRoute["Id"]);
            }
            else
            {
                if (path.StartsWith("Contents/Item/Display/") || path.StartsWith("Contents/Item/Preview/"))
                {
                    currentContentItemId = Convert.ToInt32(request.RequestContext.RouteData.Values["Id"]);
                }
            }

            return(currentContentItemId);
        }
コード例 #12
0
        private CultureSelectorResult EvaluateResult(HttpContextBase context)
        {
            if (context == null || context.Request == null)
            {
                return(null);
            }

            //TODO: check for a more efficient way to get content item for the current request
            string relativePath = Utils.GetAppRelativePath(context.Request.Url.AbsolutePath, context.Request);

            relativePath = HttpUtility.UrlDecode(relativePath);
            RouteValueDictionary routeValueDictionary = _aliasService.Get(relativePath);

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

            int routeId = Convert.ToInt32(routeValueDictionary["Id"]);

            ContentItem content = _orchardServices.ContentManager.Get(routeId, VersionOptions.Published);

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

            //NOTE: we can't use ILocalizationService.GetContentCulture for this, because it causes circular dependency
            var localized = content.As <ILocalizableAspect>();

            if (localized == null || string.IsNullOrEmpty(localized.Culture))
            {
                return(null);
            }

            return(new CultureSelectorResult {
                Priority = SelectorPriority, CultureName = localized.Culture
            });
        }
コード例 #13
0
        public IContent GetContentForRequest()
        {
            if (_contentWasChecked)
            {
                return(_contentForRequest);
            }

            _contentWasChecked = true;

            // Checking if the page we're currently on is a content item
            var itemRoute = _aliasService.Get(_workContextAccessor.GetContext().HttpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(1).TrimStart('/'));

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

            var itemId = Convert.ToInt32(itemRoute["Id"]);

            _contentForRequest = _contentManager.Get(itemId);

            return(_contentForRequest);
        }
コード例 #14
0
        public IEnumerable <MenuItem> Filter(IEnumerable <MenuItem> items)
        {
            foreach (var item in items)
            {
                if (item.Content != null && item.Content.ContentItem.ContentType == "AliasBreadcrumbMenuItem")
                {
                    var request       = _hca.Current().Request;
                    var path          = request.Path;
                    var appPath       = request.ApplicationPath ?? "/";
                    var requestUrl    = (path.StartsWith(appPath) ? path.Substring(appPath.Length) : path).TrimStart('/');
                    var endsWithSlash = requestUrl.EndsWith("/");

                    var menuPosition = item.Position;

                    var urlLevel  = endsWithSlash ? requestUrl.Count(l => l == '/') - 1 : requestUrl.Count(l => l == '/');
                    var menuLevel = menuPosition.Count(l => l == '.');

                    // Checking the menu item whether it's the leaf element or it's an intermediate element
                    // or it's an unneccessary element according to the url.
                    RouteValueDictionary contentRoute;
                    if (menuLevel == urlLevel)
                    {
                        contentRoute = request.RequestContext.RouteData.Values;
                    }
                    else
                    {
                        // If menuLevel doesn't equal to urlLevel it can mean that this menu item is
                        // an intermediate element (the difference is a positive value) or this menu
                        // item is lower in the navigation hierarchy according to the url (negative
                        // value). If the value is negative, removing the menu item, if the value
                        // is positive finding its place in the hierarchy.
                        var levelDifference = urlLevel - menuLevel;
                        if (levelDifference > 0)
                        {
                            if (endsWithSlash)
                            {
                                levelDifference += levelDifference;
                            }
                            for (int i = 0; i < levelDifference; i++)
                            {
                                requestUrl = requestUrl.Remove(requestUrl.LastIndexOf('/'));
                                path       = path.Remove(path.LastIndexOf('/'));
                            }
                            contentRoute = _aliasService.Get(requestUrl);
                            if (contentRoute == null)
                            {
                                // After the exact number of segments is cut out from the url and the
                                // currentRoute is still null, trying another check with the added slash,
                                // because we don't know if the alias was created with a slash at the end or not.
                                contentRoute = _aliasService.Get(requestUrl.Insert(requestUrl.Length, "/"));
                                path         = path.Insert(path.Length, "/");
                                if (contentRoute == null)
                                {
                                    contentRoute = new RouteValueDictionary();
                                }
                            }
                        }
                        else
                        {
                            contentRoute = new RouteValueDictionary();
                        }
                    }

                    object id;
                    contentRoute.TryGetValue("Id", out id);
                    int contentId;
                    int.TryParse(id as string, out contentId);
                    if (contentId == 0)
                    {
                        // If failed to get the Id's value from currentRoute, transform the alias to the virtual path
                        // and try to get the content item's id from there. E.g. "Blogs/Blog/Item?blogId=12" where
                        // the last digits represents the content item's id. If there is a match in the path we get
                        // the digits after the equality sign.
                        // There is an another type of the routes: like "Contents/Item/Display/13", but when the
                        // content item's route is in this form we already have the id from contentRoute.TryGetValue("Id", out id).
                        var virtualPath = _aliasService.LookupVirtualPaths(contentRoute, _hca.Current()).FirstOrDefault();
                        int.TryParse(virtualPath != null ? virtualPath.VirtualPath.Substring(virtualPath.VirtualPath.LastIndexOf('=') + 1) : "0", out contentId);
                    }
                    if (contentId != 0)
                    {
                        var currentContentItem = _contentManager.Get(contentId);
                        if (currentContentItem != null)
                        {
                            var menuText = _contentManager.GetItemMetadata(currentContentItem).DisplayText;
                            var routes   = _contentManager.GetItemMetadata(currentContentItem).DisplayRouteValues;

                            var inserted = new MenuItem {
                                Text             = new LocalizedString(menuText),
                                IdHint           = item.IdHint,
                                Classes          = item.Classes,
                                Url              = path,
                                Href             = item.Href,
                                LinkToFirstChild = false,
                                RouteValues      = routes,
                                LocalNav         = item.LocalNav,
                                Items            = Enumerable.Empty <MenuItem>(),
                                Position         = menuPosition,
                                Permissions      = item.Permissions,
                                Content          = item.Content
                            };

                            yield return(inserted);
                        }
                    }
                }
                else
                {
                    yield return(item);
                }
            }
        }
        public void ApplyFilter(dynamic context)
        {
            var httpContext = _orchardServices.WorkContext.HttpContext;
            var path        = httpContext.Request.AppRelativeCurrentExecutionFilePath.Replace("~/", string.Empty);

            var routeValues = _aliasService.Get(path);

            if (routeValues == null)
            {
                return;
            }

            object id;

            if (routeValues.TryGetValue("id", out id))
            {
                var castedId = Convert.ToInt32(id);
                var ids      = _taxonomyService.GetTermsForContentItem(castedId).Select(o => o.Id).ToList();

                if (ids.Any())
                {
                    int op         = Convert.ToInt32(context.State.Operator);
                    int?taxonomyId = context.State.TaxonomyId != null?Convert.ToInt32(context.State.TaxonomyId) : default(int?);

                    var terms       = ids.Select(_taxonomyService.GetTerm);
                    var allChildren = new List <TermPart>();

                    if (taxonomyId != null)
                    {
                        var selectedTerm = _taxonomyService.GetTermsForContentItem(castedId).FirstOrDefault(x => x.TaxonomyId == taxonomyId);

                        if (selectedTerm != null)
                        {
                            terms = terms.Where(x => x.Id == selectedTerm.Id);
                        }
                    }

                    foreach (var term in terms)
                    {
                        allChildren.AddRange(_taxonomyService.GetChildren(term));
                        allChildren.Add(term);
                    }

                    allChildren = allChildren.Distinct().ToList();

                    var predicates = allChildren.Select(localTerm => (Action <IHqlExpressionFactory>)(a => a.Eq("Id", localTerm.Id))).ToList();

                    switch (op)
                    {
                    case 0:
                        // is one of
                        Action <IAliasFactory>         selector1 = alias => alias.ContentPartRecord <TermsPartRecord>().Property("Terms", "terms").Property("TermRecord", "termRecord");
                        Action <IHqlExpressionFactory> filterA   = x => x.Disjunction(predicates.Take(1).Single(), predicates.Skip(1).ToArray());
                        context.Query.Where(selector1, filterA);

                        if (context.State.IncludeSelf == null)
                        {
                            Action <IAliasFactory>         selector2  = alias => alias.ContentItem();
                            Action <IHqlExpressionFactory> filter2    = x => x.Eq("Id", castedId);
                            Action <IHqlExpressionFactory> filter2Not = x => x.Not(filter2);
                            context.Query.Where(selector2, filter2Not);
                        }

                        break;

                    case 1:
                        // is not one of
                        Action <IAliasFactory>         selector = alias => alias.ContentPartRecord <TermsPartRecord>().Property("Terms", "terms").Property("TermRecord", "termRecord");
                        Action <IHqlExpressionFactory> filterB  = x => x.Disjunction(predicates.Take(1).Single(), predicates.Skip(1).ToArray());
                        context.Query.Where(selector, filterB);
                        break;

                    case 2:
                        // is all of
                        break;
                    }
                }
            }
        }
コード例 #16
0
        protected override DriverResult Editor(AutoroutePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var settings = part.TypePartDefinition.Settings.GetModel <AutorouteSettings>();

            // if the content type has no pattern for autoroute, then use a default one
            if (!settings.Patterns.Any())
            {
                settings.AllowCustomPattern        = true;
                settings.AutomaticAdjustmentOnEdit = false;
                settings.DefaultPatternIndex       = 0;
                settings.Patterns = new List <RoutePattern> {
                    new RoutePattern {
                        Name = "Title", Description = "my-title", Pattern = "{Content.Slug}"
                    }
                };

                _notifier.Warning(T("No route patterns are currently defined for this Content Type. If you don't set one in the settings, a default one will be used."));
            }

            var viewModel = new AutoroutePartEditViewModel {
                CurrentUrl = part.DisplayAlias,
                Settings   = settings
            };

            // retrieve home page
            var homepage           = _aliasService.Get(string.Empty);
            var displayRouteValues = _contentManager.GetItemMetadata(part).DisplayRouteValues;

            if (homepage.Match(displayRouteValues))
            {
                viewModel.PromoteToHomePage = true;
            }

            if (settings.PerItemConfiguration)
            {
                // if enabled, the list of all available patterns is displayed, and the user can
                // select which one to use

                // todo: later
            }

            var previous = part.DisplayAlias;

            if (updater != null && updater.TryUpdateModel(viewModel, Prefix, null, null))
            {
                // remove any trailing slash in the permalink
                while (!string.IsNullOrEmpty(viewModel.CurrentUrl) && viewModel.CurrentUrl.StartsWith("/"))
                {
                    viewModel.CurrentUrl = viewModel.CurrentUrl.Substring(1);
                }

                part.DisplayAlias = viewModel.CurrentUrl;

                // reset the alias if we need to force regeneration, and the user didn't provide a custom one
                if (settings.AutomaticAdjustmentOnEdit && previous == part.DisplayAlias)
                {
                    part.DisplayAlias = string.Empty;
                }

                if (!_autorouteService.IsPathValid(part.DisplayAlias))
                {
                    updater.AddModelError("CurrentUrl", T("Please do not use any of the following characters in your permalink: \":\", \"?\", \"#\", \"[\", \"]\", \"@\", \"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\", \", \"<\", \">\", \"\\\", \"|\", \"%\", \".\". No spaces are allowed (please use dashes or underscores instead)."));
                }

                // if CurrentUrl is set, the handler won't try to create an alias for it
                // but instead keep the value

                // if home page is requested, use "/" to have the handler create a homepage alias
                if (viewModel.PromoteToHomePage)
                {
                    part.DisplayAlias = "/";
                }
            }

            var usr = _orchardServices.WorkContext.CurrentUser;
            var r   = usr.As <UserRolesPart>();

            if (r.Roles.Any(p => p == "vendedor"))
            {
                viewModel.FixedPart  = string.Concat("tiendas/", usr.UserName, "/");
                viewModel.CurrentUrl = viewModel.CurrentUrl.Replace(viewModel.FixedPart, "");
            }



            return(ContentShape("Parts_Autoroute_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Autoroute.Edit", Model: viewModel, Prefix: Prefix)));
        }
コード例 #17
0
ファイル: IHomePageService.cs プロジェクト: YSRE/SuperRocket
        public bool ShouldBeTranslated(ActionExecutingContext actionContext, out string newUrl)
        {
            newUrl = null;
            var controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName     = actionContext.ActionDescriptor.ActionName;

            if (controllerName == null)
            {
                controllerName = string.Empty;
            }
            if (actionName == null)
            {
                actionName = string.Empty;
            }
            if (!string.Equals(controllerName, "Item", StringComparison.InvariantCultureIgnoreCase) ||
                !string.Equals(actionName, "Display", StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            var settings = GetSettings();

            if (settings == null || !settings.Enabled)
            {
                Logger.Debug("ShouldBeTranslated: Home Pages Settings disabled.");
                return(false);
            }
            var currentCulture = _cultureService.GetCurrentCulture();

            if (string.IsNullOrWhiteSpace(currentCulture))
            {
                Logger.Debug("ShouldBeTranslated: Current Culture null.");
                return(false);
            }

            // Look for Home Page
            RouteValueDictionary homepageRouteValueDictionary = _aliasService.Get(string.Empty);
            int         routeId = Convert.ToInt32(homepageRouteValueDictionary["Id"]);
            ContentItem content = _orchardServices.ContentManager.Get(routeId, VersionOptions.Published);

            if (content == null)
            {
                Logger.Debug(string.Format("ShouldBeTranslated: Object not found for Home Page Id={0}", routeId));
                return(false);
            }
            IEnumerable <Tuple <string, int> > HPLocalizations = _cultureService.GetLocalizationsIds(content);

            //var routeData       = new RouteData();
            int ItemId = -1;

            foreach (var routeValue in actionContext.RequestContext.RouteData.Values)
            {
                //routeData.Values[routeValue.Key] = routeValue.Value;
                if (string.Equals(routeValue.Key, "id", StringComparison.InvariantCultureIgnoreCase))
                {
                    string IdStr = routeValue.Value as string;
                    if (IdStr != null)
                    {
                        int Id = -1;
                        if (int.TryParse(IdStr, out Id))
                        {
                            ItemId = Id;
                        }
                    }
                }
            }
            // Is the request concerning homepage ?
            bool isHomepageRequest = HPLocalizations.Where(t => t.Item2 == ItemId).Any();
            var  context           = actionContext.HttpContext;

            if (context == null)
            {
                context = _workContextAccessor.GetContext().HttpContext;
            }
            if (ItemId == -1)
            {
                Logger.Debug(string.Format("ShouldBeTranslated: No contentItem found for route {0}.", (context.Request != null) ? context.Request.Path: "No Request"));
                return(false);
            }

            if (!settings.AllPages && !isHomepageRequest)
            {
                Logger.Debug("ShouldBeTranslated: Settings set for Home Page only.");
                return(false);
            }

            var siteCulture = _cultureService.GetSiteCulture();

            if (isHomepageRequest)
            {
                if (routeId == ItemId)
                {
                    if (string.Equals(currentCulture, siteCulture, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // this is the correct culture for this Id
                        return(false);
                    }
                }
                else
                {
                    // Does the required Id correspond to current culture
                    Tuple <string, int> contenTuple = HPLocalizations.Where(t => t.Item2 == ItemId).FirstOrDefault();
                    if (string.Equals(contenTuple.Item1, currentCulture, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(false);
                    }
                    //we must find the content for current culture
                }
            }
            else
            {
                // get the required content
                content = _orchardServices.ContentManager.Get(ItemId, VersionOptions.Published);
                if (content == null)
                {
                    Logger.Debug(string.Format("ShouldBeTranslated: Object not found for target Page where Id={0}", ItemId));
                    return(false);
                }
                HPLocalizations = _cultureService.GetLocalizationsIds(content);
            }
            // is there a localization for current culture
            Tuple <string, int> contentLoc = HPLocalizations.Where(t => t.Item1 == currentCulture).FirstOrDefault();

            if (contentLoc != null)
            {
                if (contentLoc.Item2 == ItemId)
                {
                    return(false); // no reroute needed
                }
                return(FindRoute(HPLocalizations, ItemId, currentCulture, out newUrl));
            }
            // Invoke the fallback rules
            return(FindUrlFromFallbackCulture(content, currentCulture, context.Request.RequestContext, out newUrl, ItemId, HPLocalizations, siteCulture, true));

            /*
             * switch( settings.FallBackMode)
             * {
             *  case CultureFallbackMode.FallbackToSite:
             *      break;
             *  case CultureFallbackMode.FallbackToFirstExisting:
             *      return false;
             *  case CultureFallbackMode.ShowExistingTranslations:
             *      UrlHelper urlHelper                         = new UrlHelper(context.Request.RequestContext);
             *      newUrl                                      = urlHelper.RouteUrl(new { Area = "Datwendo.Localization", Action = "NotTranslated", Controller = "LocalizedHome", Culture = currentCulture, Id = ItemId });
             *      return true;
             *  case CultureFallbackMode.UseRegex:
             *      if (!string.IsNullOrWhiteSpace(settings.FallBackRegex))
             *      {
             *          string regExCulture = _cultureService.CultureFromRegEx(currentCulture, settings.FallBackRegex);
             *          if (!string.IsNullOrWhiteSpace(regExCulture))
             *              return FindRoute(HPLocalizations, ItemId, regExCulture, out newUrl);
             *      }
             *      break;
             * }
             * return FindRoute(HPLocalizations, ItemId,siteCulture, out newUrl);
             * */
        }
コード例 #18
0
        private CultureSelectorResult EvaluateResult(HttpContextBase context)
        {
            if (context == null || context.Request == null)
            {
                return(null);
            }

            if (AdminFilter.IsApplied(context.Request.RequestContext))   // I am in admin context so I have to use defualt site culture
            {
                return(new CultureSelectorResult {
                    Priority = SelectorPriority, CultureName = _orchardServices.WorkContext.CurrentSite.SiteCulture
                });
            }

            //TODO: check for a more efficient way to get content item for the current request
            string relativePath = Utils.GetAppRelativePath(context.Request.Url.AbsolutePath, context.Request);
            var    urlPrefix    = _orchardServices.WorkContext.Resolve <ShellSettings>().RequestUrlPrefix;

            if (!String.IsNullOrWhiteSpace(urlPrefix))
            {
                relativePath = relativePath.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase) ? relativePath.Substring(urlPrefix.Length) : relativePath;
            }
            relativePath = relativePath.StartsWith("/") ? relativePath.Substring(1) : relativePath;
            relativePath = HttpUtility.UrlDecode(relativePath);

            if (context.Request != null && context.Request.RequestContext.RouteData != null && context.Request.RequestContext.RouteData.Values["controller"] != null)
            {
                if (context.Request.RequestContext.RouteData.Values["controller"].ToString().ToLower() == "blogpost" && relativePath.IndexOf("/archive") > -1)
                {
                    relativePath = relativePath.Substring(0, relativePath.IndexOf("/archive")); // prendo sull'url che definisce il blog
                }
            }
            RouteValueDictionary routeValueDictionary = _aliasService.Get(relativePath);

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

            int routeId = Convert.ToInt32(routeValueDictionary["Id"]); //Convert.ToInt32(null) == 0

            if (routeId == 0)
            {
                routeId = Convert.ToInt32(routeValueDictionary["blogId"]); //forse è un blog?
            }

            ContentItem content = _orchardServices.ContentManager.Get(routeId, VersionOptions.Published);

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

            //NOTE: we can't use ILocalizationService.GetContentCulture for this, because it causes circular dependency
            var    localized          = content.As <ILocalizableAspect>();
            string currentCultureName = "";

            if (localized == null)
            {
                var term = content.As <TermPart>();
                if (term == null)
                {
                    return(null); // non ha la localization part e non ha nemmeno una tassonomia tradotta
                }
                else
                {
                    // verifico se per caso sto visualizzando una termPart che è figlia di una tassonomia tradottta: in tal caso la culture deve essere quella della tassonomia
                    localized = _orchardServices.ContentManager.Get(term.TaxonomyId).As <ILocalizableAspect>();
                    if (localized == null)
                    {
                        return(null);
                    }
                    else
                    {
                        currentCultureName = localized.Culture;
                    }
                }
            }
            else if (string.IsNullOrEmpty(localized.Culture))
            {
                // ha la localization part, ma non è tradotta => prendo la site culture
                currentCultureName = _orchardServices.WorkContext.CurrentSite.SiteCulture;
            }
            else
            {
                currentCultureName = localized.Culture;
            }

            _cpServices.SaveCultureCookie(currentCultureName, context);
            return(new CultureSelectorResult {
                Priority = SelectorPriority, CultureName = currentCultureName
            });
        }
コード例 #19
0
 public RouteValueDictionary GetHomeRoute()
 {
     return(_aliasService.Get(HomeAlias));
 }