#!/usr/bin/env python
""" A python program to generate an image 
    for human verification codes. OCR systems
    should be annoyed by this images


    
   You are free to distribute this software under the terms of the GNU General
   Public License as published by the Free Software Foundation;  either version
   2 of the License, or (at your option) any later version.

   copyright: 2004 Jesus Roncero Franco 
                jesus at roncero.org

    
"""
import Image, ImageDraw, ImageFont, ImageOps, sys
import cgi, os

__author__ = "Jesus Roncero Franco "


xstep = 5 
ystep = 5 
imageSize = (60,20)
bgColor = (255,255,255) # White
gridInk = (200,200,200)
fontInk = (130,130,130)
fontSize = 14
fontPath = "./veramono.ttf"

# Settings for the antispam system
TMPDIR="/tmp"
HASH_PREFIX="notreally_"



def generateImage(number):
    font = ImageFont.truetype(fontPath, fontSize)
    im = Image.new("RGB", imageSize, bgColor)
    draw = ImageDraw.Draw(im)
    
    xsize, ysize = im.size

    # Do we want the grid start at 0,0 or want some offset?
    x, y = 1,1
    
    draw.setink(gridInk)
    while x <= xsize:
        draw.line(((x, 0), (x, ysize)))
        x = x + xstep 
    while y <= ysize:
        draw.line(((0, y), (xsize, y)))
        y = y + ystep 
    
    draw.setink(fontInk)
    draw.text((3, 2), number, font=font)

    return im
    
def getHashNumber(hashtxt):
    snumber = -1
    hashfilename = "%s%s.txt" %  (HASH_PREFIX, hashtxt)
    hashfilename = os.path.join(TMPDIR, hashfilename)
    try:
        f = open(hashfilename,"r")
    except:
        # This is an error, send back this string 
        return "Error"

    snumber = f.readline()
    f.close()
    return snumber


def sendData(image):
    # Sending header
    print "Content-type: image/png\n"

    image.save(sys.stdout, "PNG")
    

def main():
    form = cgi.FieldStorage()
    if form.has_key('hash'):
        hash = form['hash'].value
        number = getHashNumber(hash)
    else:
        number = "ERROR"
    	error = 1
    image = generateImage(number)
    sendData(image)



if __name__ == '__main__':
    main()



# vim: shiftwidth=4 tabstop=4 expandtab
