| 1 | /*global Autolinker */ |
| 2 | /** |
| 3 | * @class Autolinker.htmlParser.HtmlParser |
| 4 | * @extends Object |
| 5 | * |
| 6 | * An HTML parser implementation which simply walks an HTML string and returns an array of |
| 7 | * {@link Autolinker.htmlParser.HtmlNode HtmlNodes} that represent the basic HTML structure of the input string. |
| 8 | * |
| 9 | * Autolinker uses this to only link URLs/emails/mentions within text nodes, effectively ignoring / "walking |
| 10 | * around" HTML tags. |
| 11 | */ |
| 12 | Autolinker.htmlParser.HtmlParser = Autolinker.Util.extend( Object, { |
| 13 | |
| 14 | /** |
| 15 | * @private |
| 16 | * @property {RegExp} htmlRegex |
| 17 | * |
| 18 | * The regular expression used to pull out HTML tags from a string. Handles namespaced HTML tags and |
| 19 | * attribute names, as specified by http://www.w3.org/TR/html-markup/syntax.html. |
| 20 | * |
| 21 | * Capturing groups: |
| 22 | * |
| 23 | * 1. The "!DOCTYPE" tag name, if a tag is a <!DOCTYPE> tag. |
| 24 | * 2. If it is an end tag, this group will have the '/'. |
| 25 | * 3. If it is a comment tag, this group will hold the comment text (i.e. |
| 26 | * the text inside the `<!--` and `-->`. |
| 27 | * 4. The tag name for a tag without attributes (other than the <!DOCTYPE> tag) |
| 28 | * 5. The tag name for a tag with attributes (other than the <!DOCTYPE> tag) |
| 29 | */ |
| 30 | htmlRegex : (function() { |
| 31 | var commentTagRegex = /!--([\s\S]+?)--/, |
| 32 | tagNameRegex = /[0-9a-zA-Z][0-9a-zA-Z:]*/, |
| 33 | attrNameRegex = /[^\s"'>\/=\x00-\x1F\x7F]+/, // the unicode range accounts for excluding control chars, and the delete char |
| 34 | attrValueRegex = /(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/, // double quoted, single quoted, or unquoted attribute values |
| 35 | optionalAttrValueRegex = '(?:\\s*?=\\s*?' + attrValueRegex.source + ')?'; // optional '=[value]' |
| 36 | |
| 37 | var getNameEqualsValueRegex = function(group) { |
| 38 | return '(?=(' + attrNameRegex.source + '))\\' + group + optionalAttrValueRegex; |
| 39 | }; |
| 40 | |
| 41 | return new RegExp( [ |
| 42 | // for <!DOCTYPE> tag. Ex: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">) |
| 43 | '(?:', |
| 44 | '<(!DOCTYPE)', // *** Capturing Group 1 - If it's a doctype tag |
| 45 | |
| 46 | // Zero or more attributes following the tag name |
| 47 | '(?:', |
| 48 | '\\s+', // one or more whitespace chars before an attribute |
| 49 | |
| 50 | // Either: |
| 51 | // A. attr="value", or |
| 52 | // B. "value" alone (To cover example doctype tag: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">) |
| 53 | // *** Capturing Group 2 - Pseudo-atomic group for attrNameRegex |
| 54 | '(?:', getNameEqualsValueRegex(2), '|', attrValueRegex.source + ')', |
| 55 | ')*', |
| 56 | '>', |
| 57 | ')', |
| 58 | |
| 59 | '|', |
| 60 | |
| 61 | // All other HTML tags (i.e. tags that are not <!DOCTYPE>) |
| 62 | '(?:', |
| 63 | '<(/)?', // Beginning of a tag or comment. Either '<' for a start tag, or '</' for an end tag. |
| 64 | // *** Capturing Group 3: The slash or an empty string. Slash ('/') for end tag, empty string for start or self-closing tag. |
| 65 | |
| 66 | '(?:', |
| 67 | commentTagRegex.source, // *** Capturing Group 4 - A Comment Tag's Text |
| 68 | |
| 69 | '|', |
| 70 | |
| 71 | // Handle tag without attributes. |
| 72 | // Doing this separately from a tag that has attributes |
| 73 | // to fix a regex time complexity issue seen with the |
| 74 | // example in https://github.com/gregjacobs/Autolinker.js/issues/172 |
| 75 | '(?:', |
| 76 | // *** Capturing Group 5 - The tag name for a tag without attributes |
| 77 | '(' + tagNameRegex.source + ')', |
| 78 | |
| 79 | '\\s*/?', // any trailing spaces and optional '/' before the closing '>' |
| 80 | ')', |
| 81 | |
| 82 | '|', |
| 83 | |
| 84 | // Handle tag with attributes |
| 85 | // Doing this separately from a tag with no attributes |
| 86 | // to fix a regex time complexity issue seen with the |
| 87 | // example in https://github.com/gregjacobs/Autolinker.js/issues/172 |
| 88 | '(?:', |
| 89 | // *** Capturing Group 6 - The tag name for a tag with attributes |
| 90 | '(' + tagNameRegex.source + ')', |
| 91 | |
| 92 | '\\s+', // must have at least one space after the tag name to prevent ReDoS issue (issue #172) |
| 93 | |
| 94 | // Zero or more attributes following the tag name |
| 95 | '(?:', |
| 96 | '(?:\\s+|\\b)', // any number of whitespace chars before an attribute. NOTE: Using \s* here throws Chrome into an infinite loop for some reason, so using \s+|\b instead |
| 97 | // *** Capturing Group 7 - Pseudo-atomic group for attrNameRegex |
| 98 | getNameEqualsValueRegex(7), // attr="value" (with optional ="value" part) |
| 99 | ')*', |
| 100 | |
| 101 | '\\s*/?', // any trailing spaces and optional '/' before the closing '>' |
| 102 | ')', |
| 103 | ')', |
| 104 | '>', |
| 105 | ')' |
| 106 | ].join( "" ), 'gi' ); |
| 107 | } )(), |
| 108 | |
| 109 | /** |
| 110 | * @private |
| 111 | * @property {RegExp} htmlCharacterEntitiesRegex |
| 112 | * |
| 113 | * The regular expression that matches common HTML character entities. |
| 114 | * |
| 115 | * Ignoring & as it could be part of a query string -- handling it separately. |
| 116 | */ |
| 117 | htmlCharacterEntitiesRegex: /( | |<|<|>|>|"|"|')/gi, |
| 118 | |
| 119 | |
| 120 | /** |
| 121 | * Parses an HTML string and returns a simple array of {@link Autolinker.htmlParser.HtmlNode HtmlNodes} |
| 122 | * to represent the HTML structure of the input string. |
| 123 | * |
| 124 | * @param {String} html The HTML to parse. |
| 125 | * @return {Autolinker.htmlParser.HtmlNode[]} |
| 126 | */ |
| 127 | parse : function( html ) { |
| 128 | var htmlRegex = this.htmlRegex, |
| 129 | currentResult, |
| 130 | lastIndex = 0, |
| 131 | textAndEntityNodes, |
| 132 | nodes = []; // will be the result of the method |
| 133 | |
| 134 | while( ( currentResult = htmlRegex.exec( html ) ) !== null ) { |
| 135 | var tagText = currentResult[ 0 ], |
| 136 | commentText = currentResult[ 4 ], // if we've matched a comment |
| 137 | tagName = currentResult[ 1 ] || currentResult[ 5 ] || currentResult[ 6 ], // The <!DOCTYPE> tag (ex: "!DOCTYPE"), or another tag (ex: "a" or "img") |
| 138 | isClosingTag = !!currentResult[ 3 ], |
| 139 | offset = currentResult.index, |
| 140 | inBetweenTagsText = html.substring( lastIndex, offset ); |
| 141 | |
| 142 | // Push TextNodes and EntityNodes for any text found between tags |
| 143 | if( inBetweenTagsText ) { |
| 144 | textAndEntityNodes = this.parseTextAndEntityNodes( lastIndex, inBetweenTagsText ); |
| 145 | nodes.push.apply( nodes, textAndEntityNodes ); |
| 146 | } |
| 147 | |
| 148 | // Push the CommentNode or ElementNode |
| 149 | if( commentText ) { |
| 150 | nodes.push( this.createCommentNode( offset, tagText, commentText ) ); |
| 151 | } else { |
| 152 | nodes.push( this.createElementNode( offset, tagText, tagName, isClosingTag ) ); |
| 153 | } |
| 154 | |
| 155 | lastIndex = offset + tagText.length; |
| 156 | } |
| 157 | |
| 158 | // Process any remaining text after the last HTML element. Will process all of the text if there were no HTML elements. |
| 159 | if( lastIndex < html.length ) { |
| 160 | var text = html.substring( lastIndex ); |
| 161 | |
| 162 | // Push TextNodes and EntityNodes for any text found between tags |
| 163 | if( text ) { |
| 164 | textAndEntityNodes = this.parseTextAndEntityNodes( lastIndex, text ); |
| 165 | |
| 166 | // Note: the following 3 lines were previously: |
| 167 | // nodes.push.apply( nodes, textAndEntityNodes ); |
| 168 | // but this was causing a "Maximum Call Stack Size Exceeded" |
| 169 | // error on inputs with a large number of html entities. |
| 170 | textAndEntityNodes.forEach( function( node ) { |
| 171 | nodes.push( node ); |
| 172 | } ); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | return nodes; |
| 177 | }, |
| 178 | |
| 179 | |
| 180 | /** |
| 181 | * Parses text and HTML entity nodes from a given string. The input string |
| 182 | * should not have any HTML tags (elements) within it. |
| 183 | * |
| 184 | * @private |
| 185 | * @param {Number} offset The offset of the text node match within the |
| 186 | * original HTML string. |
| 187 | * @param {String} text The string of text to parse. This is from an HTML |
| 188 | * text node. |
| 189 | * @return {Autolinker.htmlParser.HtmlNode[]} An array of HtmlNodes to |
| 190 | * represent the {@link Autolinker.htmlParser.TextNode TextNodes} and |
| 191 | * {@link Autolinker.htmlParser.EntityNode EntityNodes} found. |
| 192 | */ |
| 193 | parseTextAndEntityNodes : function( offset, text ) { |
| 194 | var nodes = [], |
| 195 | textAndEntityTokens = Autolinker.Util.splitAndCapture( text, this.htmlCharacterEntitiesRegex ); // split at HTML entities, but include the HTML entities in the results array |
| 196 | |
| 197 | // Every even numbered token is a TextNode, and every odd numbered token is an EntityNode |
| 198 | // For example: an input `text` of "Test "this" today" would turn into the |
| 199 | // `textAndEntityTokens`: [ 'Test ', '"', 'this', '"', ' today' ] |
| 200 | for( var i = 0, len = textAndEntityTokens.length; i < len; i += 2 ) { |
| 201 | var textToken = textAndEntityTokens[ i ], |
| 202 | entityToken = textAndEntityTokens[ i + 1 ]; |
| 203 | |
| 204 | if( textToken ) { |
| 205 | nodes.push( this.createTextNode( offset, textToken ) ); |
| 206 | offset += textToken.length; |
| 207 | } |
| 208 | if( entityToken ) { |
| 209 | nodes.push( this.createEntityNode( offset, entityToken ) ); |
| 210 | offset += entityToken.length; |
| 211 | } |
| 212 | } |
| 213 | return nodes; |
| 214 | }, |
| 215 | |
| 216 | |
| 217 | /** |
| 218 | * Factory method to create an {@link Autolinker.htmlParser.CommentNode CommentNode}. |
| 219 | * |
| 220 | * @private |
| 221 | * @param {Number} offset The offset of the match within the original HTML |
| 222 | * string. |
| 223 | * @param {String} tagText The full text of the tag (comment) that was |
| 224 | * matched, including its <!-- and -->. |
| 225 | * @param {String} commentText The full text of the comment that was matched. |
| 226 | */ |
| 227 | createCommentNode : function( offset, tagText, commentText ) { |
| 228 | return new Autolinker.htmlParser.CommentNode( { |
| 229 | offset : offset, |
| 230 | text : tagText, |
| 231 | comment: Autolinker.Util.trim( commentText ) |
| 232 | } ); |
| 233 | }, |
| 234 | |
| 235 | |
| 236 | /** |
| 237 | * Factory method to create an {@link Autolinker.htmlParser.ElementNode ElementNode}. |
| 238 | * |
| 239 | * @private |
| 240 | * @param {Number} offset The offset of the match within the original HTML |
| 241 | * string. |
| 242 | * @param {String} tagText The full text of the tag (element) that was |
| 243 | * matched, including its attributes. |
| 244 | * @param {String} tagName The name of the tag. Ex: An <img> tag would |
| 245 | * be passed to this method as "img". |
| 246 | * @param {Boolean} isClosingTag `true` if it's a closing tag, false |
| 247 | * otherwise. |
| 248 | * @return {Autolinker.htmlParser.ElementNode} |
| 249 | */ |
| 250 | createElementNode : function( offset, tagText, tagName, isClosingTag ) { |
| 251 | return new Autolinker.htmlParser.ElementNode( { |
| 252 | offset : offset, |
| 253 | text : tagText, |
| 254 | tagName : tagName.toLowerCase(), |
| 255 | closing : isClosingTag |
| 256 | } ); |
| 257 | }, |
| 258 | |
| 259 | |
| 260 | /** |
| 261 | * Factory method to create a {@link Autolinker.htmlParser.EntityNode EntityNode}. |
| 262 | * |
| 263 | * @private |
| 264 | * @param {Number} offset The offset of the match within the original HTML |
| 265 | * string. |
| 266 | * @param {String} text The text that was matched for the HTML entity (such |
| 267 | * as '&nbsp;'). |
| 268 | * @return {Autolinker.htmlParser.EntityNode} |
| 269 | */ |
| 270 | createEntityNode : function( offset, text ) { |
| 271 | return new Autolinker.htmlParser.EntityNode( { offset: offset, text: text } ); |
| 272 | }, |
| 273 | |
| 274 | |
| 275 | /** |
| 276 | * Factory method to create a {@link Autolinker.htmlParser.TextNode TextNode}. |
| 277 | * |
| 278 | * @private |
| 279 | * @param {Number} offset The offset of the match within the original HTML |
| 280 | * string. |
| 281 | * @param {String} text The text that was matched. |
| 282 | * @return {Autolinker.htmlParser.TextNode} |
| 283 | */ |
| 284 | createTextNode : function( offset, text ) { |
| 285 | return new Autolinker.htmlParser.TextNode( { offset: offset, text: text } ); |
| 286 | } |
| 287 | |
| 288 | } ); |