# comment_captcha.rb $ Revision: 4 $
# Copyright (C) 2006 Michitaka Ohno <elpeo@mars.dti.ne.jp>
# You can redistribute it and/or modify it under GPL2.
#
# @options['captcha.secret'] = '秘密の言葉'

require 'digest/md5'
require 'open-uri'
require 'rexml/document'
require 'timeout'

def comment_captcha_label
	'右の画像に書かれている文字列を入力してください'
end

alias :comment_body_label_orig :comment_body_label

def comment_body_label
	r = ""
	doc = nil
	if @mode == 'day' then
		timeout( 5 ) do
			begin
				doc = open( "http://www.trynt.com/captcha-api/v1/?code=auto" ){|f| REXML::Document.new( f.read ).root}
			rescue Exception
			end
		end
	end
	if doc && doc.elements['captcha_code'] && doc.elements['captcha_image'] then
		code = doc.elements['captcha_code'].text
		image = doc.elements['captcha_image'].text
		secret = @conf['captcha.secret'] || ''
		expire = (Time.now.to_i+86400).to_s
		digest = Digest::MD5.hexdigest( code+secret+expire )
		r << %Q[<div class="captcha-image" style="float: right"><img src="#{CGI.escapeHTML( image )}" alt="CAPTCHA Image" width="100" height="50">]
		r << %Q[<br><a href="http://www.trynt.com/" title="TRYNT Web Services">TRYNT Web Services</a> Powered]
		r << %Q[</div>]
		r << comment_captcha_label
		r << %Q[:<input class="field" name="captcha_code" value="">]
		r << %Q[<input type="hidden" name="captcha_digest" value="#{digest}">]
		r << %Q[<input type="hidden" name="captcha_expire" value="#{expire}">]
		r << %Q[<br>]
	else
		secret = @conf['captcha.secret'] || ''
		expire = (Time.now.to_i+86400).to_s
		digest = Digest::MD5.hexdigest( secret+expire )
		r << %Q[<input type="hidden" name="captcha_code" value="">]
		r << %Q[<input type="hidden" name="captcha_digest" value="#{digest}">]
		r << %Q[<input type="hidden" name="captcha_expire" value="#{expire}">]
	end
	r << comment_body_label_orig
end
