示例#1
0
        public CultureAlternatesFactory(ICultureService cultureService, IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _cultureService      = cultureService;
            _HomePageAlternates  = new Lazy <string>(() => {
                var httpContext = _httpContextAccessor.Current();

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

                var request = httpContext.Request;

                if (request == null)
                {
                    return(null);
                }
                string culture = _cultureService.GetCurrentCulture();
                // extract each segment of the url
                var urlSegments = VirtualPathUtility.ToAppRelative(request.Path.ToLower())
                                  .Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
                                  .Skip(1) // ignore the heading ~ segment
                                  .ToArray();
                int cnt = urlSegments.Count();
                if (cnt == 0 || ((cnt == 1) && string.Equals(urlSegments[0], culture, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return("__CultureHomepage");
                }

                return(null);
            });
        }
示例#2
0
        public ActionResult NotTranslated(string culture, int?id)
        {
            ViewBag.Culture       = culture ?? _cultureService.GetCurrentCulture();
            ViewBag.ContentItem   = id.HasValue ? _orchardServices.ContentManager.Get(id.Value) : null;
            ViewBag.Localizations = ViewBag.ContentItem != null?_cultureService.GetLocalizations((ViewBag.ContentItem as IContent).As <LocalizationPart>(), VersionOptions.Latest).ToArray() : new LocalizationPart[0];

            return(View("NotTranslated"));
        }
示例#3
0
        protected override DriverResult Display(CookieCulturePickerPart part, string displayType, dynamic shapeHelper)
        {
            var urlHelper          = new UrlHelper(_orchardServices.WorkContext.HttpContext.Request.RequestContext);
            var cookieCultureItems = new List <CookieCultureItemViewModel>();
            // Is content item shown?
            var contentItem    = _cultureService.GetCurrentContentItem();
            var currentCulture = _cultureService.GetCurrentCulture();
            var returnUrl      = _orchardServices.WorkContext.HttpContext.Request.Url.LocalPath;
            var localizations  = contentItem != null?_cultureService.GetLocalizations(contentItem.As <LocalizationPart>(), VersionOptions.Latest).ToList() : null;

            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.IndexOf("/NotTranslated", StringComparison.OrdinalIgnoreCase) > 0)
            {
                returnUrl = urlHelper.Content("~/");
            }

            foreach (var cultureItem in _cultureService.ListCultures())
            {
                var cookieCultureItem = new CookieCultureItemViewModel
                {
                    CultureItem = cultureItem,
                    Current     = string.Equals(currentCulture, cultureItem.Culture, StringComparison.OrdinalIgnoreCase),
                    ReturnUrl   = returnUrl,
                    Rel         = contentItem == null ? "nofollow" : null
                };
                if (localizations != null)
                {
                    var localizedContentItem = localizations.Where(p => string.Equals(p.Culture.Culture, cultureItem.Culture, StringComparison.OrdinalIgnoreCase)).Select(p => p.ContentItem).FirstOrDefault();
                    var metadata             = localizedContentItem != null?localizedContentItem.ContentManager.GetItemMetadata(localizedContentItem) : null;

                    if (metadata != null && metadata.DisplayRouteValues != null)
                    {
                        cookieCultureItem.ReturnUrl = urlHelper.Content(urlHelper.RouteUrl(metadata.DisplayRouteValues));
                    }
                    else
                    {
                        cookieCultureItem.ReturnUrl = urlHelper.RouteUrl(new { Area = "RM.Localization", Action = "NotTranslated", Controller = "LocalizedHome", Culture = cultureItem.Culture, Id = contentItem.Id });
                        cookieCultureItem.Rel       = "nofollow";
                    }
                }
                cookieCultureItems.Add(cookieCultureItem);
            }

            if (part.Style == Styles[1])
            {
                return(ContentShape("Parts_CookieCulturePicker", () => shapeHelper.Parts_DropdownCookieCulturePicker(Cultures: cookieCultureItems, CurrentCulture: currentCulture)));
            }
            else
            {
                return(ContentShape("Parts_CookieCulturePicker", () => shapeHelper.Parts_InlineListCookieCulturePicker(Cultures: cookieCultureItems, CurrentCulture: currentCulture)));
            }
        }
示例#4
0
        public async Task InvokeAsync(HttpContext context, ICultureService cultureService)
        {
            var currentCulture = cultureService.GetCurrentCulture();

            if (!string.IsNullOrWhiteSpace(currentCulture))
            {
                var langCulture = new CultureInfo(currentCulture);
                var culture     = CultureInfo.CreateSpecificCulture(langCulture.Name);
                culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
                CultureInfo.CurrentCulture   = culture;
                CultureInfo.CurrentUICulture = culture;
            }
            await _next(context);
        }
示例#5
0
        public ActionResult RedirectToCulture()
        {
            // Add check for existing translation and redirect to nottranslated page
            var currentCulture = _cultureService.GetCurrentCulture();

            if (string.IsNullOrWhiteSpace(currentCulture))
            {
                currentCulture = _cultureService.GetSiteCulture();
            }

            var context     = _workContextAccessor.GetContext(HttpContext);
            var aliasHolder = context.Resolve <IAliasHolder>();
            var aliasMap    = aliasHolder.GetMap("Contents");

            currentCulture = currentCulture.ToLower();
            IDictionary <string, string> routeValues = null;

            if (aliasMap.TryGetAlias(currentCulture, out routeValues))
            {
                return(Redirect(Url.Content("~/" + currentCulture)));
            }

            return(RedirectToRoute(new { Area = "RM.Localization", Action = "NotTranslated", Controller = "LocalizedHome", Culture = currentCulture }));
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            await Task.Yield();

            var lang             = _cultureService.GetCurrentCulture();
            var key              = lang.Length >= 2 ? lang.Substring(0, 2) : "pl";
            var supportedLangDic = _cultureService.GetSupportedLanguages();

            var vm = supportedLangDic.TryGetValue(key, out var culture)
                ? culture
                : supportedLangDic.Values.First();

            TempData[TempDataKeys.CultureKey]           = vm.key;
            TempData[TempDataKeys.ReturnUrlFromCulture] = Request.Headers["Referer"].ToString();
            return(View(new LanguageVM(vm.key, vm.caption)));
        }
示例#7
0
        protected override DriverResult Display(CookieCulturePickerPart part, string displayType, dynamic shapeHelper)
        {
            var userCultures = _curentUserCulturesProvider.GetCulturesForCurrentUser();
            var l            = _cultureService.ListCultures().Where(c => userCultures.Contains(c.Culture));

            var result = ContentShape("Parts_CookieCulturePicker",
                                      () => shapeHelper.Parts_CookieCulturePicker(
                                          Cultures: l, CurrentCulture: _cultureService.GetCurrentCulture()
                                          )
                                      );

            return(result);

            //var result = ContentShape("Parts_CookieCulturePicker",
            //        () => shapeHelper.Parts_CookieCulturePicker(
            //            Cultures: _cultureService.ListCultures(), CurrentCulture: _cultureService.GetCurrentCulture()
            //            )
            //    );
        }
示例#8
0
        public void GetNavigation(NavigationBuilder builder)
        {
            var cultures           = _cultureService.ListCultures();
            var currentCultureName = _cultureService.GetCurrentCulture();
            var currentCulture     = cultures.FirstOrDefault(x => x.Culture == currentCultureName);

            builder.Add(T(currentCulture != null ? currentCulture.FullName : currentCultureName), "-2", menu => {
                menu.AddClass("section-dashboard");
                menu.LinkToFirstChild(false);
                foreach (var c in cultures)
                {
                    if (c.Culture == currentCultureName)
                    {
                        continue;
                    }
                    menu.Add(T(c.FullName), item => item.Action("SetCulture", "CookieCulture", new { Area = "RM.Localization", culture = c.Culture, returnUrl = _workContextAccessor.GetContext().HttpContext.Request.ToUrlString() }));
                }
                menu.Add(T("Reset"), item => item.Action("ResetCulture", "CookieCulture", new { Area = "RM.Localization", returnUrl = _workContextAccessor.GetContext().HttpContext.Request.ToUrlString() }));
            }, null);
        }
示例#9
0
        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);
             * */
        }
示例#10
0
        public override void Displaying(ShapeDisplayingContext context)
        {
            context.ShapeMetadata.OnDisplaying(displayedContext =>
            {
                string culture = _cultureService.GetCurrentCulture();
                if (string.IsNullOrEmpty(culture))
                {
                    return;
                }

                int idx            = culture.IndexOf('-');
                var parentCulture  = (idx > 0) ? culture.Substring(0, idx) : null;
                var countryCulture = (idx > 0) ? culture.Substring(idx + 1) : null;
                culture            = culture.Replace("-", string.Empty);
                var cultureTag     = "__" + culture;

                // prevent applying alternate again, c.f. http://orchard.codeplex.com/workitem/18298
                if (displayedContext.ShapeMetadata.Alternates.Any(x => x.Contains(cultureTag)))
                {
                    return;
                }
                var countryTag = (countryCulture != null) ? "__" + countryCulture : null;
                var parentTag  = (parentCulture != null) ?  "__" + parentCulture : null;


                List <string> _cultureAlternates = new List <string>(new string[] { cultureTag, countryTag, parentTag });

                // appends culture alternates to current ones
                displayedContext.ShapeMetadata.Alternates = displayedContext.ShapeMetadata.Alternates.SelectMany(
                    alternate => new [] { alternate }.Union(_cultureAlternates.Select(a =>
                {
                    int id = alternate.IndexOf("__");
                    if (id > 0)
                    {
                        return(alternate.Substring(0, id) + a + alternate.Substring(id));
                    }
                    return(alternate + a);
                }))).ToList();

                // appends [ShapeType]__culture__[Culture] alternates
                displayedContext.ShapeMetadata.Alternates = _cultureAlternates.Select(cult => displayedContext.ShapeMetadata.Type + "__culture" + cult)
                                                            .Union(displayedContext.ShapeMetadata.Alternates)
                                                            .ToList();

                if (_HomePageAlternates.Value != null)
                {
                    _cultureAlternates.Clear();
                    string homeTag = _HomePageAlternates.Value;
                    _cultureAlternates.Add(homeTag);
                    _cultureAlternates.Add(homeTag + cultureTag);
                    if (countryCulture != null)
                    {
                        _cultureAlternates.Add(homeTag + countryTag);
                    }
                    if (parentCulture != null)
                    {
                        _cultureAlternates.Add(homeTag + parentTag);
                    }

                    // appends [ShapeType]__CultureHomepage__[Culture] alternates
                    displayedContext.ShapeMetadata.Alternates = _cultureAlternates.Select(cult => displayedContext.ShapeMetadata.Type + cult)
                                                                .Union(displayedContext.ShapeMetadata.Alternates)
                                                                .ToList();
                }
            });
        }