Exemplo n.º 1
0
        private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, PublishEventArgs <IContent> args)
        {
            Result result = null;

            foreach (IContent node in args.PublishedEntities)
            {
                //This is where the magic happens. Unicorns. Free burgers.
                result = Restrictor.Instance.Run(node);
            }

            //No rule applied, as you were.
            if (result == null)
            {
                return;
            }

            //If a result has come back, see if limit has been reached or not.
            if (result.LimitReached)
            {
                //Show limit reached message to warn user that he/she has no hope of ever publishing another node.
                args.CancelOperation(new EventMessage(result.Rule.GetMessageCategory(), result.Rule.GetMessage(), EventMessageType.Error));
            }
            else if (result.Rule.ShowWarnings)
            {
                //Show warning message to let the user know how many nodes can still be published.
                args.Messages.Add(new EventMessage(result.Rule.GetWarningMessageCategory(), result.Rule.GetWarningMessage(result.NodeCount), EventMessageType.Warning));
            }
        }
Exemplo n.º 2
0
        public void OnUnpublish(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            base.ReturnOtherThanRestricted(e);

            foreach (var entity in base._restrictedEntities)
            {
                //element not at the root level
                if (entity.ParentId != -1)
                {
                    continue;
                }

                //umbraco context is already defined as we are in one of the pluggins
                var siblingsAliases = Umbraco.Web.UmbracoContext.Current.ContentCache.GetAtRoot()
                                      .Where(x => x.Id != entity.Id)
                                      .Select(x => x.DocumentTypeAlias)
                                      .ToList();

                //any siblings with the same doc type ?
                var noOther = !base._restrictedEntities.Any(x => siblingsAliases.Contains(x.ContentType.Alias));

                //documents with the restriction have been found
                if (noOther)
                {
                    e.CancelOperation(new EventMessage("Content Restriction", base._rule.ErrorMessage, EventMessageType.Error));
                }
            }
        }
        private void ContentService_Unpublishing(IContentService sender, PublishEventArgs <IContent> eventArgs)
        {
            ActionModel unpublish = null;
            int         _currentUserId;

            using (var contextReference = _context.EnsureUmbracoContext()) {
                _currentUserId = contextReference.UmbracoContext.Security.CurrentUser.Id;
            }

            try {
                using (var scope = _scopeProvider.CreateScope(autoComplete: true)) {
                    var sql = scope.SqlContext.Sql().Select("*").From <ActionModel>()
                              .Where <ActionModel>(x => x.id == 7);
                    unpublish = scope.Database.Fetch <ActionModel>(sql).FirstOrDefault();
                }
            }
            catch (Exception ex) {
                _logger.Error <ActionModel>("Failed to get Content Protector setting for unpublish action: " + ex.Message);
            }

            foreach (var node in eventArgs.PublishedEntities)
            {
                if (unpublish != null)
                {
                    if (unpublish.nodes.Split(',').Contains(node.Id.ToString()) || unpublish.disableAction)
                    {
                        if (!unpublish.userExceptions.Split(',').Contains(_currentUserId.ToString()))
                        {
                            eventArgs.CancelOperation(new EventMessage("Action rejected. Contact website admin", "You cannot unpublish " + node.Name, EventMessageType.Error));
                        }
                    }
                }
            }
        }
        static void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            // Check if the node has an override for the UnPublish date.
            // Need to check in the Publishing event as the URL is not assigned until now.
            try
            {
                var expiryRuleProvider = new ExpiryRulesFromUmbraco(UmbracoContext.Current.ContentCache);
                if (expiryRuleProvider.IsEnabled)
                {
                    // Create the rule evaluator
                    var ruleEvaluator = new ExpiryRuleEvaluator();

                    // Check if there is an override for this content element.
                    // If not, check that the unPublish date is within allowed date range.
                    foreach (var entity in e.PublishedEntities)
                    {
                        if (entity.Id == 0)
                        {
                            // Do a save to get the Id and other info
                            ApplicationContext.Current.Services.ContentService.Save(entity);
                        }

                        var result = ruleEvaluator.ApplyExpiryRules(DateTime.Now, expiryRuleProvider.DefaultMaximumExpiry, new DocumentTypeRuleMatcher(expiryRuleProvider.DocumentTypeRules), new PathRuleMatcher(expiryRuleProvider.PathRules), entity, new NodeUrlBuilder());

                        if (!String.IsNullOrEmpty(result.CancellationMessage))
                        {
                            e.CancelOperation(new EventMessage("Publish Failed", result.CancellationMessage, EventMessageType.Error));
                            return;
                        }

                        if (!String.IsNullOrEmpty(result.ExpireDateChangedMessage))
                        {
                            entity.ExpireDate = result.ExpireDate;
                            e.Messages.Add(new EventMessage("Warning", result.ExpireDateChangedMessage, EventMessageType.Warning));
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <ExpiryRulesEventHandler>("Error checking page expiry date.", ex);
                e.CancelOperation(new EventMessage("Publish Failed", ex.Message, EventMessageType.Error));
            }
        }
        public void OnPublishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            base.ReturnOtherThanRestricted(e);

            foreach (var entity in base._restrictedEntities)
            {
                if (entity.Children().Any())
                {
                    return;
                }

                e.CancelOperation(new EventMessage("Content Restriction", base._rule.ErrorMessage, EventMessageType.Error));
            }
        }
Exemplo n.º 6
0
        public void OnPublish(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            var rule = _config.RulesNode.RuleList.FirstOrDefault(x => x.Name == ruleName);

            if (rule == null)
            {
                return;
            }

            var aliases = rule.AddList.Select(x => x.DocTypeAlias);

            if (!aliases.Any())
            {
                return;
            }

            //one of the documents we publish has a restriction
            var restrictedEntities = e.PublishedEntities.Where(x => aliases.Contains(x.ContentType.Alias));

            if (!restrictedEntities.Any())
            {
                return;
            }

            foreach (var entity in restrictedEntities)
            {
                //element not at the root level
                if (entity.ParentId != -1)
                {
                    continue;
                }

                //umbraco context is already defined as we are in one of the pluggins
                var siblingsAliases = Umbraco.Web.UmbracoContext.Current.ContentCache.GetAtRoot()
                                      .Where(x => x.Id != entity.Id)
                                      .Select(x => x.DocumentTypeAlias)
                                      .ToList();

                //any siblings with the same doc type ?
                var cachedDocumentsCondition = restrictedEntities.Any(x => siblingsAliases.Contains(x.ContentType.Alias));

                //documents with the restriction have been found
                if (cachedDocumentsCondition)
                {
                    e.CancelOperation(new EventMessage("Content Restriction", rule.ErrorMessage, EventMessageType.Error));
                }
            }
        }
Exemplo n.º 7
0
        private void ValidateModel(PublishEventArgs <IContent> e, IDomainModel model)
        {
            dynamic castModel = Convert.ChangeType(model, model.GetType());
            var     result    = validateBus.Validate(castModel);

            if (!result.IsValid)
            {
                e.Cancel = true;

                foreach (var error in result.Errors)
                {
                    var errors = new EventMessage(error.PropertyName, error.ErrorMessage, EventMessageType.Error);
                    e.CancelOperation(errors);
                }
            }
        }
Exemplo n.º 8
0
        public void LatchContentUnPublishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            if (!LatchesShouldBeChecked)
            {
                return;
            }

            var latches      = latchOperationSvc.GetLatches(LatchOperationType.Content, LatchOperationAction.Unpublish);
            var contentItems = e.PublishedEntities;
            var user         = HttpContext.Current.GetCurrentBackofficeUser();

            var parentItem = contentItems.First();
            var lockedNode = GetLockedNodeRecursively(latches, contentItems, user.Id);

            if (lockedNode != null)
            {
                var errorMessage = lockedNode.Id.Equals(parentItem.Id)
                    ? GetErrorMessage("contentUnpublish")
                    : GetErrorMessage("contentUnpublishChildren");
                var eventMessage = new EventMessage(LatchConstants.SectionName, errorMessage, EventMessageType.Error);
                e.CancelOperation(eventMessage);
            }
        }
Exemplo n.º 9
0
        public void LatchContentPublishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            if (!LatchesShouldBeChecked)
            {
                return;
            }

            var user    = HttpContext.Current.GetCurrentBackofficeUser();
            var latches = latchOperationSvc.GetLatches(LatchOperationType.Content, LatchOperationAction.Publish);

            foreach (var content in e.PublishedEntities)
            {
                var latchesToApply = GetLatchesToApply(latches, content.Id, user.Id);
                var nodeIsLocked   = AnyLatchIsClosed(latches);
                if (nodeIsLocked)
                {
                    var errorMessage = GetErrorMessage("contentPublish");
                    var eventMessage = new EventMessage(LatchConstants.SectionName, errorMessage, EventMessageType.Error);
                    e.CancelOperation(eventMessage);
                    break;
                }
            }
        }
        static void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            // Check if the node has an override for the UnPublish date.
            // Need to check in the Publishing event as the URL is not assigned until now.
            try
            {
                // Get default time period. Expiry time will be the same as the node creation time.
                var maxDate = DateTime.Now.AddMonths(6);
                // Convert the date time to a string for event messages
                var dateString = maxDate.ToString("dd MMMM yyyy");
                dateString += maxDate.ToString(" h:mm:sstt").ToLower();

                // Check if there is an override for this content element.
                // If not, check that the unPublish date is within allowed date range.
                foreach (var entity in e.PublishedEntities)
                {
                    if (entity.Id == 0)
                    {
                        // Do a save to get the Id and other info
                        ApplicationContext.Current.Services.ContentService.Save(entity);
                    }


                    if (entity.ExpireDate.HasValue)
                    {
                        // Check for override
                        if (UnpublishOverrides.UnpublishOverrides.CheckOverride(entity))
                        {
                            // Date not allowed because there is an override
                            e.CancelOperation(new EventMessage("Publish Failed", "You cannot enter an 'Unpublish at' date for this page", EventMessageType.Error));
                        }

                        // Date cannot be less than 1 day in the future
                        else if (entity.ExpireDate < DateTime.Now.AddDays(1).AddMinutes(-10))
                        {
                            e.CancelOperation(new EventMessage("Publish Failed", "The 'Unpublish at' date must be at least 1 day in the future", EventMessageType.Error));
                        }

                        // Date cannot be more than 6 months in the future
                        else if (entity.ExpireDate > maxDate)
                        {
                            // Default the date to the maximum allowed and continue publishing.
                            entity.ExpireDate = maxDate;
                            e.Messages.Add(new EventMessage("Warning", "The 'Unpublish at' date cannot be more than 6 months in the future. The date has been set to: " + dateString + ". You can refresh the page to see the new date.", EventMessageType.Warning));
                        }
                    }
                    else
                    {
                        // Check for no override
                        if (!UnpublishOverrides.UnpublishOverrides.CheckOverride(entity))
                        {
                            // Date is required as no override exists
                            // As no date has been provided and there is no override, default the date to the maximum allowed and continue publishing.
                            entity.ExpireDate = maxDate;
                            e.Messages.Add(new EventMessage("Warning", "The 'Unpublish at' date is a required field. The date has been set to " + dateString + ". You can refresh the page to see the new date.", EventMessageType.Warning));
                        }

                        // No date is OK because there is an override
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <UnpublishAtEventHandler>("Error checking page expiry date.", ex);
                e.CancelOperation(new EventMessage("Publish Failed", ex.Message, EventMessageType.Error));
            }
        }