<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Signum.Entities.Mailing;
using Signum.Utilities;

namespace Signum.Web.Mailing
{
    public class WebMailOptions
    {
        public bool ForEditing;
        public IEnumerable<EmailAttachmentDN> Attachments;
        public string UntrustedImage;
        public UrlHelper Url;
        public bool HasUntrusted;
    }

    public static class WebMailProcessor
    {
        public static string ReplaceUntrusted(string body, WebMailOptions options)
        {
            if (options.UntrustedImage == null)
                return body; 

            var result = Regex.Replace(body, @"<img [^>]*>", (Match img) =>
            {
                string prevSource = null;

                var newImg = Regex.Replace(img.Value, "src=\"(?<link>[^\"]*)\"", src =>
                {
                    var value = src.Groups["link"].Value;

                    if (!value.StartsWith("cid:"))
                    {
                        options.HasUntrusted = true;
                        prevSource = value;
                        return "src=\"{0}\"".Formato(options.Url.Content(options.UntrustedImage));
                    }

                    return src.Value;
                });

                if (prevSource == null)
                    return newImg;
                
                var title = prevSource;

                var alt = Regex.Match(img.Value, "alt=\"(?<alt>[^\"]*)\"");
                if (alt.Success && alt.Groups["alt"].Value.HasText())
                    title = alt.Groups["alt"].Value + "\r\n" + title;

                return newImg.Insert("<img ".Length, "title=\"" + title + "\" ");
            });

            return result;
        }

        public static string AssertNoUntrusted(string body, WebMailOptions options)
        {
            if (options.UntrustedImage == null)
                return body;

            string imageUrl = options.Url.Content(options.UntrustedImage);

            if (body.Contains(imageUrl))
                throw new InvalidOperationException("{0} found when saving the Email".Formato(imageUrl));

            return body; 
        }

        public static string CidToFilePath(string body, WebMailOptions options)
        {
            if (!options.Attachments.Any())
                return body;
         
            var dic = options.Attachments.Where(a => a.File.FullWebPath.HasText()).ToDictionary(a => a.ContentId, a => options.Url.Content(a.File.FullWebPath));

            var newBody = Regex.Replace(body, "src=\"(?<link>[^\"]*)\"", src =>
            {
                var value = src.Groups["link"].Value;

                if (!value.StartsWith("cid:"))
                {
                    return src.Value;
                }

                value = value.After("cid:");

                var link = dic.TryGetC(value);

                if (link == null)
                    return src.Value;

                return "src=\"{0}\"".Formato(options.Url.Content(link));
            });

            return newBody;
        }

        public static string FilePathToCid(string body, WebMailOptions options)
        {<commit_msg>WebMailProcessor tries to find by name<commit_after>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Signum.Entities.Mailing;
using Signum.Utilities;

namespace Signum.Web.Mailing
{
    public class WebMailOptions
    {
        public bool ForEditing;
        public IEnumerable<EmailAttachmentDN> Attachments;
        public string UntrustedImage;
        public UrlHelper Url;
        public bool HasUntrusted;
    }

    public static class WebMailProcessor
    {
        public static string ReplaceUntrusted(string body, WebMailOptions options)
        {
            if (options.UntrustedImage == null)
                return body; 

            var result = Regex.Replace(body, @"<img [^>]*>", (Match img) =>
            {
                string prevSource = null;

                var newImg = Regex.Replace(img.Value, "src=\"(?<link>[^\"]*)\"", src =>
                {
                    var value = src.Groups["link"].Value;

                    if (!value.StartsWith("cid:"))
                    {
                        options.HasUntrusted = true;
                        prevSource = value;
                        return "src=\"{0}\"".Formato(options.Url.Content(options.UntrustedImage));
                    }

                    return src.Value;
                });

                if (prevSource == null)
                    return newImg;
                
                var title = prevSource;

                var alt = Regex.Match(img.Value, "alt=\"(?<alt>[^\"]*)\"");
                if (alt.Success && alt.Groups["alt"].Value.HasText())
                    title = alt.Groups["alt"].Value + "\r\n" + title;

                return newImg.Insert("<img ".Length, "title=\"" + title + "\" ");
            });

            return result;
        }

        public static string AssertNoUntrusted(string body, WebMailOptions options)
        {
            if (options.UntrustedImage == null)
                return body;

            string imageUrl = options.Url.Content(options.UntrustedImage);

            if (body.Contains(imageUrl))
                throw new InvalidOperationException("{0} found when saving the Email".Formato(imageUrl));

            return body; 
        }

        public static string CidToFilePath(string body, WebMailOptions options)
        {
            if (!options.Attachments.Any())
                return body;

            var newBody = Regex.Replace(body, "src=\"(?<link>[^\"]*)\"", src =>
            {
                string value = src.Groups["link"].Value;

                if (!value.StartsWith("cid:"))
                    return src.Value;

                string cid = value.After("cid:");

                EmailAttachmentDN only = options.Attachments.Where(a => a.ContentId == cid).Only();
                if (only != null)
                    return "src=\"{0}\"".Formato(options.Url.Content(only.File.FullWebPath));

                string fileName = cid.TryBefore('@');
                if (fileName == null)
                    return src.Value;

                only = options.Attachments.Where(a => a.File.FileName == fileName).Only();
                if (only != null)
                    return "src=\"{0}\"".Formato(options.Url.Content(only.File.FullWebPath));

                return src.Value;
            });

            return newBody;
        }

        public static string FilePathToCid(string body, WebMailOptions options)
        {
{'fraction_non_alphanumeric': 0.12044117647058823, 'fraction_numerical': 0.0010294117647058824, 'mean_word_length': 1.562547098718915, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 26, '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': '819127', 'n_tokens_mistral': 1843, 'n_tokens_neox': 1733, 'n_words': 384}