Search in sources :

Example 1 with TextNode

use of org.htmlparser.nodes.TextNode in project jforum2 by rafaelsteil.

the class SafeHtml method makeSafe.

/**
	 * Given an input, makes it safe for HTML displaying. 
	 * Removes any not allowed HTML tag or attribute, as well
	 * unwanted Javascript statements inside the tags. 
	 * @param contents the input to analyze
	 * @return the modified and safe string
	 */
public String makeSafe(String contents) {
    if (contents == null || contents.length() == 0) {
        return contents;
    }
    StringBuffer sb = new StringBuffer(contents.length());
    try {
        Lexer lexer = new Lexer(contents);
        Node node;
        while ((node = lexer.nextNode()) != null) {
            boolean isTextNode = node instanceof TextNode;
            if (isTextNode) {
                // Text nodes are raw data, so we just
                // strip off all possible html content
                String text = node.toHtml();
                if (text.indexOf('>') > -1 || text.indexOf('<') > -1) {
                    StringBuffer tmp = new StringBuffer(text);
                    ViewCommon.replaceAll(tmp, "<", "&lt;");
                    ViewCommon.replaceAll(tmp, ">", "&gt;");
                    ViewCommon.replaceAll(tmp, "\"", "&quot;");
                    node.setText(tmp.toString());
                }
            }
            if (isTextNode || (node instanceof Tag && this.isTagWelcome(node))) {
                sb.append(node.toHtml());
            } else {
                StringBuffer tmp = new StringBuffer(node.toHtml());
                ViewCommon.replaceAll(tmp, "<", "&lt;");
                ViewCommon.replaceAll(tmp, ">", "&gt;");
                sb.append(tmp.toString());
            }
        }
    } catch (Exception e) {
        throw new ForumException("Error while parsing HTML: " + e, e);
    }
    return sb.toString();
}
Also used : Lexer(org.htmlparser.lexer.Lexer) ForumException(net.jforum.exceptions.ForumException) Node(org.htmlparser.Node) TextNode(org.htmlparser.nodes.TextNode) TextNode(org.htmlparser.nodes.TextNode) Tag(org.htmlparser.Tag) ForumException(net.jforum.exceptions.ForumException)

Aggregations

ForumException (net.jforum.exceptions.ForumException)1 Node (org.htmlparser.Node)1 Tag (org.htmlparser.Tag)1 Lexer (org.htmlparser.lexer.Lexer)1 TextNode (org.htmlparser.nodes.TextNode)1