LocalizationPart ILocalizationService.GetLocalizedContentItem(IContent content, string culture, VersionOptions versionOptions)
        {
            var cultureRecord = _cultureManager.GetCultureByName(culture);

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

            var localized = content.As <LocalizationPart>();

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

            // Warning: Returns only the first of same culture localizations.
            return(_contentManager
                   .Query <LocalizationPart>(versionOptions, content.ContentItem.ContentType)
                   .Where <LocalizationPartRecord>(l =>
                                                   (l.Id == content.ContentItem.Id || l.MasterContentItemId == content.ContentItem.Id) &&
                                                   l.CultureId == cultureRecord.Id)
                   .Slice(1)
                   .FirstOrDefault());
        }
Esempio n. 2
0
        protected override void Importing(LocalizationPart part, ImportContentContext context)
        {
            var masterContentItem = context.Attribute(part.PartDefinition.Name, "MasterContentItem");

            if (masterContentItem != null)
            {
                var contentItem = context.GetItemFromSession(masterContentItem);
                if (contentItem != null)
                {
                    part.MasterContentItem = contentItem;
                }
            }

            var culture = context.Attribute(part.PartDefinition.Name, "Culture");

            if (culture != null)
            {
                var targetCulture = _cultureManager.GetCultureByName(culture);
                // Add Culture.
                if (targetCulture == null && _cultureManager.IsValidCulture(culture))
                {
                    _cultureManager.AddCulture(culture);
                    targetCulture = _cultureManager.GetCultureByName(culture);
                }
                part.Culture = targetCulture;
            }
        }
Esempio n. 3
0
        protected override void Importing(LocalizationPart part, ImportContentContext context)
        {
            // Don't do anything if the tag is not specified.
            if (context.Data.Element(part.PartDefinition.Name) == null)
            {
                return;
            }

            context.ImportAttribute(part.PartDefinition.Name, "MasterContentItem", masterContentItem => {
                var contentItem = context.GetItemFromSession(masterContentItem);
                if (contentItem != null)
                {
                    part.MasterContentItem = contentItem;
                }
            });

            context.ImportAttribute(part.PartDefinition.Name, "Culture", culture => {
                var targetCulture = _cultureManager.GetCultureByName(culture);
                // Add Culture.
                if (targetCulture == null && _cultureManager.IsValidCulture(culture))
                {
                    _cultureManager.AddCulture(culture);
                    targetCulture = _cultureManager.GetCultureByName(culture);
                }
                part.Culture = targetCulture;
            });
        }
 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. 5
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. 6
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());
 }
        LocalizationPart ILocalizationService.GetLocalizedContentItem(IContent content, string culture)
        {
            var cultureRecord = _cultureManager.GetCultureByName(culture);

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

            return(_contentManager.Query(content.ContentItem.ContentType)
                   .Where <LocalizationPartRecord>(l => l.MasterContentItemId == content.ContentItem.Id && l.CultureId == cultureRecord.Id)
                   .List()
                   .Select(i => i.As <LocalizationPart>())
                   .SingleOrDefault());
        }
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);
        }
        private IHqlQuery IntegrateAdditionalConditions(IHqlQuery query, Int32?idlocalization)
        {
            if (query == null)
            {
                query = _orchardServices.ContentManager.HqlQuery().ForType(new string[] { "CommunicationContact" });
            }
            // Query in base alla localizzazione del contenuto
            //  var localizedPart = content.As<LocalizationPart>();
            if (idlocalization != null)
            {
                //var langId = _cultureManager.GetCultureByName(_orchardServices.WorkContext.CurrentSite.SiteCulture).Id;  //default site lang
                //if (localizedPart.Culture != null) {
                //    langId = localizedPart.Culture.Id;
                //}
                if (idlocalization == _cultureManager.GetCultureByName(_orchardServices.WorkContext.CurrentSite.SiteCulture).Id)
                {
                    // la lingua è quella di default del sito, quindi prendo tutti quelli che hanno espresso la preferenza sulla lingua e quelli che non l'hanno espressa
                    query = query
                            .Where(x => x.ContentPartRecord <FavoriteCulturePartRecord>(), x => x.Disjunction(a => a.Eq("Culture_Id", idlocalization), b => b.Eq("Culture_Id", 0))); // lingua prescelta uguale a lingua contenuto oppure nessuna lingua prescelta e allora
                }
                else
                {
                    // la lingua NON è quella di default del sito, quindi prendo SOLO quelli che hanno espresso la preferenza sulla lingua
                    query = query
                            .Where(x => x.ContentPartRecord <FavoriteCulturePartRecord>(), x => x.Eq("Culture_Id", idlocalization));
                }
            }

            query = query
                    .Where(x => x.ContentPartRecord <EmailContactPartRecord>(), x => x.IsNotEmpty("EmailRecord"));

            return(query);
        }
        /// <summary>
        /// Get pending policies: policies for which the user has not yet expressed his opinion
        /// </summary>
        /// <param name="context">Context of the showing content</param>
        /// <param name="part">the PolicyPart that describe which policies should be checked</param>
        /// <returns>The IContentQuery that returns the list of the pending policies</returns>
        private IContentQuery GetPendingPolicies(LoadContentContext context, PolicyPart part)
        {
            var loggedUser = _workContext.GetContext().CurrentUser;
            int currentLanguageId;
            IContentQuery <PolicyTextInfoPart> query;

            if (context.ContentItem.As <LocalizationPart>() != null && context.ContentItem.As <LocalizationPart>().Culture != null && context.ContentItem.As <LocalizationPart>().Culture.Id > 0)
            {
                currentLanguageId = context.ContentItem.As <LocalizationPart>().Culture.Id;
            }
            else
            {
                //Nel caso di contenuto senza Localizationpart prendo la CurrentCulture
                currentLanguageId = _cultureManager.GetCultureByName(_workContext.GetContext().CurrentCulture).Id;
            }

            query = _contentManager.Query <PolicyTextInfoPart>().Join <LocalizationPartRecord>().Where(w => w.CultureId == currentLanguageId || w.CultureId == 0);

            //recupero solo le Policy Pendenti, alle quali l'utente non ha risposto ancora

            IContentQuery <PolicyTextInfoPart, PolicyTextInfoPartRecord> items;

            if (loggedUser != null)
            {
                var answeredIds = loggedUser.As <UserPolicyPart>().UserPolicyAnswers.Select(s => s.PolicyTextInfoPartRecord.Id).ToArray();
                items = query.Where <PolicyTextInfoPartRecord>(w => !answeredIds.Contains(w.Id));
            }
            else
            {
                IList <PolicyForUserViewModel> answers = _policyServices.GetCookieOrVolatileAnswers();
                var answeredIds = answers.Select(s => s.PolicyTextId).ToArray();
                items = query.Where <PolicyTextInfoPartRecord>(w => !answeredIds.Contains(w.Id));
            }

            var settings = part.Settings.GetModel <PolicyPartSettings>();

            if (!settings.PolicyTextReferences.Contains("{All}"))
            {
                int[] filterIds;

                string[] filterComplexIds = _policyServices.GetPoliciesForContent(part);

                if (filterComplexIds != null)
                {
                    if (filterComplexIds.Length == 1)
                    {
                        filterComplexIds = filterComplexIds[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    filterIds = filterComplexIds.Select(s => {
                        int id = 0;
                        int.TryParse(s.Replace("{", "").Replace("}", ""), out id);
                        return(id);
                    }).ToArray();

                    items = items.Where <PolicyTextInfoPartRecord>(w => filterIds.Contains(w.Id));
                }
            }

            return(items.OrderByDescending(x => x.Priority));
        }
Esempio n. 11
0
        protected override DriverResult Editor(CommunicationAdvertisingPart part, dynamic shapeHelper)
        {
            bool linkinterno = true;

            if (!string.IsNullOrEmpty(((dynamic)part).UrlLinked.Value))
            {
                linkinterno = false;
            }

            var shapes = new List <DriverResult>();
            Dictionary <string, Int32> model = new Dictionary <string, int>();

            if (part.ContentItem.As <LocalizationPart>().Culture != null)
            {
                model.Add("LocalizationId", part.ContentItem.As <LocalizationPart>().Culture.Id);
            }
            else
            {
                model.Add("LocalizationId", _cultureManager.GetCultureByName(_orchardServices.WorkContext.CurrentSite.SiteCulture).Id);
            }
            model.Add("ContentItemId", part.ContentItem.Id);
            shapes.Add(ContentShape("Parts_Advertising_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts/Advertising_Edit", Model: model, Prefix: Prefix)));//
            shapes.Add(ContentShape("Parts_AdvertisingSwitcher", () => shapeHelper.EditorTemplate(TemplateName: "Parts/AdvertisingSwitcher", Model: linkinterno, Prefix: Prefix)));

            return(new CombinedResult(shapes));
        }
Esempio n. 12
0
        public void ApplyFilter(dynamic context)
        {
            string currentCulture   = _workContextAccessor.GetContext().CurrentCulture;
            var    currentCultureId = _cultureManager.GetCultureByName(currentCulture).Id;

            var query = (IHqlQuery)context.Query;

            context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(), x => x.Eq("CultureId", currentCultureId));
        }
Esempio n. 13
0
        public void ApplyFilter(dynamic context)
        {
            string siteCulture          = _workContextAccessor.GetContext().CurrentSite.SiteCulture;
            int    siteCultureId        = _cultureManager.GetCultureByName(siteCulture).Id;
            string currentCulture       = _workContextAccessor.GetContext().CurrentCulture;
            var    currentCultureRecord = _cultureManager.GetCultureByName(currentCulture);
            int    currentCultureId     = siteCultureId;

            if (currentCultureRecord != null)
            {
                currentCultureId = currentCultureRecord.Id;
            }

            var query = (IHqlQuery)context.Query;

            if (currentCultureId == siteCultureId)
            {
                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(), x => x.Or(c => c.Eq("CultureId", currentCultureId), nc => nc.Eq("CultureId", 0)));
            }
            else
            {
                var listIdsQ = _contentManager.HqlQuery()
                               .ForPart <LocalizationPart>()
                               .Where(alias => alias.ContentPartRecord <LocalizationPartRecord>(), x => x.Or(expr => expr.Eq("CultureId", currentCultureId), expr2 => expr2.Eq("CultureId", 0))).List();
                var listIds = new int[] { 0 };
                if (listIdsQ != null)
                {
                    listIds = listIdsQ.Where(w => w.MasterContentItem != null).Select(s => s.MasterContentItem.Id).ToArray();
                }

                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(),
                                            x => x.Or(
                                                y => y.Or(
                                                    z => z.Eq("CultureId", currentCultureId),
                                                    h => h.And(
                                                        z => z.Eq("CultureId", siteCultureId),
                                                        z => z.Not(a => a.InG("Id", listIds))
                                                        )
                                                    ),
                                                y => y.Eq("CultureId", 0)
                                                )
                                            );
            }
        }
Esempio n. 14
0
 protected override void Importing(FavoriteCulturePart part, ImportContentContext context)
 {
     context.ImportAttribute(part.PartDefinition.Name, "Culture_Id", x => {
         var culture = _cultureManager.GetCultureByName(x);
         if (culture != null)
         {
             part.Culture_Id = culture.Id;
         }
     });
 }
        public IContentQuery <ContentItem> FilterCulture(IContentQuery <ContentItem> query, string cultureName)
        {
            var culture = _cultureManager.GetCultureByName(cultureName);

            if (culture != null)
            {
                return(query.Where <LocalizationPartRecord>(x => x.CultureId == culture.Id));
            }

            return(query);
        }
Esempio n. 16
0
        /// <summary>
        /// This method is to wrap a level of cache around fetching cultures
        /// from the repository, because otherwise it keeps requiring a connection
        /// to the database.
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns>The CultureRecord with the given name.</returns>
        /// <remarks>TODO: this should probably be the default behaviour of
        /// DefaultCultureManager.GetCultureByName()</remarks>
        private CultureRecord GetCultureByName(string cultureName)
        {
            var cacheKey = $"{KeyBase}_GetCultureByName_{cultureName}";

            return(_cacheManager.Get(cacheKey, true, ctx => {
                // this is the same signal used in Orchard.Framework.DefaultCultureManager
                ctx.Monitor(_signals.When("culturesChanged"));
                // invoke the method from the ICultureManager
                return _cultureManager.GetCultureByName(cultureName);
            }));
        }
        LocalizationPart ILocalizationService.GetLocalizedContentItem(IContent content, string culture, VersionOptions versionOptions)
        {
            var cultureRecord = _cultureManager.GetCultureByName(culture);

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

            var localized = content.As <LocalizationPart>();

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

            if (localized.Culture.Culture == culture)
            {
                return(localized);
            }

            return(((ILocalizationService)this).GetLocalizations(content, versionOptions).FirstOrDefault(x => x.Culture.Id == cultureRecord.Id));
        }
        public void ApplyFilter(dynamic context)
        {
            string currentCulture       = _workContextAccessor.GetContext().CurrentCulture;
            string siteCulture          = _workContextAccessor.GetContext().CurrentSite.SiteCulture;
            int    siteCultureId        = _cultureManager.GetCultureByName(siteCulture).Id;
            int    currentCultureId     = siteCultureId;
            var    currentCultureRecord = _cultureManager.GetCultureByName(currentCulture);

            if (currentCultureRecord != null)
            {
                currentCultureId = currentCultureRecord.Id;
            }
            var query = (IHqlQuery)context.Query;

            if (currentCultureId == siteCultureId)
            {
                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(), x => x.Or(c => c.Eq("CultureId", currentCultureId), nc => nc.Eq("CultureId", 0)));
            }
            else
            {
                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(), c => c.Eq("CultureId", currentCultureId));
            }
        }
        public IEnumerable <LocalizationPart> GetLocalizations(LocalizationPart part, VersionOptions versionOptions)
        {
            CultureRecord siteCulture = null;

            return(new[] { (part.MasterContentItem ?? part.ContentItem).As <LocalizationPart>() }
                   .Union(part.Id > 0 ? _localizationService.GetLocalizations(part.MasterContentItem ?? part.ContentItem, versionOptions) : new LocalizationPart[0])
                   .Select(c =>
            {
                var localized = c.ContentItem.As <LocalizationPart>();
                if (localized.Culture == null)
                {
                    localized.Culture = siteCulture ?? (siteCulture = _cultureManager.GetCultureByName(GetSiteCulture()));
                }
                return c;
            }));
        }
Esempio n. 20
0
        public void ApplyFilter(dynamic context)
        {
            var query = (IHqlQuery)context.Query;

            if (context.State != null)
            {
                if (context.State.FavoriteCulture != null && context.State.FavoriteCulture != "")
                {
                    var cultureId = 0;
                    if (!int.TryParse(context.State.FavoriteCulture.Value.ToString(), out cultureId))
                    {
                        try {
                            cultureId = _cultureManager.GetCultureByName(context.State.FavoriteCulture.Value).Id;
                        } catch { // Nel caso in cui non riesca a recuperare la cultura dalla stringa, allora considera la culture nulla e non restituisce nessun record
                        }
                    }
                    context.Query = query.Where(x => x.ContentPartRecord <FavoriteCulturePartRecord>(), x => x.Eq("Culture_Id", cultureId));
                }
            }
            return;
        }
Esempio n. 21
0
 public Orchard.Localization.Records.CultureRecord GetCultureByName(string cultureName)
 {
     return(_underlyingCultureManager.GetCultureByName(cultureName));
 }
        public ActionResult MediaItems(string folderPath, int skip = 0, int count = 0, string order = "created", string mediaType = "", string culture = "")
        {
            if (String.IsNullOrWhiteSpace(folderPath))
            {
                folderPath = null;
            }
            if (!_mediaLibraryService.CheckMediaFolderPermission(Permissions.SelectMediaContent, folderPath))
            {
                Services.Notifier.Add(UI.Notify.NotifyType.Error, T("Cannot select media"));
                var model = new MediaManagerMediaItemsViewModel {
                    MediaItems      = new List <MediaManagerMediaItemViewModel>(),
                    MediaItemsCount = 0,
                    FolderPath      = folderPath
                };

                return(View(model));
            }

            // Check permission
            if (!_mediaLibraryService.CheckMediaFolderPermission(Permissions.SelectMediaContent, folderPath) && !_mediaLibraryService.CanManageMediaFolder(folderPath))
            {
                var model = new MediaManagerMediaItemsViewModel {
                    MediaItems      = new List <MediaManagerMediaItemViewModel>(),
                    MediaItemsCount = 0,
                    FolderPath      = folderPath
                };

                return(View(model));
            }

            IEnumerable <MediaPart> mediaParts;
            var mediaPartsCount = 0;

            if (culture == "")
            {
                mediaParts      = _mediaLibraryService.GetMediaContentItems(folderPath, skip, count, order, mediaType, VersionOptions.Latest);
                mediaPartsCount = _mediaLibraryService.GetMediaContentItemsCount(folderPath, mediaType, VersionOptions.Latest);
            }
            else
            {
                var cultureId = _cultureManager.GetCultureByName(culture).Id;
                var query     = BuildGetMediaContentItemsQuery(Services.ContentManager, folderPath, order: order, mediaType: mediaType, versionOptions: VersionOptions.Latest)
                                .Join <LocalizationPartRecord>()
                                .Where(x => x.CultureId == cultureId)
                                .Join <MediaPartRecord>();
                mediaParts = query
                             .Slice(skip, count);
                mediaPartsCount = query.Count();
            }

            var mediaItems = mediaParts.Select(x => new MediaManagerMediaItemViewModel {
                MediaPart = x,
                Shape     = Services.ContentManager.BuildDisplay(x.ContentItem, "Thumbnail")
            }).ToList();

            var viewModel = new MediaManagerMediaItemsViewModel {
                MediaItems      = mediaItems,
                MediaItemsCount = mediaPartsCount,
                FolderPath      = folderPath
            };

            return(View(viewModel));
        }
Esempio n. 23
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);
            }
        }
        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
            });
        }
Esempio n. 25
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);
                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));
        }
        /// <summary>
        /// Formato DateTimeField: 2009-06-15T13:45:30  yyyy-MM-ddThh:mm:ss NB: L’ora deve essere riferita all’ora di Greenwich
        /// </summary>
        /// <param name="eObj"></param>
        /// <param name="TheContentItem"></param>
        /// <returns></returns>
        private Response StoreNewContentItem(ExpandoObject eObj)
        {
            // Reasoning on permissions will require us to know the type
            // of the content.
            string tipoContent = ((dynamic)eObj).ContentType;
            // We will also need to know the content's Id in case we are
            // trying to edit an existing ContentItem.
            Int32 IdContentToModify = 0; // new content

            try {
                if ((Int32)(((dynamic)eObj).Id) > 0)
                {
                    IdContentToModify = (Int32)(((dynamic)eObj).Id);
                }
            } catch {
                // Fix per Username nullo
                if (tipoContent == "User")
                {
                    return(_utilsServices.GetResponse(ResponseType.Validation, "Missing user Id"));
                }
            }
            // We will be doing a first check on the ContentType, to validate what's coming
            // to the API. The call to the GetTypeDefinition method will also do null checks
            // on the type name for us.
            var typeDefinition = _contentDefinitionManager.GetTypeDefinition(tipoContent);

            if (typeDefinition == null)
            {
                // return an error of some sort here
                return(_utilsServices.GetResponse(ResponseType.Validation, "Invalid ContentType"));
            }
            // The ContentItem we will create/edit
            ContentItem NewOrModifiedContent;

            if (IdContentToModify == 0)
            {
                // We are going to be creating a new ContentItem
                NewOrModifiedContent = _contentManager.New(tipoContent);
                if (!_authorizer.Authorize(CorePermissions.CreateContent, NewOrModifiedContent))
                {
                    // the user cannot create content of the given type, so
                    // return an error
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
                // since we may create, create
                _contentManager.Create(NewOrModifiedContent, VersionOptions.Draft);
            }
            else
            {
                // we are attempting to modify an existing items
                NewOrModifiedContent = _contentManager.Get(IdContentToModify, VersionOptions.DraftRequired);
            }
            if (NewOrModifiedContent == null)
            {
                // something went horribly wrong, so return an error
                return(_utilsServices.GetResponse(ResponseType.Validation, "No content with this Id"));
            }
            // If either of these validations fail, return an error because we cannot
            // edit the content
            // Validation 1: item should be of the given type
            if (NewOrModifiedContent.TypeDefinition.Name != tipoContent)
            {
                // return an error
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }
            // Validation 2: check EditContent Permissions
            if (!_authorizer.Authorize(CorePermissions.EditContent, NewOrModifiedContent)
                // we also check permissions that may exist for this specific method
                && !_contentExtensionService.HasPermission(tipoContent, Methods.Post, NewOrModifiedContent))
            {
                // return an error
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }
            // Validation 3: if we are also trying to publish, check PublishContent Permissions
            if (NewOrModifiedContent.Has <IPublishingControlAspect>() ||
                NewOrModifiedContent.TypeDefinition.Settings.GetModel <ContentTypeSettings>().Draftable)
            {
                // in this case, simply the EditContent permission is not enough because that
                // would only allow the user to create a draftable
                if (!_authorizer.Authorize(CorePermissions.PublishContent, NewOrModifiedContent))
                {
                    // return an error
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
            }
            // To summarize, here we have a valid ContentItem that we are authorized to edit
            Response rsp = new Response();
            // do some further custom validation
            string validateMessage = ValidateMessage(NewOrModifiedContent, IdContentToModify == 0 ? "Created" : "Modified");

            if (string.IsNullOrEmpty(validateMessage))
            {
                // act like _contentManager.UpdateEditor
                var context = new UpdateContentContext(NewOrModifiedContent);
                // 1. invoke the Updating handlers
                Handlers.Invoke(handler => handler.Updating(context), Logger);
                // 2. do all the update operations
                rsp = _contentExtensionService.StoreInspectExpando(eObj, NewOrModifiedContent);
                if (rsp.Success)
                {
                    try {
                        string language = "";
                        try {
                            language = ((dynamic)eObj).Language;
                        } catch { }
                        if (NewOrModifiedContent.As <LocalizationPart>() != null)
                        {
                            if (!string.IsNullOrEmpty(language))
                            {
                                NewOrModifiedContent.As <LocalizationPart>().Culture = _cultureManager.GetCultureByName(language);
                            }
                            NewOrModifiedContent.As <LocalizationPart>().MasterContentItem = NewOrModifiedContent;
                        }
                        validateMessage = ValidateMessage(NewOrModifiedContent, "");
                        if (!string.IsNullOrEmpty(validateMessage))
                        {
                            rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
                        }
                        // Have a validation actually return a response saying there
                        // was a validation error
                        validateMessage = ValidateMessage(NewOrModifiedContent, "Validation");
                        if (!string.IsNullOrEmpty(validateMessage))
                        {
                            rsp = _utilsServices.GetResponse(ResponseType.Validation, validateMessage);
                            // TODO: define better resolution actions depending
                            // error details?
                            rsp.ResolutionAction = ResolutionAction.AddParameter;
                        }
                        dynamic data = new ExpandoObject();
                        data.Id          = (Int32)(((dynamic)NewOrModifiedContent).Id);
                        data.ContentType = ((dynamic)NewOrModifiedContent).ContentType;
                        if (NewOrModifiedContent.As <AutoroutePart>() != null)
                        {
                            data.DisplayAlias = ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias;
                        }
                        rsp.Data = data;
                    }
                    catch (Exception ex) {
                        rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                    }
                }
                // 3. invoke the Updated handlers
                Handlers.Invoke(handler => handler.Updated(context), Logger);
                // Check whether any handler set some Error notifications (???)
                foreach (var notifi in _notifier.List())
                {
                    if (notifi.Type == NotifyType.Error)
                    {
                        // we'll cancel the transaction later
                        //_transactionManager.Cancel();
                        rsp.Success = false;
                        rsp.Message = "Error on update";
                        Logger.Error(notifi.Message.ToString());
                        break;
                    }
                }
            }
            else
            {
                // Custom validation failed
                // this one has by definition rsp.Success == false
                rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
            }

            if (!rsp.Success)
            {
                // update failed
                _transactionManager.Cancel();
                // return an error
                return(rsp);
            }


            // we want the ContentItem to be published, so it can be "seen" by mobile
            // and the caches generated by the content will be evicted as well
            _contentManager.Publish(NewOrModifiedContent);
            return(rsp);
        }
Esempio n. 27
0
        public ActionResult Translate(int id, string to)
        {
            var masterContentItem = _contentManager.Get(id, VersionOptions.Latest);

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

            if (!Services.Authorizer.Authorize(Permissions.ViewContent, masterContentItem, T("Couldn't open original content")))
            {
                return(new HttpUnauthorizedResult());
            }

            var masterLocalizationPart = masterContentItem.As <LocalizationPart>();

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

            // Check if current item still exists, and redirect.
            var existingTranslation = _localizationService.GetLocalizedContentItem(masterContentItem, to);

            if (existingTranslation != null)
            {
                var existingTranslationMetadata = _contentManager.GetItemMetadata(existingTranslation);
                return(RedirectToAction(
                           Convert.ToString(existingTranslationMetadata.EditorRouteValues["action"]),
                           existingTranslationMetadata.EditorRouteValues));
            }

            // pass a dummy content to the authorization check to check for "own" variations
            var dummyContent = _contentManager.New(masterContentItem.ContentType);

            var contentItemTranslation = _contentManager.Clone(masterContentItem);

            if (!Services.Authorizer.Authorize(Permissions.EditContent, contentItemTranslation, T("Couldn't create translated content")))
            {
                return(new HttpUnauthorizedResult());
            }

            var localizationPart = contentItemTranslation.As <LocalizationPart>();

            if (localizationPart != null)
            {
                localizationPart.MasterContentItem = masterContentItem;
                localizationPart.Culture           = string.IsNullOrWhiteSpace(to) ? null : _cultureManager.GetCultureByName(to);
            }

            Services.Notifier.Success(T("Successfully cloned. The translated content was saved as a draft."));

            var adminRouteValues = _contentManager.GetItemMetadata(contentItemTranslation).AdminRouteValues;

            return(RedirectToRoute(adminRouteValues));
        }
        public ActionResult Translate(int id, string to)
        {
            var masterContentItem = _contentManager.Get(id, VersionOptions.Latest);

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

            if (!Services.Authorizer.Authorize(Permissions.ViewContent, masterContentItem, T("Couldn't open original content")))
            {
                return(new HttpUnauthorizedResult());
            }

            var masterLocalizationPart = masterContentItem.As <LocalizationPart>();

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

            // Check if current item still exists, and redirect.
            var existingTranslation = _localizationService.GetLocalizedContentItem(masterContentItem, to);

            if (existingTranslation != null)
            {
                var existingTranslationMetadata = _contentManager.GetItemMetadata(existingTranslation);
                return(RedirectToAction(
                           Convert.ToString(existingTranslationMetadata.EditorRouteValues["action"]),
                           existingTranslationMetadata.EditorRouteValues));
            }

            // pass a dummy content to the authorization check to check for "own" variations
            var dummyContent = _contentManager.New(masterContentItem.ContentType);

            if (!Services.Authorizer.Authorize(Permissions.EditContent, dummyContent, T("Couldn't create translated content")))
            {
                return(new HttpUnauthorizedResult());
            }

            var contentItemTranslation = _contentManager.Clone(masterContentItem);

            var localizationPart = contentItemTranslation.As <LocalizationPart>();

            if (localizationPart != null)
            {
                localizationPart.MasterContentItem = masterLocalizationPart.MasterContentItem == null ? masterContentItem : masterLocalizationPart.MasterContentItem;
                localizationPart.Culture           = string.IsNullOrWhiteSpace(to) ? null : _cultureManager.GetCultureByName(to);
            }

            Services.Notifier.Success(T("Successfully cloned. The translated content was saved as a draft."));

            var editorRouteValues = _contentManager.GetItemMetadata(contentItemTranslation).EditorRouteValues;

            // adds request variables of current controller to the new redirect route
            // for example the returnUrl parameter
            foreach (var key in Request.Form.AllKeys.Where(x => !x.StartsWith("__") && !editorRouteValues.Keys.Contains(x)))
            {
                editorRouteValues.Add(key, Request.Form[key]);
            }
            foreach (var key in Request.QueryString.AllKeys.Where(x => !x.StartsWith("__") && !editorRouteValues.Keys.Contains(x)))
            {
                editorRouteValues.Add(key, Request.QueryString[key]);
            }
            return(RedirectToRoute(editorRouteValues));
        }
        public void ApplyFilter(dynamic context)
        {
            string siteCulture          = _workContextAccessor.GetContext().CurrentSite.SiteCulture;
            int    siteCultureId        = _cultureManager.GetCultureByName(siteCulture).Id;
            string currentCulture       = _workContextAccessor.GetContext().CurrentCulture;
            var    currentCultureRecord = _cultureManager.GetCultureByName(currentCulture);
            int    currentCultureId     = siteCultureId;

            if (currentCultureRecord != null)
            {
                currentCultureId = currentCultureRecord.Id;
            }
            var query = (IHqlQuery)context.Query;

            if (currentCultureId == siteCultureId)
            {
                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(), x => x.Or(c => c.Eq("CultureId", currentCultureId), nc => nc.Eq("CultureId", 0)));
            }
            else
            {
                //     var listIdsQ = _contentManager.HqlQuery()
                //.ForPart<LocalizationPart>()
                //.Where(alias => alias.ContentPartRecord<LocalizationPartRecord>(), x => x.Or(expr => expr.Eq("CultureId", currentCultureId), expr2 => expr2.Eq("CultureId", 0))).List();
                //     var listIds = new int[] { 0 };
                //     if (listIdsQ != null) {
                //         listIds = listIdsQ.Where(w => w.MasterContentItem != null).Select(s => s.MasterContentItem.Id).ToArray();
                //     }

                //   var subquery = @"SELECT loca.MasterContentItemId FROM Orchard.Localization.Models.LocalizationPartRecord as loca ";
                //  subquery += " WHERE ((loca.CultureId= :parCultureId OR loca.CultureId=0) and MasterContentItemId>0)";

                var subquery = @"SELECT MasterContentItemId FROM localizationPartRecord ";
                subquery += " WHERE ((CultureId= :parCultureId OR CultureId=0) and MasterContentItemId>0)";


                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("parCultureId", currentCultureId);

                context.Query = query.Where(x => x.ContentPartRecord <LocalizationPartRecord>(),
                                            c => c.Or(
                                                y => y.Or(
                                                    h => h.And(w => w.Eq("CultureId", siteCultureId),
                                                               u => u.Not(a => a.InSubquery("Id", subquery, parameters))
                                                               //p => p.Or(u => u.Not(a => a.InSubquery("Id", subquery, parameters)),
                                                               //           q => q.Not(a => a.InSubquery("MasterContentItemId", subquery, parameters))
                                                               //        )
                                                               ),
                                                    z => z.Eq("CultureId", currentCultureId)
                                                    ),
                                                r => r.Eq("CultureId", 0)
                                                )
                                            );

                //context.Query = query.Where(x => x.ContentPartRecord<LocalizationPartRecord>(),
                //        e => e.And(
                //             w => w.Eq("CultureId", siteCultureId),
                //                p => p.Or(
                //                        u => u.Not(a => a.InSubquery("Id", subquery, parameters)),
                //                        q => q.Not(v => v.InSubquery("MasterContentItemId", subquery, parameters))
                //                         )


                //                        ));
            }
        }
Esempio n. 30
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. 31
0
        private Response StoreNewContentItem(ExpandoObject eObj, ContentItem TheContentItem)
        {
            string tipoContent       = ((dynamic)eObj).ContentType;
            Int32  IdContentToModify = 0; // new content

            // NewContent.As<TitlePart>.Title = "Creazione";
            try {
                if ((Int32)(((dynamic)eObj).Id) > 0)
                {
                    IdContentToModify = (Int32)(((dynamic)eObj).Id);
                }
            }
            catch {
            }
            ContentItem NewOrModifiedContent;
            Response    rsp             = new Response();
            string      validateMessage = "";

            if (IdContentToModify > 0)
            {
                NewOrModifiedContent = _orchardServices.ContentManager.Get(IdContentToModify, VersionOptions.Latest);
                //if (NewOrModifiedContent==null){
                //    var pippo = _orchardServices.ContentManager.GetAllVersions(IdContentToModify);
                //}
                //  endif IdContentToModify).Where(x=>x.VersionRecord.Id>);
                if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.EditContent, NewOrModifiedContent))
                {
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
                validateMessage = ValidateMessage(NewOrModifiedContent, "Modified");
            }
            else
            {
                NewOrModifiedContent = _orchardServices.ContentManager.New(tipoContent);
                if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.EditContent, NewOrModifiedContent))
                {
                    return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
                }
                _orchardServices.ContentManager.Create(NewOrModifiedContent, VersionOptions.Draft);// se non faccio il create poi non vengono salvati i field
                validateMessage = ValidateMessage(NewOrModifiedContent, "Created");
            }

            if (string.IsNullOrEmpty(validateMessage))
            {
                rsp = _contentExtensionsServices.StoreInspectExpando(eObj, NewOrModifiedContent);
            }
            else
            {
                rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
            }

            if (rsp.Success)
            {
                try {
                    string language = "";
                    try {
                        language = ((dynamic)eObj).Language;
                    }
                    catch { }
                    if (NewOrModifiedContent.As <LocalizationPart>() != null)
                    {
                        if (!string.IsNullOrEmpty(language))
                        {
                            NewOrModifiedContent.As <LocalizationPart>().Culture = _cultureManager.GetCultureByName(language);
                        }
                        NewOrModifiedContent.As <LocalizationPart>().MasterContentItem = NewOrModifiedContent;
                    }
                    validateMessage = ValidateMessage(NewOrModifiedContent, "");
                    if (string.IsNullOrEmpty(validateMessage))
                    {
                        _orchardServices.ContentManager.Create(NewOrModifiedContent, VersionOptions.DraftRequired);
                    }
                    else
                    {
                        rsp = _utilsServices.GetResponse(ResponseType.None, validateMessage);
                    }

                    // _localizationService.SetContentCulture(NewContent, language);
                    if (((dynamic)NewOrModifiedContent).AutoroutePart != null)
                    {
                        ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias = _autorouteService.Value.GenerateAlias(((dynamic)NewOrModifiedContent).AutoroutePart);
                        _autorouteService.Value.ProcessPath(((dynamic)NewOrModifiedContent).AutoroutePart);
                        _autorouteService.Value.PublishAlias(((dynamic)NewOrModifiedContent).AutoroutePart);
                        dynamic data = new ExpandoObject();
                        data.DisplayAlias = ((dynamic)NewOrModifiedContent).AutoroutePart.DisplayAlias;
                        rsp.Data          = data;
                    }
                    //   Handlers.Invoke(handler => handler.Updating(context), Logger);
                }
                catch (Exception ex) {
                    try {
                        _orchardServices.ContentManager.Remove(NewOrModifiedContent);
                    }
                    catch (Exception ex2) {
                        rsp = _utilsServices.GetResponse(ResponseType.None, ex2.Message);
                    }
                    rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                }
            }
            else
            {
                try {
                    _orchardServices.ContentManager.Remove(NewOrModifiedContent);
                }
                catch (Exception ex2) {
                    rsp = _utilsServices.GetResponse(ResponseType.None, ex2.Message);
                }
            }
            //if (this.ExternalContentCreated != null) {
            //    this.ExternalContentCreated(this, new EventArgs());
            //}

            return(rsp);
        }