public string Format(string raw, ContextInformation context, FormattingPhase phase) { var requestedPage = GetRequestedPage(context); Log(String.Format("Rendering tab menu, requested page is {0}", requestedPage)); return new Formatter(this).FormatMenu(raw, requestedPage); }
/// <summary> /// Performs the Phases 1 and 2 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <param name="linkedPages">The Pages linked by the current Page.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase1And2(string raw, bool forIndexing, FormattingContext context, PageInfo current, out string[] linkedPages) { ContextInformation info = null; string username = SessionFacade.CurrentUsername; info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, username, SessionFacade.GetCurrentGroupNames()); IList<IFormatterProviderV30> providers = GetSortedFormatters(); // Phase 1 foreach(IFormatterProviderV30 provider in providers) { if(provider.PerformPhase1) { try { raw = provider.Format(raw, info, FormattingPhase.Phase1); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase1 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } raw = Formatter.Format(raw, forIndexing, context, current, out linkedPages); // Phase 2 foreach(IFormatterProviderV30 provider in providers) { if(provider.PerformPhase2) { try { raw = provider.Format(raw, info, FormattingPhase.Phase2); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase2 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } return raw; }
public string Format(string raw, ContextInformation context, FormattingPhase phase) { try { MatchCollection colM = Regex.Matches(raw, @"\{RenderPages(.*?)\=(.*?)\}", RegexOptions.Singleline | RegexOptions.Compiled); foreach (Match m in colM) { ArrayList al = new ArrayList(); al.AddRange(m.Groups[2].Value.Split(':')); // fix per lum for v3 compatibility - assume current namespace string currentNamespace, currentPagename = String.Empty; NameTools.ExpandFullName(context.Page.FullName, out currentNamespace, out currentPagename); NamespaceInfo nsiCurrentNamespace = host.FindNamespace(currentNamespace); StringBuilder sbAllPages = new StringBuilder(); StringBuilder sbTOC = new StringBuilder(); if (!String.IsNullOrEmpty(cssFromConfig)) sbTOC.AppendFormat("<style type='text/css'>{0}</style>", cssFromConfig); sbTOC.Append("<div class='toc'>"); sbTOC.Append("<h2>Table of Contents</h2>"); sbTOC.Append("<div id='tocItems'>"); int pageNum = 0; switch (m.Groups[1].Value.TrimStart(' ').Substring(0, 1).ToLower()) { // exclude pages case "p": foreach (PageInfo Pg in host.GetPages(nsiCurrentNamespace)) { // ensure current RenderPages page isn't included if (!al.Contains(Pg.FullName) && Pg.FullName != context.Page.FullName) { sbTOC.Append(formatTocItem(pageNum, Pg.FullName, false)); sbAllPages.Append(formatPage(pageNum, formatPageHeader(pageNum, Pg.FullName), host.GetFormattedContent(Pg))); pageNum++; } } break; // include categories case "c": foreach (CategoryInfo ci in host.GetCategories(nsiCurrentNamespace)) { if (al.Contains("#ALL#") || al.Contains(ci.FullName)) { sbTOC.Append("<div class='tocCategory'>" + formatTocItem(pageNum, ci.FullName, true)); sbAllPages.Append(formatPage(pageNum, formatCategoryHeader(pageNum, ci.FullName), String.Empty)); pageNum++; // fix per jantony to ensure alpha sorting of pages Array.Sort(ci.Pages); foreach (string strPage in ci.Pages) { // ensure current RenderPages page isn't included if (strPage != context.Page.FullName) { PageInfo Pg = host.FindPage(strPage); sbTOC.Append(formatTocItem(pageNum, Pg.FullName, false)); sbAllPages.Append(formatPage(pageNum, formatPageHeader(pageNum, Pg.FullName), host.GetFormattedContent(Pg))); pageNum++; } } sbTOC.Append("</div>"); } } break; default: break; } raw = Regex.Replace(raw, m.Value, sbTOC.ToString() + "</div></div>" + sbAllPages.ToString(), RegexOptions.Singleline | RegexOptions.Compiled); } return raw; } catch (Exception ex) { host.LogEntry(String.Format("Failed RenderPages Format method for page {0} - {1}", context.Page.FullName, ex.Message), LogEntryType.Error, null, this); return "Unexpected problem encountered in RenderPages plugin: " + ex.Message; } }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { return raw; }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { // <countDownloads pattern="..."[ startDate="yyyy/mm/dd"]> // <file name="..."[ provider="..."] /> // <attachment name="..." page="..."[ provider="..."] /> // </countDownloads> // All downloads are grouped together // Pattern placeholders: #COUNT#, #DAILY#, #WEEKLY#, #MONTHLY# (case insensitive) // Pattern example: "Downloaded #COUNT# times (#MONTHLY#/month)!" // StartDate omitted -> 2009/01/01 // Provider omitted -> default // File/attachment/page not found -> ignored StringBuilder buffer = new StringBuilder(raw); KeyValuePair<int, string> block = FindAndRemoveFirstOccurrence(buffer); while(block.Key != -1) { string blockHash = "DownCount-" + block.Value.ToString(); string result = null; if(System.Web.HttpContext.Current != null) { result = System.Web.HttpContext.Current.Cache[blockHash] as string; } if(result == null) { XmlDocument doc = new XmlDocument(); doc.LoadXml(block.Value); string pattern; DateTime startDate; GetRootAttributes(doc, out pattern, out startDate); double downloads = CountAllDownloads(doc); double timeSpanInDays = (DateTime.Now - startDate).TotalDays; int dailyDownloads = (int)Math.Round(downloads / timeSpanInDays); int weeklyDownloads = (int)Math.Round(downloads / (timeSpanInDays / 7D)); int monthlyDownloads = (int)Math.Round(downloads / (timeSpanInDays / 30D)); result = BuildResult(pattern, (int)downloads, dailyDownloads, weeklyDownloads, monthlyDownloads); if(System.Web.HttpContext.Current != null) { System.Web.HttpContext.Current.Cache.Add(blockHash, result, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } } buffer.Insert(block.Key, result); block = FindAndRemoveFirstOccurrence(buffer); } return buffer.ToString(); }
/// <summary> /// Gets the rating of the plugin from the backendpage and display it to the user. /// </summary> /// <param name="context">The context.</param> /// <param name="buffer">The page content.</param> /// <param name="fullPageName">Full name of the page.</param> private void ComputeRating(ContextInformation context, StringBuilder buffer, string fullPageName) { KeyValuePair<int, Match> block = FindAndRemoveFirstOccurrence(buffer); int numRatings = 0; while(block.Key != -1) { foundRatings = true; numRatings++; string result = null; if(block.Value.Groups[2].Value != "") { int average = (int)Math.Round((decimal)GetCurrentAverage(block.Value.Groups[2].Value), 0, MidpointRounding.AwayFromZero); result += @"<span id=""staticStar" + numRatings + @""" class=""rating""></span>"; result += @"<script type=""text/javascript""> <!-- $(document).ready(function() { $('#staticStar" + numRatings + @"').html(GenerateStaticStars(" + average + @", 'ui-rating-full')); }); //--> </script>"; } else if(context.HttpContext.Request.Cookies.Get("RatingManagerPlugin_" + fullPageName) != null) { int average = (int)Math.Round((decimal)GetCurrentAverage(fullPageName), 0, MidpointRounding.AwayFromZero); result += @"<span id=""staticStar" + numRatings + @""" class=""rating""></span>"; result += @"<script type=""text/javascript""> <!-- $(document).ready(function() { $('#staticStar" + numRatings + @"').html(GenerateStaticStars(" + average + @", 'ui-rating-full')); }); //--> </script>"; } else { int average = (int)Math.Round((decimal)GetCurrentAverage(fullPageName), 0, MidpointRounding.AwayFromZero); result += @"<select name=""myRating"" class=""rating"" id=""serialStar" + numRatings + @"""> <option value=""1"">Alright</option> <option value=""2"">Ok</option> <option value=""3"">Getting Better</option> <option value=""4"">Pretty Good</option> <option value=""5"">Awesome</option> </select> <span id=""staticStar" + numRatings + @""" style=""vertical-align: middle;""></span> <span id=""average" + numRatings + @""" style=""margin-left: 5px; font-weight: bold;""></span>"; result += @"<script type=""text/javascript""> <!-- $(document).ready(function(){ var voting = true; //Show that we can bind on the select box $('#serialStar" + numRatings + @"').bind(""change"", function(){ if(voting){ voting = false; var vote = $('#serialStar" + numRatings + @"').val(); $.ajax({ url: '?vote=' + vote }); $('#serialStar" + numRatings + @"').remove(); $('.ui-rating').remove(); $('#staticStar" + numRatings + @"').html(GenerateStaticStars(vote, 'ui-rating-hover')); $('#average" + numRatings + @"').html('Thanks!'); } }); //Set the initial value $('#serialStar" + numRatings + @"').rating({showCancel: false, startValue: " + average + @"}); }); //--> </script>"; } result += @""; buffer.Insert(block.Key, result); block = FindAndRemoveFirstOccurrence(buffer); } }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { // {rating} // _backendpage not found -> ignored StringBuilder buffer = new StringBuilder(raw); try { if(context.Context == FormattingContext.PageContent && context.Page != null) { if(context.HttpContext.Request["vote"] != null) { AddRating(context.Page.FullName, int.Parse(context.HttpContext.Request["vote"])); System.Web.HttpCookie cookie = new System.Web.HttpCookie("RatingManagerPlugin_" + context.Page.FullName, context.HttpContext.Request["vote"]); cookie.Expires = DateTime.Now.AddYears(10); context.HttpContext.Response.Cookies.Add(cookie); return ""; } } if(context.Page != null) { ComputeRating(context, buffer, context.Page.FullName); } else { return raw; } } catch(Exception ex) { LogWarning(string.Format("Exception occurred: {0}", ex.StackTrace)); } if(foundRatings) { buffer.Append(@"<script type=""text/javascript"" src=""GetFile.aspx?file=" + defaultDirectoryName + jsFileName + @"""></script>"); buffer.Append(@"<link rel=""StyleSheet"" href=""GetFile.aspx?file=" + defaultDirectoryName + cssFileName + @""" type=""text/css"" />"); buffer.Append(@"<script type=""text/javascript""> <!-- function GenerateStaticStars(rate, cssClass) { var string = ''; var i = 0; for (i=0; i<rate; i++) { string +='<span class=""static-rating ' + cssClass + '""></span>'; } for(i=rate; i<5; i++) { string +='<span class=""static-rating ui-rating-empty""></span>'; } return string; } //--> </script>"); foundRatings = false; } return buffer.ToString(); }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { // {RSS:FeedAddress} // FeedAddress not found -> ignored StringBuilder buffer = new StringBuilder(raw); try { KeyValuePair<int, Match> block = FindAndRemoveFirstOccurrence(buffer); while(block.Key != -1) { string blockHash = block.Value.ToString(); string result = null; if(System.Web.HttpContext.Current != null) { result = System.Web.HttpContext.Current.Cache[blockHash] as string; } if(result == null) { bool isTwitter = block.Value.Groups[1].Value.ToLowerInvariant() == "twitter"; int entries = 1; bool newWindow = true; int words = 350; if(block.Value.Groups.Count > 3) { AnalyzeSettings(block.Value.Groups[4].Value, out entries, out newWindow, out words); } if(isTwitter) { result = @"<div class=""twitterfeed"">"; } else { result = @"<div class=""rssfeed"">"; } XmlDocument feedXml = GetXml(block.Value.Groups[2].Value); XmlNode node = feedXml.DocumentElement; for(int i = 0; i < entries; i++) { XmlNode itemTitle = node.SelectNodes("/rss/channel/item/title")[i]; if(itemTitle != null) { XmlNode itemLink = node.SelectNodes("/rss/channel/item/link")[i]; XmlNode itemContent = node.SelectNodes("/rss/channel/item/description")[i]; string itemContentStr = StripHtml(itemContent.InnerText); itemContentStr = (itemContentStr.Length > words && itemContentStr.Substring(words - 3, 5) != "[...]") ? itemContentStr.Substring(0, itemContentStr.IndexOf(" ", words - 5) + 1) + " [...]" : itemContentStr; if(itemContentStr.Length <= 1) itemContentStr = StripHtml(itemContent.InnerText); if(isTwitter) { string tweet = itemTitle.InnerText; tweet = tweet.Substring(tweet.IndexOf(":") + 2); result += @"<div class=""tweet""> <a href=""" + itemLink.InnerText + @""" title=""Go to this Tweet"""; if(newWindow) result += @" target=""_blank"""; result += @">" + tweet + @"</a> </div>"; } else { result += @"<div class=""rssentry""> <span class=""rsstitle""> <a href=""" + itemLink.InnerText + @""" title=""" + itemTitle.InnerText + @""""; if(newWindow) result += @" target=""_blank"""; result += @">" + itemTitle.InnerText + @"</a> </span> <br /> <span class=""rsscontent"">" + itemContentStr + @"</span> </div>"; } } } result += @"</div>"; if(System.Web.HttpContext.Current != null) { System.Web.HttpContext.Current.Cache.Add(blockHash, result, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } } buffer.Insert(block.Key, result); block = FindAndRemoveFirstOccurrence(buffer); } } catch(Exception ex) { LogWarning(string.Format("Exception occurred: {0}", ex.Message)); } return buffer.ToString(); }
/// <summary> /// Prepares the title of an item for display. /// </summary> /// <param name="title">The input title.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The context information.</param> /// <param name="current">The current page, if any.</param> /// <returns>The prepared title, properly sanitized.</returns> public static string PrepareTitle(string title, bool forIndexing, FormattingContext context, PageInfo current) { string temp = title; ContextInformation info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()); foreach(IFormatterProviderV30 prov in GetSortedFormatters()) { temp = prov.PrepareTitle(temp, info); } return PrepareItemTitle(temp); }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { string result = ExtractLocalizedContent(context.Language, raw); // Try to load localized content bool notLocalized = false; bool noLocalization = false; if(result == null) { result = ExtractLocalizedContent(defaultLanguage, raw); // Load content in the default language notLocalized = true; noLocalization = false; } if(result == null) { result = raw; // The Page is not localized, return all the content notLocalized = false; noLocalization = true; } if(displayWarning && !noLocalization && context.Page != null) { if(notLocalized) return NotLocalizedMessage + result; else return StandardMessage + result; } else return result; }
/// <summary> /// Prepares the title of an item for display (always during phase 3). /// </summary> /// <param name="title">The input title.</param> /// <param name="context">The context information.</param> /// <returns>The prepared title (no markup allowed).</returns> public string PrepareTitle(string title, ContextInformation context) { string result = ExtractLocalizedContent(context.Language, title); // Try to load localized content if(context.ForIndexing || result == null) { result = ExtractLocalizedContent(defaultLanguage, title); // Load content in the default language } if(result == null) { result = title; // The Page is not localized, return all the content } return result; }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { var buffer = new StringBuilder(raw); var block = FindAndRemoveFirstOccurrence(buffer); if(block.Key != -1) { string unfuddleTickets = null; if(HttpContext.Current != null) { unfuddleTickets = HttpContext.Current.Cache["UnfuddleTicketsStore"] as string; } if(string.IsNullOrEmpty(unfuddleTickets)) { unfuddleTickets = LoadUnfuddleTicketsFromWeb(); } if(string.IsNullOrEmpty(unfuddleTickets)) { unfuddleTickets = LoadErrorMessage; } do { buffer.Insert(block.Key, unfuddleTickets); block = FindAndRemoveFirstOccurrence(buffer); } while(block.Key != -1); } return buffer.ToString(); }
/// <summary> /// Performs the Phase 3 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase3(string raw, FormattingContext context, PageInfo current) { raw = Formatter.FormatPhase3(raw, context, current); ContextInformation info = null; string username = SessionFacade.CurrentUsername; info = new ContextInformation(false, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, username, SessionFacade.GetCurrentGroupNames()); // Phase 3 foreach(IFormatterProviderV30 provider in GetSortedFormatters()) { if(provider.PerformPhase3) { try { raw = provider.Format(raw, info, FormattingPhase.Phase3); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase3 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } return raw; }
public string Format(string raw, ContextInformation context, FormattingPhase phase) { if (context.Context != FormattingContext.PageContent) return raw; var targetText = new StringBuilder(); string openingTag = "{quote}"; string closingTag = "{/quote}"; var pattern = new Regex(openingTag + ".*?" + closingTag, RegexOptions.IgnoreCase | RegexOptions.Singleline); var match = pattern.Match(raw); while (match.Success) { if (match.Index > 0) targetText.Append(raw.Substring(0, match.Index)); // Remove the part before the found code block, and the code block, from the remaining // source text raw = raw.Substring(match.Index + match.Length); // Get the content of the found code block string content = match.Value; // The RegEx match still contains the opening and closing tags. Remove them so we get only the // text within the tag. int openingTagLen = openingTag.Length; int closingTagLen = closingTag.Length; int contentLen = content.Length - closingTagLen - openingTagLen; content = content.Substring(openingTagLen, contentLen); if (!String.IsNullOrWhiteSpace(content)) { var closings = FindAnySingleClosingTags(ref content); // Add an opening "pre" tag with a language ("brush") definition... targetText.AppendFormat( "<blockquote style=\"display: block; background: #F4F5F7; border: 1px dashed #CCC; margin: 5px 10px 10px 20px; padding: 8px 12px 8px 10px\"> \n"); // ... the content... targetText.Append(content); // ... and a closing tag. targetText.Append("</blockquote>"); closings.ForEach(x => { targetText.Append(x); }); } // Get the next code block. match = pattern.Match(raw); } // Append rest of source text to target. targetText.Append(raw); return targetText.ToString(); }
string GetRequestedPage(ContextInformation context) { var defaultPage = _host.GetSettingValue(SettingName.RootNamespaceDefaultPage); if (context.Page == null) { return defaultPage; } return context.Page.FullName ?? defaultPage; }
public string PrepareTitle(string title, ContextInformation context) { return title; }
/// <summary> /// Performs a Formatting phase. /// </summary> /// <param name="raw">The raw content to Format.</param> /// <param name="context">The Context information.</param> /// <param name="phase">The Phase.</param> /// <returns>The Formatted content.</returns> public string Format(string raw, ContextInformation context, FormattingPhase phase) { // Match all <ref>*</ref> MatchCollection mc = RefRegex.Matches(raw); // No ref-tag found, nothing to do if(mc.Count == 0) return raw; // No references tag if(ReferencesRegex.Matches(raw).Count == 0) { return raw + "<br/><span style=\"color: #FF0000;\">Reference Error! Missing element <references/></span>"; } string output = raw; string ref_string = "<table class=\"footnotes\">"; int footnoteCounter = 0; // For each <ref>...</ref> replace it with Footnote, append it to ref-section foreach(Match m in mc) { footnoteCounter++; output = ReplaceFirst(output, m.Value, "<a id=\"refnote" + footnoteCounter.ToString() + "\" href=\"#footnote" + footnoteCounter.ToString() + "\"><sup>" + footnoteCounter.ToString() + "</sup></a>"); ref_string += "<tr><td><a id=\"footnote" + footnoteCounter.ToString() + "\" href=\"#refnote" + footnoteCounter.ToString() + "\"><sup>" + footnoteCounter.ToString() + "</sup></a></td><td>" + RefRemovalRegex.Replace(m.Value, "") + "</td></tr>"; } ref_string += "</table>"; // Replace <reference/> with ref-section output = ReferencesRegex.Replace(output, ref_string); return output; }