# auth_captcha.rb $ Revision: 1 $
# 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 auth_captcha_label
	'左の画像に書かれている文字列を入力してください'
end

if @command == 'save' then
	alias :save_orig :save
	def save( *param )
		if @cgi.include?( 'captcha_code' ) && @cgi.include?( 'captcha_digest' ) && @cgi.include?( 'captcha_expire' ) then
			code = @cgi.params['captcha_code'][0]
			digest = @cgi.params['captcha_digest'][0]
			expire = @cgi.params['captcha_expire'][0]
			return true if Time.now.to_i > expire.to_i
			secret = @conf['captcha.secret'] || ''
			return save_orig( *param ) if Digest::MD5.hexdigest( code+secret+expire ) == digest
		end
		true
	end
end

add_edit_proc do
	r = %Q[<div style="margin: 5px">]
	doc = nil
	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
	if doc 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[<img src="#{CGI.escapeHTML( image )}" alt="CAPTCHA Image" width="100" height="50">]
		r << %Q[ #{auth_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[ <a href="http://www.trynt.com/" title="TRYNT Web Services"><img src="http://images.trynt.com/trynt-powered-2.png" border="0" title="TRYNT Web Services"></a>]
	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 << %Q[</div>]
end
