Exemple #1
0
    /// <summary>
    ///     Deletes an <see cref="IMacro" />
    /// </summary>
    /// <param name="macro"><see cref="IMacro" /> to delete</param>
    /// <param name="userId">Optional id of the user deleting the macro</param>
    public void Delete(IMacro macro, int userId = Constants.Security.SuperUserId)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            EventMessages eventMessages        = EventMessagesFactory.Get();
            var           deletingNotification = new MacroDeletingNotification(macro, eventMessages);
            if (scope.Notifications.PublishCancelable(deletingNotification))
            {
                scope.Complete();
                return;
            }

            _macroRepository.Delete(macro);

            scope.Notifications.Publish(
                new MacroDeletedNotification(macro, eventMessages).WithStateFrom(deletingNotification));
            Audit(AuditType.Delete, userId, -1);

            scope.Complete();
        }
    }
Exemple #2
0
    /// <summary>
    ///     Deletes a UserGroup
    /// </summary>
    /// <param name="userGroup">UserGroup to delete</param>
    public void DeleteUserGroup(IUserGroup userGroup)
    {
        EventMessages evtMsgs = EventMessagesFactory.Get();

        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            var deletingNotification = new UserGroupDeletingNotification(userGroup, evtMsgs);
            if (scope.Notifications.PublishCancelable(deletingNotification))
            {
                scope.Complete();
                return;
            }

            _userGroupRepository.Delete(userGroup);

            scope.Notifications.Publish(
                new UserGroupDeletedNotification(userGroup, evtMsgs).WithStateFrom(deletingNotification));

            scope.Complete();
        }
    }
Exemple #3
0
    /// <inheritdoc />
    public IEnumerable <IRelation> GetByParentId(int id, string?relationTypeAlias)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
        {
            if (relationTypeAlias.IsNullOrWhiteSpace())
            {
                IQuery <IRelation> qry1 = Query <IRelation>().Where(x => x.ParentId == id);
                return(_relationRepository.Get(qry1));
            }

            IRelationType?relationType = GetRelationType(relationTypeAlias !);
            if (relationType == null)
            {
                return(Enumerable.Empty <IRelation>());
            }

            IQuery <IRelation> qry2 =
                Query <IRelation>().Where(x => x.ParentId == id && x.RelationTypeId == relationType.Id);
            return(_relationRepository.Get(qry2));
        }
    }
        /// <summary>
        /// Deletes the entry and all associated rules
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationResult?> Delete(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                var deletingNotification = new PublicAccessEntryDeletingNotification(entry, evtMsgs);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                _publicAccessRepository.Delete(entry);
                scope.Complete();

                scope.Notifications.Publish(new PublicAccessEntryDeletedNotification(entry, evtMsgs).WithStateFrom(deletingNotification));
            }

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
Exemple #5
0
        /// <summary>
        /// Deactivates a server.
        /// </summary>
        /// <param name="serverIdentity">The server unique identity.</param>
        public void DeactiveServer(string serverIdentity)
        {
            // because the repository caches "all" and has queries disabled...

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                scope.WriteLock(Cms.Core.Constants.Locks.Servers);

                _serverRegistrationRepository.ClearCache(); // ensure we have up-to-date cache // ensure we have up-to-date cache

                var server = _serverRegistrationRepository.GetMany()?.FirstOrDefault(x => x.ServerIdentity?.InvariantEquals(serverIdentity) ?? false);
                if (server == null)
                {
                    return;
                }
                server.IsActive = server.IsSchedulingPublisher = false;
                _serverRegistrationRepository.Save(server); // will trigger a cache reload // will trigger a cache reload

                scope.Complete();
            }
        }
Exemple #6
0
        public Attempt <OperationResult?> Delete(IDomain domain)
        {
            EventMessages eventMessages = EventMessagesFactory.Get();

            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                var deletingNotification = new DomainDeletingNotification(domain, eventMessages);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(eventMessages));
                }

                _domainRepository.Delete(domain);
                scope.Complete();

                scope.Notifications.Publish(new DomainDeletedNotification(domain, eventMessages).WithStateFrom(deletingNotification));
            }

            return(OperationResult.Attempt.Succeed(eventMessages));
        }
Exemple #7
0
    /// <inheritdoc />
    public void DeleteRelationsOfType(IRelationType relationType)
    {
        var relations = new List <IRelation>();

        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            IQuery <IRelation> query = Query <IRelation>().Where(x => x.RelationTypeId == relationType.Id);
            var allRelations         = _relationRepository.Get(query).ToList();
            relations.AddRange(allRelations);

            // TODO: N+1, we should be able to do this in a single call
            foreach (IRelation relation in relations)
            {
                _relationRepository.Delete(relation);
            }

            scope.Complete();

            scope.Notifications.Publish(new RelationDeletedNotification(relations, EventMessagesFactory.Get()));
        }
    }
        public Attempt<OperationResult<MoveOperationStatusType>?> Move(IDataType toMove, int parentId)
        {
            var evtMsgs = EventMessagesFactory.Get();
            var moveInfo = new List<MoveEventInfo<IDataType>>();

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                var moveEventInfo = new MoveEventInfo<IDataType>(toMove, toMove.Path, parentId);

                var movingDataTypeNotification = new DataTypeMovingNotification(moveEventInfo, evtMsgs);
                if (scope.Notifications.PublishCancelable(movingDataTypeNotification))
                {
                    scope.Complete();
                    return OperationResult.Attempt.Fail(MoveOperationStatusType.FailedCancelledByEvent, evtMsgs);
                }

                try
                {
                    EntityContainer? container = null;
                    if (parentId > 0)
                    {
                        container = _dataTypeContainerRepository.Get(parentId);
                        if (container == null)
                            throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound); // causes rollback
                    }
                    moveInfo.AddRange(_dataTypeRepository.Move(toMove, container));

                    scope.Notifications.Publish(new DataTypeMovedNotification(moveEventInfo, evtMsgs).WithStateFrom(movingDataTypeNotification));

                    scope.Complete();
                }
                catch (DataOperationException<MoveOperationStatusType> ex)
                {
                    scope.Complete(); // TODO: what are we doing here exactly?
                    return OperationResult.Attempt.Fail(ex.Operation, evtMsgs);
                }
            }

            return OperationResult.Attempt.Succeed(MoveOperationStatusType.Success, evtMsgs);
        }
    public Attempt <OperationResult <OperationResultType, EntityContainer>?> CreateContainer(int parentId, Guid key, string name, int userId = Constants.Security.SuperUserId)
    {
        EventMessages eventMessages = EventMessagesFactory.Get();

        using ICoreScope scope = ScopeProvider.CreateCoreScope();
        scope.WriteLock(WriteLockIds); // also for containers

        try
        {
            var container = new EntityContainer(ContainedObjectType)
            {
                Name      = name,
                ParentId  = parentId,
                CreatorId = userId,
                Key       = key
            };

            var savingNotification = new EntityContainerSavingNotification(container, eventMessages);
            if (scope.Notifications.PublishCancelable(savingNotification))
            {
                scope.Complete();
                return(OperationResult.Attempt.Cancel(eventMessages, container));
            }

            _containerRepository?.Save(container);
            scope.Complete();

            var savedNotification = new EntityContainerSavedNotification(container, eventMessages);
            savedNotification.WithStateFrom(savingNotification);
            scope.Notifications.Publish(savedNotification);
            // TODO: Audit trail ?

            return(OperationResult.Attempt.Succeed(eventMessages, container));
        }
        catch (Exception ex)
        {
            scope.Complete();
            return(OperationResult.Attempt.Fail <OperationResultType, EntityContainer>(OperationResultType.FailedCancelledByEvent, eventMessages, ex));
        }
    }
        /// <summary>
        /// Adds a rule
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ruleType"></param>
        /// <param name="ruleValue"></param>
        /// <returns></returns>
        public Attempt <OperationResult <OperationResultType, PublicAccessEntry>?> AddRule(IContent content, string ruleType, string ruleValue)
        {
            var evtMsgs = EventMessagesFactory.Get();
            PublicAccessEntry?entry;

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                entry = _publicAccessRepository.GetMany().FirstOrDefault(x => x.ProtectedNodeId == content.Id);
                if (entry == null)
                {
                    return(OperationResult.Attempt.Cannot <PublicAccessEntry>(evtMsgs)); // causes rollback
                }
                var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue);
                if (existingRule == null)
                {
                    entry.AddRule(ruleValue, ruleType);
                }
                else
                {
                    //If they are both the same already then there's nothing to update, exit
                    return(OperationResult.Attempt.Succeed(evtMsgs, entry));
                }

                var savingNotifiation = new PublicAccessEntrySavingNotification(entry, evtMsgs);
                if (scope.Notifications.PublishCancelable(savingNotifiation))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs, entry));
                }

                _publicAccessRepository.Save(entry);

                scope.Complete();

                scope.Notifications.Publish(new PublicAccessEntrySavedNotification(entry, evtMsgs).WithStateFrom(savingNotifiation));
            }

            return(OperationResult.Attempt.Succeed(evtMsgs, entry));
        }
    /// <summary>
    ///     Deletes a <see cref="IDictionaryItem" /> object and its related translations
    ///     as well as its children.
    /// </summary>
    /// <param name="dictionaryItem"><see cref="IDictionaryItem" /> to delete</param>
    /// <param name="userId">Optional id of the user deleting the dictionary item</param>
    public void Delete(IDictionaryItem dictionaryItem, int userId = Constants.Security.SuperUserId)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            EventMessages eventMessages        = EventMessagesFactory.Get();
            var           deletingNotification = new DictionaryItemDeletingNotification(dictionaryItem, eventMessages);
            if (scope.Notifications.PublishCancelable(deletingNotification))
            {
                scope.Complete();
                return;
            }

            _dictionaryRepository.Delete(dictionaryItem);
            scope.Notifications.Publish(
                new DictionaryItemDeletedNotification(dictionaryItem, eventMessages)
                .WithStateFrom(deletingNotification));

            Audit(AuditType.Delete, "Delete DictionaryItem", userId, dictionaryItem.Id, "DictionaryItem");

            scope.Complete();
        }
    }
Exemple #12
0
            /// <inheritdoc/>
            public ProcessInstructionsResult ProcessInstructions(
                CacheRefresherCollection cacheRefreshers,
                ServerRole serverRole,
                CancellationToken cancellationToken,
                string localIdentity,
                DateTime lastPruned,
                int lastId)
            {
                using (_profilingLogger.DebugDuration <CacheInstructionService>("Syncing from database..."))
                    using (ICoreScope scope = ScopeProvider.CreateCoreScope())
                    {
                        var numberOfInstructionsProcessed = ProcessDatabaseInstructions(cacheRefreshers, cancellationToken,
                                                                                        localIdentity, ref lastId);

                        // Check for pruning throttling.
                        if (cancellationToken.IsCancellationRequested || (DateTime.UtcNow - lastPruned) <=
                            _globalSettings.DatabaseServerMessenger.TimeBetweenPruneOperations)
                        {
                            scope.Complete();
                            return(ProcessInstructionsResult.AsCompleted(numberOfInstructionsProcessed, lastId));
                        }

                        var instructionsWerePruned = false;
                        switch (serverRole)
                        {
                        case ServerRole.Single:
                        case ServerRole.SchedulingPublisher:
                            PruneOldInstructions();
                            instructionsWerePruned = true;
                            break;
                        }

                        scope.Complete();

                        return(instructionsWerePruned
                        ? ProcessInstructionsResult.AsCompletedAndPruned(numberOfInstructionsProcessed, lastId)
                        : ProcessInstructionsResult.AsCompleted(numberOfInstructionsProcessed, lastId));
                    }
            }
    public IEnumerable <TItem> GetDescendants(int id, bool andSelf)
    {
        using ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true);
        scope.ReadLock(ReadLockIds);

        var descendants = new List <TItem>();

        if (andSelf)
        {
            TItem?self = Repository.Get(id);
            if (self is not null)
            {
                descendants.Add(self);
            }
        }

        var ids = new Stack <int>();

        ids.Push(id);

        while (ids.Count > 0)
        {
            var            i     = ids.Pop();
            IQuery <TItem> query = Query <TItem>().Where(x => x.ParentId == i);
            TItem[]? result = Repository.Get(query).ToArray();

            if (result is not null)
            {
                foreach (TItem c in result)
                {
                    descendants.Add(c);
                    ids.Push(c.Id);
                }
            }
        }

        return(descendants.ToArray());
    }
Exemple #14
0
        public Attempt <OperationResult <OperationResultType, EntityContainer>?> CreateContainer(int parentId, Guid key, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                try
                {
                    var container = new EntityContainer(Cms.Core.Constants.ObjectTypes.DataType)
                    {
                        Name      = name,
                        ParentId  = parentId,
                        CreatorId = userId,
                        Key       = key
                    };

                    var savingEntityContainerNotification = new EntityContainerSavingNotification(container, evtMsgs);
                    if (scope.Notifications.PublishCancelable(savingEntityContainerNotification))
                    {
                        scope.Complete();
                        return(OperationResult.Attempt.Cancel(evtMsgs, container));
                    }

                    _dataTypeContainerRepository.Save(container);
                    scope.Complete();

                    scope.Notifications.Publish(new EntityContainerSavedNotification(container, evtMsgs).WithStateFrom(savingEntityContainerNotification));

                    // TODO: Audit trail ?

                    return(OperationResult.Attempt.Succeed(evtMsgs, container));
                }
                catch (Exception ex)
                {
                    return(OperationResult.Attempt.Fail <EntityContainer>(evtMsgs, ex));
                }
            }
        }
Exemple #15
0
        public Attempt <OperationResult <OperationResultType, EntityContainer>?> RenameContainer(int id, string name, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                try
                {
                    var container = _dataTypeContainerRepository.Get(id);

                    //throw if null, this will be caught by the catch and a failed returned
                    if (container == null)
                    {
                        throw new InvalidOperationException("No container found with id " + id);
                    }

                    container.Name = name;

                    var renamingEntityContainerNotification = new EntityContainerRenamingNotification(container, evtMsgs);
                    if (scope.Notifications.PublishCancelable(renamingEntityContainerNotification))
                    {
                        scope.Complete();
                        return(OperationResult.Attempt.Cancel(evtMsgs, container));
                    }

                    _dataTypeContainerRepository.Save(container);
                    scope.Complete();

                    scope.Notifications.Publish(new EntityContainerRenamedNotification(container, evtMsgs).WithStateFrom(renamingEntityContainerNotification));

                    return(OperationResult.Attempt.Succeed(OperationResultType.Success, evtMsgs, container));
                }
                catch (Exception ex)
                {
                    return(OperationResult.Attempt.Fail <EntityContainer>(evtMsgs, ex));
                }
            }
        }
Exemple #16
0
    /// <summary>
    ///     Replaces the same permission set for a single group to any number of entities
    /// </summary>
    /// <remarks>If no 'entityIds' are specified all permissions will be removed for the specified group.</remarks>
    /// <param name="groupId">Id of the group</param>
    /// <param name="permissions">
    ///     Permissions as enumerable list of <see cref="char" /> If nothing is specified all permissions
    ///     are removed.
    /// </param>
    /// <param name="entityIds">Specify the nodes to replace permissions for. </param>
    public void ReplaceUserGroupPermissions(int groupId, IEnumerable <char>?permissions, params int[] entityIds)
    {
        if (entityIds.Length == 0)
        {
            return;
        }

        EventMessages evtMsgs = EventMessagesFactory.Get();

        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            _userGroupRepository.ReplaceGroupPermissions(groupId, permissions, entityIds);
            scope.Complete();

            var assigned = permissions?.Select(p => p.ToString(CultureInfo.InvariantCulture)).ToArray();
            if (assigned is not null)
            {
                EntityPermission[] entityPermissions =
                    entityIds.Select(x => new EntityPermission(groupId, x, assigned)).ToArray();
                scope.Notifications.Publish(new AssignedUserGroupPermissionsNotification(entityPermissions, evtMsgs));
            }
        }
    }
    public string GetDefault()
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
        {
            scope.ReadLock(ReadLockIds);

            using (IEnumerator <IMemberType> e = _memberTypeRepository.GetMany(new int[0]).GetEnumerator())
            {
                if (e.MoveNext() == false)
                {
                    throw new InvalidOperationException("No member types could be resolved");
                }

                var first   = e.Current.Alias;
                var current = true;
                while (e.Current.Alias.InvariantEquals("Member") == false && (current = e.MoveNext()))
                {
                }

                return(current ? e.Current.Alias : first);
            }
        }
    }
Exemple #18
0
        public Attempt <OperationResult?> DeleteContainer(int containerId, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateCoreScope())
            {
                var container = _dataTypeContainerRepository.Get(containerId);
                if (container == null)
                {
                    return(OperationResult.Attempt.NoOperation(evtMsgs));
                }

                // 'container' here does not know about its children, so we need
                // to get it again from the entity repository, as a light entity
                var entity = _entityRepository.Get(container.Id);
                if (entity?.HasChildren ?? false)
                {
                    scope.Complete();
                    return(Attempt.Fail(new OperationResult(OperationResultType.FailedCannot, evtMsgs)));
                }

                var deletingEntityContainerNotification = new EntityContainerDeletingNotification(container, evtMsgs);
                if (scope.Notifications.PublishCancelable(deletingEntityContainerNotification))
                {
                    scope.Complete();
                    return(Attempt.Fail(new OperationResult(OperationResultType.FailedCancelledByEvent, evtMsgs)));
                }

                _dataTypeContainerRepository.Delete(container);

                scope.Notifications.Publish(new EntityContainerDeletedNotification(container, evtMsgs).WithStateFrom(deletingEntityContainerNotification));
                scope.Complete();
            }

            // TODO: Audit trail ?
            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
Exemple #19
0
    /// <summary>
    ///     Saves a list of <see cref="IUser" /> objects
    /// </summary>
    /// <param name="entities"><see cref="IEnumerable{IUser}" /> to save</param>
    public void Save(IEnumerable <IUser> entities)
    {
        EventMessages evtMsgs = EventMessagesFactory.Get();

        IUser[] entitiesA = entities.ToArray();

        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            var savingNotification = new UserSavingNotification(entitiesA, evtMsgs);
            if (scope.Notifications.PublishCancelable(savingNotification))
            {
                scope.Complete();
                return;
            }

            foreach (IUser user in entitiesA)
            {
                if (string.IsNullOrWhiteSpace(user.Username))
                {
                    throw new ArgumentException("Empty username.", nameof(entities));
                }

                if (string.IsNullOrWhiteSpace(user.Name))
                {
                    throw new ArgumentException("Empty name.", nameof(entities));
                }

                _userRepository.Save(user);
            }

            scope.Notifications.Publish(
                new UserSavedNotification(entitiesA, evtMsgs).WithStateFrom(savingNotification));

            // commit the whole lot in one go
            scope.Complete();
        }
    }
        /// <summary>
        /// Saves a <see cref="ILanguage"/> object
        /// </summary>
        /// <param name="language"><see cref="ILanguage"/> to save</param>
        /// <param name="userId">Optional id of the user saving the language</param>
        public void Save(ILanguage language, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            using (var scope = ScopeProvider.CreateCoreScope())
            {
                // write-lock languages to guard against race conds when dealing with default language
                scope.WriteLock(Cms.Core.Constants.Locks.Languages);

                // look for cycles - within write-lock
                if (language.FallbackLanguageId.HasValue)
                {
                    var languages = _languageRepository.GetMany().ToDictionary(x => x.Id, x => x);
                    if (!languages.ContainsKey(language.FallbackLanguageId.Value))
                    {
                        throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback id={language.FallbackLanguageId.Value} which is not a valid language id.");
                    }
                    if (CreatesCycle(language, languages))
                    {
                        throw new InvalidOperationException($"Cannot save language {language.IsoCode} with fallback {languages[language.FallbackLanguageId.Value].IsoCode} as it would create a fallback cycle.");
                    }
                }

                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new LanguageSavingNotification(language, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return;
                }

                _languageRepository.Save(language);
                scope.Notifications.Publish(new LanguageSavedNotification(language, eventMessages).WithStateFrom(savingNotification));

                Audit(AuditType.Save, "Save Language", userId, language.Id, ObjectTypes.GetName(UmbracoObjectTypes.Language));

                scope.Complete();
            }
        }
Exemple #21
0
    /// <summary>
    ///     Gets a user by Id
    /// </summary>
    /// <param name="id">Id of the user to retrieve</param>
    /// <returns>
    ///     <see cref="IUser" />
    /// </returns>
    public IUser?GetUserById(int id)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
        {
            try
            {
                return(_userRepository.Get(id));
            }
            catch (DbException)
            {
                // TODO: refactor users/upgrade
                // currently kinda accepting anything on upgrade, but that won't deal with all cases
                // so we need to do it differently, see the custom UmbracoPocoDataBuilder which should
                // be better BUT requires that the app restarts after the upgrade!
                if (IsUpgrading)
                {
                    // NOTE: this will not be cached
                    return(_userRepository.Get(id, false));
                }

                throw;
            }
        }
    }
Exemple #22
0
        /// <summary>
        /// Returns paged items in the audit trail for a given user
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <param name="orderDirection">
        /// By default this will always be ordered descending (newest first)
        /// </param>
        /// <param name="auditTypeFilter">
        /// Since we currently do not have enum support with our expression parser, we cannot query on AuditType in the query or the custom filter
        /// so we need to do that here
        /// </param>
        /// <param name="customFilter">
        /// Optional filter to be applied
        /// </param>
        /// <returns></returns>
        public IEnumerable <IAuditItem> GetPagedItemsByUser(int userId, long pageIndex, int pageSize, out long totalRecords, Direction orderDirection = Direction.Descending, AuditType[]?auditTypeFilter = null, IQuery <IAuditItem>?customFilter = null)
        {
            if (pageIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageIndex));
            }
            if (pageSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageSize));
            }

            if (userId < Cms.Core.Constants.Security.SuperUserId)
            {
                totalRecords = 0;
                return(Enumerable.Empty <IAuditItem>());
            }

            using (ScopeProvider.CreateCoreScope(autoComplete: true))
            {
                var query = Query <IAuditItem>().Where(x => x.UserId == userId);

                return(_auditRepository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, orderDirection, auditTypeFilter, customFilter));
            }
        }
Exemple #23
0
            /// <inheritdoc />
            public bool IsColdBootRequired(int lastId)
            {
                using ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true);
                if (lastId <= 0)
                {
                    var count = _cacheInstructionRepository.CountAll();

                    // If there are instructions but we haven't synced, then a cold boot is necessary.
                    if (count > 0)
                    {
                        return(true);
                    }
                }
                else
                {
                    // If the last synced instruction is not found in the db, then a cold boot is necessary.
                    if (!_cacheInstructionRepository.Exists(lastId))
                    {
                        return(true);
                    }
                }

                return(false);
            }
        /// <summary>
        /// Saves a <see cref="IDictionaryItem"/> object
        /// </summary>
        /// <param name="dictionaryItem"><see cref="IDictionaryItem"/> to save</param>
        /// <param name="userId">Optional id of the user saving the dictionary item</param>
        public void Save(IDictionaryItem dictionaryItem, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            using (var scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new DictionaryItemSavingNotification(dictionaryItem, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return;
                }

                _dictionaryRepository.Save(dictionaryItem);

                // ensure the lazy Language callback is assigned
                // ensure the lazy Language callback is assigned

                EnsureDictionaryItemLanguageCallback(dictionaryItem);
                scope.Notifications.Publish(new DictionaryItemSavedNotification(dictionaryItem, eventMessages).WithStateFrom(savingNotification));

                Audit(AuditType.Save, "Save DictionaryItem", userId, dictionaryItem.Id, "DictionaryItem");
                scope.Complete();
            }
        }
        /// <summary>
        /// Deletes a <see cref="ILanguage"/> by removing it (but not its usages) from the db
        /// </summary>
        /// <param name="language"><see cref="ILanguage"/> to delete</param>
        /// <param name="userId">Optional id of the user deleting the language</param>
        public void Delete(ILanguage language, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            using (var scope = ScopeProvider.CreateCoreScope())
            {
                // write-lock languages to guard against race conds when dealing with default language
                scope.WriteLock(Cms.Core.Constants.Locks.Languages);

                EventMessages eventMessages = EventMessagesFactory.Get();
                var           deletingLanguageNotification = new LanguageDeletingNotification(language, eventMessages);
                if (scope.Notifications.PublishCancelable(deletingLanguageNotification))
                {
                    scope.Complete();
                    return;
                }

                // NOTE: Other than the fall-back language, there aren't any other constraints in the db, so possible references aren't deleted
                _languageRepository.Delete(language);

                scope.Notifications.Publish(new LanguageDeletedNotification(language, eventMessages).WithStateFrom(deletingLanguageNotification));

                Audit(AuditType.Delete, "Delete Language", userId, language.Id, ObjectTypes.GetName(UmbracoObjectTypes.Language));
                scope.Complete();
            }
        }
Exemple #26
0
        private Attempt <IPartialView?> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int?userId = null)
        {
            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new PartialViewSavingNotification(partialView, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return(Attempt <IPartialView?> .Fail());
                }

                userId ??= Constants.Security.SuperUserId;
                IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
                repository.Save(partialView);

                Audit(AuditType.Save, userId.Value, -1, partialViewType.ToString());
                scope.Notifications.Publish(new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification));

                scope.Complete();
            }

            return(Attempt.Succeed(partialView));
        }
Exemple #27
0
        /// <summary>
        /// Saves a collection of <see cref="Template"/> objects
        /// </summary>
        /// <param name="templates">List of <see cref="Template"/> to save</param>
        /// <param name="userId">Optional id of the user</param>
        public void SaveTemplate(IEnumerable <ITemplate> templates, int userId = Constants.Security.SuperUserId)
        {
            ITemplate[] templatesA = templates.ToArray();
            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new TemplateSavingNotification(templatesA, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return;
                }

                foreach (ITemplate template in templatesA)
                {
                    _templateRepository.Save(template);
                }

                scope.Notifications.Publish(new TemplateSavedNotification(templatesA, eventMessages).WithStateFrom(savingNotification));

                Audit(AuditType.Save, userId, -1, UmbracoObjectTypes.Template.GetName());
                scope.Complete();
            }
        }
 /// <inheritdoc />
 public bool VerifyMemberDbCache()
 {
     using ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true);
     scope.ReadLock(Constants.Locks.MemberTree);
     return(_repository.VerifyMemberDbCache());
 }
Exemple #29
0
        private Attempt <IPartialView?> CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string?snippetName = null, int?userId = Constants.Security.SuperUserId)
        {
            string partialViewHeader;

            switch (partialViewType)
            {
            case PartialViewType.PartialView:
                partialViewHeader = PartialViewHeader;
                break;

            case PartialViewType.PartialViewMacro:
                partialViewHeader = PartialViewMacroHeader;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(partialViewType));
            }

            string?partialViewContent = null;

            if (snippetName.IsNullOrWhiteSpace() == false)
            {
                //create the file
                Attempt <string> snippetPathAttempt = TryGetSnippetPath(snippetName);
                if (snippetPathAttempt.Success == false)
                {
                    throw new InvalidOperationException("Could not load snippet with name " + snippetName);
                }

                using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result !)))
                {
                    var snippetContent = snippetFile.ReadToEnd().Trim();

                    //strip the @inherits if it's there
                    snippetContent = StripPartialViewHeader(snippetContent);

                    //Update Model.Content. to be Model. when used as PartialView
                    if (partialViewType == PartialViewType.PartialView)
                    {
                        snippetContent = snippetContent.Replace("Model.Content.", "Model.");
                    }

                    partialViewContent = $"{partialViewHeader}{Environment.NewLine}{snippetContent}";
                }
            }

            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages        = EventMessagesFactory.Get();
                var           creatingNotification = new PartialViewCreatingNotification(partialView, eventMessages);
                if (scope.Notifications.PublishCancelable(creatingNotification))
                {
                    scope.Complete();
                    return(Attempt <IPartialView?> .Fail());
                }

                IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
                if (partialViewContent != null)
                {
                    partialView.Content = partialViewContent;
                }

                repository.Save(partialView);

                scope.Notifications.Publish(new PartialViewCreatedNotification(partialView, eventMessages).WithStateFrom(creatingNotification));

                Audit(AuditType.Save, userId !.Value, -1, partialViewType.ToString());

                scope.Complete();
            }

            return(Attempt <IPartialView?> .Succeed(partialView));
        }
        public void Delete(TItem item, int userId = Cms.Core.Constants.Security.SuperUserId)
        {
            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages = EventMessagesFactory.Get();
                DeletingNotification <TItem> deletingNotification = GetDeletingNotification(item, eventMessages);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return;
                }

                scope.WriteLock(WriteLockIds);

                // all descendants are going to be deleted
                TItem[] descendantsAndSelf = GetDescendants(item.Id, true)
                                             .ToArray();
                TItem[] deleted = descendantsAndSelf;

                // all impacted (through composition) probably lose some properties
                // don't try to be too clever here, just report them all
                // do this before anything is deleted
                TItem[] changed = descendantsAndSelf.SelectMany(xx => GetComposedOf(xx.Id))
                                  .Distinct()
                                  .Except(descendantsAndSelf)
                                  .ToArray();

                // delete content
                DeleteItemsOfTypes(descendantsAndSelf.Select(x => x.Id));

                // Next find all other document types that have a reference to this content type
                IEnumerable <TItem> referenceToAllowedContentTypes = GetAll().Where(q => q.AllowedContentTypes?.Any(p => p.Id.Value == item.Id) ?? false);
                foreach (TItem reference in referenceToAllowedContentTypes)
                {
                    reference.AllowedContentTypes = reference.AllowedContentTypes?.Where(p => p.Id.Value != item.Id);
                    var changedRef = new List <ContentTypeChange <TItem> >()
                    {
                        new ContentTypeChange <TItem>(reference, ContentTypeChangeTypes.RefreshMain)
                    };
                    // Fire change event
                    scope.Notifications.Publish(GetContentTypeChangedNotification(changedRef, eventMessages));
                }

                // finally delete the content type
                // - recursively deletes all descendants
                // - deletes all associated property data
                //  (contents of any descendant type have been deleted but
                //   contents of any composed (impacted) type remain but
                //   need to have their property data cleared)
                Repository.Delete(item);

                ContentTypeChange <TItem>[] changes = descendantsAndSelf.Select(x => new ContentTypeChange <TItem>(x, ContentTypeChangeTypes.Remove))
                                                      .Concat(changed.Select(x => new ContentTypeChange <TItem>(x, ContentTypeChangeTypes.RefreshMain | ContentTypeChangeTypes.RefreshOther)))
                                                      .ToArray();

                // Publish this in scope, see comment at GetContentTypeRefreshedNotification for more info.
                _eventAggregator.Publish(GetContentTypeRefreshedNotification(changes, eventMessages));

                scope.Notifications.Publish(GetContentTypeChangedNotification(changes, eventMessages));

                DeletedNotification <TItem> deletedNotification = GetDeletedNotification(deleted.DistinctBy(x => x.Id), eventMessages);
                deletedNotification.WithStateFrom(deletingNotification);
                scope.Notifications.Publish(deletedNotification);

                Audit(AuditType.Delete, userId, item.Id);
                scope.Complete();
            }
        }