using System.Text.RegularExpressions; using System.Web; namespace atakanozbancom.Models.classes { /// /// Renders user-entered project/affiliate descriptions as safe HTML. /// The whole input is HTML-encoded first (so no raw tags/scripts can ever /// survive), then a very small Markdown-style link syntax is turned into /// real anchor tags: [Link text](https://example.com) /// Only http:// and https:// URLs are accepted; anything else is left as /// plain (encoded) text. /// public static class DescriptionFormatter { // [label](https://url) - label can't contain "]", url must be http(s) and can't contain whitespace or ")" private static readonly Regex LinkPattern = new Regex( @"\[([^\]\r\n]{1,200})\]\((https?://[^\s)]{1,2000})\)", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static string ToSafeHtml(string raw) { if (string.IsNullOrWhiteSpace(raw)) return string.Empty; // 1) Neutralize everything (script/tags/attributes) up front. var encoded = HttpUtility.HtmlEncode(raw); // 2) Re-introduce ONLY safe links for the [text](url) syntax. // Both groups are already HTML-encoded, so this can't break out // of the href attribute or inject new tags/attributes. var withLinks = LinkPattern.Replace(encoded, m => { var label = m.Groups[1].Value; var url = m.Groups[2].Value; return $"{label}"; }); // 3) Preserve line breaks the admin typed in the textarea. var withBreaks = withLinks .Replace("\r\n", "\n") .Replace("\n", "
"); return withBreaks; } } }