@comment_dir = "#{@plugindir}/comment" unless @comment_dir
@comment_flavour = "html" unless @comment_flavour
@recent_comment_count = 5 unless @recent_comment_count
begin
  @comment_key = File.open(@comment_key){|f| f.gets.chomp}
rescue
  @comment_key = 'LILY-COMMENT'
end
@comment_report_spam = (@comment_report_spam.nil? || @comment_report_spam == "on" || @comment_report_spam == true) ? true : false

require 'digest/md5'

def comment
  path = ""
  if @storys.size == 1
    reg = Regexp.new("#{@datadir}/((.*/)?[^.]*)\.(.*)")
    @storys[0].sub(reg){ path = $1 }

    addr = @cgi.params['addr'][0].to_s
    validaddr = false
    begin
      Resolv::DNS.new.getresource(addr.split(/@/, 2)[1], Resolv::DNS::Resource::IN::MX)
      validaddr = true
    rescue Resolv::ResolvError, ArgumentError
    end
    validcomment = @cgi.params['mode'][0] == 'comment'
    validname =  @cgi.params['name'][0] != ''
    validcontent = @cgi.params['content'][0] != ''
    validtime = @cgi.params['time'][0].to_i >= Time.now.to_i - 60 * 60 && @cgi.params['time'][0].to_i < Time.now.to_i
    validkey = @cgi.params['key'][0] == Digest::MD5.hexdigest(@cgi.params['time'][0] + @comment_key)

    if validcomment && validname && validaddr && validcontent && validtime && validkey
      content = @cgi.params['content'][0].gsub(/\r/, '')
      text =  "#{@cgi.params['name'][0]}\n"
      text << "#{@cgi.params['addr'][0]}\n"
      text << "#{@cgi.remote_addr}\n"
      text << "#{content}\n"
      spam = false
      if respond_to?(:check_spam) && check_spam(content, @cgi.params['addr'][0])
        spam = true
      else
        File::open("#{@comment_dir}/#{CGI.escape(path)}","a") do |f|
          f.puts CGI.escapeHTML(text)
          f.puts '--------'
        end

        list = ""
        lc = 1
        begin
          File::open("#{@comment_dir}/recent.list","r") do |f|
            f.each_line do |line|
              line.chomp!
              if !line.nil? and line != ''
                list += "#{line}\n"
                lc += 1
              end
            end
          end
        rescue
        end
        File::open("#{@comment_dir}/recent.list","w") do |f|
          f.print "#{path}\t#{CGI.escapeHTML(@cgi.params['name'][0])}\t"
          f.print "#{Time.now.strftime("%Y-%m-%d")}\n"
          f.print list
        end
      end

      if respond_to?(:send_mail) && (@comment_report_spam || !spam)
        subject = "comment to #{@url}/#{path}.#{@comment_flavour}"
        subject = "(spam) " + subject if spam
        send_mail(@cgi.params['addr'][0], @mailto.untaint,
                  subject, [subject, text].join("\n"))
      end
    end

    redirect(@cgi, "#{@url}/#{path}.#{@comment_flavour}")
    @echo_off = true
  end
end

def comment_input
  time = Time.now.to_i.to_s
  key = Digest::MD5.hexdigest(time + @comment_key)
  src =<<"EOS"
<form name="comment" method="POST" action="#{@url}/#{@path}#{@fn}.#{@comment_flavour}">
  <dl>
    <dt>name:</dt><dd><input type="text" id="name" name="name" value="" /></dd>
    <dt>E-Mail (not open to the public):</dt><dd><input type="text" id="addr" name="addr" value="" /></dd>
    <dt>text:</dt>
    <dd>
      <textarea id="content" name="content"></textarea>
    </dd>
  </dl>
  <p>
    <input type="hidden" name="mode" value="comment" />
    <input type="hidden" name="time" value="#{time}" />
    <input type="hidden" name="key" value="#{key}" />
    <input type="submit" value="send" /> 
    <input type="reset" value="clear" />
  </p>
</form>
EOS
  return src
end

def comment_count
  cnt = 0

  begin
    File::open("#{@comment_dir}/#{CGI.escape(@path + @fn)}","r"){|f|
      while line = f.gets
        line.chomp!
        if line == '--------' then cnt += 1; end
      end
    }
  rescue
  end

  return cnt
end

def comment_disp
  src = ""
  
  begin
    File::open("#{@comment_dir}/#{CGI.escape(@path + @fn)}","r"){|f|
      while name = f.gets
        name.chomp!
        link = f.gets.chomp!
        host = f.gets.chomp!
        content = ""
        
        while line = f.gets
          line.chomp!
          if line == '--------' then break; end
          content += line + "<br />"
        end
        
        src +=<<EOS
<div class="comment">
EOS
        src += %(<h5>#{convert(name)}</h5>)
        src +=<<EOS
#{convert(content).gsub(/(http:[^<>\s]*)/){|m| %(<a href="#{$1}">#{$1}</a>)}}
</div>
EOS
      end
    }
  rescue
  end

  return src
end

def disp_commentshort
  src =  %(<div class="comment_box">\n)
  src += %(<p><a href="#{@url}/#{@path}#{@fn}.html#comment">comment</a></p>)
  
  begin
    File::open("#{@comment_dir}/#{CGI.escape(@path + @fn)}","r"){|f|
      while name = f.gets
        name.chomp!
        link = f.gets.chomp!
        host = f.gets.chomp!
        content = ""
        
        while line = f.gets
          line.chomp!
          if line == '--------' then break; end
          content += line + "\n"
        end
        
        content = content.split(/\n/)[0]
        
        src += %(<em>#{convert(name)}</em> [#{content}]<br/>\n)
      end
    }
  rescue
  end

  return src + "</div>"
end

def recent_comment
  src = "<ul>\n"
  begin
    sw = {}
    File::open("#{@comment_dir}/recent.list"){|f|
      count = 0
      f.each_line do |ln|
        ln.chomp!
        if !ln.nil? and ln != ''
          m = ln.split(/\t/)
          src += %(<li><a href="#{@url}/#{m[0]}.html#comment">#{m[1]} #{m[2]}</a></li>\n)
          count += 1
          break if count >= @recent_comment_count
        end
      end
    }
    
    src += "</ul>\n"
  rescue
  end
end

def make_link(url)
  if url =~ /(.*)\@(.*)/
    return "mailto:#{url}"
  elsif url =~ /http:.*/
    return url
  end
  
  return ""
end
