public void Replace(int offset, int length, string newText) { newText = HtmlUtils.EscapeEntities(newText); Highlight(offset, length); _textBox.SelectedText = newText; _drift += _currentWord.Len - newText.Length; }
protected internal override void HandleResult(string homepageHtml, ITestResults results) { Regex regex = new Regex(Regex.Escape(guid1) + "(.*?)" + Regex.Escape(guid2)); SimpleHtmlParser parser = new SimpleHtmlParser(homepageHtml); for (Element e = parser.Next(); e != null; e = parser.Next()) { if (e is Text) { Match m = regex.Match(e.ToString()); if (m.Success) { string str = m.Groups[1].Value; if (str == HtmlUtils.EscapeEntities(TEST_STRING)) { results.AddResult("requiresHtmlTitles", YES); } else if (str == HtmlUtils.EscapeEntities(HtmlUtils.EscapeEntities(TEST_STRING))) { results.AddResult("requiresHtmlTitles", NO); } else { results.AddResult("requiresHtmlTitles", "[ERROR] (value was: " + str + ")"); } return; } } } throw new InvalidOperationException("Title encoding test failed--title was not detected"); }
public string GenerateMetadataHtml(bool editMode) { StringBuilder metadataHtml = new StringBuilder(); string editModeAttributes = string.Format(CultureInfo.InvariantCulture, " contentEditable=\"true\" maxCharactersAccepted=\"{0}\" class=\"{1}\" defaultText=\"{2}\" wlPropertyPath=\"{3}\" ", Res.Get(StringId.VideoCaptionMaxCharactersAccepted), InlineEditField.EDIT_FIELD, Res.Get(StringId.VideoCaptionDefaultText), HtmlUtils.EscapeEntities(VIDEO_CAPTION) ); if (Caption.Trim() != String.Empty) { metadataHtml.Append(string.Format(CultureInfo.InvariantCulture, "<div style=\"width:{0}px;clear:both;font-size:{1}\"{2}>", HtmlSize.Width, Res.Get(StringId.Plugin_Video_Caption_Size), editMode ? editModeAttributes : string.Empty)); metadataHtml.Append(Caption.Trim()); metadataHtml.Append("</div>"); return(metadataHtml.ToString()); } if (editMode) { metadataHtml.Append(string.Format(CultureInfo.InvariantCulture, "<div style=\"width:{0}px;clear:both;font-size:{1};\"{2}></div>", HtmlSize.Width, Res.Get(StringId.Plugin_Video_Caption_Size), editModeAttributes)); } return(metadataHtml.ToString()); }
/// <summary> /// Escapes HTML entities and optionally replaces any plain-text HTTP, HTTPS and FTP URLs with a HTML link to /// that URL. These must be done at the same time to avoid escaping URL characters. /// </summary> private static string EscapeHtmlEntitiesAndAddLinks(string text, bool addLinks) { StringBuilder output = new StringBuilder(); int pos = 0; if (addLinks) { // Links start with http://, https://, or ftp:// at a word break, and continue until < or > is encountered, or whitespace. // If whitespace, then a single "." or "," character may also be removed from the link. Match match = Regex.Match(text, @"\b(http://|https://|ftp://).+?(?=[\<\>]|(([.,])?[\s$]))", RegexOptions.IgnoreCase); for (; match.Success; match = match.NextMatch()) { if (match.Index > pos) { output.Append(HtmlUtils.EscapeEntities(text.Substring(pos, match.Index - pos))); } pos = match.Index + match.Length; output.AppendFormat("<a href=\"{0}\">{0}</a>", HtmlUtils.EscapeEntities(match.Value)); } } if (pos < text.Length) { output.Append(HtmlUtils.EscapeEntities(text.Substring(pos))); } return(output.ToString()); }
public void WriteElementAttribute(StringBuilder sb, String attrName, String attrValue) { Debug.Assert(Regex.IsMatch(attrName, "^[a-zA-Z-]+$"), "Illegal attribute name: " + attrName); sb.Append(" "); sb.Append(attrName); sb.Append("=\""); sb.Append(HtmlUtils.EscapeEntities(attrValue)); sb.Append("\""); }
private void NavigateToProgressPage() { try { // write progress page if we need to string tifDirectory = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); string progressPageDirectory = Path.Combine(tifDirectory, "OpenLiveWriter\\ProgressPage"); string progressPagePath = Path.Combine(progressPageDirectory, "index.htm"); if (!File.Exists(progressPagePath)) { // create the directory if necessary if (!Directory.Exists(progressPageDirectory)) { Directory.CreateDirectory(progressPageDirectory); } // write the animation string animationGifName = "BallSpinner.gif"; string animationGifPath = Path.Combine(progressPageDirectory, animationGifName); ResourceHelper.SaveAssemblyResourceToFile("Images." + animationGifName, animationGifPath); // write the web page string progressText = Res.Get(StringId.BrowserMiniFormProgress); int bodyHeight = _explorerBrowserControl.Height - 50; int progressTop = Math.Max((bodyHeight / 2) - 50, 0); using (StreamWriter writer = new StreamWriter(progressPagePath, false, Encoding.UTF8)) { writer.Write(@" <html> <head></head> <body> <div style=""height={0}px;""> <div style=""position: absolute; top: {1}; width: 100%; text-align: center"" > <img src=""{2}""></img> <p> <font size=""2"" face=""Tahoma, Arial"" color=""rgb(190,200,210)""> <b>{3}</b> </font> </p> </div> </div> </body> </html> ", bodyHeight, progressTop, animationGifName, HtmlUtils.EscapeEntities(progressText)); } } // navigate to progress page _explorerBrowserControl.DocumentComplete += new BrowserDocumentEventHandler(_explorerBrowserControl_ProgressDocumentComplete); _explorerBrowserControl.Navigate(progressPagePath); } catch (Exception ex) { Trace.Fail("Unexpected exception occurred while attempting to display progress page: " + ex.ToString()); } }
/// <summary> /// Overridable hook to allow custom handling of reading the post title for insertion into an XML-RPC request. /// This method is called when reading the post title for insertion in an XML-RPC response. Most providers /// represent the post title value as HTML, so the default implementation here escapes plain text post Title /// into HTML format. /// </summary> /// <param name="post"></param> /// <returns></returns> protected string GetPostTitleForXmlValue(BlogPost post) { if (!this.Options.RequiresHtmlTitles) { return(post.Title); } else { return(HtmlUtils.EscapeEntities(post.Title)); } }
private string GenerateHtml(string onLoadAttribute) { // see if the caller wants a new window string newWindowAttribute = OpenPreviewInNewWindow ? "target=\"_new\"" : String.Empty; // see if the user has requested a size override string imageHtmlSize = !PreviewImageSize.IsEmpty ? String.Format(CultureInfo.InvariantCulture, "width=\"{0}\" height=\"{1}\"", PreviewImageSize.Width, PreviewImageSize.Height) : String.Empty; // return the preview html return(String.Format(CultureInfo.InvariantCulture, "<div><a href=\"{0}\" {1}><img src=\"{2}\" style=\"border-style: none\" galleryimg=\"no\" {3} {4} alt=\"\"></a></div>", HtmlUtils.EscapeEntities(PreviewLink), newWindowAttribute, HtmlUtils.EscapeEntities(PreviewImageSrc), imageHtmlSize, onLoadAttribute)); }
public string ToHTML() { if (_value == null) { return(null); } switch (_type) { case AtomContentValueType.Text: return(HtmlUtils.EscapeEntities(_value)); case AtomContentValueType.HTML: case AtomContentValueType.XHTML: return(_value); } throw new InvalidOperationException("Unknown text type: " + _type); }
private string GenerateEditorVideoHtml() { StringBuilder videoHtml = new StringBuilder(); if (VideoHasError() || VideoHasProgress()) { string videoImageFile = _content.Files.GetUri(_content.Properties.GetString(VIDEO_PUBLISH_IMAGE, String.Empty)).ToString(); // Add the snapshot of the video videoHtml.Append(String.Format(CultureInfo.InvariantCulture, "<div id=\"{3}\" style=\"float:left;width:{0}px;height:{1}px;background-image:url({2})\">", HtmlSize.Width, HtmlSize.Height, HtmlUtils.EscapeEntities(videoImageFile), HtmlUtils.EscapeEntities(VideoThumbnailId))); Uri uriProgressPath = _content.Files.GetUri(VIDEO_PROGRESS_PATH); if (uriProgressPath != null) { // If the video is being published, show the progress animation on the placeholder, the gif is 32x32 videoHtml.Append(String.Format(CultureInfo.InvariantCulture, @"<img style=""padding:0;margin:0;border-style:none"" title=""{2}"" src=""{0}"" alt=""{1}"" hspace=""{3}"" vspace=""{4}"" >", HtmlUtils.EscapeEntities(uriProgressPath.ToString()), HtmlUtils.EscapeEntities(Res.Get(StringId.Plugin_Video_Alt_Text)), _content.Properties.GetString(VIDEO_STATUS, null), (HtmlSize.Width / 2) - 16, (HtmlSize.Height / 2) - 32 - 15)); } videoHtml.Append(("</div>")); } else { if (string.IsNullOrEmpty(EditorFormat)) { EditorFormat = Provider.EditorFormat; } // Add the snapshot of the video videoHtml.Append(EditorFormat); } return(videoHtml.ToString()); }
/// <summary> /// Write a begin tag to the StringBuilder. Attributes will be /// filtered according to the provided TagDesc, if any. /// </summary> private void WriteBeginTag(TagDesc desc, string tagName, Attr[] attributes, StringBuilder output) { output.Append("<" + tagName); for (int i = 0; i < attributes.Length; i++) { Attr attr = attributes[i]; if (attr != null && (desc == null || desc.AttributeAllowed(attr.Name))) { output.Append(" "); output.Append(attributes[i].Name); string val = attributes[i].Value; if (val != null) { // hack for Word 2007 footnotes. if (tagName == "a") { if (attributes[i].NameEquals("name")) { // Do a fast check before doing an expensive one if (val.StartsWith("_ftn", StringComparison.OrdinalIgnoreCase) && Regex.IsMatch(val, @"^_ftn(ref)?(\d+)$", RegexOptions.IgnoreCase)) { val += WordFootnoteAnchorSuffix; } } else if (attributes[i].NameEquals("href")) { // Do a fast check before doing an expensive one if (val.StartsWith("#_ftn", StringComparison.OrdinalIgnoreCase) && Regex.IsMatch(val, @"^#_ftn(ref)?(\d+)$", RegexOptions.IgnoreCase)) { val += WordFootnoteAnchorSuffix; } } } output.Append("=\"" + HtmlUtils.EscapeEntities(val) + "\""); } } } output.Append(">"); }
public virtual string GenerateHtmlFromFiles(string[] files) { StringBuilder html = new StringBuilder(); foreach (string file in files) { if (html.Length > 0) { html.Append("\r\n"); } if (PathHelper.IsPathImage(file)) { html.AppendFormat("<img src=\"{0}\" />", HtmlUtils.EscapeEntities(UrlHelper.CreateUrlFromPath(file))); } else { html.AppendFormat("<a href=\"{0}\">{1}</a>", HtmlUtils.EscapeEntities(UrlHelper.CreateUrlFromPath(file)), HtmlUtils.EscapeEntities(Path.GetFileNameWithoutExtension(file))); } } return(html.ToString()); }
public void InsertLink(string url, string linkText, string linkTitle, string rel, bool newWindow) { StringBuilder link = new StringBuilder("<a href=\"{0}\""); if (newWindow) { link.Append(" target=\"_blank\""); } if (String.Empty != linkTitle && null != linkTitle) { link.Append(" title=\"{2}\""); } if (String.Empty != rel && null != rel) { link.Append(" rel=\"{3}\""); } link.Append(">{1}</a>"); InsertHtml(String.Format(CultureInfo.InvariantCulture, link.ToString(), HtmlUtils.EscapeEntities(url), HtmlUtils.EscapeEntities(linkText), HtmlUtils.EscapeEntities(linkTitle), HtmlUtils.EscapeEntities(rel)), true); }
public virtual string GenerateHtmlFromLink(string url, string linkText, string linkTitle, string rel, bool newWindow) { StringBuilder link = new StringBuilder("<a href=\"{0}\""); url = HtmlUtils.EscapeEntities(url); linkText = TextHelper.GetHTMLFromText(linkText, false); linkTitle = HtmlUtils.EscapeEntities(linkTitle); rel = HtmlUtils.EscapeEntities(rel); if (newWindow) { link.Append(" target='_blank'"); } if (String.Empty != linkTitle && null != linkTitle) { link.Append(" title=\"{2}\""); } if (String.Empty != rel && null != rel) { link.Append(" rel=\"{3}\""); } link.Append(">{1}</a>"); return(String.Format(CultureInfo.InvariantCulture, link.ToString(), url, linkText, linkTitle, rel)); }
/// <summary> /// Convert plain-text to HTML by escaping standard HTML entities. /// </summary> /// <param name="plainText">Plain-text to escape.</param> /// <returns>Escaped HTML content.</returns> public static string HtmlEncode(string plainText) { return(HtmlUtils.EscapeEntities(plainText)); }
/// <summary> /// Converts tag names, attribute names, and style text to lowercase. /// </summary> private string CleanupHtml(string html, bool xml) { bool needsCleanup; do { needsCleanup = false; StringBuilder output = new StringBuilder(html.Length); SimpleHtmlParser htmlParser = new SimpleHtmlParser(html); for (Element el; null != (el = htmlParser.Next());) { if (el is BeginTag) { BeginTag bt = (BeginTag)el; if (RemoveMeaninglessTags(htmlParser, bt)) { // Since we are removing a tag, we will want to clean up again, since that might mean // there will be another tag to remove needsCleanup = true; continue; } output.Append("<"); output.Append(bt.Name.ToLower(CultureInfo.InvariantCulture)); foreach (Attr attr in bt.Attributes) { if (attr.NameEquals("contenteditable") || attr.NameEquals("atomicselection") || attr.NameEquals("unselectable")) { continue; } output.Append(" "); output.Append(attr.Name.ToLower(CultureInfo.InvariantCulture)); if (attr.Value != null) { string attrVal = attr.Value; if (attr.NameEquals("style")) { attrVal = LowerCaseCss(attrVal); } else if (attr.Name == attr.Value) { attrVal = attrVal.ToLower(CultureInfo.InvariantCulture); } output.AppendFormat("=\"{0}\"", xml ? HtmlUtils.EscapeEntitiesForXml(attrVal, true) : HtmlUtils.EscapeEntities(attrVal)); } } if (bt.HasResidue) { if (bt.Attributes.Length == 0) { output.Append(" "); } output.Append(bt.Residue); } if (bt.Complete) { output.Append(" /"); } output.Append(">"); } else if (el is EndTag) { output.AppendFormat("</{0}>", ((EndTag)el).Name.ToLower(CultureInfo.InvariantCulture)); } else if (el is Text) { string textHtml = HtmlUtils.TidyNbsps(el.RawText); if (xml) { textHtml = HtmlUtils.EscapeEntitiesForXml( HtmlUtils.UnEscapeEntities(textHtml, HtmlUtils.UnEscapeMode.NonMarkupText), false); } output.Append(textHtml); } else if (el is StyleText) { output.Append(el.RawText.ToLower(CultureInfo.InvariantCulture)); } else { output.Append(el.RawText); } } html = output.ToString(); } while (needsCleanup); return(html); }
/// <summary> /// Inserts a set of images into the current editor, optionally assigning each image an id. /// </summary> /// <param name="imagePaths">paths of the images to insert</param> internal static void InsertImagesCore(IBlogPostHtmlEditor currentEditor, ISupportingFileService fileService, IEditorAccount editorAccount, OpenLiveWriter.PostEditor.ContentEditor editor, string[] imagePaths) { using (OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit undo = new OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit(currentEditor)) { StringBuilder htmlBuilder = new StringBuilder(); //calculate the size for inserted images (based on the user's saved default for this blog) DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager); Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize(); //Generate the default img HTML for the image paths. Initially, the images are linked to the source image //path so that the DOM version of the HTML can be loaded. Once the images are loaded into the DOM, we can apply //the image decorators to generate scaled images, borders, etc. ImagePropertiesInfo[] imageInfos = new ImagePropertiesInfo[imagePaths.Length]; // don't insert into the title currentEditor.FocusBody(); for (int i = 0; i < imageInfos.Length; i++) { string imagePath = imagePaths[i]; Uri imgUri; if (UrlHelper.IsUrl(imagePath)) { imgUri = new Uri(imagePath); } else { imgUri = new Uri(UrlHelper.CreateUrlFromPath(imagePath)); } Size imageSize = new Size(1, 1); if (imgUri.IsFile && File.Exists(imagePath)) { if (!File.Exists(imgUri.LocalPath)) { Trace.Fail("Error inserting image - the image URL was corrupted: " + imagePath); } else { try { //check the validity of the image file imageSize = ImageUtils.GetImageSize(imagePath); } catch (Exception) { Trace.WriteLine("There is a problem with the image file: " + imagePath); // Insert anyway, MSHTML will show a red X in place of the image. htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri))); continue; } } } // If the image has an embedded thumbnail, we'll use it as a place holder for the <img src="..."> // until we generate an inline image and apply decorators. Stream embeddedThumbnailStream = ImageHelper2.GetEmbeddedThumbnailStream(imagePath); if (embeddedThumbnailStream != null) { // Save thumbnail to disk. ISupportingFile imageFileEmbeddedThumbnail = fileService.CreateSupportingFile(Path.GetFileName(imagePath), Guid.NewGuid().ToString(), embeddedThumbnailStream); imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize); //insert the default image html String imageElementAttrs = String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height); htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" srcDelay=\"{1}\" {2} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imageFileEmbeddedThumbnail.FileUri)), HtmlUtils.EscapeEntities(imgUri.ToString()), imageElementAttrs); } else if (currentEditor is BlogPostHtmlEditorControl && (imagePaths.Length > DELAYED_IMAGE_THRESHOLD || imageSize.Width * imageSize.Height > 16777216 /*4096 X 4096*/)) { // If we are using a delayed loading tactic then we insert using the srcdelay htmlBuilder.Append(MakeHtmlForImageSourceDelay(imgUri.ToString())); } else { imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize); //insert the default image html String imageElementAttrs = imgUri.IsFile ? String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height) : String.Empty; htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" {1} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri)), imageElementAttrs); } } //insert the HTML into the editor currentEditor.InsertHtml(htmlBuilder.ToString(), false); selectionChanged = false; BlogPostHtmlEditorControl blogPostEditor = currentEditor as BlogPostHtmlEditorControl; if (blogPostEditor != null) { blogPostEditor.SelectionChanged += blogPostEditor_SelectionChanged; } //now that the image HTML is inserted into the editor, apply the default settings to the new images. undo.Commit(); } }
private string ThinInternal(string html, bool preserveImages, bool strict, params ModifyReplacement[] modifyReplacements) { Hashtable replacements = _tagSpecs; if (strict) { replacements = _tagSpecsStrict; } if (modifyReplacements != null) { replacements = (Hashtable)replacements.Clone(); foreach (ModifyReplacement modifyReplacement in modifyReplacements) { modifyReplacement(replacements); } } // Will hold the results of the leading whitespace buffer. // This buffer may or may not make it into the final result, // depending on whether any block-level tags are present. StringBuilder leadingOutput = new StringBuilder(10); // Will hold the results of everything else. StringBuilder mainOutput = new StringBuilder(html.Length); // references whichever output buffer is current. StringBuilder output = leadingOutput; SimpleHtmlParser parser = new SimpleHtmlParser(html); Element el; bool preserveWhitespace = false; // <pre> blocks should preserve whitespace WhitespaceBuffer whitespaceBuffer = new WhitespaceBuffer(); whitespaceBuffer.Promote(WhitespaceClass.Paragraph); // Insert an implicit <p> unless the first non-whitespace element is a block bool hasBlock = false; while (null != (el = parser.Next())) { if (el is Tag) { Tag t = (Tag)el; string lowerName = t.Name.ToLower(CultureInfo.InvariantCulture); TagDesc desc = (TagDesc)replacements[lowerName]; // if this tag is not in the table, drop it if (desc == null) { continue; } // Replace tag with substitute tag if necessary (e.g. <DIV> becomes <P>) string tagName = desc.Substitute; if (tagName == null) { tagName = lowerName; } // special case for images if (!preserveImages && tagName == TAG_IMG) { continue; } bool beginTag = el is BeginTag; ElementClass elClass = WhitespaceBuffer.ClassifyTag(tagName, desc.TagType); hasBlock |= (elClass == ElementClass.Block || elClass == ElementClass.Paragraph || elClass == ElementClass.Break); if (!preserveWhitespace && WhitespaceBuffer.ProcessElementClass(ref whitespaceBuffer, output, elClass, true)) { continue; } output = mainOutput; if (beginTag) { WriteBeginTag(desc, tagName, ((BeginTag)el).Attributes, output); if (tagName == TAG_PRE) { preserveWhitespace = true; } } else if (el is EndTag) { if (!((EndTag)el).Implicit && desc.TagType != TagType.Empty) { output.Append(string.Format(CultureInfo.InvariantCulture, "</{0}>", tagName)); } if (tagName == TAG_PRE) { preserveWhitespace = false; } } } else if (el is Text) { string text = el.RawText; text = HtmlUtils.EscapeEntities(HtmlUtils.UnEscapeEntities(text, HtmlUtils.UnEscapeMode.NonMarkupText)); if (!preserveWhitespace && WhitespaceBuffer.ProcessElementClass(ref whitespaceBuffer, output, WhitespaceBuffer.ClassifyText(text), false)) { continue; } output = mainOutput; output.Append(text); } } if (hasBlock && ReferenceEquals(mainOutput, output)) { output.Insert(0, leadingOutput.ToString()); } // The whitespace buffer may not be empty at this point. That's OK--we want to drop trailing whitespace return(output.ToString()); }
public override string OnTitleInserted(string title) { return(String.Format(CultureInfo.InvariantCulture, "<span id=\"{0}\" class='postTitle' style='margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; border: 0px;'>{1}</span>", TITLE_FRAGMENT_ID, HtmlUtils.EscapeEntities(title))); }
public static string MakeHtmlForImageSourceDelay(string path) { return (String.Format(CultureInfo.InvariantCulture, "<img src=\"{1}\" srcDelay=\"{0}\" />", HtmlUtils.EscapeEntities(path), HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(LoadingImagePath)))); }