<commit_before>﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Linq;
using Autofac;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using Orchard.ContentManagement.Handlers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.Records;
using Orchard.Data;
using Orchard.Indexing;
using Orchard.Logging;
using Orchard.UI;

namespace Orchard.ContentManagement {
    public class DefaultContentManager : IContentManager {
        private readonly IComponentContext _context;
        private readonly IRepository<ContentTypeRecord> _contentTypeRepository;
        private readonly IRepository<ContentItemRecord> _contentItemRepository;
        private readonly IRepository<ContentItemVersionRecord> _contentItemVersionRepository;
        private readonly IContentDefinitionManager _contentDefinitionManager;
        private readonly Func<IContentManagerSession> _contentManagerSession;
        private readonly Lazy<IContentDisplay> _contentDisplay;
        private readonly Lazy<ISessionLocator> _sessionLocator; 
        private readonly Lazy<IEnumerable<IContentHandler>> _handlers;
        private const string Published = "Published";
        private const string Draft = "Draft";

        public DefaultContentManager(
            IComponentContext context,
            IRepository<ContentTypeRecord> contentTypeRepository,
            IRepository<ContentItemRecord> contentItemRepository,
            IRepository<ContentItemVersionRecord> contentItemVersionRepository,
            IContentDefinitionManager contentDefinitionManager,
            Func<IContentManagerSession> contentManagerSession,
            Lazy<IContentDisplay> contentDisplay,
            Lazy<ISessionLocator> sessionLocator,
            Lazy<IEnumerable<IContentHandler>> handlers) {
            _context = context;
            _contentTypeRepository = contentTypeRepository;
            _contentItemRepository = contentItemRepository;
            _contentItemVersionRepository = contentItemVersionRepository;
            _contentDefinitionManager = contentDefinitionManager;
            _contentManagerSession = contentManagerSession;
            _handlers = handlers;
            _contentDisplay = contentDisplay;
            _sessionLocator = sessionLocator;
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public IEnumerable<IContentHandler> Handlers {
              get { return _handlers.Value; }
        }

        public IEnumerable<ContentTypeDefinition> GetContentTypeDefinitions() {
            return _contentDefinitionManager.ListTypeDefinitions();
        }

        public virtual ContentItem New(string contentType) {
            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentType);
            if (contentTypeDefinition == null) {
                contentTypeDefinition = new ContentTypeDefinitionBuilder().Named(contentType).Build();
            }

            // create a new kernel for the model instance
            var context = new ActivatingContentContext {
                ContentType = contentTypeDefinition.Name,
                Definition = contentTypeDefinition,
                Builder = new ContentItemBuilder(contentTypeDefinition)
            };

            // invoke handlers to weld aspects onto kernel
            Handlers.Invoke(handler => handler.Activating(context), Logger);

            var context2 = new ActivatedContentContext {
                ContentType = contentType,
                ContentItem = context.Builder.Build()
            };

            // back-reference for convenience (e.g. getting metadata when in a view)
            context2.ContentItem.ContentManager = this;

            Handlers.Invoke(handler => handler.Activated(context2), Logger);

            var context3 = new InitializingContentContext {
                ContentType = context2.ContentType,
                ContentItem = context2.ContentItem,
            };

            Handlers.Invoke(handler => handler.Initializing(context3), Logger);

            // composite result is returned
            return context3.ContentItem;
        }

        public virtual ContentItem Get(int id) {
            return Get(id, VersionOptions.Published);
        }

        public virtual ContentItem Get(int id, VersionOptions options) {
            return Get(id, options, QueryHints.Empty);
        }

        public virtual ContentItem Get(int id, VersionOptions options, QueryHints hints) {
            var session = _contentManagerSession();
            ContentItem contentItem;

            ContentItemVersionRecord versionRecord = null;

            // obtain the root records based on version options
            if (options.VersionRecordId != 0) {
                // short-circuit if item held in session
                if (session.RecallVersionRecordId(options.VersionRecordId, out contentItem)) {
                    return contentItem;
                }

                versionRecord = _contentItemVersionRepository.Get(options.VersionRecordId);
            }
            else if (session.RecallContentRecordId(id, out contentItem)) {
                // try to reload a previously loaded published content item

                if (options.IsPublished) {
                    return contentItem;
                }

                versionRecord = contentItem.VersionRecord;
            }
            else {
                // do a query to load the records in case Get is called directly
                var contentItemVersionRecords = GetManyImplementation(hints,
                    (contentItemCriteria, contentItemVersionCriteria) => {
                        contentItemCriteria.Add(Restrictions.Eq("Id", id));
                        if (options.IsPublished) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Published", true));
                        }
                        else if (options.IsLatest) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true));
                        }
                        else if (options.IsDraft && !options.IsDraftRequired) {
                            contentItemVersionCriteria.Add(
                                Restrictions.And(Restrictions.Eq("Published", false),
                                                Restrictions.Eq("Latest", true)));
                        }
                        else if (options.IsDraft || options.IsDraftRequired) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true));
                        }

                        contentItemVersionCriteria.SetFetchMode("ContentItemRecord", FetchMode.Eager);
                        contentItemVersionCriteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager);
                        contentItemVersionCriteria.SetMaxResults(1);
                    });

                versionRecord = contentItemVersionRecords.FirstOrDefault();
            }

            // no record means content item is not in db
            if (versionRecord == null) {
                // check in memory
                var record = _contentItemRepository.Get(id);
                if (record == null) {
                    return null;
                }

                versionRecord = GetVersionRecord(options, record);

                if (versionRecord == null) {<commit_msg>#18723: Fixing Get() when a specific version is requested<commit_after>﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Linq;
using Autofac;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using Orchard.ContentManagement.Handlers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.Records;
using Orchard.Data;
using Orchard.Indexing;
using Orchard.Logging;
using Orchard.UI;

namespace Orchard.ContentManagement {
    public class DefaultContentManager : IContentManager {
        private readonly IComponentContext _context;
        private readonly IRepository<ContentTypeRecord> _contentTypeRepository;
        private readonly IRepository<ContentItemRecord> _contentItemRepository;
        private readonly IRepository<ContentItemVersionRecord> _contentItemVersionRepository;
        private readonly IContentDefinitionManager _contentDefinitionManager;
        private readonly Func<IContentManagerSession> _contentManagerSession;
        private readonly Lazy<IContentDisplay> _contentDisplay;
        private readonly Lazy<ISessionLocator> _sessionLocator; 
        private readonly Lazy<IEnumerable<IContentHandler>> _handlers;
        private const string Published = "Published";
        private const string Draft = "Draft";

        public DefaultContentManager(
            IComponentContext context,
            IRepository<ContentTypeRecord> contentTypeRepository,
            IRepository<ContentItemRecord> contentItemRepository,
            IRepository<ContentItemVersionRecord> contentItemVersionRepository,
            IContentDefinitionManager contentDefinitionManager,
            Func<IContentManagerSession> contentManagerSession,
            Lazy<IContentDisplay> contentDisplay,
            Lazy<ISessionLocator> sessionLocator,
            Lazy<IEnumerable<IContentHandler>> handlers) {
            _context = context;
            _contentTypeRepository = contentTypeRepository;
            _contentItemRepository = contentItemRepository;
            _contentItemVersionRepository = contentItemVersionRepository;
            _contentDefinitionManager = contentDefinitionManager;
            _contentManagerSession = contentManagerSession;
            _handlers = handlers;
            _contentDisplay = contentDisplay;
            _sessionLocator = sessionLocator;
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public IEnumerable<IContentHandler> Handlers {
              get { return _handlers.Value; }
        }

        public IEnumerable<ContentTypeDefinition> GetContentTypeDefinitions() {
            return _contentDefinitionManager.ListTypeDefinitions();
        }

        public virtual ContentItem New(string contentType) {
            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentType);
            if (contentTypeDefinition == null) {
                contentTypeDefinition = new ContentTypeDefinitionBuilder().Named(contentType).Build();
            }

            // create a new kernel for the model instance
            var context = new ActivatingContentContext {
                ContentType = contentTypeDefinition.Name,
                Definition = contentTypeDefinition,
                Builder = new ContentItemBuilder(contentTypeDefinition)
            };

            // invoke handlers to weld aspects onto kernel
            Handlers.Invoke(handler => handler.Activating(context), Logger);

            var context2 = new ActivatedContentContext {
                ContentType = contentType,
                ContentItem = context.Builder.Build()
            };

            // back-reference for convenience (e.g. getting metadata when in a view)
            context2.ContentItem.ContentManager = this;

            Handlers.Invoke(handler => handler.Activated(context2), Logger);

            var context3 = new InitializingContentContext {
                ContentType = context2.ContentType,
                ContentItem = context2.ContentItem,
            };

            Handlers.Invoke(handler => handler.Initializing(context3), Logger);

            // composite result is returned
            return context3.ContentItem;
        }

        public virtual ContentItem Get(int id) {
            return Get(id, VersionOptions.Published);
        }

        public virtual ContentItem Get(int id, VersionOptions options) {
            return Get(id, options, QueryHints.Empty);
        }

        public virtual ContentItem Get(int id, VersionOptions options, QueryHints hints) {
            var session = _contentManagerSession();
            ContentItem contentItem;

            ContentItemVersionRecord versionRecord = null;

            // obtain the root records based on version options
            if (options.VersionRecordId != 0) {
                // short-circuit if item held in session
                if (session.RecallVersionRecordId(options.VersionRecordId, out contentItem)) {
                    return contentItem;
                }

                versionRecord = _contentItemVersionRepository.Get(options.VersionRecordId);
            }
            else if (session.RecallContentRecordId(id, out contentItem)) {
                // try to reload a previously loaded published content item

                if (options.IsPublished) {
                    return contentItem;
                }

                versionRecord = contentItem.VersionRecord;
            }
            else {
                // do a query to load the records in case Get is called directly
                var contentItemVersionRecords = GetManyImplementation(hints,
                    (contentItemCriteria, contentItemVersionCriteria) => {
                        contentItemCriteria.Add(Restrictions.Eq("Id", id));
                        if (options.IsPublished) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Published", true));
                        }
                        else if (options.IsLatest) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true));
                        }
                        else if (options.IsDraft && !options.IsDraftRequired) {
                            contentItemVersionCriteria.Add(
                                Restrictions.And(Restrictions.Eq("Published", false),
                                                Restrictions.Eq("Latest", true)));
                        }
                        else if (options.IsDraft || options.IsDraftRequired) {
                            contentItemVersionCriteria.Add(Restrictions.Eq("Latest", true));
                        }

                        contentItemVersionCriteria.SetFetchMode("ContentItemRecord", FetchMode.Eager);
                        contentItemVersionCriteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager);
                        contentItemVersionCriteria.SetMaxResults(1);
                    });


                if (options.VersionNumber != 0) {
                    versionRecord = contentItemVersionRecords.FirstOrDefault(
                        x => x.Number == options.VersionNumber) ??
                           _contentItemVersionRepository.Get(
                               x => x.ContentItemRecord == contentItem.Record && x.Number == options.VersionNumber);
                }
                else {
                    versionRecord = contentItemVersionRecords.FirstOrDefault();
                }
            }

            // no record means content item is not in db
            if (versionRecord == null) {
                // check in memory
                var record = _contentItemRepository.Get(id);
                if (record == null) {
                    return null;
                }

                versionRecord = GetVersionRecord(options, record);

                if (versionRecord == null) {
{'fraction_non_alphanumeric': 0.06651982378854626, 'fraction_numerical': 0.0016362492133417243, 'mean_word_length': 2.093439750827331, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1082834', 'n_tokens_mistral': 3591, 'n_tokens_neox': 3403, 'n_words': 813}