#!/bin/bash

# SSI script to display a captcha for processing by a user,
# Value of the captcha is stored on the server rather than in a HTML form
# Copyright Ben Tasker 2009
# Released under the GNU GPL
#
# See Http://benscomputer.no-ip.org/LICENSE for more information


# Check that Captcha Cleanup isn't in operation
if [ -e /tmp/scaptcha.lock ]
then

echo "Captchas are temporarily disabled, please try again in a few minutes"


else

# On which server are the Captcha's stored
SERVERADDY="SERVERSFQDN"

# Which folder are the captchas in?
CAPTCHAPATH="captchas"

# Where is the text file containing captcha information?
CAPTCHADB="/path/to/captchadb"

CAPTCHAIMAGES="/path/to/captchas/"
SERVERROOT="/path/to/htdocs"

# Captcha Selection

# Select the Captcha based on the Second, not the most random method, but with regular rotation, should not be 
# an issue



CAPTCHANAME=$( date +'%S' )

# Until the Captcha Generation is complete I'm basing the captcha on 1 second
# with a full rotation being complete every 10 seconds


CAPTCHAIMAGE="$CAPTCHANAME"".jpg"
# Names will always be two digits, i.e. 01 not 1

# Now lets grab the Captcha Details from the Captcha Database
CAPTCHAINFO=$( cat "$CAPTCHADB" | grep $CAPTCHAIMAGE )
CAPTCHATEXT=$( echo "$CAPTCHAINFO" | sed -n 's/^.*TEXT=\([^&]*\).*$/\1/p' | sed "s/%20/ /g" )
CAPTCHAMATHS=$( echo "$CAPTCHAINFO" | sed -n 's/^.*MATHS=\([^&]*\).*$/\1/p' | sed "s/%20/ /g" )

# Session ID is generated based on the current time
# We could potentially be generating several sessions at the same time
# So it includes NanoSeconds
SESSIONID=$( date +'%H%M%S%N' )

# Write the Captcha text to a session file so it can x/refd later on in the chain
echo "$CAPTCHATEXT" > /tmp/captcha."$SESSIONID"

# To make it a little harder for Spammers to work out our captchas, lets only publish them when needed

GRABPATH="$CAPTCHAIMAGES""/""$CAPTCHANAME"".jpg"
PUTPATH="$SERVERROOT""/""$CAPTCHAPATH""/""$SESSIONID"".jpg"
cp "$GRABPATH" "$PUTPATH"

# Display the captcha

echo "<img src=""$SERVERADDY""/""$CAPTCHAPATH""/""$SESSIONID"".jpg""><br>"
echo "<INPUT TYPE=hidden value=""$SESSIONID"" NAME=Session>"
if [ "$CAPTCHAMATHS" == "Y" ]
then
echo "<br>Please Solve the Maths Puzzle Shown Above<br>"
echo "Please provide your answer using numerals and without any leading 0's <br><br>"
else
echo "<br>Please enter the text shown above (Case Sensitive, Letters only - no numbers, spaces or other characters)<br>"
fi

# Log which Captcha was used in case Spammers manage to crack one, e-mails contain session ID so it's a simple 
# grep job to locate the weak captcha

echo "$SESSIONID $CAPTCHAIMAGE" >> /tmp/captchalog


fi
