<commit_before>﻿using EPiServer.Core;
using EPiServer.Framework;
using EPiServer.Security;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using EPiServer.Web.Routing;
using System;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace EPiServer.CdnSupport
{
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class CdnModule : IInitializableHttpModule
    {
        private static Regex _validateUrl = new Regex("^/[a-z0-9]{6}/.+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
        public static object CdnRequest = new object();
        private static Lazy<string> _cdnUrl = new Lazy<string>(() => VirtualPathUtility.AppendTrailingSlash(ConfigurationManager.AppSettings["episerver:CdnExternalMediaUrl"]) ?? "/");
        private static string[] _mediaPaths = new string[] { "contentassets", RouteCollectionExtensions.SiteAssetStaticSegment, RouteCollectionExtensions.GlobalAssetStaticSegment };

        private static Injected<IContentLoader> Loader;

        public void InitializeHttpEvents(HttpApplication application)
        {
            if (String.IsNullOrEmpty(_cdnUrl.Value)) { return; }
            application.BeginRequest += new EventHandler(OnBeginRequest);
        }

        public void Initialize(Framework.Initialization.InitializationEngine context)
        {
            if (String.IsNullOrEmpty(_cdnUrl.Value)) { return; }
            context.Locate.Advanced.GetInstance<IContentRouteEvents>().CreatedVirtualPath += ContentRoute_CreatedVirtualPath;
        }

        public void Uninitialize(Framework.Initialization.InitializationEngine context)
        {
        }

        private static void OnBeginRequest(object sender, EventArgs e)
        {
            HttpContext c = ((HttpApplication)sender).Context;
            if (!_validateUrl.IsMatch(c.Request.Path))
            {
                return;
            }
            string newPath = c.Request.Path.Substring(8);
            if (_mediaPaths.Any(p => newPath.StartsWith(p)))
            {
                c.Items[CdnRequest] = c.Request.Path.Substring(1, 6);
                c.RewritePath("/" + newPath, String.Empty, String.Empty, true);
            }
        }

        private static void ContentRoute_CreatedVirtualPath(object sender, UrlBuilderEventArgs e)
        {
            if (e.RequestContext.GetContextMode() != ContextMode.Default || !_mediaPaths.Any(p => e.UrlBuilder.Path.StartsWith(p)))
            {
                return;
            }

            var contentLink = e.RouteValues[RoutingConstants.NodeKey] as ContentReference;
            IContent content;<commit_msg>Bugfix: Querystring is not passed to the RewritePath methode, when translating back to original path(and query). To be able to use CDN for images resized through ImageResizer, this change need to be done.<commit_after>﻿using EPiServer.Core;
using EPiServer.Framework;
using EPiServer.Security;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using EPiServer.Web.Routing;
using System;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace EPiServer.CdnSupport
{
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class CdnModule : IInitializableHttpModule
    {
        private static Regex _validateUrl = new Regex("^/[a-z0-9]{6}/.+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
        public static object CdnRequest = new object();
        private static Lazy<string> _cdnUrl = new Lazy<string>(() => VirtualPathUtility.AppendTrailingSlash(ConfigurationManager.AppSettings["episerver:CdnExternalMediaUrl"]) ?? "/");
        private static string[] _mediaPaths = new string[] { "contentassets", RouteCollectionExtensions.SiteAssetStaticSegment, RouteCollectionExtensions.GlobalAssetStaticSegment };

        private static Injected<IContentLoader> Loader;

        public void InitializeHttpEvents(HttpApplication application)
        {
            if (String.IsNullOrEmpty(_cdnUrl.Value)) { return; }
            application.BeginRequest += new EventHandler(OnBeginRequest);
        }

        public void Initialize(Framework.Initialization.InitializationEngine context)
        {
            if (String.IsNullOrEmpty(_cdnUrl.Value)) { return; }
            context.Locate.Advanced.GetInstance<IContentRouteEvents>().CreatedVirtualPath += ContentRoute_CreatedVirtualPath;
        }

        public void Uninitialize(Framework.Initialization.InitializationEngine context)
        {
        }

        private static void OnBeginRequest(object sender, EventArgs e)
        {
            HttpContext c = ((HttpApplication)sender).Context;
            if (!_validateUrl.IsMatch(c.Request.Path))
            {
                return;
            }
            string newPath = c.Request.Path.Substring(8);
            if (_mediaPaths.Any(p => newPath.StartsWith(p)))
            {
                c.Items[CdnRequest] = c.Request.Path.Substring(1, 6);
                c.RewritePath("/" + newPath, String.Empty, c.Request.QueryString.ToString(), true);
            }
        }

        private static void ContentRoute_CreatedVirtualPath(object sender, UrlBuilderEventArgs e)
        {
            if (e.RequestContext.GetContextMode() != ContextMode.Default || !_mediaPaths.Any(p => e.UrlBuilder.Path.StartsWith(p)))
            {
                return;
            }

            var contentLink = e.RouteValues[RoutingConstants.NodeKey] as ContentReference;
            IContent content;
{'fraction_non_alphanumeric': 0.09504352460472552, 'fraction_numerical': 0.0021318173743116006, 'mean_word_length': 3.00711743772242, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7037294', 'n_tokens_mistral': 1494, 'n_tokens_neox': 1465, 'n_words': 299}