Class HtmlFilter
In: lib/more/facets/htmlfilter.rb
Parent: Object

HtmlFilter

HTML Filter library can be used to sanitize and sterilize HTML. A good idea if you let users submit HTML in comments, for instance.

lib_filter.php, v1.15 by Cal Henderson <cal@iamcal.com>

This code is licensed under a Creative Commons Attribution-ShareAlike 2.5 License creativecommons.org/licenses/by-sa/2.5/

Thanks to Jang Kim for adding support for single quoted attributes.

Reference

Methods

filter   new  

Included Modules

Multiton

Constants

DEFAULT = { 'allowed' => { 'a' => ['href', 'target'], 'b' => [], 'i' => [], 'img' => ['src', 'width', 'height', 'alt']   default settings

Attributes

allow_numbered_entities  [RW]  entity control option (true, false)
allowed  [RW]  tags and attributes that are allowed

Eg.

  {
    'a' => ['href', 'target'],
    'b' => [],
    'img' => ['src', 'width', 'height', 'alt']
  }
allowed_entities  [RW]  entity control option (amp, gt, lt, quot, etc.)
allowed_protocols  [RW]  protocols which are allowed (http, ftp, mailto)
always_close  [RW]  tags which must always have seperate opening and closing tags (e.g. "")
always_make_tags  [RW]  should we try and make a b tag out of "b>" (true, false)
no_close  [RW]  tags which should always be self-closing (e.g. "<img />")
protocol_attributes  [RW]  attributes which should be checked for valid protocols (src,href)
remove_blanks  [RW]  tags which should be removed if they contain no content (e.g. "" or "<b />")
strip_comments  [RW]  should we remove comments? (true, false)
tag_counts  [R]  internal tag counter

Public Class methods

New html filter.

[Source]

# File lib/more/facets/htmlfilter.rb, line 122
  def initialize( options=nil )
    if options
      h = DEFAULT.dup
      options.each do |k,v|
        h[k.to_s] = v
      end
      options = h
    else
      options = DEFAULT.dup
    end

    options.each{ |k,v| send("#{k}=",v) }
  end

Public Instance methods

Filter html string.

[Source]

# File lib/more/facets/htmlfilter.rb, line 138
  def filter(data)
    @tag_counts = {}

    data = escape_comments(data)
    data = balance_html(data)
    data = check_tags(data)
    data = process_remove_blanks(data)
    data = validate_entities(data)

    return data
  end

[Validate]