private HtmlForm HandleForm(BeginTag formTag)
        {
            string name = formTag.GetAttributeValue("name");
            string action = formTag.GetAttributeValue("action");
            string method = formTag.GetAttributeValue("method");

            HtmlForm htmlForm = new HtmlForm(name, action, method);

            Element el;
            while (null != (el = parser.Next()))
            {
                if (el is EndTag && ((EndTag)el).NameEquals("form"))
                    break;

                BeginTag tag = el as BeginTag;
                if (tag == null)
                    continue;

                switch (tag.Name.ToLowerInvariant())
                {
                    case "input":
                        HandleInput(htmlForm, tag);
                        break;
                    case "select":
                        HandleSelect(htmlForm, tag);
                        break;
                    case "textarea":
                        HandleTextarea(htmlForm, tag);
                        break;
                }
            }

            return htmlForm;
        }
        protected override string Replace(Element el)
        {
            if (el is BeginTag)
            {
                BeginTag tag       = (BeginTag)el;
                string   lowerName = tag.Name.ToLowerInvariant();
                if (elements.ContainsKey(lowerName))
                {
                    Hashtable attrs = elements[lowerName] as Hashtable;
                    if (attrs != null)
                    {
                        foreach (Attr attr in tag.Attributes)
                        {
                            if (attrs.Contains(attr.Name.ToLowerInvariant()))
                            {
                                return(OnMatchingAttr(tag, attr));
                            }
                        }
                    }
                }
            }
            else if (el is ScriptLiteral)
            {
                return(OnScriptLiteral((ScriptLiteral)el));
            }

            return(base.Replace(el));
        }
        public bool IsMatch(Element e)
        {
            BeginTag tag = e as BeginTag;

            if (tag == null)
            {
                return(false);
            }

            if (tagName != null && !tag.NameEquals(tagName))
            {
                return(false);
            }

            foreach (RequiredAttribute reqAttr in attrs)
            {
                int  foundAt;
                Attr attr = tag.GetAttribute(reqAttr.Name, true, 0, out foundAt);
                if (attr == null)
                {
                    return(false);
                }
                if (reqAttr.Value != null && reqAttr.Value != attr.Value)
                {
                    return(false);
                }
            }

            return(true);
        }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag.NameEquals(HTMLTokens.Body))
            {
                bodyBeginTag = tag;
            }

            base.OnBeginTag(tag);
        }
        private string EnumerateLocalFileReference(BeginTag tag, string reference)
        {
            // check if the local file is contained in the supporting file directory
            string localFilePath = new Uri(reference).LocalPath;
            if (this.ContainsFile(localFilePath))
                _supportingFileScratchList.Add(localFilePath);

            // don't transform the url
            return reference;
        }
        internal static IElementPredicate Parse(string criterion)
        {
            SimpleHtmlParser parser = new SimpleHtmlParser(criterion);
            Element          el     = parser.Next();

            if (el == null)
            {
                Debug.Fail("Criterion was null");
                throw new ArgumentException("Criterion was null");
            }
            if (parser.Next() != null)
            {
                Debug.Fail("Too many criteria");
                throw new ArgumentException("Too many criteria");
            }

            if (el is BeginTag)
            {
                BeginTag tag = (BeginTag)el;

                if (tag.HasResidue || tag.Unterminated)
                {
                    Debug.Fail("Malformed criterion");
                    throw new ArgumentException("Malformed criterion");
                }

                RequiredAttribute[] attributes = new RequiredAttribute[tag.Attributes.Length];
                for (int i = 0; i < attributes.Length; i++)
                {
                    attributes[i] = new RequiredAttribute(tag.Attributes[i].Name, tag.Attributes[i].Value);
                }
                return(new BeginTagPredicate(tag.Name, attributes));
            }
            else if (el is EndTag)
            {
                return(new EndTagPredicate(((EndTag)el).Name));
            }
            else if (el is Text)
            {
                return(new TextPredicate(el.RawText));
            }
            else if (el is Comment)
            {
                return(new CommentPredicate(el.RawText));
            }
            else
            {
                Debug.Fail("Invalid criterion \"" + criterion + "\"");
                throw new ArgumentException("Invalid criterion \"" + criterion + "\"");
            }
        }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag.NameEquals(HTMLTokens.Title) && !tag.Complete)
                _inTitle = true;

            if (TagsToPreserve.Contains(tag.Name.ToUpper(CultureInfo.InvariantCulture)))
            {
                EmitTagAndAttributes(tag.Name, tag);
            }
            else if (ReplaceTags.ContainsKey(tag.Name.ToUpper(CultureInfo.InvariantCulture)))
            {
                EmitTagAndAttributes((string)ReplaceTags[tag.Name.ToUpper(CultureInfo.InvariantCulture)], tag);
            }
        }
        private void HandleInput(HtmlForm parentForm, BeginTag inputTag)
        {
            string type = inputTag.GetAttributeValue("type");
            if (type != null)
                type = type.Trim().ToLowerInvariant();

            string name = inputTag.GetAttributeValue("name");
            string value = inputTag.GetAttributeValue("value");

            switch (type)
            {
                case "password":
                    new Textbox(parentForm, name, value);
                    break;

                case "checkbox":
                    {
                        int dummy;
                        bool isChecked = inputTag.GetAttribute("checked", true, 0, out dummy) != null;
                        new Checkbox(parentForm, name, value, isChecked);
                        break;
                    }

                case "radio":
                    {
                        int dummy;
                        bool isChecked = inputTag.GetAttribute("checked", true, 0, out dummy) != null;
                        new Radio(parentForm, name, value, isChecked);
                        break;
                    }

                case "submit":
                    new SubmitButton(parentForm, name, value);
                    break;

                case "image":
                    new ImageButton(parentForm, name, value, inputTag.GetAttributeValue("src"));
                    break;

                case "hidden":
                    new Hidden(parentForm, name, value);
                    break;

                case "text":
                default:
                    new Textbox(parentForm, name, value);
                    break;
            }
        }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag.NameEquals(HTMLTokens.Ul))
            {
                unorderedListLevel++;
            }
            else if (tag.NameEquals(HTMLTokens.Ol))
            {
                orderedListLevel++;
            }
            else if ((unorderedListLevel < 1) &&
                (orderedListLevel < 1) &&
                (tag.NameEquals(HTMLTokens.Li)))
            {
                hasIncompleteList = true;
            }

            base.OnBeginTag(tag);
        }
 protected override void OnBeginTag(BeginTag tag)
 {
     if (tag != null && LightWeightHTMLDocument.AllUrlElements.ContainsKey(tag.Name.ToUpper(CultureInfo.InvariantCulture)))
     {
         Attr attr = tag.GetAttribute((string)LightWeightHTMLDocument.AllUrlElements[tag.Name.ToUpper(CultureInfo.InvariantCulture)]);
         if (attr != null)
         {
             string oldRef = attr.Value;
             string newRef = _referenceFixer(tag, attr.Value);
             attr.Value = newRef;
             if (oldRef != newRef && _referenceFixed != null)
             {
                 //notify the reference fixed callback that a reference was fixed.
                 _referenceFixed(oldRef, newRef);
             }
         }
     }
     base.OnBeginTag(tag);
 }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag != null && LightWeightHTMLDocument.AllUrlElements.ContainsKey(tag.Name.ToUpper(CultureInfo.InvariantCulture)))
            {
                Attr attr = tag.GetAttribute((string)LightWeightHTMLDocument.AllUrlElements[tag.Name.ToUpper(CultureInfo.InvariantCulture)]);
                if (attr != null)
                {
                    string url = attr.Value;
                    if (!UrlHelper.IsUrl(url) && ShouldEscapeRelativeUrl(url))
                        attr.Value = UrlHelper.EscapeRelativeURL(BaseUrl, url);
                }
            }

            // Special case params
            if (tag != null && tag.NameEquals(HTMLTokens.Param))
            {
                // Handle Params
                foreach (string paramValue in LightWeightHTMLDocument.ParamsUrlElements)
                {
                    Attr attr = tag.GetAttribute(HTMLTokens.Name);
                    if (attr != null)
                    {
                        if (attr.Value.ToUpper(CultureInfo.InvariantCulture) == paramValue)
                        {
                            Attr valueAttr = tag.GetAttribute(HTMLTokens.Value);
                            if (valueAttr != null)
                            {
                                string url = valueAttr.Value;
                                if (!UrlHelper.IsUrl(url))
                                    valueAttr.Value = UrlHelper.EscapeRelativeURL(BaseUrl, url);
                            }
                        }
                    }
                }
            }
            base.OnBeginTag(tag);
        }
 public LightWeightTag(BeginTag tag)
 {
     _beginTag = tag;
 }
            internal string FixImageReferences(BeginTag tag, string reference)
            {
                if (!UrlHelper.IsUrl(reference))
                {
                    //Warning: fixing of relative paths is not currently supported.  This would only be
                    //a problem for post synchronization if blog servers returned relative paths when uploading
                    //(which they can't since this interface requires a URI), or if the blog service re-wrote the
                    //URL when the content was published (which is likely to cause the URL to be unmatchable
                    //anyhow). Sharepoint images cause this path to be hit, but image synchronization is not
                    //supported for SharePoint anyhow since the URLs are always re-written by the server.
                    Debug.WriteLine("warning: relative image URLs cannot be resolved for edited posts");
                }
                else
                {
                    Uri fixedImageUri = (Uri)urlFixupTable[new Uri(reference)];
                    if (fixedImageUri != null)
                    {
                        Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "RecentPostSyncrhonizer: converting remote image reference [{0}] to local reference", reference));
                        reference = fixedImageUri.ToString();
                    }
                }

                return reference;
            }
 private string AddHtmlReference(BeginTag tag, string reference)
 {
     if (UrlHelper.IsUrl(reference))
     {
         ISupportingFile supportingFile = _editingContext.SupportingFileService.GetFileByUri(new Uri(reference));
         if (supportingFile != null && supportingFile.Embedded)
         {
             AddReference(supportingFile);
         }
     }
     return reference;
 }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag != null)
            {
                // Reset any frame urls
                // This is done because the HTML that is often in this document may have
                // incorrect urls for frames.  The frames enumeration is accurate, so if the
                // name from the frames enumeration is the same as this frame, we should fix its
                // url up.
                if (tag.NameEquals(HTMLTokens.Frame))
                {
                    Attr name = tag.GetAttribute(HTMLTokens.Name);
                    if (name != null && this._frames != null)
                    {
                        LightWeightHTMLDocument frameDoc = GetFrameDocumentByName(name.Value);
                        if (frameDoc != null)
                        {
                            Attr src = tag.GetAttribute(HTMLTokens.Src);
                            if (src != null && src.Value != frameDoc.Url)
                                Generator.AddSubstitionUrl(new UrlToReplace(src.Value, frameDoc.Url));
                        }
                    }
                }

                LightWeightTag currentTag = new LightWeightTag(tag);
                // The key we'll use for the table
                string key = tag.Name.ToUpper(CultureInfo.InvariantCulture);
                if (!_tagTable.ContainsKey(key))
                    _tagTable[key] = new LightWeightTag[0];

                LightWeightTag[] currentTags = (LightWeightTag[])_tagTable[key];
                LightWeightTag[] grownTags = new LightWeightTag[currentTags.Length + 1];
                currentTags.CopyTo(grownTags, 0);
                grownTags[currentTags.Length] = currentTag;
                _tagTable[key] = grownTags;

                // Accumulate the title text
                if (tag.NameEquals(HTMLTokens.Title) && !tag.Complete)
                    _nextTextIsTitleText = true;
                else if (tag.NameEquals(HTMLTokens.A) && !tag.Complete && tag.GetAttribute(HTMLTokens.Href) != null)
                {
                    if (_collectingForTag != null)
                    {
                        if (tag.NameEquals(HTMLTokens.A))
                            _collectingForTagDepth++;
                    }
                    else
                        _collectingForTag = currentTag;
                }

            }
            base.OnBeginTag(tag);
        }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (FlagIsSet(Flag.RemovePartialTags) && tag.Unterminated)
            {
                return;
            }

            //remove all illegal attributes from the tag
            foreach (Attr attr in tag.Attributes)
            {
                if (IsIllegalAttribute(attr))
                    attr.Value = string.Empty;
            }

            if (tag.NameEquals("script"))
                Debug.WriteLine("Script tag");
            if (IsRegexMatch(IllegalTagTreeName, tag.Name))
            {
                suspendTagDepth++;
            }
            else if (!IsIllegalTag(tag) && suspendTagDepth == 0)
            {
                PushStartTag(tag.Name);
                base.OnBeginTag(tag);
            }
        }
        private int ParseBeginTag(Match beginMatch, out Element element, out EndTag trailingEnd)
        {
            trailingEnd = null;

            Group  tagNameGroup = beginMatch.Groups["tagname"];
            string tagName      = tagNameGroup.Value;

            int tagPos = tagNameGroup.Index + tagNameGroup.Length;

            ArrayList     attributes   = null;
            LazySubstring extraResidue = null;
            bool          isComplete   = false;

            while (true)
            {
                Match match = endBeginTagMatcher.Match(tagPos);
                if (match != null)
                {
                    tagPos += match.Length;
                    if (match.Groups[1].Success)
                    {
                        isComplete = true;
                        if (supportTrailingEnd)
                        {
                            trailingEnd = new EndTag(data, tagPos, 0, tagName, true);
                        }
                    }
                    break;
                }

                match = attrNameMatcher.Match(tagPos);
                if (match == null)
                {
                    int residueStart = tagPos;
                    int residueEnd;

                    residueEnd = tagPos = data.IndexOfAny(new char[] { '<', '>' }, tagPos);
                    if (tagPos == -1)
                    {
                        residueEnd = tagPos = data.Length;
                    }
                    else if (data[tagPos] == '>')
                    {
                        tagPos++;
                    }
                    else
                    {
                        Debug.Assert(data[tagPos] == '<');
                    }

                    extraResidue = residueStart < residueEnd ? new LazySubstring(data, residueStart, residueEnd - residueStart) : null;
                    break;
                }
                else
                {
                    tagPos += match.Length;
                    LazySubstring attrName  = new LazySubstring(data, match.Groups[1].Index, match.Groups[1].Length);
                    LazySubstring attrValue = null;
                    match = quotedAttrValueMatcher.Match(tagPos);
                    if (match != null)
                    {
                        attrValue = new LazySubstring(data, match.Groups[2].Index, match.Groups[2].Length);
                        tagPos   += match.Length;
                    }
                    else
                    {
                        match = unquotedAttrValueMatcher.Match(tagPos);
                        if (match != null)
                        {
                            attrValue = new LazySubstring(data, match.Groups[1].Index, match.Groups[1].Length);
                            tagPos   += match.Length;
                        }
                    }

                    // no attribute value; that's OK

                    if (attributes == null)
                    {
                        attributes = new ArrayList();
                    }
                    attributes.Add(new Attr(attrName, attrValue));
                }
            }

            int len = tagPos - beginMatch.Index;

            element = new BeginTag(data, beginMatch.Index, len, tagName, attributes == null ? null : (Attr[])attributes.ToArray(typeof(Attr)), isComplete, extraResidue);
            return(len);
        }
 protected abstract string OnMatchingAttr(BeginTag tag, Attr attr);
 protected override void OnBeginTag(BeginTag tag)
 {
     if (IsPreserveWhitespaceTag(tag.Name))
         preserveLinebreaksDepth++;
     base.OnBeginTag(tag);
 }
 public string ReferenceFixer(BeginTag tag, string reference)
 {
     return ImageInsertionManager.ReferenceFixer(tag, reference, _fileService, this);
 }
 protected abstract string OnMatchingAttr(BeginTag tag, Attr attr);
 protected override void OnBeginTag(BeginTag tag)
 {
     if (tag != null && LightWeightHTMLDocument.AllUrlElements.ContainsKey(tag.Name.ToUpper(CultureInfo.InvariantCulture)))
     {
         Attr attr = tag.GetAttribute((string)LightWeightHTMLDocument.AllUrlElements[tag.Name.ToUpper(CultureInfo.InvariantCulture)]);
         if (attr != null && attr.Value != null)
         {
             if (UrlHelper.IsUrl(attr.Value))
             {
                 Uri reference = new Uri(attr.Value);
                 if (_fileReferenceList.IsReferenced(reference))
                 {
                     ISupportingFile supportingFile = _fileReferenceList.GetSupportingFileByUri(reference);
                     if (supportingFile.Embedded)
                         AddFileReference(supportingFile);
                 }
             }
         }
     }
     base.OnBeginTag(tag);
 }
            internal string Transform(BeginTag tag, string reference)
            {
                if (UrlHelper.IsUrl(reference))
                {
                    Uri localReferenceUri = new Uri(reference);

                    /*
                     * If we need to drop a hint to the photo uploader about
                     * whether Lightbox-like preview is enabled, so that we know to link to
                     * the image itself rather than the photo "self" page on photos.live.com;
                     * this is where we would figure that out (by looking at the tag) and
                     * pass that info through to the DoUploadWork call.
                     */
                    bool isLightboxCloneEnabled = false;

                    _referenceFixer._fileUploadWorker.DoUploadWork(reference, _uploader, isLightboxCloneEnabled);

                    ISupportingFile supportingFile = _fileService.GetFileByUri(localReferenceUri);
                    if (supportingFile != null)
                    {
                        Uri uploadUri = supportingFile.GetUploadInfo(_uploader.DestinationContext).UploadUri;
                        if (uploadUri != null)
                            return UrlHelper.SafeToAbsoluteUri(uploadUri);
                    }
                }
                return reference;
            }
 private bool IsIllegalTag(BeginTag tag)
 {
     if (IsRegexMatch(IllegalTagName, tag.Name))
     {
         return true;
     }
     else if (FlagIsSet(Flag.RemoveStyles) && tag.NameEquals("link"))
     {
         //if this link element is a stylesheet, it is illegal
         Attr relAttr = tag.GetAttribute("rel");
         if (relAttr != null && relAttr.Value != null && relAttr.Value.ToUpperInvariant().Trim() == "STYLESHEET")
         {
             return true;
         }
     }
     return false;
 }
        /// <summary>
        /// Is the tag a meaningless tag such as <p></p> or <a href="..."></a> or <a href="...">&nbsp;</a>
        /// </summary>
        /// <param name="htmlParser"></param>
        /// <param name="bt"></param>
        /// <returns></returns>
        private static bool RemoveMeaninglessTags(SimpleHtmlParser htmlParser, BeginTag bt)
        {
            // Look to see if the tag is a <p> without any attributes
            if ((bt.NameEquals("p") && bt.Attributes.Length == 0 && !bt.HasResidue))
            {
                Element e = htmlParser.Peek(0);

                // Look to see if thereis a matching end tag to the element we are looking at
                if (e != null && e is EndTag && ((EndTag)e).NameEquals("p"))
                {
                    // eat up the end tag
                    htmlParser.Next();
                    return true;
                }
            }

            // Look to see if the tag is an <a> without a style/id/name attribute, but has an href... meaning the link is not useful
            if ((bt.NameEquals("a") && bt.GetAttribute("name") == null && bt.GetAttributeValue("style") == null && bt.GetAttributeValue("id") == null && bt.GetAttributeValue("href") != null))
            {
                bool hadWhiteSpaceText = false;
                Element e = htmlParser.Peek(0);

                // Look to see if the a just has whitespace inside of it
                if (e is Text && HtmlUtils.UnEscapeEntities(e.RawText, HtmlUtils.UnEscapeMode.NonMarkupText).Trim().Length == 0)
                {
                    e = htmlParser.Peek(1);
                    hadWhiteSpaceText = true;
                }

                // Look to see if thereis a matching end tag to the element we are looking at
                if (e != null && e is EndTag && ((EndTag)e).NameEquals("a"))
                {
                    // if this was an <a> with whitespace in the middle eat it up
                    if (hadWhiteSpaceText)
                        htmlParser.Next();
                    // eat up the end tag
                    htmlParser.Next();

                    return true;
                }
            }

            return false;
        }
        private string LocalFileReferenceFixer(BeginTag tag, string reference)
        {
            Uri referenceUri = new Uri(reference);

            string localPath = referenceUri.LocalPath;
            if (!File.Exists(localPath) || Directory.Exists(localPath) || referenceUri.IsUnc)
                return reference;

            try
            {
                string referenceBaseDir = Path.GetDirectoryName(referenceUri.LocalPath);
                if (new DirectoryInfo(referenceBaseDir).FullName.Equals(new DirectoryInfo(_supportingFileStorage.StoragePath).FullName))
                {
                    //then this file is already in the supporting file storage, so don't fix it!
                    //This fixes a bug where moving internal HTML causes linked items to get recreated in storage
                    //(which hoses up image meta data since the image URL gets changed)
                    return reference;
                }
                else
                {
                    using (FileStream referenceStream = new FileStream(referenceUri.LocalPath, FileMode.Open, FileAccess.Read))
                    {
                        ISupportingFile supportingFile = _fileService.CreateSupportingFile(Path.GetFileName(referenceUri.LocalPath), referenceStream);
                        return UrlHelper.SafeToAbsoluteUri(supportingFile.FileUri);
                    }
                }
            }
            catch (IOException e)
            {
                Trace.Fail("Error importing local file reference: " + reference, e.ToString());
                return reference;
            }
        }
        private int ParseBeginTag(Match beginMatch, out Element element, out EndTag trailingEnd)
        {
            trailingEnd = null;

            Group tagNameGroup = beginMatch.Groups["tagname"];
            string tagName = tagNameGroup.Value;

            int tagPos = tagNameGroup.Index + tagNameGroup.Length;

            ArrayList attributes = null;
            LazySubstring extraResidue = null;
            bool isComplete = false;

            while (true)
            {
                Match match = endBeginTagMatcher.Match(tagPos);
                if (match != null)
                {
                    tagPos += match.Length;
                    if (match.Groups[1].Success)
                    {
                        isComplete = true;
                        if (supportTrailingEnd)
                            trailingEnd = new EndTag(data, tagPos, 0, tagName, true);
                    }
                    break;
                }

                match = attrNameMatcher.Match(tagPos);
                if (match == null)
                {
                    int residueStart = tagPos;
                    int residueEnd;

                    residueEnd = tagPos = data.IndexOfAny(new char[] { '<', '>' }, tagPos);
                    if (tagPos == -1)
                    {
                        residueEnd = tagPos = data.Length;
                    }
                    else if (data[tagPos] == '>')
                    {
                        tagPos++;
                    }
                    else
                    {
                        Debug.Assert(data[tagPos] == '<');
                    }

                    extraResidue = residueStart < residueEnd ? new LazySubstring(data, residueStart, residueEnd - residueStart) : null;
                    break;
                }
                else
                {
                    tagPos += match.Length;
                    LazySubstring attrName = new LazySubstring(data, match.Groups[1].Index, match.Groups[1].Length);
                    LazySubstring attrValue = null;
                    match = quotedAttrValueMatcher.Match(tagPos);
                    if (match != null)
                    {
                        attrValue = new LazySubstring(data, match.Groups[2].Index, match.Groups[2].Length);
                        tagPos += match.Length;
                    }
                    else
                    {
                        match = unquotedAttrValueMatcher.Match(tagPos);
                        if (match != null)
                        {
                            attrValue = new LazySubstring(data, match.Groups[1].Index, match.Groups[1].Length);
                            tagPos += match.Length;
                        }
                    }

                    // no attribute value; that's OK

                    if (attributes == null)
                        attributes = new ArrayList();
                    attributes.Add(new Attr(attrName, attrValue));
                }
            }

            int len = tagPos - beginMatch.Index;
            element = new BeginTag(data, beginMatch.Index, len, tagName, attributes == null ? null : (Attr[])attributes.ToArray(typeof(Attr)), isComplete, extraResidue);
            return len;
        }
 private void ModifyMetaDataAttribute(BeginTag tag, string attributeName, string valueToChangeTo)
 {
     Attr valueAttr = tag.GetAttribute(attributeName);
     if (valueAttr != null && valueToChangeTo != null)
         valueAttr.Value = valueToChangeTo;
 }
            public string FixReferences(BeginTag tag, string reference)
            {
                // protect against unexpected/empty input
                if (!UrlHelper.IsUrl(reference))
                    return reference;

                Uri referenceUri = new Uri(reference);
                if (referenceUri.IsFile)
                    return _fixer(tag, reference);
                else
                    return reference;
            }
            public string ReferenceFixerForPublish(BeginTag tag, string reference)
            {
                if (_imageConverter != null)
                    return _imageConverter.GetUriForImage(reference);

                return reference;
            }
Example #31
0
 public string FixReference(BeginTag tag, string reference)
 {
     if (UrlHelper.IsUrl(reference))
     {
         Uri referenceUri = new Uri(reference);
         if (referencesTable.ContainsKey(referenceUri))
             return (string)referencesTable[referenceUri];
     }
     return reference;
 }
 private bool TagPermittedAboveBody(BeginTag tag)
 {
     foreach (string permittedAboveBody in _permittedBeforeBody)
         if (tag.NameEquals(permittedAboveBody))
             return true;
     return false;
 }
        protected override void OnBeginTag(BeginTag tag)
        {
            if (tag == null)
                return;

            if (_firstTag)
            {
                if (!tag.NameEquals(HTMLTokens.Html))
                    EmitTag(HTMLTokens.Html);
                _firstTag = false;
            }

            if (!_seenHead && !TagPermittedAboveBody(tag))
            {
                Emit("<head>");
                EmitAdditionalMetaData();
                Emit("</head>");
                _seenHead = true;
            }

            if (tag.NameEquals(HTMLTokens.Script))
            {
                if (!tag.Complete)
                    _scriptDepth++;
                return;
            }

            if (tag.NameEquals(HTMLTokens.Head))
                _seenHead = true;
            else if (!_seenBody && !tag.NameEquals(HTMLTokens.Body))
            {
                if (!TagPermittedAboveBody(tag))
                {
                    EmitTag(HTMLTokens.Body);
                    _seenBody = true;
                }
            }
            else if (!_seenBody && tag.NameEquals(HTMLTokens.Body))
                _seenBody = true;

            if (tag.NameEquals(HTMLTokens.Base))
            {
                if (_metaData == null || _metaData.Base == null)
                    return;
                else
                {
                    Attr href = tag.GetAttribute(HTMLTokens.Href);
                    if (href != null)
                        href.Value = _metaData.Base;
                }
                _emittedMetaData.Add(HTMLTokens.Base);
            }

            if (tag.NameEquals(HTMLTokens.Meta))
                ModifyMetaDataAsNecessary(tag);

            foreach (Attr attr in tag.Attributes)
                if (attr != null)
                {
                    if (IsScriptAttribute(attr))
                        tag.RemoveAttribute(attr.Name);
                    else
                        attr.Value = ReplaceValue(attr.Value);
                }

            Emit(tag.ToString());
            base.OnBeginTag(tag);
        }
        /// <summary>
        /// Retrieves the next element from the stream, or null
        /// if the end of the stream has been reached.
        /// </summary>
        private Element Next(bool allowPeekElement)
        {
            if (allowPeekElement && peekElements.Count > 0)
            {
                Element peekElement = peekElements[0];
                peekElements.RemoveAt(0);
                return(peekElement);
            }

            if (elementStack.Count != 0)
            {
                return(elementStack.Pop());
            }

            int dataLen = data.Length;

            if (dataLen == pos)
            {
                // If we're at EOF, return

                return(null);
            }

            // None of the special cases are true.  Start consuming characters

            int tokenStart = pos;

            while (true)
            {
                // Consume everything until a tag-looking thing
                while (pos < dataLen && data[pos] != '<')
                {
                    pos++;
                }

                if (pos >= dataLen)
                {
                    // EOF has been reached.
                    if (tokenStart != pos)
                    {
                        return(new Text(data, tokenStart, pos - tokenStart));
                    }
                    else
                    {
                        return(null);
                    }
                }

                // We started parsing right on a tag-looking thing.  Try
                // parsing it as such.  If it doesn't turn out to be a tag,
                // we'll return it as text

                int oldPos = pos;

                Element element;
                EndTag  trailingEnd;
                int     len = ParseMarkup(out element, out trailingEnd);
                if (len >= 0)
                {
                    pos += len;

                    if (trailingEnd != null)
                    {
                        // empty-element tag detected, add implicit end tag
                        elementStack.Push(trailingEnd);
                    }
                    else if (element is BeginTag)
                    {
                        // look for <script> or <style> body

                        Regex consumeTextUntil = null;

                        BeginTag tag = (BeginTag)element;
                        if (tag.NameEquals("script"))
                        {
                            consumeTextUntil = endScript;
                        }
                        else if (tag.NameEquals("style"))
                        {
                            consumeTextUntil = endStyle;
                        }

                        if (consumeTextUntil != null)
                        {
                            int structuredTextLen = ConsumeStructuredText(data, pos, consumeTextUntil);
                            pos += structuredTextLen;
                        }
                    }

                    elementStack.Push(element);
                    if (oldPos != tokenStart)
                    {
                        elementStack.Push(new Text(data, tokenStart, oldPos - tokenStart));
                    }

                    return(elementStack.Pop());
                }
                else
                {
                    // '<' didn't begin a tag after all;
                    // consume it and continue
                    pos++;
                    continue;
                }
            }
        }
 protected override void OnBeginTag(BeginTag tag)
 {
 }
        private void ModifyMetaDataAsNecessary(BeginTag tag)
        {
            if (_metaData == null)
                return;

            Attr nameAttr = tag.GetAttribute(HTMLTokens.Name);
            if (nameAttr == null)
            {
                nameAttr = tag.GetAttribute(HTMLTokens.HttpEquiv);
            }

            if (nameAttr != null)
            {
                switch (nameAttr.Value.ToUpper(CultureInfo.InvariantCulture))
                {
                    case (HTMLTokens.Author):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Author);
                        break;
                    case (HTMLTokens.ContentType):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, string.Format(CultureInfo.InvariantCulture, "text/html; {0}", _metaData.Charset));
                        break;
                    case (HTMLTokens.Charset):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Charset);
                        break;
                    case (HTMLTokens.Description):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Description);
                        break;
                    case (HTMLTokens.Generator):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Generator);
                        break;
                    case (HTMLTokens.CopyRight):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.CopyRight);
                        break;
                    case (HTMLTokens.Keywords):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.KeywordString);
                        break;
                    case (HTMLTokens.Pragma):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Pragma);
                        break;
                    case (HTMLTokens.Robots):
                        ModifyMetaDataAttribute(tag, HTMLTokens.Content, _metaData.Robots);
                        break;
                }
                _emittedMetaData.Add(nameAttr.Value.ToUpper(CultureInfo.InvariantCulture));
            }
        }