source: products/qPloneCaptchas/tags/1.0/utils.py @ 458

Last change on this file since 458 was 1, checked in by myroslav, 18 years ago

Building directory structure

  • Property svn:eol-style set to native
File size: 3.1 KB
Line 
1import os
2from string import atoi
3import md5
4from random import randint
5from Products.qPloneCaptchas.data import basic_english
6from Products.qPloneCaptchas.config import havePIL, CAPTCHAS_COUNT
7from DateTime import DateTime
8import re
9try:
10    import Crypto.Cipher.DES as Crypto
11except:
12    import Crypto
13
14def encrypt1(s):
15    return md5.new(s).hexdigest().upper()
16
17def gen_captcha(text, fnt_sz, fmt='JPEG'):
18    """Generate a captcha image"""
19    import ImageFile
20    import Image
21    import ImageFont
22    import ImageDraw
23    import ImageFilter
24    from PIL import ImageFile as pyImageFile
25    import sys
26    sys.modules['ImageFile'] = pyImageFile
27    from cStringIO import StringIO
28    outFile = StringIO()
29
30    DATA_PATH = os.path.abspath(os.path.dirname(__file__)) + '/data'
31    FONT_PATH = DATA_PATH + '/fonts'
32
33    # randomly select the foreground color
34    fgcolor = randint(0x000000,0x000fff)
35    # make the background color the opposite of fgcolor
36    bgcolor = fgcolor ^ 0xffffff
37    # create a font object
38    import sys
39    font = ImageFont.truetype(FONT_PATH+'/vera/Vera.ttf', fnt_sz)
40    # determine dimensions of the text
41    dim = font.getsize(text)
42    # create a new image slightly larger that the text
43    im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor)
44    d = ImageDraw.Draw(im)
45    x, y = im.size
46    r = randint
47    # draw 100 random colored boxes on the background
48
49    for num in range(50):
50        d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0xfff000,0xffffff))
51
52    # add the text to the image
53    d.text((3,3), text, font=font, fill=fgcolor)
54   
55    for num in range(10):
56        d.line([(r(0,x), r(0,y)), (r(0,x), r(0,y))], fill=r(0xf0f000, 0xffffff))
57
58    im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
59
60    # save the image to a file
61    im.save(outFile, format=fmt)
62    outFile.seek(0)
63    src = outFile.read()
64    size = len(src)
65    sys.modules['ImageFile'] = ImageFile
66    return {'src':src, 'size':size}
67
68
69def getWord(index):
70    words = basic_english.words.split()
71    return words[index]
72
73def getIndex(word):
74    words = basic_english.words.split()
75    try:
76        res = words.index(word)
77    except ValueError:
78        res = getLen()+1
79    return res
80
81def getCaptchasCount(havePIL):
82    def getLen():
83        return len(basic_english.words.split())
84    return havePIL and getLen() or CAPTCHAS_COUNT
85
86def formKey(num):
87    def normalize(s):
88        return (not len(s)%8 and s) or normalize(s+str(randint(0, 9)))
89
90    return normalize('%s_%i_'%(str(DateTime().timeTime()), num))
91
92def encrypt(key, s):
93    return toHex(Crypto.new(key).encrypt(s))
94
95def decrypt(key, s):
96    return Crypto.new(key).decrypt(toStr(s))
97
98def parseKey(s):
99    ps = re.match('^(.+?)_(.+?)_', s)
100    return {'date': ps.group(1), 'key':ps.group(2)}
101
102"""
103def addExpiredKey(context, key):
104    context.portal_captchas.new(key)
105"""
106
107def toHex(s):
108    lst = []
109    for ch in s:
110        hv = hex(ord(ch)).replace('0x', '')
111        if len(hv) == 1:
112            hv = '0'+hv
113        lst.append(hv)
114
115    return reduce(lambda x,y:x+y, lst)
116
117def toStr(s):
118    return s and chr(atoi(s[:2], base=16)) + toStr(s[2:]) or ''
Note: See TracBrowser for help on using the repository browser.