This class is useful for creating a custom parser. You can customize which tags are available and how they are translated to HTML. In order to use this library, we require a link to http://codekicker.de/ from you. Licensed unter the Creative Commons Attribution 3.0 Licence: http://creativecommons.org/licenses/by/3.0/.
예제 #1
0
 public string GetHtml(string bbCode)
 {
     var parser = new BBCodeParser(
         new []
             {
                 new BBTag("b", "<b>", "</b>"),
                 new BBTag("i", "<span style=\"font-style:italic;\">", "</span>"),
                 new BBTag("u", "<span style=\"text-decoration:underline;\">", "</span>"),
                 new BBTag("img", "<img src=\"${content}\" />", string.Empty, false, true),
                 new BBTag("url", "<a href=\"${href}\">", "</a>", new BBAttribute("href", string.Empty), new BBAttribute("href", "href")),
                 new BBTag("size", "<span style=\"font-size:${size}%;\">", "</span>", new BBAttribute("size", string.Empty), new BBAttribute("size", "size")),
                 new BBTag("list", "<ul>", "</ul>"),
                 new BBTag("*", "<li>", "</li>", true, false),
                 new BBTag("quote", "<blockquote>", "</blockquote>"),
                 new BBTag("code", "<pre>", "</pre>")
             });
     try
     {
         return parser.Transform(bbCode).Replace("\r", string.Empty).Replace("\n", "<br />");
     }
     catch (BBCodeParsingException ex)
     {
         return "Error: " + ex.Message;
     }
 }
예제 #2
0
        /// <summary>
        /// HTML encodes a string then parses BB codes.
        /// </summary>
        /// <param name="text">The string to HTML encode anad BB code parse</param>
        /// <returns></returns>
        public string ParseBBCodeText(string text)
        {
            var tags = _bbCodeRepository.Get().Select(GetTag).ToList();
            var parser = new BBCodeParser(ErrorMode.ErrorFree, null, tags);
            var result = parser.ToHtml(text);
            result = result.Replace(Environment.NewLine, "<br />");

            return result;
        }
예제 #3
0
파일: HtmlUtility.cs 프로젝트: hbulzy/SYS
 public static string BBCodeToHtml(string rawString, System.Collections.Generic.IList<BBTag> bbTags, bool htmlEncode = false)
 {
     if (string.IsNullOrEmpty(rawString) || bbTags == null)
     {
         return rawString;
     }
     BBCodeParser bBCodeParser = new BBCodeParser(bbTags);
     return bBCodeParser.ToHtml(rawString, htmlEncode);
 }
예제 #4
0
 /// <summary>
 /// Transforms the given BBCode into safe HTML with the default configuration from http://codekicker.de
 /// This method is thread safe.
 /// In order to use this library, we require a link to http://codekicker.de/ from you. Licensed unter the Creative Commons Attribution 3.0 Licence: http://creativecommons.org/licenses/by/3.0/.
 /// </summary>
 /// <param name="bbCode">A non-null string of valid BBCode.</param>
 /// <returns></returns>
 public static String ToHtml(BBCodeParser rules, String bbCode)
 {
     if (rules == null)
     {
         rules = defaultParser;
     }
     if (bbCode == null)
     {
         throw new ArgumentNullException("bbCode");
     }
     return(rules.ToHtml(bbCode));
 }
예제 #5
0
        private BBCodeParser BuildParser()
        {
            if (_parser != null) return _parser;

            TryLoadDefaultTags();

            _parser = new BBCodeParser(
                ErrorMode.ErrorFree,
                null,
                _tags.Select(kvp => kvp.Value).ToList());

            return _parser;
        }
예제 #6
0
        /// <summary>
        /// Find formatting tags in the text and transform them into the appropriate HTML.
        /// </summary>
        /// <param name="text">The text to be transformed.</param>
        /// <returns>A formatted string.</returns>
        public static string ConvertTagsToHtml(string text)
        {
            var parser = new BBCodeParser(new[]
                {
                    new BBTag("code", "<pre><code>", "</code></pre>"), 
                    new BBTag("color", "<span style='color: ${color}; border-color: ${color};'>", "</span>", new BBAttribute("color", "")), 
                    new BBTag("img", "", "", true, true, content =>
                        {
                            string imageUrl = ConfirmHttp(content);
                            try
                            {
                                var client = new WebClient();
                                var stream = client.OpenRead(imageUrl);
                                var bitmap = new Bitmap(stream);
                                stream.Flush();
                                stream.Close();
                                var width = Convert.ToDecimal(bitmap.Size.Width);
                                var height = Convert.ToDecimal(bitmap.Size.Height);
                                if (width > 500m)
                                {
                                    var ratio = width / 500m;
                                    height = height / ratio;
                                    width = 500m;
                                }
                                return string.Format("<div style='height: {0}px; width: {1}px;'><a target='_blank' href='{2}'><img style='height: {0}px; width: {1}px;' src='{2}' /></a></div>", height, width, imageUrl);
                            }
                            catch
                            {
                                return string.Format("<div><a target='_blank' href='{0}'><img src='{0}' /></a></div>", imageUrl);
                            }
                        }), 
                    new BBTag("url", "<a target='_blank' href='${href}'>", "</a>", new BBAttribute("href", "", context =>
                            {
                                if (!string.IsNullOrWhiteSpace(context.AttributeValue))
                                    return context.AttributeValue;

                                var tagContent = context.GetAttributeValueByID(BBTag.ContentPlaceholderName);
                                return tagContent;   
                            })), 
                    new BBTag("quote", "<div class='quote'>", "</div>"), 
                    new BBTag("b", "<b>", "</b>"), 
                    new BBTag("i", "<span style=\"font-style:italic;\">", "</span>"),
                    new BBTag("u", "<span style=\"text-decoration:underline;\">", "</span>"),
                    new BBTag("s", "<strike>", "</strike>"),
                    new BBTag("br", "<br />", "", true, false)
                });
            return parser.ToHtml(text);
        }
 public static string ConvertTagsForConsole(string text)
 {
     var parser = new BBCodeParser(new[]
         {
             new BBTag("code", "{", "}"),
             new BBTag("color", "", ""),
             new BBTag("img", "", ""),
             new BBTag("url", "(${content}) ${href}", "", false, true, new BBAttribute("href", "")),
             new BBTag("transmit", "", ""),
             new BBTag("quote", "\n\"", "\"\n"),
             new BBTag("b", "*", "*"),
             new BBTag("i", "'", "'"),
             new BBTag("u", "_", "_"),
             new BBTag("s", "-", "-"),
         });
     return parser.ToHtml(text, false);
 }
예제 #8
0
 public void RemoveTag(string name)
 {
     TryLoadDefaultTags(); // This is so defaults can be modified
     _tags.Remove(name);
     _parser = null;
 }
        public void AttributeValueTransformer()
        {
            var parser = new BBCodeParser(ErrorMode.Strict, null, new[]
                {
                    new BBTag("font", "<span style=\"${color}${font}\">", "</span>", true, true,
                        new BBAttribute("color", "color", attributeRenderingContext => string.IsNullOrEmpty(attributeRenderingContext.AttributeValue) ? "" : "color:" + attributeRenderingContext.AttributeValue + ";"),
                        new BBAttribute("font", "font", attributeRenderingContext => string.IsNullOrEmpty(attributeRenderingContext.AttributeValue) ? "" : "font-family:" + attributeRenderingContext.AttributeValue + ";")),
                });

            Assert.AreEqual("<span style=\"color:red;font-family:Arial;\">abc</span>", parser.ToHtml("[font color=red font=Arial]abc[/font]"));
            Assert.AreEqual("<span style=\"color:red;\">abc</span>", parser.ToHtml("[font color=red]abc[/font]"));
        }
 /// <summary>
 /// Find formatting tags in the text and transform them into static tags.
 /// </summary>
 /// <param name="text">The text to be transformed.</param>
 /// <param name="replyRepository">An instance of IReplyRepository.</param>
 /// <param name="isModerator">True if the current user is a moderator.</param>
 /// <returns>A formatted string.</returns>
 public static string SimplifyComplexTags(string text, IReplyRepository replyRepository, bool isModerator)
 {
     var parser = new BBCodeParser(new[]
         {
             new BBTag("quote", "", "", true, true, content =>
                 {
                     string reformattedQuote = string.Format(@"[quote]{0}[/quote]", content);
                     if (content.IsLong())
                     {
                         Reply reply = replyRepository.GetReply(content.ToLong());
                         if (reply != null)
                             if (!reply.IsModsOnly() || isModerator)
                             {
                                 var author = reply.Topic.Board.Anonymous ? "Anon" : reply.Username;
                                 reformattedQuote = string.Format("[quote]Posted by: [transmit=USER]{0}[/transmit] on {1}\n\n{2}[/quote]", author, reply.PostedDate, reply.Body);
                             }
                     }
                     return reformattedQuote;
                 }),
         });
     return parser.ToHtml(text, false);
 }
        public void TextNodeHtmlTemplate()
        {
            var parserNull = new BBCodeParser(ErrorMode.Strict, null, new[]
                {
                    new BBTag("b", "<b>", "</b>"), 
                });
            var parserEmpty = new BBCodeParser(ErrorMode.Strict, "", new[]
                {
                    new BBTag("b", "<b>", "</b>"), 
                });
            var parserDiv = new BBCodeParser(ErrorMode.Strict, "<div>${content}</div>", new[]
                {
                    new BBTag("b", "<b>", "</b>"), 
                });

            Assert.AreEqual(@"", parserNull.ToHtml(@""));
            Assert.AreEqual(@"abc", parserNull.ToHtml(@"abc"));
            Assert.AreEqual(@"abc<b>def</b>", parserNull.ToHtml(@"abc[b]def[/b]"));

            Assert.AreEqual(@"", parserEmpty.ToHtml(@""));
            Assert.AreEqual(@"", parserEmpty.ToHtml(@"abc"));
            Assert.AreEqual(@"<b></b>", parserEmpty.ToHtml(@"abc[b]def[/b]"));

            Assert.AreEqual(@"", parserDiv.ToHtml(@""));
            Assert.AreEqual(@"<div>abc</div>", parserDiv.ToHtml(@"abc"));
            Assert.AreEqual(@"<div>abc</div><b><div>def</div></b>", parserDiv.ToHtml(@"abc[b]def[/b]"));
        }
예제 #12
0
 static BBCode()
 {
     InvalidBBCodeTextChars = @"[]\";
     _defaultParser         = GetParser();
 }
        private void FinalParsing(CommandResult commandResult)
        {
            foreach (var displayItem in commandResult.DisplayItems)
            {
                if (_currentUser != null && !_currentUser.Sound)
                    displayItem.DisplayMode |= DisplayMode.Mute;

                if (ParseAsHtml)
                {
                    if ((displayItem.DisplayMode & DisplayMode.Parse) != 0)
                        displayItem.Text = BBCodeUtility.ConvertTagsToHtml(displayItem.Text);
                    else
                        displayItem.Text = HttpUtility.HtmlEncode(displayItem.Text);

                    var masterParser = new BBCodeParser(new[]
                    {
                        new BBTag("transmit", "<span class='transmit' transmit='${transmit}'>", "</span>", new BBAttribute("transmit", "")),
                        new BBTag("topicboardid", "<span id='topicboardid'>", "</span>"),
                        new BBTag("topicstatus", "<span id='topicstatus'>", "</span>"),
                        new BBTag("topictitle", "<span id='topictitle'>", "</span>"),
                        new BBTag("topicreplycount", "<span id='topicreplycount'>", "</span>"),
                        new BBTag("topicbody", "<div id='topicbody'>", "</div>"),
                        new BBTag("topicmaxpages", "<span id='topicmaxpages'>", "</span>"),
                        new BBTag("topiceditedby", "<span id='topiceditedby'>", "</span>"),
                        new BBTag("replyeditedby", "<span id='replyeditedby'>", "</span>")
                    });

                    displayItem.Text = masterParser.ToHtml(displayItem.Text, false);

                    displayItem.Text = displayItem.Text
                        .Replace("\n", "<br />")
                        .Replace("\r", "")
                        .Replace("  ", " &nbsp;");

                    string cssClass = null;
                    if ((displayItem.DisplayMode & DisplayMode.Inverted) != 0)
                    {
                        cssClass += "inverted ";
                        displayItem.Text = string.Format("&nbsp;{0}&nbsp;", displayItem.Text);
                    }
                    if ((displayItem.DisplayMode & DisplayMode.Dim) != 0)
                        cssClass += "dim ";
                    if ((displayItem.DisplayMode & DisplayMode.Italics) != 0)
                        cssClass += "italics ";
                    if ((displayItem.DisplayMode & DisplayMode.Bold) != 0)
                        cssClass += "bold ";
                    displayItem.Text = string.Format("<span class='{0}'>{1}</span>", cssClass, displayItem.Text);
                }
                else
                {
                    var masterParser = new BBCodeParser(new[]
                    {
                        new BBTag("transmit", "", ""),
                        new BBTag("topicboardid", "", ""),
                        new BBTag("topicstatus", "", ""),
                        new BBTag("topictitle", "", ""),
                        new BBTag("topicreplycount", "", ""),
                        new BBTag("topicbody", "", ""),
                        new BBTag("topicmaxpages", "", ""),
                        new BBTag("topiceditedby", "", ""),
                        new BBTag("replyeditedby", "", "")
                    });

                    displayItem.Text = masterParser.ToHtml(displayItem.Text, false);

                    if ((displayItem.DisplayMode & DisplayMode.DontWrap) == 0)
                        displayItem.Text = displayItem.Text.WrapOnSpace(AppSettings.MaxLineLength);
                }
            }
        }
        public void StopProcessingDirective_StopsParserProcessingTagLikeText_UntilClosingTag()
        {
            var parser = new BBCodeParser(ErrorMode.ErrorFree, null, new[] { new BBTag("code", "<pre>", "</pre>") { StopProcessing = true } });

            var input = "[code][i]This should [u]be a[/u] text literal[/i][/code]";
            var expected = "<pre>[i]This should [u]be a[/u] text literal[/i]</pre>";

            Assert.AreEqual(expected, parser.ToHtml(input));
        }
        public void GreedyAttributeProcessing_ConsumesAllTokensForAttributeValue()
        {
            var parser = new BBCodeParser(ErrorMode.ErrorFree, null, new[] { new BBTag("quote", "<div><span>Posted by ${name}</span>", "</div>", new BBAttribute("name", "")) { GreedyAttributeProcessing = true } });

            var input = "[quote=Test User With Spaces]Here is my comment[/quote]";
            var expected = "<div><span>Posted by Test User With Spaces</span>Here is my comment</div>";

            Assert.AreEqual(expected, parser.ToHtml(input));
        }
        public void TagContentTransformer()
        {
            var parser = new BBCodeParser(new[]
                {
                    new BBTag("b", "<b>", "</b>", true, true, content => content.Trim()), 
                });

            Assert.AreEqual("<b>abc</b>", parser.ToHtml("[b] abc [/b]"));
        }
예제 #17
0
 public void AddTag(BBTag tag)
 {
     TryLoadDefaultTags(); // This is so defaults can be modified
     _tags[tag.Name] = tag;
     _parser = null;
 }
        public void SuppressFirstNewlineAfter_StopsFirstNewlineAfterClosingTag()
        {
            var parser = new BBCodeParser(ErrorMode.ErrorFree, null, new[] { new BBTag("code", "<pre>", "</pre>"){ SuppressFirstNewlineAfter = true } });

            var input = "[code]Here is some code[/code]\nMore text!";
            var expected = "<pre>Here is some code</pre>More text!"; // No newline after the closing PRE

            Assert.AreEqual(expected, parser.ToHtml(input));
        }
        public void NewlineTrailingOpeningTagIsIgnored()
        {
            var parser = new BBCodeParser(ErrorMode.ErrorFree, null, new[] { new BBTag("code", "<pre>", "</pre>") });

            var input = "[code]\nHere is some code[/code]";
            var expected = "<pre>Here is some code</pre>"; // No newline after the opening PRE

            Assert.AreEqual(expected, parser.ToHtml(input));
        }