private bool TryWriteApprovalRequestBodyWithPreview(Body destiniationBody, DsnHumanReadableWriter approvalRequestWriter, ApprovalInformation info, Charset outputCharset)
        {
            if (this.originalEmailMessage == null)
            {
                return(false);
            }
            TextConverter textConverter;

            if (this.originalMesssageBodyFormat == Microsoft.Exchange.Data.Transport.Email.BodyFormat.Rtf)
            {
                textConverter = new RtfToHtml
                {
                    Header             = approvalRequestWriter.GetHtmlModerationBody(info),
                    HeaderFooterFormat = HeaderFooterFormat.Html,
                    OutputEncoding     = outputCharset.GetEncoding()
                };
            }
            else if (this.originalMesssageBodyFormat == Microsoft.Exchange.Data.Transport.Email.BodyFormat.Text)
            {
                textConverter = new TextToHtml
                {
                    Header             = approvalRequestWriter.GetHtmlModerationBody(info),
                    HeaderFooterFormat = HeaderFooterFormat.Html,
                    InputEncoding      = this.originalMessageBodyCharset.GetEncoding(),
                    OutputEncoding     = outputCharset.GetEncoding()
                };
            }
            else
            {
                if (this.originalMesssageBodyFormat != Microsoft.Exchange.Data.Transport.Email.BodyFormat.Html)
                {
                    return(false);
                }
                textConverter = new HtmlToHtml
                {
                    Header             = approvalRequestWriter.GetHtmlModerationBody(info),
                    HeaderFooterFormat = HeaderFooterFormat.Html,
                    InputEncoding      = this.originalMessageBodyCharset.GetEncoding(),
                    OutputEncoding     = outputCharset.GetEncoding()
                };
            }
            BodyWriteConfiguration configuration = new BodyWriteConfiguration(Microsoft.Exchange.Data.Storage.BodyFormat.TextHtml, outputCharset);

            using (Stream stream = destiniationBody.OpenWriteStream(configuration))
            {
                using (Stream contentReadStream = this.originalEmailMessage.Body.GetContentReadStream())
                {
                    try
                    {
                        textConverter.Convert(contentReadStream, stream);
                    }
                    catch (ExchangeDataException arg)
                    {
                        ModerationApprovalRequestWriter.diag.TraceDebug <ExchangeDataException>(0L, "Approval request with inline preview failed {0}", arg);
                        return(false);
                    }
                }
            }
            return(true);
        }
Esempio n. 2
0
        protected override void VisitTextPart(TextPart entity)
        {
            string text;

            if (entity.IsHtml)
            {
                var converter = new HtmlToHtml {
                    HtmlTagCallback = HtmlTagCallback
                };

                text = converter.Convert(entity.Text);
            }
            else if (entity.IsFlowed)
            {
                var converter = new FlowedToText();

                text = converter.Convert(entity.Text);
                text = QuoteText(text);
            }
            else
            {
                // quote the original message text
                text = QuoteText(entity.Text);
            }

            var part = new TextPart(entity.ContentType.MediaSubtype.ToLowerInvariant())
            {
                Text = text
            };

            Push(part);
        }
Esempio n. 3
0
        // Token: 0x06001B94 RID: 7060 RVA: 0x00069C84 File Offset: 0x00067E84
        public static string CleanHtml(string input)
        {
            string     text       = null;
            HtmlToHtml htmlToHtml = new HtmlToHtml();

            htmlToHtml.FilterHtml         = true;
            htmlToHtml.OutputHtmlFragment = true;
            string result;

            using (TextReader textReader = new StringReader(input))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    try
                    {
                        htmlToHtml.Convert(textReader, textWriter);
                        text = textWriter.ToString();
                    }
                    catch (ExchangeDataException innerException)
                    {
                        throw FaultExceptionUtilities.CreateFault(new OwaCannotSanitizeHtmlException("Sanitization of the HTML failed", innerException, htmlToHtml), FaultParty.Sender);
                    }
                    result = text;
                }
            }
            return(result);
        }
        // Token: 0x06000128 RID: 296 RVA: 0x00004FB0 File Offset: 0x000031B0
        internal static Stream GetFilteredStream(ConfigurationContextBase configurationContext, Stream inputStream, Charset charset, BlockStatus blockStatus)
        {
            HtmlToHtml htmlToHtml = new HtmlToHtml();

            TextConvertersInternalHelpers.SetPreserveDisplayNoneStyle(htmlToHtml, true);
            WebBeaconFilterLevels filterWebBeaconsAndHtmlForms = configurationContext.FilterWebBeaconsAndHtmlForms;
            bool     flag     = filterWebBeaconsAndHtmlForms == WebBeaconFilterLevels.DisableFilter || blockStatus == BlockStatus.NoNeverAgain;
            Encoding encoding = null;

            if (charset != null && charset.TryGetEncoding(out encoding))
            {
                htmlToHtml.DetectEncodingFromMetaTag = false;
                htmlToHtml.InputEncoding             = encoding;
                htmlToHtml.OutputEncoding            = encoding;
            }
            else
            {
                htmlToHtml.DetectEncodingFromMetaTag = true;
                htmlToHtml.InputEncoding             = Encoding.ASCII;
                htmlToHtml.OutputEncoding            = null;
            }
            htmlToHtml.FilterHtml = true;
            if (!flag)
            {
                htmlToHtml.HtmlTagCallback = new HtmlTagCallback(AttachmentUtilities.webBeaconFilter.ProcessTag);
            }
            return(new ConverterStream(inputStream, htmlToHtml, ConverterStreamAccess.Read));
        }
Esempio n. 5
0
        // Token: 0x060018CE RID: 6350 RVA: 0x00055CC0 File Offset: 0x00053EC0
        protected static string ConvertToSafeHtml(string html)
        {
            string text = null;

            if (html != null)
            {
                HtmlToHtml htmlToHtml = new HtmlToHtml();
                htmlToHtml.FilterHtml         = true;
                htmlToHtml.OutputHtmlFragment = true;
                using (TextReader textReader = new StringReader(html))
                {
                    using (TextWriter textWriter = new StringWriter())
                    {
                        try
                        {
                            htmlToHtml.Convert(textReader, textWriter);
                            text = textWriter.ToString().Trim();
                            if (text.StartsWith("<div>", StringComparison.OrdinalIgnoreCase))
                            {
                                text = text.Substring("<div>".Length, text.Length - "<div>".Length - "</div>".Length);
                            }
                        }
                        catch (ExchangeDataException localizedException)
                        {
                            GetLinkPreview.ThrowLocalizedException("HtmlConversionFailed", localizedException);
                        }
                    }
                }
            }
            return(text);
        }
Esempio n. 6
0
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML fragment</param>
        /// <returns>Safe HTML fragment</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            using TextReader stringReader = new StringReader(input);
            using TextWriter stringWriter = new StringWriter();
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = true,
                NormalizeHtml      = true
            };

            htmlObject.Convert(stringReader, stringWriter);

            if (stringWriter.ToString().Length == 0)
            {
                return(string.Empty);
            }

            // stripping <div> tags
            string output = stringWriter.ToString();

            if (string.Equals(output.Substring(0, 5), "<div>", System.StringComparison.OrdinalIgnoreCase))
            {
                output = output.Substring(5);
                output = output.Substring(0, output.Length - 8);
            }

            return(output);
        }
Esempio n. 7
0
        public static string MakeSafeHtml(int traceId, string unsafeHtml)
        {
            MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Entering MakeSafeHtml");
            HtmlToHtml htmlToHtml = new HtmlToHtml();

            htmlToHtml.FilterHtml         = true;
            htmlToHtml.OutputHtmlFragment = true;
            string result;

            using (TextReader textReader = new StringReader(unsafeHtml))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    try
                    {
                        htmlToHtml.Convert(textReader, textWriter);
                    }
                    catch (ExchangeDataException ex)
                    {
                        MailTipsUtility.GetMailTipsTracer.TraceDebug <string>((long)traceId, "Exception thrown while filtering HTML: {0}", ex.Message);
                        return(string.Empty);
                    }
                    result = textWriter.ToString().Trim();
                }
            }
            return(result);
        }
     protected override void VisitTextPart (TextPart entity)
     {
         TextConverter converter;
 
         if (body != null) {
             // since we've already found the body, treat this as an attachment
             attachments.Add (entity);
             return;
         }
 
         if (entity.IsHtml) {
             converter = new HtmlToHtml {
                 HtmlTagCallback = HtmlTagCallback
             };
         } else if (entity.IsFlowed) {
             var flowed = new FlowedToHtml ();
             string delsp;
 
             if (entity.ContentType.Parameters.TryGetValue ("delsp", out delsp))
                 flowed.DeleteSpace = delsp.ToLowerInvariant () == "yes";
 
             converter = flowed;
         } else {
             converter = new TextToHtml ();
         }
 
         body = converter.Convert (entity.Text);
     }
Esempio n. 9
0
        /// <summary>
        /// Returns a safe version of HTML fragment by either sanitizing or removing all malicious scripts.
        /// </summary>
        /// <param name="input">String containing user supplied HTML</param>
        /// <returns>Safe version of user supplied HTML</returns>
        /// <remarks>Input string is passed through the HtmlToHtml class where any unsafe HTML
        /// it might contain is stripped out. A white list of non scriptable tags and attributes
        /// are used to parse the input HTML fragment for malicious scripts. For santizing entire
        /// HTML pages see <see cref="GetSafeHtml(string)"/>.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            // Check for NULL || EMPTY
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            TextReader stringReader = null;
            TextWriter stringWriter = null;
            HtmlToHtml htmlObject   = null;

            try
            {
                htmlObject   = new HtmlToHtml();
                stringReader = new StringReader(input);
                stringWriter = new StringWriter(CultureInfo.InvariantCulture);

                // Set the properties.
                htmlObject.FilterHtml         = true;
                htmlObject.OutputHtmlFragment = true;
                htmlObject.NormalizeHtml      = true;

                htmlObject.Convert(stringReader, stringWriter);

                if (stringWriter.ToString().Length != 0)
                {
                    //stripping <div> tags
                    var output = stringWriter.ToString();
                    if (output.Substring(0, 5).ToLower() == "<div>")
                    {
                        //strpping begin tag
                        output = output.Substring(5);

                        //stripping end tag + linefeed
                        output = output.Substring(0, output.Length - 8);
                    }
                    return(output);
                }
                else
                {
                    return(string.Empty);
                }
            }
            finally
            {
                if (stringReader != null)
                {
                    stringReader.Close();
                }

                if (stringWriter != null)
                {
                    stringWriter.Close();
                }
            }
        }
Esempio n. 10
0
        protected override void VisitTextPart(TextPart entity)
        {
            TextConverter converter;
            string        header, footer;

            if (_body != null)
            {
                // since we've already found the body, treat this as an attachment
                _attachments.Add(entity);
                return;
            }

            GetHeaderFooter(out header, out footer);

            if (entity.IsHtml)
            {
                converter = new HtmlToHtml
                {
                    Header          = UIStrings.MarkOfTheWeb + Environment.NewLine,
                    HeaderFormat    = HeaderFooterFormat.Html,
                    HtmlTagCallback = HtmlTagCallback
                };
            }
            else if (entity.IsFlowed)
            {
                var flowed = new FlowedToHtml
                {
                    Header       = UIStrings.MarkOfTheWeb + Environment.NewLine + header,
                    HeaderFormat = HeaderFooterFormat.Html,
                    Footer       = footer,
                    FooterFormat = HeaderFooterFormat.Html
                };
                string delsp;

                if (entity.ContentType.Parameters.TryGetValue("delsp", out delsp))
                {
                    flowed.DeleteSpace = delsp.ToLowerInvariant() == "yes";
                }

                converter = flowed;
            }
            else
            {
                converter = new TextToHtml
                {
                    Header       = UIStrings.MarkOfTheWeb + Environment.NewLine + header,
                    HeaderFormat = HeaderFooterFormat.Html,
                    Footer       = footer,
                    FooterFormat = HeaderFooterFormat.Html
                };
            }

            string text = entity.Text;

            _body = converter.Convert(entity.Text);
        }
 internal IcalSquigglieFixHtmlReader(Stream bodyStream, Charset charset, bool trustMetaTag)
 {
     IcalSquigglieFixHtmlReader < > 4__this = this;
     ConvertUtils.CallCts(ExTraceGlobals.CcBodyTracer, "IcalSquigglieFixHtmlReader::Constructor", ServerStrings.ConversionBodyConversionFailed, delegate
     {
         Encoding unicodeEncoding             = ConvertUtils.UnicodeEncoding;
         HtmlToHtml htmlToHtml                = new HtmlToHtml();
         htmlToHtml.InputEncoding             = charset.GetEncoding();
         htmlToHtml.OutputEncoding            = unicodeEncoding;
         htmlToHtml.DetectEncodingFromMetaTag = trustMetaTag;
Esempio n. 12
0
        /// <summary>
        /// Get safe version of HTML fragment.
        /// </summary>
        /// <param name="sourceReader"> TextReader as source of HTML</param>
        /// <param name="destinationStream">Stream as safeHTML</param>
        public static void GetSafeHtmlFragment(TextReader sourceReader, Stream destinationStream)
        {
            var htmlObject = new HtmlToHtml();

            // Set the properties.
            htmlObject.FilterHtml         = true;
            htmlObject.OutputHtmlFragment = true;
            htmlObject.NormalizeHtml      = true;

            htmlObject.Convert(sourceReader, destinationStream);
        }
Esempio n. 13
0
        /// <summary>
        /// Get safe version of HTML fragment.
        /// </summary>
        /// <param name="sourceReader"> TextReader as source of HTML</param>
        /// <param name="destinationWriter">TextWriter as safeHTML</param>
        public static void GetSafeHtmlFragment(TextReader sourceReader, TextWriter destinationWriter)
        {
            HtmlToHtml htmlObject = htmlObject = new HtmlToHtml();

            // Set the properties.
            htmlObject.FilterHtml         = true;
            htmlObject.OutputHtmlFragment = true;
            htmlObject.NormalizeHtml      = true;

            htmlObject.Convert(sourceReader, destinationWriter);
        }
        public void TestSimpleHtmlToHtml()
        {
            string expected  = File.ReadAllText("../../TestData/html/xamarin3.xhtml");
            string text      = File.ReadAllText("../../TestData/html/xamarin3.html");
            var    converter = new HtmlToHtml {
                HtmlTagCallback = ReplaceUrlsWithFileNames
            };
            var result = converter.Convert(text);

            Assert.AreEqual(expected, result);
        }
Esempio n. 15
0
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="sourceReader">Source text reader with malicious HTML</param>
        /// <param name="destinationStream">Stream to write safe HTML</param>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static void GetSafeHtmlFragment(TextReader sourceReader, Stream destinationStream)
        {
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = true,
                NormalizeHtml      = true
            };

            htmlObject.Convert(sourceReader, destinationStream);
        }
Esempio n. 16
0
        /// <summary>
        /// Sanitizes input HTML document for safe display on browser.
        /// </summary>
        /// <param name="sourceReader">Source text reader with malicious HTML</param>
        /// <param name="destinationWriter">Text Writer to write safe HTML</param>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static void GetSafeHtml(TextReader sourceReader, TextWriter destinationWriter)
        {
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = false,
                NormalizeHtml      = true
            };

            htmlObject.Convert(sourceReader, destinationWriter);
        }
Esempio n. 17
0
        public void TestFilterHtml()
        {
            const string input     = "<html><head><script>/* this is a script */</script></head><body>Here is the body content which seems fine so far</body></html>";
            const string expected  = "<html><head></head><body>Here is the body content which seems fine so far</body></html>";
            var          converter = new HtmlToHtml {
                FilterHtml = true
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Esempio n. 18
0
        public void TestFilterComments()
        {
            const string input     = "<html><head><!-- this is a comment --></head><body>Here is the body content <!-- this is another comment -->which seems fine so far</body></html>";
            const string expected  = "<html><head></head><body>Here is the body content which seems fine so far</body></html>";
            var          converter = new HtmlToHtml {
                FilterComments = true
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Esempio n. 19
0
        public void TestSupressInnerContent()
        {
            const string input     = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-2\"><meta name=Generator content=\"Microsoft Word 15 (filtered medium)\"><!--[if !mso]><style>v\\:* {behavior:url(#default#VML);}\r\no\\:* {behavior:url(#default#VML);}\r\nw\\:* {behavior:url(#default#VML);}\r\n.shape{behavior:url(#default#VML);}\r\n</style><![endif]--><style><!--\r\n/* Font Definitions */\r\n@font-face\r\n\t{font-family:\"Cambria Math\";\r\n\tpanose-1:2 4 5 3 5 4 6 3 2 4;}\r\n@font-face\r\n\t{font-family:Calibri;\r\n\tpanose-1:2 15 5 2 2 2 4 3 2 4;}\r\n@font-face\r\n\t{font-family:\"Segoe UI\";\r\n\tpanose-1:2 11 5 2 4 2 4 2 2 3;}\r\n@font-face\r\n\t{font-family:Verdana;\r\n\tpanose-1:2 11 6 4 3 5 4 4 2 4;}\r\n/* Style Definitions */\r\np.MsoNormal, li.MsoNormal, div.MsoNormal\r\n\t{margin:0cm;\r\n\tmargin-bottom:.0001pt;\r\n\tfont-size:11.0pt;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tmso-fareast-language:EN-US;}\r\nh3\r\n\t{mso-style-priority:9;\r\n\tmso-style-link:\"Heading 3 Char\";\r\n\tmso-margin-top-alt:auto;\r\n\tmargin-right:0cm;\r\n\tmso-margin-bottom-alt:auto;\r\n\tmargin-left:0cm;\r\n\tfont-size:13.5pt;\r\n\tfont-family:\"Times New Roman\",serif;}\r\na:link, span.MsoHyperlink\r\n\t{mso-style-priority:99;\r\n\tcolor:#0563C1;\r\n\ttext-decoration:underline;}\r\na:visited,span.MsoHyperlinkFollowed\r\n\t{mso-style-priority:99;\r\n\tcolor:#954F72;\r\n\ttext-decoration:underline;}\r\nspan.Heading3Char\r\n\t{mso-style-name:\"Heading 3 Char\";\r\n\tmso-style-priority:9;\r\n\tmso-style-link:\"Heading 3\";\r\n\tfont-family:\"Times New Roman\",serif;\r\n\tmso-fareast-language:FR;\r\n\tfont-weight:bold;}\r\nspan.EmailStyle18\r\n\t{mso-style-type:personal;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tcolor:windowtext;}\r\nspan.EmailStyle19\r\n\t{mso-style-type:personal-reply;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tcolor:#1F497D;}\r\n.MsoChpDefault\r\n\t{mso-style-type:export-only;\r\n\tfont-size:10.0pt;}\r\n@page WordSection1\r\n\t{size:612.0pt 792.0pt;\r\n\tmargin:70.85pt 70.85pt 70.85pt 70.85pt;}\r\ndiv.WordSection1\r\n\t{page:WordSection1;}\r\n--></style><!--[if gte mso 9]><xml>\r\n<o:shapedefaults v:ext=\"edit\" spidmax=\"1026\" />\r\n</xml><![endif]--><!--[if gte mso 9]><xml>\r\n<o:shapelayout v:ext=\"edit\">\r\n<o:idmap v:ext=\"edit\" data=\"1\" />\r\n</o:shapelayout></xml><![endif]--></head><body lang=FR link=\"#0563C1\" vlink=\"#954F72\">Here is the body content which seems fine so far</body></html>";
            const string expected  = "Here is the body content which seems fine so far";
            var          converter = new HtmlToHtml {
                HtmlTagCallback = SupressInnerContentCallback
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Esempio n. 20
0
        public static void RenderMultipartRelated(MultipartRelated related, WebBrowserEditabil pWebBrowser)
        {
            var root      = related.Root;
            var multipart = root as Multipart;
            var text      = root as TextPart;

            if (multipart != null)
            {
                for (int i = multipart.Count; i > 0; i--)
                {
                    var body = multipart[i - 1] as TextPart;

                    if (body == null)
                    {
                        continue;
                    }

                    if (body.ContentType.IsMimeType("text", "html"))
                    {
                        text = body;
                        break;
                    }

                    if (text == null)
                    {
                        text = body;
                    }
                }
            }
            if (text != null)
            {
                if (text.ContentType.IsMimeType("text", "html"))
                {
                    var ctx       = new MultipartRelatedImageContext(related);
                    var converter = new HtmlToHtml()
                    {
                        HtmlTagCallback = ctx.HtmlTagCallback
                    };
                    var html = converter.Convert(text.Text);

                    pWebBrowser.DocumentText = html;
                }
                else
                {
                    RenderText(text, pWebBrowser);
                }
            }
            else
            {
                return;
            }
        }
Esempio n. 21
0
        public void TestSimpleHtmlToHtml()
        {
            string expected  = File.ReadAllText(Path.Combine(TestHelper.ProjectDir, "TestData", "html", "xamarin3.xhtml"));
            string text      = File.ReadAllText(Path.Combine(TestHelper.ProjectDir, "TestData", "html", "xamarin3.html"));
            var    converter = new HtmlToHtml {
                Header = null, Footer = null, HtmlTagCallback = ReplaceUrlsWithFileNames
            };
            var result = converter.Convert(text);

            Assert.AreEqual(TextFormat.Html, converter.InputFormat, "InputFormat");
            Assert.AreEqual(TextFormat.Html, converter.OutputFormat, "OutputFormat");
            Assert.AreEqual(expected, result);
        }
Esempio n. 22
0
        public void TestTextHeaderFooter()
        {
            const string input     = "<body>Here is the body content which seems fine so far</body>";
            const string expected  = "&lt;html&gt;&lt;head&gt;&lt;/head&gt;<br/><body>Here is the body content which seems fine so far</body>&lt;/html&gt;<br/>";
            var          converter = new HtmlToHtml {
                HeaderFormat = HeaderFooterFormat.Text,
                Header       = "<html><head></head>",
                FooterFormat = HeaderFooterFormat.Text,
                Footer       = "</html>"
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Esempio n. 23
0
        public string RenderMultipartRelated(MultipartRelated related)
        {
            var root = related.Root;
            var text = root as TextPart;

            if (root is Multipart multipart)
            {
                for (int i = multipart.Count; i > 0; i--)
                {
                    if (!(multipart[i - 1] is TextPart body))
                    {
                        continue;
                    }

                    if (body.ContentType.IsMimeType("text", "html"))
                    {
                        text = body;
                        break;
                    }

                    if (text == null)
                    {
                        text = body;
                    }
                }
            }

            if (text != null)
            {
                if (text.ContentType.IsMimeType("text", "html"))
                {
                    var ctx       = new MultipartRelatedImageContext(related);
                    var converter = new HtmlToHtml()
                    {
                        HtmlTagCallback = ctx.HtmlTagCallback
                    };
                    return(converter.Convert(text.Text));
                }
                else
                {
                    return(RenderText(text));
                }
            }
            else
            {
                return("Uncknown message type.");
            }
        }
Esempio n. 24
0
        protected async override void VisitTextPart(TextPart entity)
        {
            TextConverter converter;

            if (renderedBody)
            {
                // since we've already found the body, treat this as an attachment
                attachments.Add(entity);
                return;
            }

            if (entity.IsHtml)
            {
                converter = new HtmlToHtml
                {
                    HtmlTagCallback = HtmlTagCallback
                };
            }
            else if (entity.IsFlowed)
            {
                var flowed = new FlowedToHtml();

                if (entity.ContentType.Parameters.TryGetValue("delsp", out string delsp))
                {
                    flowed.DeleteSpace = delsp.ToLowerInvariant() == "yes";
                }

                converter = flowed;
            }
            else
            {
                converter = new TextToHtml();
            }

            var client = new MultipartRelatedWebViewClient(stack);
            var html   = converter.Convert(entity.Text);

            // Add print header
            html = Regex.Replace(html, "<[Bb][Oo][Dd][Yy].*?>", "$0" + "<p id=\"emlReaderPrintHeader\" style=\"background: white; color: black;\"></p>");

            await webView.EnsureCoreWebView2Async();

            webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
            webView.CoreWebView2.WebResourceRequested += client.ShouldInterceptRequest;
            webView.NavigateToString(html);
            renderedBody = true;
        }
Esempio n. 25
0
        internal Stream ConvertWriteStreamFormat(Stream stream, Charset writeStreamCharset)
        {
            if (this.internalFormat == (InternalBodyFormat)this.format && (writeStreamCharset == null || this.charset == writeStreamCharset))
            {
                return(stream);
            }
            Charset       charset = writeStreamCharset ?? this.charset;
            TextConverter converter;

            if (this.internalFormat == InternalBodyFormat.RtfCompressed)
            {
                stream = new ConverterStream(stream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                if (BodyFormat.Rtf == this.format)
                {
                    return(stream);
                }
                converter = new TextToRtf
                {
                    InputEncoding = charset.GetEncoding()
                };
            }
            else if (this.internalFormat == InternalBodyFormat.Enriched)
            {
                converter = new HtmlToEnriched
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            else if (this.internalFormat == InternalBodyFormat.Html)
            {
                converter = new HtmlToHtml
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            else
            {
                converter = new TextToText
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            return(new ConverterStream(stream, converter, ConverterStreamAccess.Write));
        }
Esempio n. 26
0
        /// <summary>
        /// Returns a safe version of HTML page by either sanitizing or removing all malicious scripts.
        /// </summary>
        /// <param name="input">String containing user supplied HTML</param>
        /// <returns>Safe version of user supplied HTML</returns>
        /// <remarks>Input string is passed through the HtmlToHtml class where any unsafe HTML
        /// it might contain is stripped out. A white list of non scriptable tags and attributes
        /// are used to parse the input HTML page for malicious scripts. For santizing simple
        /// HTML fragments see <see cref="GetSafeHtmlFragment(string)"/>.
        /// </remarks>

        public static string GetSafeHtml(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            TextReader stringReader = null;
            TextWriter stringWriter = null;
            HtmlToHtml htmlObject   = null;

            try
            {
                htmlObject   = new HtmlToHtml();
                stringReader = new StringReader(input);
                stringWriter = new StringWriter(CultureInfo.InvariantCulture);

                // Set the properties.
                htmlObject.FilterHtml         = true;
                htmlObject.OutputHtmlFragment = false;
                htmlObject.NormalizeHtml      = true;

                htmlObject.Convert(stringReader, stringWriter);

                if (stringWriter.ToString().Length != 0)
                {
                    return(stringWriter.ToString());
                }
                else
                {
                    return(string.Empty);
                }
            }
            finally
            {
                if (stringReader != null)
                {
                    stringReader.Close();
                }

                if (stringWriter != null)
                {
                    stringWriter.Close();
                }
            }
        }
Esempio n. 27
0
        private static object FromHtmlToRtf(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                stream = new BodyCharsetDetectionStream(stream, null, coreItem, BodyStreamFormat.RtfUncompressed, null, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                HtmlToRtf htmlToRtf = new HtmlToRtf();
                htmlToRtf.InputEncoding             = configuration.SourceEncoding;
                htmlToRtf.DetectEncodingFromMetaTag = false;
                htmlToRtf.Header             = configuration.InjectPrefix;
                htmlToRtf.Footer             = configuration.InjectSuffix;
                htmlToRtf.HeaderFooterFormat = configuration.InjectionHeaderFooterFormat;
                if (configuration.ImageRenderingCallback != null)
                {
                    TextConvertersInternalHelpers.SetImageRenderingCallback(htmlToRtf, configuration.ImageRenderingCallback);
                }
                TextConverter converter = htmlToRtf;
                if (configuration.FilterHtml || configuration.InternalHtmlTagCallback != null)
                {
                    stream    = new ConverterStream(stream, htmlToRtf, ConverterStreamAccess.Write);
                    converter = new HtmlToHtml
                    {
                        InputEncoding             = configuration.SourceEncoding,
                        OutputEncoding            = configuration.SourceEncoding,
                        DetectEncodingFromMetaTag = false,
                        FilterHtml      = configuration.FilterHtml,
                        HtmlTagCallback = configuration.InternalHtmlTagCallback
                    };
                }
                obj = BodyWriteDelegates.GetConverterStreamOrWriter(stream, converter, createWriter);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
Esempio n. 28
0
        public void TestArgumentExceptions()
        {
            var converter = new HtmlToHtml();
            var reader    = new StringReader("");
            var writer    = new StringWriter();

            Assert.AreEqual(TextFormat.Html, converter.InputFormat);
            Assert.AreEqual(TextFormat.Html, converter.OutputFormat);
            Assert.IsFalse(converter.DetectEncodingFromByteOrderMark);
            Assert.IsFalse(converter.FilterComments);
            Assert.IsFalse(converter.FilterHtml);
            Assert.IsNull(converter.Footer);
            Assert.IsNull(converter.Header);
            Assert.AreEqual(HeaderFooterFormat.Text, converter.FooterFormat);
            Assert.AreEqual(HeaderFooterFormat.Text, converter.HeaderFormat);

            Assert.Throws <ArgumentNullException> (() => converter.Convert((TextReader)null, writer));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(reader, (TextWriter)null));
        }
Esempio n. 29
0
        public void TestDefaultPropertyValues()
        {
            var converter = new HtmlToHtml();

            Assert.IsFalse(converter.DetectEncodingFromByteOrderMark, "DetectEncodingFromByteOrderMark");
            Assert.IsFalse(converter.FilterComments, "FilterComments");
            Assert.IsFalse(converter.FilterHtml, "FilterHtml");
            Assert.IsNull(converter.Footer, "Footer");
            Assert.AreEqual(HeaderFooterFormat.Text, converter.FooterFormat, "FooterFormat");
            Assert.IsNull(converter.Header, "Header");
            Assert.AreEqual(HeaderFooterFormat.Text, converter.HeaderFormat, "HeaderFormat");
            Assert.IsNull(converter.HtmlTagCallback, "HtmlTagCallback");
            Assert.AreEqual(Encoding.UTF8, converter.InputEncoding, "InputEncoding");
            Assert.AreEqual(TextFormat.Html, converter.InputFormat, "InputFormat");
            Assert.AreEqual(4096, converter.InputStreamBufferSize, "InputStreamBufferSize");
            Assert.AreEqual(Encoding.UTF8, converter.OutputEncoding, "OutputEncoding");
            Assert.AreEqual(TextFormat.Html, converter.OutputFormat, "OutputFormat");
            Assert.AreEqual(4096, converter.OutputStreamBufferSize, "OutputStreamBufferSize");
        }
        public void SetCharset(Charset detectedCharset)
        {
            if (this.toHtmlConverter == null)
            {
                throw new InvalidOperationException("HtmlWriteConverterStream.SetCharset() should only be called once.");
            }
            HtmlToHtml htmlToHtml = this.toHtmlConverter as HtmlToHtml;

            if (htmlToHtml != null)
            {
                if (CodePageMap.GetCodePage(htmlToHtml.InputEncoding) == detectedCharset.CodePage && this.skipConversionOnMatchingCharset)
                {
                    this.writeStream = this.outputStream;
                }
                else
                {
                    htmlToHtml.OutputEncoding = detectedCharset.GetEncoding();
                    this.writeStream          = new ConverterStream(this.outputStream, htmlToHtml, ConverterStreamAccess.Write);
                }
            }
            else
            {
                RtfToHtml rtfToHtml = this.toHtmlConverter as RtfToHtml;
                if (rtfToHtml != null)
                {
                    rtfToHtml.OutputEncoding = detectedCharset.GetEncoding();
                }
                else
                {
                    TextToHtml textToHtml = this.toHtmlConverter as TextToHtml;
                    if (textToHtml != null)
                    {
                        textToHtml.OutputEncoding = detectedCharset.GetEncoding();
                    }
                }
                this.writeStream = new ConverterStream(this.outputStream, this.toHtmlConverter, ConverterStreamAccess.Write);
            }
            this.toHtmlConverter = null;
            this.cachedContentStream.Position = 0L;
            Util.StreamHandler.CopyStreamData(this.cachedContentStream, this.writeStream);
            this.cachedContentStream.Dispose();
            this.cachedContentStream = null;
        }