Esempio n. 1
0
        public void ListCultures()
        {
            Context.Output.WriteLine(T("Listing Cultures:"));

            var cultures = string.Join(" ", _cultureManager.ListCultures());

            Context.Output.WriteLine(cultures);
        }
        public void ListCultures()
        {
            Context.Output.WriteLine(T("Listing Cultures:"));

            string cultures = _cultureManager.ListCultures().Aggregate <string, string>(null, (current, culture) => current + culture + " ");

            Context.Output.WriteLine(cultures);
        }
Esempio n. 3
0
        protected override DriverResult Editor(SiteSettingsPart part, dynamic shapeHelper)
        {
            var site = _siteService.GetSiteSettings().As <SiteSettingsPart>();

            var model = new SiteSettingsPartViewModel {
                Site         = site,
                SiteCultures = _cultureManager.ListCultures(),
                TimeZones    = TimeZoneInfo.GetSystemTimeZones()
            };

            return(ContentShape("Parts_Settings_SiteSettingsPart",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Settings.SiteSettingsPart", Model: model, Prefix: Prefix)));
        }
Esempio n. 4
0
        protected override DriverResult Display(LocalizationPart part, string displayType, dynamic shapeHelper) {

            return Combined(
                ContentShape("Parts_Localization_ContentTranslations",
                             () => shapeHelper.Parts_Localization_ContentTranslations(Id: part.ContentItem.Id, MasterId: ActualMasterId(part), Culture: GetCulture(part), Localizations: GetDisplayLocalizations(part, VersionOptions.Published))),
                ContentShape("Parts_Localization_ContentTranslations_Summary",
                             () => shapeHelper.Parts_Localization_ContentTranslations_Summary(Id: part.ContentItem.Id, MasterId: ActualMasterId(part), Culture: GetCulture(part), Localizations: GetDisplayLocalizations(part, VersionOptions.Published))),
                ContentShape("Parts_Localization_ContentTranslations_SummaryAdmin", () => {
                    var siteCultures = _cultureManager.ListCultures();

                    return shapeHelper.Parts_Localization_ContentTranslations_SummaryAdmin(Id: part.ContentItem.Id, MasterId: ActualMasterId(part), Culture: GetCulture(part), Localizations: GetDisplayLocalizations(part, VersionOptions.Latest), SiteCultures: siteCultures, ContentPart: part);
                })
                );
        }
        private List <string> RetrieveMissingCultures(LocalizationPart part, bool excludePartCulture)
        {
            var editorLocalizations = GetEditorLocalizations(part);
            var cultures            = _cultureManager
                                      .ListCultures()
                                      .Where(s => editorLocalizations.All(l => l.Culture.Culture != s))
                                      .ToList();

            if (excludePartCulture)
            {
                cultures.Remove(part.Culture.Culture);
            }
            return(cultures);
        }
Esempio n. 6
0
        public void RemoveSiteCulture(string cultureName)
        {
            Context.Output.WriteLine(T("Removing site culture {0}", cultureName));

            if (!_cultureManager.IsValidCulture(cultureName))
            {
                Context.Output.WriteLine(T("Supplied culture name {0} is not valid.", cultureName));
                return;
            }
            if (_orchardServices.WorkContext.CurrentSite.SiteCulture == cultureName)
            {
                Context.Output.WriteLine(T("Cannot remove current culture {0} from site. Change current culture first.", cultureName));
                return;
            }

            var cultureCheck = _cultureManager.ListCultures().FirstOrDefault(x => x == cultureName);

            if (string.IsNullOrEmpty(cultureCheck))
            {
                Context.Output.WriteLine(T("Culture {0} is not activated on this site.", cultureName));
                return;
            }
            _cultureManager.DeleteCulture(cultureName);

            Context.Output.WriteLine(T("Site culture {0} removed successfully", cultureName));
        }
Esempio n. 7
0
        protected override DriverResult Display(CulturePickerPart part, string displayType, dynamic shapeHelper)
        {
            part.AvailableCultures = _cultureManager.ListCultures();
            part.UserCulture       = _cultureManager.GetCurrentCulture(_workContextAccessor.GetContext().HttpContext);

            return(ContentShape("Parts_CulturePicker", () => shapeHelper.Parts_CulturePicker(AvailableCultures: part.AvailableCultures, UserCulture: part.UserCulture)));
        }
Esempio n. 8
0
        public void ApplyFilter(FilterContext context)
        {
            var cultureName = (string)context.State.Culture;
            // Default action does nothing
            Action <FilterContext> ActualFilter = fc => { };

            if (!string.IsNullOrWhiteSpace(cultureName))
            {
                var cultures = _cultureManager.ListCultures();
                // get the culture with the given name
                var culture = cultures
                              .FirstOrDefault(c => c.Equals(cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (culture != null)
                {
                    var cultureRecord = _cultureManager.GetCultureByName(culture);
                    if (cultureRecord != null)   //sanity check
                    // define the Action that will actually do a query
                    {
                        ActualFilter = fc => {
                            fc.Query.Where(
                                x => x.ContentPartRecord <LocalizationPartRecord>(),
                                c => c.Eq("CultureId", cultureRecord.Id));
                        };
                    }
                }
            }
            // execute the filter
            ActualFilter(context);
        }
        public IList <ExtendedCultureRecord> CultureList(IEnumerable <string> cultureListSource = null, bool ordered = true)
        {
            _extendedCultureRepository.Flush();
            List <string> listCultures;

            if (cultureListSource == null)
            {
                listCultures = _cultureManager.ListCultures().ToList();
            }
            else
            {
                listCultures = cultureListSource.ToList();
            }
            var siteCulture          = _cultureManager.GetSiteCulture();
            var listExtendedCultures = _extendedCultureRepository.Table.ToList();
            var joinedCultures       = from c in listCultures
                                       join
                                       ec in listExtendedCultures on c.ToString() equals ec.CultureCode into temp_ec
                                       from ec in temp_ec.DefaultIfEmpty()
                                       select new ExtendedCultureRecord
            {
                CultureCode = c.ToString(), Id = (ec != null ? ec.Id : 0), Priority = (ec != null ? ec.Priority : (c.ToString() == siteCulture ? 0 : 1)), DisplayName = (ec != null ? ec.DisplayName : null)
            };

            if (ordered)
            {
                return(joinedCultures.OrderBy(o => o.Priority).ToList());
            }
            else
            {
                return(joinedCultures.ToList());
            }
        }
Esempio n. 10
0
        protected override DriverResult Display(CulturePickerPart part, string displayType, dynamic shapeHelper) {
            var siteAvailableCultures = _cultureManager.ListCultures().AsQueryable();
            var context = _workContextAccessor.GetContext();
            var baseUrl = context.CurrentSite.BaseUrl;
            var cleanUrl = context.HttpContext.Request.Url.AbsoluteUri.Replace(baseUrl, "");
            cleanUrl = context.HttpContext.Server.UrlDecode(cleanUrl);
            cleanUrl = cleanUrl.StartsWith("/") ? cleanUrl.Substring(1) : cleanUrl;
            // reading settings
            var settings = _extendedCultureService.ReadSettings();
            part.AvailableCultures = settings.ExtendedCulturesList;
            part.ShowOnlyPertinentCultures = settings.Settings.ShowOnlyPertinentCultures;
            part.ShowLabel = settings.Settings.ShowLabel;
            settings = null;
            var urlPrefix = _workContextAccessor.GetContext().Resolve<ShellSettings>().RequestUrlPrefix;
            if (!String.IsNullOrWhiteSpace(urlPrefix)) {
                cleanUrl = cleanUrl.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase) ? cleanUrl.Substring(urlPrefix.Length) : cleanUrl;
            }
            cleanUrl = HttpUtility.UrlDecode(cleanUrl);
            cleanUrl = cleanUrl.StartsWith("/") ? cleanUrl.Substring(1) : cleanUrl;
            var isHomePage = String.IsNullOrWhiteSpace(cleanUrl);
            part.TranslatedCultures = _localizableContentService.AvailableTranslations(cleanUrl, isHomePage);


            part.UserCulture = _extendedCultureService.GetExtendedCulture(_cultureManager.GetCurrentCulture(_workContextAccessor.GetContext().HttpContext));

            return ContentShape("Parts_CulturePicker", () => shapeHelper.Parts_CulturePicker(AvailableCultures: part.AvailableCultures, TranslatedCultures: part.TranslatedCultures, UserCulture: part.UserCulture, ShowOnlyPertinentCultures: part.ShowOnlyPertinentCultures, ShowLabel: part.ShowLabel));
        }
Esempio n. 11
0
        protected override DriverResult Editor(FaqEntryPart part, dynamic shapeHelper)
        {
            part.AvailableLanguages = _cultureManager.ListCultures();
            part.AvailableSections  = _faqService.GetFaqSections(part.Language);

            return(ContentShape("Parts_FaqEntry_Edit", () => shapeHelper
                                .EditorTemplate(TemplateName: "Parts/FaqEntry", Model: part, Prefix: Prefix)));
        }
Esempio n. 12
0
        public ActionResult Translate(int id, string to)
        {
            var contentItem = _contentManager.Get(id, VersionOptions.Latest);

            // only support translations from the site culture, at the moment at least
            if (contentItem == null)
            {
                return(HttpNotFound());
            }

            if (!contentItem.Is <LocalizationPart>() || contentItem.As <LocalizationPart>().MasterContentItem != null)
            {
                var metadata = _contentManager.GetItemMetadata(contentItem);
                return(RedirectToAction(Convert.ToString(metadata.EditorRouteValues["action"]), metadata.EditorRouteValues));
            }

            var siteCultures    = _cultureManager.ListCultures().Where(s => s != _localizationService.GetContentCulture(contentItem) && s != _cultureManager.GetSiteCulture());
            var selectedCulture = siteCultures.SingleOrDefault(s => string.Equals(s, to, StringComparison.OrdinalIgnoreCase))
                                  ?? _cultureManager.GetCurrentCulture(HttpContext); // could be null but the person doing the translating might be translating into their current culture

            //todo: need a better solution for modifying some parts when translating - or go with a completely different experience

            /*
             * if (contentItem.Has<RoutePart>()) {
             *  RoutePart routePart = contentItem.As<RoutePart>();
             *  routePart.Slug = string.Format("{0}{2}{1}", routePart.Slug, siteCultures.Any(s => string.Equals(s, selectedCulture, StringComparison.OrdinalIgnoreCase)) ? selectedCulture : "", !string.IsNullOrWhiteSpace(routePart.Slug) ? "-" : "");
             *  routePart.Path = null;
             * }*/

            if (contentItem.As <LocalizationPart>().Culture != null)
            {
                contentItem.As <LocalizationPart>().Culture.Culture = null;
            }
            var model = new AddLocalizationViewModel {
                Id = id,
                SelectedCulture = selectedCulture,
                SiteCultures    = siteCultures,
                Content         = _contentManager.BuildEditor(contentItem)
            };

            // Cancel transaction so that the routepart is not modified.
            Services.TransactionManager.Cancel();

            return(View(model));
        }
Esempio n. 13
0
        public void CultureManagerCanAddAndListValidCultures()
        {
            _cultureManager.AddCulture("tr-TR");
            _cultureManager.AddCulture("fr-FR");
            _cultureManager.AddCulture("bs-Latn-BA");
            List <string> cultures = new List <string>(_cultureManager.ListCultures());

            Assert.That(cultures.Count, Is.Not.EqualTo(0));
        }
Esempio n. 14
0
        public ActionResult Translate(int id, string to)
        {
            var contentItem = _contentManager.Get(id, VersionOptions.Latest);

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

            if (!contentItem.Is <LocalizationPart>() || contentItem.As <LocalizationPart>().MasterContentItem != null || string.IsNullOrEmpty(to))
            {
                var metadata = _contentManager.GetItemMetadata(contentItem);
                return(RedirectToAction(Convert.ToString(metadata.EditorRouteValues["action"]), metadata.EditorRouteValues));
            }

            var contentCulture = _localizationService.GetContentCulture(contentItem);

            var potCultures     = _cultureManager.ListCultures().Where(s => s != contentCulture);
            var selectedCulture = potCultures.SingleOrDefault(s => string.Equals(s, to, StringComparison.OrdinalIgnoreCase))
                                  ?? _cultureManager.GetCurrentCulture(HttpContext); // could be null but the person doing the translating might be translating into their current culture


            var lPs = _cultureService.GetLocalizations(contentItem.As <LocalizationPart>(), VersionOptions.Latest);
            // the existing culture are the real existing ones and the one we are creating
            var siteCultures = lPs.Select(p => p.Culture.Culture).Union(new string[] { selectedCulture }).Distinct().ToList();    // necessary because the culture in cultureRecord will be set to null before expr resolution

            if (contentItem.As <LocalizationPart>().Culture != null)
            {
                contentItem.As <LocalizationPart>().Culture.Culture = null;
            }
            var model = new AddLocalizationViewModel {
                Id = id,
                SelectedCulture = selectedCulture,
                SiteCultures    = siteCultures,
                Content         = _contentManager.BuildEditor(contentItem)
            };

            // Cancel transaction so that the CultureRecord is not modified.
            Services.TransactionManager.Cancel();

            return(View(model));
        }
Esempio n. 15
0
 public override void Displaying(ShapeDisplayingContext context)
 {
     context.ShapeMetadata.OnDisplaying(displayedContext => {
         if (displayedContext.ShapeMetadata.Type == "Layout" && IsActivable())
         {
             var supportedCultures = _cultureManager.ListCultures().ToList();
             if (supportedCultures.Count() > 1)
             {
                 _workContext.Layout.Header.Add(Shape.AdminCultureSelector(SupportedCultures: supportedCultures));
             }
         }
     });
 }
Esempio n. 16
0
        protected override DriverResult Editor(LocalizationPart part, dynamic shapeHelper)
        {
            var localizations = GetEditorLocalizations(part).ToList();
            var model         = new EditLocalizationViewModel {
                SelectedCulture      = part.Culture != null ? part.Culture.Culture : null,
                SiteCultures         = _cultureManager.ListCultures().Where(s => s != _cultureManager.GetSiteCulture() && !localizations.Select(l => l.Culture.Culture).Contains(s)),
                ContentItem          = part,
                MasterContentItem    = part.MasterContentItem,
                ContentLocalizations = new ContentLocalizationsViewModel(part)
                {
                    Localizations = localizations
                }
            };

            return(ContentShape("Parts_Localization_ContentTranslations_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts/Localization.ContentTranslations.Edit", Model: model, Prefix: TemplatePrefix)));
        }
        public void ContentPartAttached(ContentPartAttachedContext context)
        {
            if (context.ContentPartName == "AutoroutePart")
            {
                // Create pattern and default pattern for each culture installed and for the neutral culture

                // Get cultures
                var SiteCultures = _cultureManager.ListCultures().ToList();

                // Adding a null culture for the culture neutral pattern
                List <string> cultures = new List <string>();
                cultures.Add(null);
                cultures.AddRange(SiteCultures);

                // Create Patterns and DefaultPatterns
                var settings = new AutorouteSettings {
                    Patterns = new List <RoutePattern>()
                };

                List <RoutePattern>   newPatterns        = new List <RoutePattern>();
                List <DefaultPattern> newDefaultPatterns = new List <DefaultPattern>();
                foreach (string culture in cultures)
                {
                    newPatterns.Add(new RoutePattern {
                        Name        = "Title",
                        Description = "my-title",
                        Pattern     = "{Content.Slug}",
                        Culture     = culture
                    });
                    newDefaultPatterns.Add(new DefaultPattern {
                        Culture      = culture,
                        PatternIndex = "0"
                    });
                }

                settings.Patterns        = newPatterns;
                settings.DefaultPatterns = newDefaultPatterns;

                //Update Settings
                _contentDefinitionManager.AlterTypeDefinition(context.ContentTypeName, builder => builder.WithPart("AutoroutePart", settings.Build));

                //TODO Generate URL's for existing content items
                //We should provide a global setting to enable/disable this feature
            }
        }
Esempio n. 18
0
        public ActionResult Culture()
        {
            //todo: class and/or method attributes for our auth?
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage settings")))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = new SiteCulturesViewModel {
                CurrentCulture = _cultureManager.GetCurrentCulture(HttpContext),
                SiteCultures   = _cultureManager.ListCultures(),
            };

            model.AvailableSystemCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                                            .Select(ci => ci.Name)
                                            .Where(s => !model.SiteCultures.Contains(s));

            return(View(model));
        }
Esempio n. 19
0
        public CultureIndexViewModel GetCultures()
        {
            var model = new CultureIndexViewModel();
            var wc    = _wca.GetContext();
            {
                var _sessionLocator = wc.Resolve <ISessionLocator>();
                using (var session = _sessionLocator.For(typeof(TranslationRecord)))
                {
                    var cultures =
                        (from t in session.Linq <TranslationRecord>()
                         group t by t.Culture
                         into c
                         select new
                    {
                        c.First().Culture,
                        Count = c.Count()
                    }
                        ).ToList();
                    foreach (var culture in cultures)
                    {
                        model.TranslationStates.Add(
                            culture.Culture,
                            new CultureIndexViewModel.CultureTranslationState {
                            NumberOfTranslatedStrings = culture.Count
                        });
                    }
                    model.NumberOfStringsInDefaultCulture = GetNumberOfTranslatableStrings(session);
                }

                foreach (var cult in _cultureManager.ListCultures())
                {
                    if (!model.TranslationStates.ContainsKey(cult))
                    {
                        model.TranslationStates.Add(cult, new CultureIndexViewModel.CultureTranslationState {
                            NumberOfTranslatedStrings = 0
                        });
                    }
                }

                return(model);
            }
        }
Esempio n. 20
0
 public IEnumerable <string> ListCultures()
 {
     return(_underlyingCultureManager.ListCultures());
 }
Esempio n. 21
0
 public IEnumerable <CultureItemModel> ListCultures()
 {
     return(_cultureManager.ListCultures().Select(x => new CultureInfo(x)).Select(x => new CultureItemModel {
         Culture = x.Name, LocalizedName = x.NativeName, ShortName = x.ThreeLetterISOLanguageName, FullName = x.DisplayName
     }));
 }
        public void Describe(DescribeContext context)
        {
            Func <IShapeFactory, dynamic> form =
                shape => {
                var f = Shape.Form(
                    Id: "ActionPush",
                    _Type: Shape.FieldSet(
                        Title: T("Send Push"),
                        _ddlDevice: Shape.SelectList(
                            Id: "allDevice",
                            Name: "allDevice",
                            Title: T("Device"),
                            Size: 10,
                            Multiple: false
                            ),
                        _UsersList: Shape.Textbox(
                            Id: "userId",
                            Name: "userId",
                            Title: T("Users list (ID / e-mail / username)"),
                            Description: T("Comma separated list of User IDs or e-mails or usernames (eg. 12,45,239). Tokenized."),
                            Classes: new[] { "large", "text", "tokenized" }
                            ),
                        _ddlLanguage: Shape.SelectList(
                            Id: "allLanguage",
                            Name: "allLanguage",
                            Title: T("Language"),
                            Size: 4,
                            Multiple: false
                            ),
                        _RecipientProd: Shape.Radio(
                            Id: "Produzione",
                            Name: "Produzione",
                            Value: "Produzione",
                            Title: T("Produzione")
                            ),
                        _RecipientProd2: Shape.Radio(
                            Id: "Produzione",
                            Name: "Produzione",
                            Value: "Sviluppo",
                            Title: T("Sviluppo")
                            ),
                        _Recipientidrelated: Shape.TextBox(
                            Id: "idRelated",
                            Name: "idRelated",
                            Value: "",
                            Title: T("Link the content as Related Content"),
                            Description: T("Content ID. Tokenized. Example: the current content item is {Content.Id}."),
                            Classes: new[] { "large", "text", "tokenized" }
                            ),
                        _Recipient5: Shape.Textbox(
                            Id: "PushMessage",
                            Name: "PushMessage",
                            Title: T("Push Message"),
                            Description: T("Push Message Tokenized."),
                            Classes: new[] { "large", "text", "tokenized" }
                            )
                        )
                    );
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "All", Text = "All Devices"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "Apple", Text = "All Apple's device"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "Android", Text = "All Android's device"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "WindowsMobile", Text = "All WindowsMobile's device"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "ContentOwner", Text = "Content's Owner"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "ContentCreator", Text = "Content's Creator"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "ContentLastModifier", Text = "Content's LastModifier"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "UserId", Text = "User specified by ID"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "UserEmail", Text = "User specified by e-mail"
                });
                f._Type._ddlDevice.Add(new SelectListItem {
                    Value = "UserName", Text = "User specified by username"
                });
                f._Type._ddlLanguage.Add(new SelectListItem {
                    Value = "All", Text = "All Languages"
                });
                foreach (string up in _cultureManager.ListCultures())
                {
                    f._Type._ddlLanguage.Add(new SelectListItem {
                        Value = up.ToString(), Text = up.ToString()
                    });
                }
                return(f);
            };

            context.Form("ActivityMobileForm", form);
        }
        private CultureSelectorResult EvaluateResult(HttpContextBase context)
        {
            if (context == null)
            {
                return(null);
            }

            string requestPath = "";

            if (context.Request.QueryString["lang"] == null)
            {
                requestPath = context.Request
                              .AppRelativeCurrentExecutionFilePath.Replace("~", string.Empty);

                requestPath = (requestPath.StartsWith("/"))
                    ? requestPath.Substring(1)
                    : requestPath;
                if (!string.IsNullOrWhiteSpace(UrlPrefix) && requestPath.StartsWith(UrlPrefix))
                {
                    requestPath = requestPath.Substring(UrlPrefix.Length);
                }
            }
            else
            {
                requestPath = context.Request.QueryString["lang"].ToString() + "/";
            }
            if (string.IsNullOrWhiteSpace(requestPath))
            {
                return(null);
            }
            try {
                var cultureToken = requestPath.Substring(0, requestPath.IndexOf('/'));
                if (!string.IsNullOrWhiteSpace(cultureToken))   // sanity check
                // cultureToken may not be the actual culture name. For example, it may be 'it'
                // rather than 'it-IT'. This means we should not be using the list of CultureInfo
                // objects in the system: there may be several cultures starting with the same
                // string.
                // Rather, we should use the configured cultures in the Orchard application.
                {
                    var cultures = _cultureManager
                                   .ListCultures(); // list all configured cultures: these are the culture names
                    // first we see if a culture's name matches our token exactly
                    var cultureName = cultures
                                      .FirstOrDefault(c => c.Equals(cultureToken, StringComparison.InvariantCultureIgnoreCase));
                    if (string.IsNullOrWhiteSpace(cultureName))
                    {
                        // lacking an exact match, we get the first culture for the same language.
                        cultureName = cultures
                                      .FirstOrDefault(c => c.StartsWith(cultureToken, StringComparison.InvariantCultureIgnoreCase));
                    }
                    // cultureName here may not be the intended culture when the cultureToken does not
                    // match a culture's name exactly.
                    if (!string.IsNullOrWhiteSpace(cultureName))
                    {
                        return(new CultureSelectorResult {
                            Priority = SELECTOR_PRIORITY, CultureName = cultureName
                        });
                    }
                }
            } catch {
                return(null);
            }
            return(null);
        }
Esempio n. 24
0
 public IEnumerable <string> GetTranslatedCultures()
 {
     return(_cultureManager.ListCultures());
 }
        public override IEnumerable <TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "AutoroutePart")
            {
                yield break;
            }

            var settings = definition.Settings.GetModel <AutorouteSettings>();

            // Get cultures
            settings.SiteCultures = _cultureManager.ListCultures().ToList();
            // Get default site culture
            settings.DefaultSiteCulture = _cultureManager.GetSiteCulture();

            // Adding Patterns for the UI
            List <RoutePattern> newPatterns = new List <RoutePattern>();

            // Adding a null culture for the culture neutral pattern
            var cultures = new List <string>();

            cultures.Add(null);
            cultures.AddRange(settings.SiteCultures);

            foreach (string culture in cultures)
            {
                // Adding all existing patterns for the culture
                newPatterns.AddRange(
                    settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase))
                    );

                // Adding a pattern for each culture if there is none
                if (!settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)).Any())
                {
                    newPatterns.Add(new RoutePattern {
                        Culture = culture, Name = "Title", Description = "my-title", Pattern = "{Content.Slug}"
                    });
                }

                // Adding a new empty line for each culture
                newPatterns.Add(new RoutePattern {
                    Culture = culture, Name = null, Description = null, Pattern = null
                });

                // If the content type has no defaultPattern for autoroute, assign one
                var defaultPatternExists = false;
                if (String.IsNullOrEmpty(culture))
                {
                    defaultPatternExists = settings.DefaultPatterns.Any(x => String.IsNullOrEmpty(x.Culture));
                }
                else
                {
                    defaultPatternExists = settings.DefaultPatterns.Any(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase));
                }

                if (!defaultPatternExists)
                {
                    // If in the default culture check the old setting
                    if (String.Equals(culture, _cultureManager.GetSiteCulture(), StringComparison.OrdinalIgnoreCase))
                    {
                        var defaultPatternIndex = settings.DefaultPatternIndex;
                        if (!String.IsNullOrWhiteSpace(defaultPatternIndex))
                        {
                            var patternIndex = defaultPatternIndex;
                            settings.DefaultPatterns.Add(new DefaultPattern {
                                Culture = settings.DefaultSiteCulture, PatternIndex = patternIndex
                            });
                        }
                        else
                        {
                            settings.DefaultPatterns.Add(new DefaultPattern {
                                PatternIndex = "0", Culture = culture
                            });
                        }
                    }
                    else
                    {
                        settings.DefaultPatterns.Add(new DefaultPattern {
                            PatternIndex = "0", Culture = culture
                        });
                    }
                }
            }

            settings.Patterns = newPatterns;

            yield return(DefinitionTemplate(settings));
        }
Esempio n. 26
0
        public ActionResult Index(ListContentsViewModel model, PagerParameters pagerParameters, string part, string field, string type, int hostId)
        {
            // Check Permissions to Edit the content hosting shortcodes
            if (hostId > 0 && !Services.Authorizer.Authorize(Permissions.EditContent, Services.ContentManager.Get(hostId)))
            {
                Services.Notifier.Add(NotifyType.Error, T("Cannot add shortcode."));
                return(new HttpUnauthorizedResult());
            }

            var menuItems             = _navigationManager.BuildMenu("content-picker").ToList();
            var contentPickerMenuItem = menuItems.FirstOrDefault();

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

            if (contentPickerMenuItem.Items.All(x => x.Text.TextHint != "Recent Content"))
            {
                // the default tab should not be displayed, redirect to the next one
                var root = menuItems.FirstOrDefault();
                if (root == null)
                {
                    return(HttpNotFound());
                }

                var firstChild = root.Items.First();
                if (firstChild == null)
                {
                    return(HttpNotFound());
                }

                var routeData   = new RouteValueDictionary(firstChild.RouteValues);
                var queryString = Request.QueryString;
                foreach (var key in queryString.AllKeys)
                {
                    if (!String.IsNullOrEmpty(key))
                    {
                        routeData[key] = queryString[key];
                    }
                }

                return(RedirectToRoute(routeData));
            }

            // Filters the contents by ContentType or filters at least "Listable" content types
            ContentShortCodeSettings settings;
            var types = "";

            if (!string.IsNullOrWhiteSpace(part) && string.IsNullOrWhiteSpace(field))
            {
                ContentTypePartDefinition defintion = _contentDefinitionManager.GetTypeDefinition(type).Parts.FirstOrDefault(x => x.PartDefinition.Name == part);
                if (defintion != null)
                {
                    settings = defintion.Settings.GetModel <ContentShortCodeSettings>();
                    types    = settings.DisplayedContentTypes;
                }
            }
            else if (!string.IsNullOrWhiteSpace(part) && !string.IsNullOrWhiteSpace(field))
            {
                ContentPartFieldDefinition defintion = _contentDefinitionManager.GetTypeDefinition(type)
                                                       .Parts.Where(x => x.PartDefinition.Name == part)
                                                       .SelectMany(x => x.PartDefinition.Fields)
                                                       .FirstOrDefault(x => x.Name == field);

                settings = defintion.Settings.GetModel <ContentShortCodeSettings>();
                types    = settings.DisplayedContentTypes;
            }



            IEnumerable <ContentTypeDefinition> contentTypes;

            if (!String.IsNullOrEmpty(types))
            {
                var rawTypes = types.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                contentTypes = _contentDefinitionManager
                               .ListTypeDefinitions()
                               .Where(x => x.Parts.Any(p => rawTypes.Contains(p.PartDefinition.Name)) || rawTypes.Contains(x.Name))
                               .ToArray();
            }
            else
            {
                contentTypes = GetListableTypes(false).ToList();
            }

            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
            var query = Services.ContentManager.Query(VersionOptions.Latest, contentTypes.Select(ctd => ctd.Name).ToArray());

            if (!string.IsNullOrEmpty(model.Options.SelectedFilter))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.Options.SelectedFilter);
                if (contentTypeDefinition == null)
                {
                    return(HttpNotFound());
                }

                model.TypeDisplayName = !string.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName)
                                            ? contentTypeDefinition.DisplayName
                                            : contentTypeDefinition.Name;
                query = query.ForType(model.Options.SelectedFilter);
            }

            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Modified:
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.CreatedUtc);
                break;
            }

            if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            {
                query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            }

            model.Options.FilterOptions = contentTypes
                                          .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                          .ToList().OrderBy(kvp => kvp.Value);

            model.Options.Cultures = _cultureManager.ListCultures();

            var pagerShape         = Services.New.Pager(pager).TotalItemCount(query.Count());
            var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
            var list = Services.New.List();

            list.AddRange(pageOfContentItems.Select(ci => Services.ContentManager.BuildDisplay(ci, "SummaryAdmin")));

            foreach (IShape item in list.Items)
            {
                item.Metadata.Type = "ContentPicker";
            }

            var tab = Services.New.RecentContentTab()
                      .ContentItems(list)
                      .Pager(pagerShape)
                      .Options(model.Options)
                      .TypeDisplayName(model.TypeDisplayName ?? "");

            // retain the parameter in the pager links
            RouteData.Values["Options.SelectedFilter"]  = model.Options.SelectedFilter;
            RouteData.Values["Options.OrderBy"]         = model.Options.OrderBy.ToString();
            RouteData.Values["Options.ContentsStatus"]  = model.Options.ContentsStatus.ToString();
            RouteData.Values["Options.SelectedCulture"] = model.Options.SelectedCulture;

            return(new ShapeResult(this, Services.New.ShortCodes_ContentPicker().Tab(tab)));
        }
Esempio n. 27
0
        public ActionResult List(ListContentsViewModel model, PagerParameters pagerParameters)
        {
            Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

            var versionOptions = VersionOptions.Latest;

            switch (model.Options.ContentsStatus)
            {
            case ContentsStatus.Published:
                versionOptions = VersionOptions.Published;
                break;

            case ContentsStatus.Draft:
                versionOptions = VersionOptions.Draft;
                break;

            case ContentsStatus.AllVersions:
                versionOptions = VersionOptions.AllVersions;
                break;

            default:
                versionOptions = VersionOptions.Latest;
                break;
            }

            var query = _contentManager.Query(versionOptions, GetListableTypes(false).Select(ctd => ctd.Name).ToArray());
            ContentTypeDefinition contentTypeDefinition = null;

            if (!string.IsNullOrEmpty(model.TypeName))
            {
                contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
                if (contentTypeDefinition == null)
                {
                    return(HttpNotFound());
                }

                model.TypeDisplayName = !string.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName)
                                            ? contentTypeDefinition.DisplayName
                                            : contentTypeDefinition.Name;

                // We display a specific type even if it's not listable so that admin pages
                // can reuse the Content list page for specific types.
                query = _contentManager.Query(versionOptions, model.TypeName);
            }

            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Modified:
                //query = query.OrderByDescending<ContentPartRecord, int>(ci => ci.ContentItemRecord.Versions.Single(civr => civr.Latest).Id);
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                //query = query.OrderByDescending<ContentPartRecord, int>(ci => ci.Id);
                query = query.OrderByDescending <CommonPartRecord>(cr => cr.CreatedUtc);
                break;
            }

            if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            {
                query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            }

            if (model.Options.ContentsStatus == ContentsStatus.Owner)
            {
                query = query.Where <CommonPartRecord>(cr => cr.OwnerId == Services.WorkContext.CurrentUser.Id);
            }

            model.Options.SelectedFilter = model.TypeName;
            model.Options.FilterOptions  = GetListableTypes(false)
                                           .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                           .ToList().OrderBy(kvp => kvp.Value);

            model.Options.Cultures = _cultureManager.ListCultures();

            var maxPagedCount = _siteService.GetSiteSettings().MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }
            var pagerShape         = Shape.Pager(pager).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : query.Count());
            var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();

            var list = Shape.List();

            list.AddRange(pageOfContentItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));

            var viewModel = Shape.ViewModel(ContentType: contentTypeDefinition)
                            .ContentItems(list)
                            .Pager(pagerShape)
                            .Options(model.Options)
                            .TypeDisplayName(model.TypeDisplayName ?? "");

            return(View(viewModel));
        }
Esempio n. 28
0
        public ActionResult ExportContent(ListExportContentsViewModel model, PagerParameters pagerParameters)
        {
            Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

            var versionOptions = VersionOptions.Latest;

            switch (model.Options.ContentsStatus)
            {
            case ContentsStatus.Published:
                versionOptions = VersionOptions.Published;
                break;

            case ContentsStatus.Draft:
                versionOptions = VersionOptions.Draft;
                break;

            case ContentsStatus.AllVersions:
                versionOptions = VersionOptions.AllVersions;
                break;

            default:
                versionOptions = VersionOptions.Latest;
                break;
            }

            var query = _contentManager.Query(versionOptions, GetListableTypes(false).Select(ctd => ctd.Name).ToArray());

            if ("--content--".Equals(model.TypeName, StringComparison.InvariantCultureIgnoreCase))
            {
                model.HasCommonPartOrdering = true;
                model.TypeDisplayName       = "--content--";
            }
            else if (!string.IsNullOrEmpty(model.TypeName))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
                if (contentTypeDefinition == null)
                {
                    return(HttpNotFound());
                }

                model.TypeDisplayName = !string.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName)
                                            ? contentTypeDefinition.DisplayName
                                            : contentTypeDefinition.Name;
                query = query.ForType(model.TypeName);
                model.HasCommonPartOrdering = contentTypeDefinition.Parts.Any(x => "CommonPart".Equals(x.PartDefinition.Name));
            }
            else
            {
                model.HasCommonPartOrdering = false;
            }

            if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            {
                query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            }

            if (model.HasCommonPartOrdering)
            {
                switch (model.Options.OrderBy)
                {
                case ContentsOrder.Modified:
                    query = query.OrderByDescending <CommonPartRecord>(cr => cr.ModifiedUtc);
                    break;

                case ContentsOrder.Published:
                    query = query.OrderByDescending <CommonPartRecord>(cr => cr.PublishedUtc);
                    break;

                case ContentsOrder.Created:
                    query = query.OrderByDescending <CommonPartRecord>(cr => cr.CreatedUtc);
                    break;
                }
            }

            model.Options.SelectedFilter = model.TypeName;
            model.Options.FilterOptions  = GetListableTypes(false)
                                           .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                           .ToList().OrderBy(kvp => kvp.Value);

            model.Options.Cultures = _cultureManager.ListCultures();

            var maxPagedCount = _siteService.GetSiteSettings().MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }
            var pagerShape         = Shape.Pager(pager).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : query.Count());
            var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();

            var list = Shape.List();

            list.AddRange(pageOfContentItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));

            var viewModel = Shape.ViewModel()
                            .ContentItems(list)
                            .Pager(pagerShape)
                            .Options(model.Options)
                            .TypeDisplayName(model.TypeDisplayName ?? "")
                            .HasCommonPartOrdering(model.HasCommonPartOrdering);

            return(View(viewModel));
        }
Esempio n. 29
0
        public ActionResult Index(int?layerId, string culture)
        {
            ExtensionDescriptor currentTheme = _siteThemeService.GetSiteTheme();

            if (currentTheme == null)
            {
                Services.Notifier.Error(T("To manage widgets you must have a theme enabled."));
                return(RedirectToAction("Index", "Admin", new { area = "Dashboard" }));
            }

            IEnumerable <LayerPart> layers = _widgetsService.GetLayers().OrderBy(x => x.Name).ToList();

            if (!layers.Any())
            {
                Services.Notifier.Error(T("There are no widget layers defined. A layer will need to be added in order to add widgets to any part of the site."));
                return(RedirectToAction("AddLayer"));
            }

            LayerPart currentLayer = layerId == null
                                     // look for the "Default" layer, or take the first if it doesn't exist
                ? layers.FirstOrDefault(x => x.Name == "Default") ?? layers.FirstOrDefault()
                : layers.FirstOrDefault(layer => layer.Id == layerId);

            if (currentLayer == null && layerId != null)   // Incorrect layer id passed
            {
                Services.Notifier.Error(T("Layer not found: {0}", layerId));
                return(RedirectToAction("Index"));
            }

            IEnumerable <string> allZones           = _widgetsService.GetZones();
            IEnumerable <string> currentThemesZones = _widgetsService.GetZones(currentTheme);

            string zonePreviewImagePath = string.Format("{0}/{1}/ThemeZonePreview.png", currentTheme.Location, currentTheme.Id);
            string zonePreviewImage     = _virtualPathProvider.FileExists(zonePreviewImagePath) ? zonePreviewImagePath : null;

            var widgets = _widgetsService.GetWidgets();

            if (!String.IsNullOrWhiteSpace(culture))
            {
                widgets = widgets.Where(x => {
                    if (x.Has <ILocalizableAspect>())
                    {
                        return(String.Equals(x.As <ILocalizableAspect>().Culture, culture, StringComparison.InvariantCultureIgnoreCase));
                    }

                    return(false);
                }).ToList();
            }

            var viewModel = Shape.ViewModel()
                            .CurrentTheme(currentTheme)
                            .CurrentLayer(currentLayer)
                            .CurrentCulture(culture)
                            .Layers(layers)
                            .Widgets(widgets)
                            .Zones(currentThemesZones)
                            .Cultures(_cultureManager.ListCultures())
                            .OrphanZones(allZones.Except(currentThemesZones))
                            .OrphanWidgets(_widgetsService.GetOrphanedWidgets())
                            .ZonePreviewImage(zonePreviewImage);

            return(View(viewModel));
        }
        public override IEnumerable <TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "AutoroutePart")
            {
                yield break;
            }

            var settings = definition.Settings.GetModel <AutorouteSettings>();

            //get cultures
            settings.SiteCultures = _cultureManager.ListCultures().ToList();
            //get default site culture
            settings.DefaultSiteCulture = _cultureManager.GetSiteCulture();

            //if a culture is not set on the pattern we set it to the default site culture for backward compatibility
            if (!settings.Patterns.Any(x => String.Equals(x.Culture, settings.DefaultSiteCulture, StringComparison.OrdinalIgnoreCase)))
            {
                foreach (RoutePattern pattern in settings.Patterns.Where(x => String.IsNullOrWhiteSpace(x.Culture)))
                {
                    settings.Patterns.Where(x => x.GetHashCode() == pattern.GetHashCode()).FirstOrDefault().Culture = settings.DefaultSiteCulture;
                }
            }

            //Adding Patterns for the UI
            List <RoutePattern> newPatterns = new List <RoutePattern>();
            int current = 0;

            foreach (string culture in settings.SiteCultures)
            {
                foreach (RoutePattern routePattern in settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)))
                {
                    if (settings.Patterns.Any(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)))
                    {
                        newPatterns.Add(settings.Patterns[current]);
                    }
                    else
                    {
                        newPatterns.Add(new RoutePattern {
                            Name        = "Title",
                            Description = "my-title",
                            Pattern     = "{Content.Slug}",
                            Culture     = settings.DefaultSiteCulture
                        });
                    }
                    current++;
                }

                //We add a pattern for each culture if there is none
                if (!settings.Patterns.Where(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)).Any())
                {
                    newPatterns.Add(new RoutePattern {
                        Culture = culture, Name = "Title", Description = "my-title", Pattern = "{Content.Slug}"
                    });
                }

                //we add a new empty line for each culture
                newPatterns.Add(new RoutePattern {
                    Culture = culture, Name = null, Description = null, Pattern = null
                });

                // if the content type has no defaultPattern for autoroute, then assign one
                if (!settings.DefaultPatterns.Any(x => String.Equals(x.Culture, culture, StringComparison.OrdinalIgnoreCase)))
                {
                    //if we are in the default culture check the old setting
                    if (String.Equals(culture, _cultureManager.GetSiteCulture(), StringComparison.OrdinalIgnoreCase))
                    {
                        var defaultPatternIndex = settings.DefaultPatternIndex;
                        if (!String.IsNullOrWhiteSpace(defaultPatternIndex))
                        {
                            var patternIndex = defaultPatternIndex;
                            settings.DefaultPatterns.Add(new DefaultPattern {
                                Culture = settings.DefaultSiteCulture, PatternIndex = patternIndex
                            });
                        }
                        else
                        {
                            settings.DefaultPatterns.Add(new DefaultPattern {
                                PatternIndex = "0", Culture = culture
                            });
                        }
                    }
                    else
                    {
                        settings.DefaultPatterns.Add(new DefaultPattern {
                            PatternIndex = "0", Culture = culture
                        });
                    }
                }
            }

            settings.Patterns = newPatterns;

            yield return(DefinitionTemplate(settings));
        }