require 'cgi'
require 'uri'
class DText
def self.u(string)
CGI.escape(string)
end
def self.h(string)
CGI.escapeHTML(string)
end
def self.parse_inline(str, options = {})
str.gsub!(/&/, "&")
str.gsub!(/, "<")
str.gsub!(/>/, ">")
str.gsub!(/\n/m, "
")
str.gsub!(/\[b\](.+?)\[\/b\]/i, '\1')
str.gsub!(/\[i\](.+?)\[\/i\]/i, '\1')
str.gsub!(/(?' + text + '' + stop
end
str.gsub!(/\[url\](http.+?)\[\/url\]/i) do
%{#{$1}}
end
str.gsub!(/\[url=(http.+?)\](.+?)\[\/url\]/m) do
%{#{$2}}
end
str = parse_aliased_wiki_links(str)
str = parse_wiki_links(str)
str = parse_post_links(str)
str = parse_id_links(str)
str
end
def self.parse_aliased_wiki_links(str)
str.gsub(/\[\[(.+?)\|(.+?)\]\]/m) do
text = CGI.unescapeHTML($1)
title = CGI.unescapeHTML($2)
wiki_page = WikiPage.find_title_and_id(title)
if wiki_page
%{#{h(text)}}
else
%{#{h(text)}}
end
end
end
def self.parse_wiki_links(str)
str.gsub(/\[\[(.+?)\]\]/) do
title = CGI.unescapeHTML($1)
wiki_page = WikiPage.find_title_and_id(title)
if wiki_page
%{#{h(title)}}
else
%{#{h(title)}}
end
end
end
def self.parse_post_links(str)
str.gsub(/\{\{(.+?)\}\}/) do
tags = CGI.unescapeHTML($1)
%{#{h(tags)}}
end
end
def self.parse_id_links(str)
str = str.gsub(/\bpost #(\d+)/i, %{post #\\1})
str = str.gsub(/\bforum #(\d+)/i, %{forum #\\1})
str = str.gsub(/\bcomment #(\d+)/i, %{comment #\\1})
str = str.gsub(/\bpool #(\d+)/i, %{pool #\\1})
end
def self.parse_list(str, options = {})
html = ""
layout = []
nest = 0
str.split(/\n/).each do |line|
if line =~ /^\s*(\*+) (.+)/
nest = $1.size
content = parse_inline($2)
else
content = parse_inline(line)
end
if nest > layout.size
html += "
" end when "[/quote]" if options[:inline] "" elsif stack.last == "blockquote" stack.pop '' else "" end when /\[spoilers?\](?!\])/ stack << "div" '
' + parse_inline(block) + "
" end end stack.reverse.each do |tag| if tag == "blockquote" html << "" elsif tag == "div" html << "" end end sanitize(html.join("")).html_safe end def self.sanitize(text) Sanitize.clean( text, :elements => %w(h1 h2 h3 h4 h5 h6 a span div blockquote br p ul li ol em strong), :attributes => { "a" => %w(href title), "span" => %w(class), "div" => %w(class) }, :protocols => { "a" => { "href" => ["http", "https", :relative] } } ) end end