public string GenerateAlias(AutoroutePart part)
        {
            if (part == null)
            {
                throw new ArgumentNullException("part");
            }
            var settings    = part.TypePartDefinition.Settings.GetModel <AutorouteSettings>();
            var itemCulture = _cultureManager.GetSiteCulture();

            // If we are editing an existing content item.
            if (part.Record.Id != 0)
            {
                ContentItem contentItem = _contentManager.Get(part.Record.ContentItemRecord.Id);
                var         aspect      = contentItem.As <ILocalizableAspect>();

                if (aspect != null)
                {
                    itemCulture = aspect.Culture;
                }
            }

            if (settings.UseCulturePattern)
            {
                // TODO: Refactor the below so that we don't need to know about Request.Form["Localization.SelectedCulture"].
                // If we are creating from a form post we use the form value for culture.
                var context         = _httpContextAccessor.Current();
                var selectedCulture = context.Request.Form["Localization.SelectedCulture"];
                if (!String.IsNullOrEmpty(selectedCulture))
                {
                    itemCulture = selectedCulture;
                }
            }

            var pattern = GetDefaultPattern(part.ContentItem.ContentType, itemCulture).Pattern;

            // String.Empty forces pattern based generation.
            if (part.UseCustomPattern && (!String.IsNullOrWhiteSpace(part.CustomPattern)))
            {
                pattern = part.CustomPattern;
            }

            // Convert the pattern and route values via tokens.
            var path = _tokenizer.Replace(pattern, BuildTokenContext(part.ContentItem), new ReplaceOptions {
                Encoding = ReplaceOptions.NoEncode
            });

            // Removing trailing slashes in case the container is empty, and tokens are base on it (e.g. home page).
            while (path.StartsWith("/"))
            {
                path = path.Substring(1);
            }

            return(path);
        }
Esempio n. 2
0
 private IEnumerable <LocalizationPart> GetDisplayLocalizations(LocalizationPart part, VersionOptions versionOptions)
 {
     return(_localizationService.GetLocalizations(part.ContentItem, versionOptions)
            .Select(c => {
         var localized = c.ContentItem.As <LocalizationPart>();
         if (localized.Culture == null)
         {
             localized.Culture = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture());
         }
         return c;
     }).ToList());
 }
        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. 4
0
        public IEnumerable <PolicyTextInfoPart> GetPolicies(string culture = null, int[] ids = null)
        {
            var siteLanguage = _workContext.GetContext().CurrentSite.SiteCulture;

            // figure out the culture Id we should use in the query
            int currentLanguageId;
            IContentQuery <PolicyTextInfoPart> query;
            CultureRecord cultureRecord = null;

            if (!string.IsNullOrWhiteSpace(culture))
            {
                cultureRecord = GetCultureByName(culture);
            }
            if (cultureRecord == null)
            {
                //Nel caso di contenuto senza Localizationpart prendo la CurrentCulture
                cultureRecord = GetCultureByName(_workContext.GetContext().CurrentCulture);
            }
            if (cultureRecord == null)
            {
                cultureRecord = GetCultureByName(_cultureManager.GetSiteCulture());
            }
            currentLanguageId = cultureRecord.Id;

            // cacheKey = KeyBase_List_of_Ids
            var cacheKey = string.Join("_",
                                       KeyBase,
                                       currentLanguageId.ToString(),
                                       ids == null
                    ? "NoID"
                    : string.Join("_", ids.Select(i => i.ToString())));

            // cache the query results
            return(_cacheManager.Get(cacheKey, true, ctx => {
                ctx.Monitor(_signals.When("PolicyTextInfoPart_EvictAll"));
                if (ids != null)
                {
                    query = _contentManager.Query <PolicyTextInfoPart, PolicyTextInfoPartRecord>()
                            .Where(x => ids.Contains(x.Id))
                            .OrderByDescending(o => o.Priority)
                            .Join <LocalizationPartRecord>()
                            .Where(w =>
                                   w.CultureId == currentLanguageId ||
                                   (w.CultureId == 0 && (siteLanguage.Equals(culture) || culture == null)))
                            .ForVersion(VersionOptions.Published);
                }
                else
                {
                    query = _contentManager.Query <PolicyTextInfoPart, PolicyTextInfoPartRecord>()
                            .OrderByDescending(o => o.Priority)
                            .Join <LocalizationPartRecord>()
                            .Where(w =>
                                   w.CultureId == currentLanguageId ||
                                   (w.CultureId == 0 && (siteLanguage.Equals(culture) || culture == null)))
                            .ForVersion(VersionOptions.Published);
                }

                return query.List <PolicyTextInfoPart>();
            }));
        }
        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)));
        }
        string ILocalizationService.GetContentCulture(IContent content)
        {
            var localized = content.As <LocalizationPart>();

            return(localized != null && localized.Culture != null
                ? localized.Culture.Culture
                : _cultureManager.GetSiteCulture());
        }
 public LocalizationBucket(ICultureManager cultureManager, IWorkContextAccessor workContextAccessor)
 {
     var currentCultureName = cultureManager.GetCurrentCulture(workContextAccessor.GetContext().HttpContext);
     var defaultCultureName = cultureManager.GetSiteCulture();
     CurrentCulture = cultureManager.GetCultureByName(currentCultureName);
     DefaultCulture = cultureManager.GetCultureByName(defaultCultureName);
     IsCurrentCultureDefault = CurrentCulture != null && CurrentCulture.Id == DefaultCulture.Id;
 }
Esempio n. 8
0
            public LocalizationBucket(ICultureManager cultureManager, IWorkContextAccessor workContextAccessor)
            {
                var currentCultureName = cultureManager.GetCurrentCulture(workContextAccessor.GetContext().HttpContext);
                var defaultCultureName = cultureManager.GetSiteCulture();

                CurrentCulture          = cultureManager.GetCultureByName(currentCultureName);
                DefaultCulture          = cultureManager.GetCultureByName(defaultCultureName);
                IsCurrentCultureDefault = CurrentCulture != null && CurrentCulture.Id == DefaultCulture.Id;
            }
Esempio n. 9
0
        private CultureInfo GetContentCultureInfo(IContent content)
        {
            var localizationPart = content != null?content.As <LocalizationPart>() : null;

            if (localizationPart == null || localizationPart.Culture == null || string.IsNullOrEmpty(localizationPart.Culture.Culture))
            {
                return(new CultureInfo(_cultureManager.GetSiteCulture()));
            }
            return(new CultureInfo(localizationPart.Culture.Culture));
        }
Esempio n. 10
0
        public int UpdateFrom4()
        {
            // Adding some culture neutral patterns if they don't exist
            var autoroutePartDefinitions = ContentDefinitionManager.ListTypeDefinitions()
                                           .Where(t => t.Parts.Any(p => p.PartDefinition.Name.Equals(typeof(AutoroutePart).Name)))
                                           .Select(s => new { contentTypeName = s.Name, autoroutePart = s.Parts.First(x => x.PartDefinition.Name == "AutoroutePart") });

            foreach (var partDefinition in autoroutePartDefinitions)
            {
                var settingsDictionary = partDefinition.autoroutePart.Settings;
                var settings           = settingsDictionary.GetModel <AutorouteSettings>();

                if (!settings.Patterns.Any(x => String.IsNullOrWhiteSpace(x.Culture)))
                {
                    string        siteCulture = _cultureManager.GetSiteCulture();
                    List <string> newPatterns = new List <string>();

                    if (settings.Patterns.Any(x => String.Equals(x.Culture, siteCulture, StringComparison.OrdinalIgnoreCase)))
                    {
                        var siteCulturePatterns = settings.Patterns.Where(x => String.Equals(x.Culture, siteCulture, StringComparison.OrdinalIgnoreCase)).ToList();

                        foreach (RoutePattern pattern in siteCulturePatterns)
                        {
                            newPatterns.Add(String.Format("{{\"Name\":\"{0}\",\"Pattern\":\"{1}\",\"Description\":\"{2}\"}}", pattern.Name, pattern.Pattern, pattern.Description));
                        }
                    }
                    else
                    {
                        newPatterns.Add(String.Format("{{\"Name\":\"{0}\",\"Pattern\":\"{1}\",\"Description\":\"{2}\"}}", "Title", "{Content.Slug}", "my-title"));
                    }

                    if (settingsDictionary.ContainsKey("AutorouteSettings.PatternDefinitions"))
                    {
                        string oldPatterns = settingsDictionary["AutorouteSettings.PatternDefinitions"];
                        if (oldPatterns.StartsWith("[") && oldPatterns.EndsWith("]"))
                        {
                            newPatterns.Add(oldPatterns.Substring(1, oldPatterns.Length - 2));
                        }
                    }

                    ContentDefinitionManager.AlterTypeDefinition(partDefinition.contentTypeName, cfg => cfg
                                                                 .WithPart("AutoroutePart", builder => builder
                                                                           .WithSetting("AutorouteSettings.PatternDefinitions", "[" + String.Join(",", newPatterns) + "]")
                                                                           ));
                }
            }

            return(5);
        }
Esempio n. 11
0
        public LocalizationPartHandler(IRepository<LocalizationPartRecord> localizedRepository, ICultureManager cultureManager, IContentManager contentManager) {
            _cultureManager = cultureManager;
            _contentManager = contentManager;
            T = NullLocalizer.Instance;

            Filters.Add(StorageFilter.For(localizedRepository));

            OnActivated<LocalizationPart>(PropertySetHandlers);

            OnLoading<LocalizationPart>((context, part) => LazyLoadHandlers(part));
            OnVersioning<LocalizationPart>((context, part, versionedPart) => LazyLoadHandlers(versionedPart));

            OnIndexed<LocalizationPart>((context, localized) => context.DocumentIndex
                .Add("culture", CultureInfo.GetCultureInfo(localized.Culture != null ? localized.Culture.Culture : _cultureManager.GetSiteCulture()).LCID).Store()
                );
        }
Esempio n. 12
0
        IPageOfItems <T> ISearchService.Query <T>(string query, int page, int?pageSize, bool filterCulture, string index, string[] searchFields, Func <ISearchHit, T> shapeResult)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return(new PageOfItems <T>(Enumerable.Empty <T>()));
            }

            var searchBuilder = Search(index).Parse(searchFields, query);

            if (filterCulture)
            {
                var culture = _cultureManager.GetSiteCulture();

                // use LCID as the text representation gets analyzed by the query parser
                searchBuilder
                .WithField("culture", CultureInfo.GetCultureInfo(culture).LCID)
                .AsFilter();
            }

            var totalCount = searchBuilder.Count();

            if (pageSize != null)
            {
                searchBuilder = searchBuilder
                                .Slice((page > 0 ? page - 1 : 0) * (int)pageSize, (int)pageSize);
            }

            var searchResults = searchBuilder.Search();

            var pageOfItems = new PageOfItems <T>(searchResults.Select(shapeResult))
            {
                PageNumber     = page,
                PageSize       = pageSize != null ? (int)pageSize : totalCount,
                TotalItemCount = totalCount
            };

            return(pageOfItems);
        }
Esempio n. 13
0
        protected override DriverResult Editor(AutoroutePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var settings    = part.TypePartDefinition.Settings.GetModel <AutorouteSettings>();
            var itemCulture = _cultureManager.GetSiteCulture();

            // If we are editing an existing content item, check to see if we are an ILocalizableAspect so we can use its culture for alias generation.
            if (part.Record.Id != 0)
            {
                var localizableAspect = part.As <ILocalizableAspect>();

                if (localizableAspect != null)
                {
                    itemCulture = localizableAspect.Culture;
                }
            }

            if (settings.UseCulturePattern)
            {
                // Hack: if the LocalizedPart is attached to the content item, it will submit the following form value,
                // which we use to determine what culture to use for alias generation.
                var context = _httpContextAccessor.Current();
                if (!String.IsNullOrEmpty(context.Request.Form["Localization.SelectedCulture"]))
                {
                    itemCulture = context.Request.Form["Localization.SelectedCulture"].ToString();
                }
            }

            // We update the settings assuming that when
            // pattern culture = null or "" it means culture = default website culture
            // for patterns that we migrated.
            foreach (var pattern in settings.Patterns.Where(x => String.IsNullOrWhiteSpace(x.Culture)))
            {
                pattern.Culture = _cultureManager.GetSiteCulture();;
            }

            // We do the same for default patterns.
            foreach (var pattern in settings.DefaultPatterns.Where(x => String.IsNullOrWhiteSpace(x.Culture)))
            {
                pattern.Culture = _cultureManager.GetSiteCulture();
            }

            // If the content type has no pattern for autoroute, then use a default one.
            if (!settings.Patterns.Any(x => String.Equals(x.Culture, itemCulture, StringComparison.OrdinalIgnoreCase)))
            {
                settings.Patterns = new List <RoutePattern> {
                    new RoutePattern {
                        Name = "Title", Description = "my-title", Pattern = "{Content.Slug}", Culture = itemCulture
                    }
                };
            }

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

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

            // Retrieve home page.
            var homePageId = _homeAliasService.GetHomePageId(VersionOptions.Latest);
            var isHomePage = part.Id == homePageId;

            viewModel.IsHomePage        = isHomePage;
            viewModel.PromoteToHomePage = part.PromoteToHomePage;

            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 leading slash in the permalink.
                if (viewModel.CurrentUrl != null)
                {
                    viewModel.CurrentUrl = viewModel.CurrentUrl.TrimStart('/');
                }

                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 (part.DisplayAlias != null && part.DisplayAlias.Length > 1850)
                {
                    updater.AddModelError("CurrentUrl", T("Your permalink is too long. The permalink can only be up to 1,850 characters."));
                }

                // Mark the content item to be the homepage. Once this content isp ublished, the home alias will be updated to point to this content item.
                part.PromoteToHomePage = viewModel.PromoteToHomePage;
            }

            return(ContentShape("Parts_Autoroute_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Autoroute.Edit", Model: viewModel, Prefix: Prefix)));
        }
        public PoliciesForUserViewModel GetPoliciesForUserOrSession(bool writeMode, string language = null)
        {
            var loggedUser   = _workContext.GetContext().CurrentUser;
            var siteLanguage = _workContext.GetContext().CurrentSite.SiteCulture;

            int currentLanguageId;
            IList <PolicyForUserViewModel>     model = new List <PolicyForUserViewModel>();
            IContentQuery <PolicyTextInfoPart> query;

            // language may be a string that does not represent any language. We should handle that case.
            CultureRecord currentLanguageRecord = null;

            if (!string.IsNullOrWhiteSpace(language))
            {
                currentLanguageRecord = _cultureManager.GetCultureByName(language);
            }
            // if the language string is not a valid language (or it's empty):
            if (currentLanguageRecord == null)
            {
                currentLanguageRecord = _cultureManager.GetCultureByName(_workContext.GetContext().CurrentCulture);
            }
            if (currentLanguageRecord == null)
            {
                currentLanguageRecord = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture());
            }
            currentLanguageId = currentLanguageRecord.Id;

            query = _contentManager.Query <PolicyTextInfoPart, PolicyTextInfoPartRecord>()
                    .OrderByDescending(o => o.Priority)
                    .Join <LocalizationPartRecord>()
                    .Where(w => w.CultureId == currentLanguageId || (w.CultureId == 0 && (siteLanguage.Equals(language) || language == null)))
                    .ForVersion(VersionOptions.Published);

            if (loggedUser != null)   // loggato
            {
                model = query.List().Select(s => {
                    var answer = loggedUser.As <UserPolicyPart>().UserPolicyAnswers.Where(w => w.PolicyTextInfoPartRecord.Id.Equals(s.Id)).SingleOrDefault();
                    return(new PolicyForUserViewModel {
                        PolicyText = s,
                        PolicyTextId = s.Id,
                        AnswerId = answer != null ? answer.Id : 0,
                        AnswerDate = answer != null ? answer.AnswerDate : DateTime.MinValue,
                        OldAccepted = answer != null ? answer.Accepted : false,
                        Accepted = answer != null ? answer.Accepted : false,
                        UserId = (answer != null && answer.UserPartRecord != null) ? (int?)answer.UserPartRecord.Id : null
                    });
                }).ToList();
            }
            else   // non loggato
            {
                IList <PolicyForUserViewModel> answers = GetCookieOrVolatileAnswers();
                model = query.List().Select(s => {
                    var answer = answers.Where(w => w.PolicyTextId.Equals(s.Id)).SingleOrDefault();
                    return(new PolicyForUserViewModel {
                        PolicyText = s,
                        PolicyTextId = s.Id,
                        AnswerId = answer != null ? answer.AnswerId : 0,
                        AnswerDate = answer != null ? answer.AnswerDate : DateTime.MinValue,
                        OldAccepted = answer != null ? answer.Accepted : false,
                        Accepted = answer != null ? answer.Accepted : false,
                        UserId = answer != null ? answer.UserId : null
                    });
                }).ToList();
            }

            CreateAndAttachPolicyCookie(model.ToList(), writeMode);

            return(new PoliciesForUserViewModel {
                Policies = model
            });
        }
        public LocalizationPartHandler(IRepository <LocalizationPartRecord> localizedRepository, ICultureManager cultureManager, IContentManager contentManager)
        {
            _cultureManager = cultureManager;
            _contentManager = contentManager;
            T = NullLocalizer.Instance;

            Filters.Add(StorageFilter.For(localizedRepository));

            OnActivated <LocalizationPart>(PropertySetHandlers);

            OnLoading <LocalizationPart>((context, part) => LazyLoadHandlers(part));
            OnVersioning <LocalizationPart>((context, part, versionedPart) => LazyLoadHandlers(versionedPart));

            OnIndexed <LocalizationPart>((context, localized) => context.DocumentIndex
                                         .Add("culture", CultureInfo.GetCultureInfo(localized.Culture != null ? localized.Culture.Culture : _cultureManager.GetSiteCulture()).LCID).Store()
                                         );
        }
Esempio n. 16
0
 public string GetSiteCulture()
 {
     return(_underlyingCultureManager.GetSiteCulture());
 }
        public ActionResult List(ListContentsViewModelExtension 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());

            //the lQuery is used only in the case where we have the language queries, but since we cannot clone IContentQuery objects,
            //we create it here and build is as we build the other
            var lQuery = _contentManager.Query(versionOptions, GetListableTypes(false).Select(ctd => ctd.Name).ToArray());

            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);
                lQuery = lQuery.ForType(model.TypeName);
            }

            // FILTER QUERIES: START //

            // terms query
            if (model.AdvancedOptions.SelectedTermId > 0)
            {
                var termId = model.AdvancedOptions.SelectedTermId;
                query  = query.Join <TermsPartRecord>().Where(x => x.Terms.Any(a => a.TermRecord.Id == termId));
                lQuery = lQuery.Join <TermsPartRecord>().Where(x => x.Terms.Any(a => a.TermRecord.Id == termId));
            }

            // owner query
            if (    //user cannot see everything by default
                (
                    !Services.Authorizer.Authorize(AdvancedSearchPermissions.SeesAllContent) ||
                    (Services.Authorizer.Authorize(AdvancedSearchPermissions.SeesAllContent) && model.AdvancedOptions.OwnedByMeSeeAll)
                ) && (    //user has either limitation
                    ((Services.Authorizer.Authorize(AdvancedSearchPermissions.MayChooseToSeeOthersContent)) &&
                     (model.AdvancedOptions.OwnedByMe)) ||
                    (Services.Authorizer.Authorize(AdvancedSearchPermissions.CanSeeOwnContents) &&
                     !Services.Authorizer.Authorize(AdvancedSearchPermissions.MayChooseToSeeOthersContent))
                    )
                )
            {
                //this user can only see the contents they own
                var lowerName = Services.WorkContext.CurrentUser.UserName.ToLowerInvariant();
                var email     = Services.WorkContext.CurrentUser.Email;
                var user      = _contentManager.Query <UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName || u.Email == email).List().FirstOrDefault();
                query  = query.Join <CommonPartRecord>().Where(x => x.OwnerId == user.Id);
                lQuery = lQuery.Join <CommonPartRecord>().Where(x => x.OwnerId == user.Id);
            }
            else if (!String.IsNullOrWhiteSpace(model.AdvancedOptions.SelectedOwner))
            {
                var lowerName = model.AdvancedOptions.SelectedOwner == null ? "" : model.AdvancedOptions.SelectedOwner.ToLowerInvariant();
                var email     = model.AdvancedOptions.SelectedOwner;
                var user      = _contentManager.Query <UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName || u.Email == email).List().FirstOrDefault();
                if (user != null)
                {
                    query  = query.Join <CommonPartRecord>().Where(x => x.OwnerId == user.Id);
                    lQuery = lQuery.Join <CommonPartRecord>().Where(x => x.OwnerId == user.Id);
                }
                else
                {
                    _notifier.Add(NotifyType.Warning, T("No user found. Ownership filter not applied."));
                }
            }

            //date query
            if (model.AdvancedOptions.SelectedFromDate != null || model.AdvancedOptions.SelectedToDate != null)
            {
                //set default dates for From and To if they are null.
                var fromD = _dataLocalization.StringToDatetime(model.AdvancedOptions.SelectedFromDate, "") ?? _dataLocalization.StringToDatetime("09/05/1985", "");
                var toD   = _dataLocalization.StringToDatetime(model.AdvancedOptions.SelectedToDate, "") ?? DateTime.Now;

                if (model.AdvancedOptions.DateFilterType == DateFilterOptions.Created)
                {
                    query  = query.Join <CommonPartRecord>().Where(x => x.CreatedUtc >= fromD && x.CreatedUtc <= toD);
                    lQuery = lQuery.Join <CommonPartRecord>().Where(x => x.CreatedUtc >= fromD && x.CreatedUtc <= toD);
                }
                else if (model.AdvancedOptions.DateFilterType == DateFilterOptions.Modified)
                {
                    query  = query.Join <CommonPartRecord>().Where(x => x.ModifiedUtc >= fromD && x.ModifiedUtc <= toD);
                    lQuery = lQuery.Join <CommonPartRecord>().Where(x => x.ModifiedUtc >= fromD && x.ModifiedUtc <= toD);
                }
                else if (model.AdvancedOptions.DateFilterType == DateFilterOptions.Published)
                {
                    query  = query.Join <CommonPartRecord>().Where(x => x.PublishedUtc >= fromD && x.PublishedUtc <= toD);
                    lQuery = lQuery.Join <CommonPartRecord>().Where(x => x.PublishedUtc >= fromD && x.PublishedUtc <= toD);
                }
            }

            // Has media query
            if (model.AdvancedOptions.HasMedia)
            {
                var allCt      = GetListableTypes(false);
                var listFields = new List <string>();
                foreach (var ct in allCt)
                {
                    var allMediaFld = _contentDefinitionService.GetType(ct.Name).Fields.Where(w =>
                                                                                              w._Definition.FieldDefinition.Name == "MediaLibraryPickerField");
                    var allFieldNames = allMediaFld.Select(s => ct.Name + "." + s.Name + ".");
                    listFields.AddRange(allFieldNames);
                }

                query = query.Join <FieldIndexPartRecord>().Where(w => w.StringFieldIndexRecords.Any(
                                                                      w2 => listFields.Contains(w2.PropertyName) && w2.Value != ""
                                                                      ));
                lQuery = lQuery.Join <FieldIndexPartRecord>().Where(w => w.StringFieldIndexRecords.Any(
                                                                        w2 => listFields.Contains(w2.PropertyName) && w2.Value != ""
                                                                        ));
            }

            // Extended Status query
            if (!String.IsNullOrWhiteSpace(model.AdvancedOptions.SelectedStatus))
            {
                query = query.Join <FieldIndexPartRecord>().Where(w => w.StringFieldIndexRecords.Any(
                                                                      w2 => w2.PropertyName == "PublishExtensionPart.PublishExtensionStatus." && w2.Value == model.AdvancedOptions.SelectedStatus
                                                                      ));
                lQuery = lQuery.Join <FieldIndexPartRecord>().Where(w => w.StringFieldIndexRecords.Any(
                                                                        w2 => w2.PropertyName == "PublishExtensionPart.PublishExtensionStatus." && w2.Value == model.AdvancedOptions.SelectedStatus
                                                                        ));
            }
            // FILTER QUERIES: END //


            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);
                lQuery = lQuery.OrderByDescending <CommonPartRecord>(cr => cr.ModifiedUtc);
                break;

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

            case ContentsOrder.Created:
                //query = query.OrderByDescending<ContentPartRecord, int>(ci => ci.Id);
                query  = query.OrderByDescending <CommonPartRecord>(cr => cr.CreatedUtc);
                lQuery = lQuery.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);

            // FILTER MODELS: START //
            // language filter model
            model.AdvancedOptions.LanguageOptions = _commonService.ListCultures().Select(x => new KeyValuePair <int, string>(x.Id, x.Culture));
            // taxonomy filter model
            var termList = new List <KeyValuePair <int, string> >();

            foreach (var taxonomy in _taxonomyService.GetTaxonomies())
            {
                termList.Add(new KeyValuePair <int, string>(-1, taxonomy.Name));
                foreach (var term in _taxonomyService.GetTerms(taxonomy.Id))
                {
                    var gap = new string('-', term.GetLevels());

                    if (gap.Length > 0)
                    {
                        gap += " ";
                    }
                    termList.Add(new KeyValuePair <int, string>(term.Id, gap + term.Name));
                }
            }
            model.AdvancedOptions.TaxonomiesOptions = termList;

            // extended status
            var partDefinition = _contentDefinitionService.GetPart("PublishExtensionPart");

            if (partDefinition != null)
            {
                var      partField = partDefinition.Fields.Where(w => w.Name == "PublishExtensionStatus").SingleOrDefault();
                var      settings  = partField.Settings.GetModel <EnumerationFieldSettings>().Options;
                string[] options   = (!String.IsNullOrWhiteSpace(settings)) ? settings.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None) : null;
                model.AdvancedOptions.StatusOptions = options.Select(s => new KeyValuePair <string, string>(s, T(s).Text));
            }

            #region TEST OF CPF QUERIES
            //if (model.AdvancedOptions.CPFOwnerId != null) {
            //    var item = _contentManager.Get((int)model.AdvancedOptions.CPFOwnerId);
            //    var parts = item.Parts;
            //    list = Shape.List();
            //    foreach (var part in parts) {
            //        foreach (var field in part.Fields) {
            //            if (field.FieldDefinition.Name == "ContentPickerField") {
            //                bool noName = String.IsNullOrWhiteSpace(model.AdvancedOptions.CPFName);
            //                if (noName || (!noName && field.Name == model.AdvancedOptions.CPFName)) {
            //                    var relatedItems = _contentManager.GetMany<ContentItem>((IEnumerable<int>)field.GetType().GetProperty("Ids").GetValue(field), VersionOptions.Latest, QueryHints.Empty);

            //                    list.AddRange(relatedItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));
            //                }
            //            }
            //        }
            //    }
            //}
            if (model.AdvancedOptions.CPFIdToSearch != null && !String.IsNullOrWhiteSpace(model.AdvancedOptions.CPFName))
            {
                //given an Id, search for all items that have a Content Picker Field whose PropertyName is PCFName and that have the
                //Id among the corresponding values.
                string fieldName = (string)model.AdvancedOptions.CPFName;
                query = query.Join <FieldIndexPartRecord>()
                        .Where(fip =>
                               fip.StringFieldIndexRecords
                               .Any(sfi =>
                                    sfi.PropertyName.Contains(fieldName) &&
                                    sfi.LatestValue.Contains("{" + model.AdvancedOptions.CPFIdToSearch.ToString() + "}")
                                    )
                               );
                lQuery = lQuery.Join <FieldIndexPartRecord>()
                         .Where(fip =>
                                fip.StringFieldIndexRecords
                                .Any(sfi =>
                                     sfi.PropertyName.Contains(fieldName) &&
                                     sfi.LatestValue.Contains("{" + model.AdvancedOptions.CPFIdToSearch.ToString() + "}")
                                     )
                                );
            }
            #endregion

            // FILTER MODELS: END //


            //EXECUTE QUERIES

            var pagerShape = Shape.Pager(pager).TotalItemCount(0);
            var list       = Shape.List();
            IEnumerable <ContentItem> pageOfContentItems = (IEnumerable <ContentItem>)null;

            //Stopwatch sw = Stopwatch.StartNew();

            //the user may not have permission to see anything: in that case, do not execute the query
            #region original query
            //this is roughly 1000 slower than the variant below
            //if (Services.Authorizer.Authorize(AdvancedSearchPermissions.CanSeeOwnContents)) {
            //    // language query
            //    //For any language query, remember that Orchard's localization table, as of Orchard 1.8, has an issue where the content
            //    //created but never translated does not have the default Culture assigned to it.
            //    Expression<Func<LocalizationPartRecord, bool>> selLangPredicate = null;
            //    if (model.AdvancedOptions.SelectedLanguageId > 0) {
            //        bool siteCultureSelected = _cultureManager.GetSiteCulture() == _cultureManager.GetCultureById(model.AdvancedOptions.SelectedLanguageId).Culture;
            //        if (siteCultureSelected) {
            //            selLangPredicate =
            //                x => x.CultureId == model.AdvancedOptions.SelectedLanguageId ||
            //                    x.CultureId == 0;
            //        } else {
            //            selLangPredicate =
            //                x => x.CultureId == model.AdvancedOptions.SelectedLanguageId;
            //        }
            //    }
            //    if (model.AdvancedOptions.SelectedLanguageId > 0) {
            //        query = query.Join<LocalizationPartRecord>().Where(selLangPredicate);
            //    }
            //    //if we want only items that do not have a specific translation, we have to do things differently,
            //    //because the check is done after the query. Hence, for example, we cannot directly page.
            //    if (model.AdvancedOptions.SelectedUntranslatedLanguageId > 0) {
            //        var allCi = query.List();
            //        //for (int i = 0; i < allCi.Count(); i++) { //this loop is used to test null conditions and other stuff like that while debugging
            //        //    var ci = allCi.ElementAt(i);
            //        //    if (ci.Is<LocalizationPart>()) {
            //        //        var lci = _localizationService.GetLocalizations(ci, versionOptions);
            //        //        var clci = lci.Count();
            //        //        var bo = lci.Any(li => li.Culture.Id == model.AdvancedOptions.SelectedUntranslatedLanguageId);
            //        //    }
            //        //}
            //        var untranslatedCi = allCi
            //            .Where(x =>
            //                x.Is<LocalizationPart>() && //the content is translatable
            //                (
            //                    x.As<LocalizationPart>().Culture == null || //this is the case where the content was created and never translated to any other culture.
            //                    x.As<LocalizationPart>().Culture.Id != model.AdvancedOptions.SelectedUntranslatedLanguageId //not a content in the language in which we are looking translations
            //                ) &&
            //                _localizationService.GetLocalizations(x, versionOptions) != null &&
            //                !_localizationService.GetLocalizations(x, versionOptions).Any(li =>
            //                    li.Culture != null &&
            //                    li.Culture.Id == model.AdvancedOptions.SelectedUntranslatedLanguageId
            //                )
            //            );
            //        //.Where(x =>
            //        //    x.Is<LocalizationPart>() && //some content items may not be translatable
            //        //    (
            //        //        (x.As<LocalizationPart>().Culture != null && x.As<LocalizationPart>().Culture.Id != model.AdvancedOptions.SelectedUntranslatedLanguageId) ||
            //        //        (x.As<LocalizationPart>().Culture == null) //this is the case where the content was created and never translated to any other culture.
            //        //        //In that case, in Orchard 1.8, no culture is directly assigned to it, even though the default culture is assumed.
            //        //    ) &&
            //        //    x.As<LocalizationPart>().MasterContentItem == null &&
            //        //    !allCi.Any(y =>
            //        //        y.Is<LocalizationPart>() &&
            //        //        (y.As<LocalizationPart>().MasterContentItem == x || y.As<LocalizationPart>().MasterContentItem == x.As<LocalizationPart>().MasterContentItem) &&
            //        //        y.As<LocalizationPart>().Culture.Id == model.AdvancedOptions.SelectedUntranslatedLanguageId
            //        //    )
            //        //);
            //        //Paging
            //        pagerShape = Shape.Pager(pager).TotalItemCount(untranslatedCi.Count());
            //        int pSize = pager.PageSize != 0 ? pager.PageSize : untranslatedCi.Count();
            //        pageOfContentItems = untranslatedCi
            //            .Skip(pager.GetStartIndex())
            //            .Take((pager.GetStartIndex() + pSize) > untranslatedCi.Count() ?
            //                untranslatedCi.Count() - pager.GetStartIndex() :
            //                pSize)
            //            .ToList();
            //    } else {
            //        pagerShape = Shape.Pager(pager).TotalItemCount(query.Count());
            //        pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
            //    }
            //} else {
            //    Services.Notifier.Error(T("Not authorized to visualize any item."));
            //}
            #endregion

            if (Services.Authorizer.Authorize(AdvancedSearchPermissions.CanSeeOwnContents))
            {
                // language queries
                //For any language query, remember that Orchard's localization table, as of Orchard 1.8, has an issue where the content
                //created but never translated does not have the default Culture assigned to it.
                Expression <Func <LocalizationPartRecord, bool> > selLangPredicate = null;
                if (model.AdvancedOptions.SelectedLanguageId > 0)
                {
                    bool siteCultureSelected = _cultureManager.GetSiteCulture() == _cultureManager.GetCultureById(model.AdvancedOptions.SelectedLanguageId).Culture;
                    if (siteCultureSelected)
                    {
                        selLangPredicate =
                            x => x.CultureId == model.AdvancedOptions.SelectedLanguageId ||
                            x.CultureId == 0;
                    }
                    else
                    {
                        selLangPredicate =
                            x => x.CultureId == model.AdvancedOptions.SelectedLanguageId;
                    }

                    query = query.Join <LocalizationPartRecord>().Where(selLangPredicate);
                }
                Expression <Func <LocalizationPartRecord, bool> > untranLangPredicate = null;
                if (model.AdvancedOptions.SelectedUntranslatedLanguageId > 0)
                {
                    bool siteCultureSelected = _cultureManager.GetSiteCulture() == _cultureManager.GetCultureById(model.AdvancedOptions.SelectedUntranslatedLanguageId).Culture;
                    if (siteCultureSelected)
                    {
                        untranLangPredicate =
                            x => x.CultureId == model.AdvancedOptions.SelectedUntranslatedLanguageId ||
                            x.CultureId == 0;
                    }
                    else
                    {
                        untranLangPredicate =
                            x => x.CultureId == model.AdvancedOptions.SelectedUntranslatedLanguageId;
                    }

                    lQuery = lQuery.Join <LocalizationPartRecord>().Where(untranLangPredicate);
                    var lRes    = lQuery.List();
                    var masters = lRes.Where(x => x.As <LocalizationPart>().Record.MasterContentItemId != 0).Select(x => x.As <LocalizationPart>().Record.MasterContentItemId).ToList();
                    var items   = lRes.Select(x => x.Id).ToList();

                    Expression <Func <LocalizationPartRecord, bool> > sulPredicate =
                        x => x.CultureId != model.AdvancedOptions.SelectedUntranslatedLanguageId &&
                        !masters.Contains(x.Id) && !masters.Contains(x.MasterContentItemId) && !items.Contains(x.MasterContentItemId);

                    query = query.Join <LocalizationPartRecord>().Where(sulPredicate);
                }

                pagerShape         = Shape.Pager(pager).TotalItemCount(query.Count());
                pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
            }
            else
            {
                Services.Notifier.Error(T("Not authorized to visualize any item."));
            }

            //sw.Stop();
            //Services.Notifier.Error(new LocalizedString(sw.Elapsed.TotalMilliseconds.ToString()));

            if (pageOfContentItems != null)
            {
                list.AddRange(pageOfContentItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));
            }

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

            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();

            // 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. 19
0
        public void UserToContact(IUser userContent)
        {
            // verifiche preliminari
            if (userContent.Id == 0)
            {
                // non crea il contatto se lo user non è ancora stato salvato
                return;
            }
            var user = userContent.ContentItem;

            if (user.As <UserPart>().RegistrationStatus == UserStatus.Pending)
            {
                return;
            }
            // identifica il Contact relativo a UserContent
            var contactsUsers = _orchardServices
                                .ContentManager
                                .Query <CommunicationContactPart, CommunicationContactPartRecord>()
                                .Where(x => x.UserPartRecord_Id == userContent.Id)
                                .List().FirstOrDefault();

            var typeIsDraftable = _contentDefinitionManager.GetTypeDefinition("CommunicationContact").Settings.GetModel <ContentTypeSettings>().Draftable;

            ContentItem contact = null;

            if (contactsUsers == null)
            {
                // cerca un eventuale contatto con la stessa mail ma non ancora legato a uno user
                var contactEmailList = GetContactsFromMail(userContent.Email);
                foreach (var contactEmail in contactEmailList)
                {
                    if ((contactEmail != null) && (contactEmail.ContentType == "CommunicationContact"))
                    {
                        if ((contactEmail.As <CommunicationContactPart>().Record.UserPartRecord_Id == 0) && (contactEmail.As <CommunicationContactPart>().Master == false))
                        {
                            //contact = contactEmail;
                            contact = _orchardServices.ContentManager.Get(contactEmail.Id, typeIsDraftable ? VersionOptions.DraftRequired : VersionOptions.Latest);
                            contact.As <CommunicationContactPart>().Logs =
                                TruncateFromStart(contact.As <CommunicationContactPart>().Logs +
                                                  string.Format(T("This contact has been bound to its user on {0:yyyy-MM-dd HH:mm} by contact synchronize function. ").Text,
                                                                DateTime.Now), 4000); //4000 sembra essere la lunghezza massima gestita da NHibernate per gli nvarchar(max)
                            contact.As <CommunicationContactPart>().UserIdentifier = userContent.Id;
                            break;                                                    // associa solo il primo contatto che trova
                        }
                    }
                }

                if (contact == null)
                {
                    //even if typeIsDraftable == false, it's fine to create as Draft, because we are going to publish later in this method
                    //and creating as draft does the same things as not as draft, but sets Published = false already.
                    contact = _orchardServices.ContentManager.Create("CommunicationContact", VersionOptions.Draft);
                    contact.As <CommunicationContactPart>().Master         = false;
                    contact.As <CommunicationContactPart>().UserIdentifier = userContent.Id;
                }
            }
            else
            {
                contact = _orchardServices.ContentManager.Get(contactsUsers.Id, typeIsDraftable ? VersionOptions.DraftRequired : VersionOptions.Latest);
            }

            #region aggiorna Pushcategories
            try {
                if (((dynamic)user).User.Pushcategories != null && (((dynamic)contact).CommunicationContactPart).Pushcategories != null)
                {
                    List <TermPart> ListTermPartToAdd = _taxonomyService.GetTermsForContentItem(userContent.Id, "Pushcategories").ToList();
                    _taxonomyService.UpdateTerms(contact, ListTermPartToAdd, "Pushcategories");
                }
            }
            catch { // non ci sono le Pushcategories
            }
            #endregion

            #region aggiorna FavoriteCulture
            try {
                if ((user.As <FavoriteCulturePart>() != null) && (contact.As <FavoriteCulturePart>() != null))
                {
                    if (user.As <FavoriteCulturePart>().Culture_Id != 0)
                    {
                        if (user.As <FavoriteCulturePart>().Culture_Id != contact.As <FavoriteCulturePart>().Culture_Id)
                        {
                            contact.As <FavoriteCulturePart>().Culture_Id = user.As <FavoriteCulturePart>().Culture_Id;
                        }
                    }
                    else
                    {
                        // imposta la culture di default
                        var defaultCultureId = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture()).Id;
                        contact.As <FavoriteCulturePart>().Culture_Id = defaultCultureId;
                        user.As <FavoriteCulturePart>().Culture_Id    = defaultCultureId;
                    }
                }
            }
            catch { // non si ha l'estensione per favorite culture
            }
            #endregion

            #region aggiorna email
            if (!string.IsNullOrEmpty(userContent.Email) && user.As <UserPart>().RegistrationStatus == UserStatus.Approved)
            {
                AddEmailToContact(userContent.Email, contact);
            }
            #endregion

            #region aggiorna sms
            try {
                dynamic userPwdRecoveryPart = ((dynamic)user).UserPwdRecoveryPart;
                if (userPwdRecoveryPart != null)
                {
                    AddSmsToContact(userPwdRecoveryPart.InternationalPrefix, userPwdRecoveryPart.PhoneNumber, contact, true);
                }
            }
            catch {
                // non è abilitato il modulo Laser.Mobile.SMS, quindi non allineo il telefono
            }
            #endregion

            #region aggiorna Title
            if (string.IsNullOrWhiteSpace(userContent.UserName) == false)
            {
                contact.As <TitlePart>().Title = userContent.UserName;
            }
            else if (string.IsNullOrWhiteSpace(userContent.Email) == false)
            {
                contact.As <TitlePart>().Title = userContent.Email;
            }
            else
            {
                contact.As <TitlePart>().Title = string.Format("User with ID {0}", userContent.Id);
            }
            #endregion

            #region aggiorna CommonPart
            if (contact.Has <CommonPart>())
            {
                contact.As <CommonPart>().ModifiedUtc = DateTime.Now;
                contact.As <CommonPart>().Owner       = userContent;
            }
            #endregion

            CopyProfilePart(user, contact);

            CopyPolicyAnswers(user, contact);

            if (contact != null)
            {
                //Whether the type is draftable or not, we still want to publish it, so at worst setting Published = false does nothing
                contact.VersionRecord.Published = false;
                _orchardServices.ContentManager.Publish(contact);
            }
        }
Esempio n. 20
0
        public ActionResult TranslatePOST(int id, Action <ContentItem> conditionallyPublish)
        {
            var contentItem = _contentManager.Get(id, VersionOptions.Latest);

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

            var model = new AddLocalizationViewModel();

            TryUpdateModel(model);

            ContentItem contentItemTranslation;
            var         existingTranslation = _localizationService.GetLocalizedContentItem(contentItem, model.SelectedCulture);

            if (existingTranslation != null)
            {
                // edit existing
                contentItemTranslation = _contentManager.Get(existingTranslation.ContentItem.Id, VersionOptions.DraftRequired);
            }
            else
            {
                // create
                contentItemTranslation = _contentManager.New(contentItem.ContentType);
                if (contentItemTranslation.Has <ICommonPart>() && contentItem.Has <ICommonPart>())
                {
                    contentItemTranslation.As <ICommonPart>().Container = contentItem.As <ICommonPart>().Container;
                }

                _contentManager.Create(contentItemTranslation, VersionOptions.Draft);
            }

            model.Content = _contentManager.UpdateEditor(contentItemTranslation, this);

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();
                model.SiteCultures = _cultureManager.ListCultures().Where(s => s != _localizationService.GetContentCulture(contentItem) && s != _cultureManager.GetSiteCulture());
                var culture = contentItem.As <LocalizationPart>().Culture;
                if (culture != null)
                {
                    culture.Culture = null;
                }
                model.Content = _contentManager.BuildEditor(contentItem);

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

                return(View(model));
            }

            if (existingTranslation != null)
            {
                Services.Notifier.Information(T("Edited content item translation."));
            }
            else
            {
                LocalizationPart localized = contentItemTranslation.As <LocalizationPart>();
                localized.MasterContentItem = contentItem;
                if (!string.IsNullOrWhiteSpace(model.SelectedCulture))
                {
                    localized.Culture = _cultureManager.GetCultureByName(model.SelectedCulture);
                }

                conditionallyPublish(contentItemTranslation);

                Services.Notifier.Information(T("Created content item translation."));
            }

            var metadata = _contentManager.GetItemMetadata(model.Content.ContentItem);

            //todo: (heskew) if null, redirect to somewhere better than nowhere
            return(metadata.EditorRouteValues == null ? null : RedirectToRoute(metadata.EditorRouteValues));
        }
Esempio n. 21
0
        public void Register(UserRegistration userRegistrationParams)
        {
            if (RegistrationSettings.UsersCanRegister)
            {
                var policyAnswers = new List <PolicyForUserViewModel>();
                if (_utilsServices.FeatureIsEnabled("Laser.Orchard.Policy") &&
                    UserRegistrationExtensionsSettings.IncludePendingPolicy == Policy.IncludePendingPolicyOptions.Yes)
                {
                    IEnumerable <PolicyTextInfoPart> policies = GetUserLinkedPolicies(userRegistrationParams.Culture);
                    // controllo che tutte le policy abbiano una risposta e che le policy obbligatorie siano accettate
                    var allRight = true;
                    foreach (var policy in policies)
                    {
                        var policyId       = policy.Id;
                        var policyRequired = policy.UserHaveToAccept;
                        var answer         = userRegistrationParams.PolicyAnswers.Where(w => w.PolicyId == policyId).SingleOrDefault();
                        if (answer != null)
                        {
                            if (!answer.PolicyAnswer && policyRequired)
                            {
                                allRight = false;
                            }
                        }
                        else if (answer == null && policyRequired)
                        {
                            allRight = false;
                        }
                        if (answer != null)
                        {
                            policyAnswers.Add(new PolicyForUserViewModel {
                                OldAccepted  = false,
                                PolicyTextId = policyId,
                                Accepted     = answer.PolicyAnswer,
                                AnswerDate   = DateTime.Now
                            });
                        }
                    }
                    if (!allRight)
                    {
                        throw new SecurityException(T("User has to accept policies!").Text);
                    }
                }
                var registrationErrors = new List <string>();
                if (ValidateRegistration(userRegistrationParams.Username, userRegistrationParams.Email,
                                         userRegistrationParams.Password, userRegistrationParams.ConfirmPassword, out registrationErrors))
                {
                    var createdUser = _membershipService.CreateUser(new CreateUserParams(
                                                                        userRegistrationParams.Username,
                                                                        userRegistrationParams.Password,
                                                                        userRegistrationParams.Email,
                                                                        userRegistrationParams.PasswordQuestion,
                                                                        userRegistrationParams.PasswordAnswer,
                                                                        (RegistrationSettings.UsersAreModerated == false) && (RegistrationSettings.UsersMustValidateEmail == false),
                                                                        false
                                                                        ));
                    // _membershipService.CreateUser may return null and tell nothing about why it failed to create the user
                    // if the Creating user event handlers set the flag to cancel user creation.
                    if (createdUser == null)
                    {
                        throw new SecurityException(T("User registration failed.").Text);
                    }
                    // here user was created
                    var favCulture = createdUser.As <FavoriteCulturePart>();
                    if (favCulture != null)
                    {
                        var culture = _commonsServices.ListCultures().SingleOrDefault(x => x.Culture.Equals(userRegistrationParams.Culture));
                        if (culture != null)
                        {
                            favCulture.Culture_Id = culture.Id;
                        }
                        else
                        {
                            // usa la culture di default del sito
                            favCulture.Culture_Id = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture()).Id;
                        }
                    }
                    if ((RegistrationSettings.UsersAreModerated == false) && (RegistrationSettings.UsersMustValidateEmail == false))
                    {
                        _userEventHandler.LoggingIn(userRegistrationParams.Username, userRegistrationParams.Password);
                        _authenticationService.SignIn(createdUser, userRegistrationParams.CreatePersistentCookie);
                        // solleva l'evento LoggedIn sull'utente
                        _userEventHandler.LoggedIn(createdUser);
                    }

                    // [HS] BEGIN: Whe have to save the PoliciesAnswers cookie and persist answers on the DB after Login/SignIn events because during Login/Signin events database is not updated yet and those events override cookie in an unconsistent way.
                    if (_utilsServices.FeatureIsEnabled("Laser.Orchard.Policy") && UserRegistrationExtensionsSettings.IncludePendingPolicy == Policy.IncludePendingPolicyOptions.Yes)
                    {
                        _policyServices.PolicyForUserMassiveUpdate(policyAnswers, createdUser);
                    }
                    // [HS] END

                    if (RegistrationSettings.UsersMustValidateEmail)
                    {
                        // send challenge e-mail
                        var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
                        if (string.IsNullOrWhiteSpace(siteUrl))
                        {
                            siteUrl = HttpContext.Current.Request.ToRootUrlString();
                        }
                        UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                        _userService.SendChallengeEmail(createdUser, nonce => urlHelper.MakeAbsolute(urlHelper.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
                    }
                }
                else
                {
                    throw new SecurityException(String.Join(", ", registrationErrors));
                }
            }
            else
            {
                throw new SecurityException(T("User cannot register due to Site settings").Text);
            }
        }
Esempio n. 22
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));
        }
 public string GetSiteCulture()
 {
     return(_cultureManager.GetSiteCulture());
 }
        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));
        }