danwhite85
7/11/2012 - 7:50 PM

Umbraco - TinyMce helpers for parsing localmedia to real links

Umbraco - TinyMce helpers for parsing localmedia to real links

public static HtmlString ParseTemplates(string html)
{
  if (string.IsNullOrWhiteSpace(html)) return new HtmlString(html);

  var doc = new HtmlDocument();
  doc.LoadHtml(html);

  var root = doc.DocumentNode;
  if (root != null)
  {
    var replace = false;
    var links = root.SelectNodes("//a");
    if (links != null)
    {
      foreach (var link in links)
      {
        var href = HttpUtility.HtmlDecode(link.GetAttributeValue("href", "") ?? "");
        var matchLocalMedia = StaticRegexes.LocalMediaRegex.Match(href);
        if (matchLocalMedia.Success)
        {
          int id;
          if (int.TryParse(matchLocalMedia.Groups[1].Value, out id))
          {
            var node = LuceneNode.Load(id);
            if (node != null)
            {
              var media = new MediaItem(node);
              link.SetAttributeValue("href", media.Path);

              replace = true;
            }
          }
        }
      }
    }
       
    if (replace)
    {
      html = root.OuterHtml;
    }
  }

  return new HtmlString(html);
}