Changeset 3128 in products
- Timestamp:
- Apr 18, 2011 11:16:39 AM (13 years ago)
- Location:
- quintagroup.captcha.core/trunk
- Files:
-
- 17 edited
Legend:
- Unmodified
- Added
- Removed
-
quintagroup.captcha.core/trunk/quintagroup/captcha/core/CaptchaTool.py
r2180 r3128 5 5 from AccessControl import ClassSecurityInfo 6 6 from Products.Transience.Transience import TransientObjectContainer 7 7 8 8 9 class CaptchaTool(TransientObjectContainer): … … 13 14 security.declarePublic('addExpiredKey') 14 15 15 def __init__(self, id='portal_captchas', title='', timeout_mins=60, addNotification=None, 16 def __init__(self, id='portal_captchas', title='', 17 timeout_mins=60, addNotification=None, 16 18 delNotification=None, limit=0, period_secs=60): 17 TransientObjectContainer.__init__(self, id, title, timeout_mins, addNotification, 18 delNotification, limit, period_secs) 19 TransientObjectContainer.__init__(self, id, title, timeout_mins, 20 addNotification, delNotification, 21 limit, period_secs) 19 22 20 23 def addExpiredKey(self, key): -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/Crypto.py
r797 r3128 1 1 # xor implementation with PyCrypto interface 2 2 3 3 4 def new(key): 4 5 return Xor(key) 6 5 7 6 8 class Xor: -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/Extensions/Install.py
r1952 r3128 2 2 from Products.CMFCore.utils import getToolByName 3 3 4 4 5 def uninstall(self): 5 6 portal_setup = getToolByName(self, 'portal_setup') 6 portal_setup.runAllImportStepsFromProfile('profile-quintagroup.captcha.core:uninstall', purge_old=False) 7 profile = "profile-quintagroup.captcha.core:uninstall" 8 portal_setup.runAllImportStepsFromProfile(profile, purge_old=False) 7 9 transaction.savepoint() -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/Extensions/__init__.py
r963 r3128 1 # -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/__init__.py
r1978 r3128 7 7 from quintagroup.captcha.core import CaptchaTool 8 8 9 ProductMessageFactory = MessageFactory('quintagroup.captcha.core') 10 ModuleSecurityInfo('quintagroup.captcha.core').declarePublic("ProductMessageFactory") 9 product = 'quintagroup.captcha.core' 10 ProductMessageFactory = MessageFactory(product) 11 ModuleSecurityInfo(product).declarePublic("ProductMessageFactory") 11 12 12 13 allow_module('quintagroup.captcha.core.utils') 13 14 allow_module('quintagroup.captcha.core.config') 15 14 16 15 17 def initialize(context): -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/encrypt_images.py
r797 r3128 1 1 import md5 2 2 import os 3 3 4 4 5 def encrypt_md5(s): … … 12 13 fname = file[:-5] 13 14 hash = md5.new(fname).hexdigest().upper() 14 new_fname = str(index) +'.jpg'15 new_fname = str(index) + '.jpg' 15 16 metaname = new_fname + '.metadata' 16 meta = open(metaname, 'w')17 meta = open(metaname, 'w') 17 18 meta.write('[default]\n') 18 meta.write('title=' +hash)19 meta.write('title=' + hash) 19 20 meta.close() 20 21 os.rename(file, new_fname) -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/setuphandlers.py
r1953 r3128 6 6 ALL_LAYERS, PROPERTY_SHEET 7 7 8 8 9 def generateKey(length): 9 10 key = '' … … 11 12 key += str(randint(0, 9)) 12 13 return key 14 13 15 14 16 def setupVarious(context): … … 24 26 else: 25 27 site._setProperty(CAPTCHA_KEY, value, 'string') 28 26 29 27 30 def uninstall(context): -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/skins/captcha_core/dynamic/getCaptcha.py
r1993 r3128 12 12 # *randint* return random integer in range [a, b], 13 13 # including *both* end points. 14 key = formKey(randint(0, getCaptchasCount(True) -1))14 key = formKey(randint(0, getCaptchasCount(True) - 1)) 15 15 encrypted_key = encrypt(context.captcha_key, key) 16 16 -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/skins/captcha_core/getCaptchaType.py
r1955 r3128 16 16 default_skin = skinsTool.getDefaultSkin() 17 17 path = skinsTool.getSkinPath(default_skin) 18 path = map( string.strip, string.split( path,',' ))18 path = map(string.strip, string.split(path, ',')) 19 19 20 20 if LAYER_STATIC_CAPTCHAS in path: -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/base.py
r1991 r3128 24 24 burn 25 25 """ 26 27 26 28 def testPatch(): 27 29 # PATCH dictionary for captcha testing … … 32 34 utils.CAPTCHAS_COUNT = len(utils.basic_english.words.split()) 33 35 # END OF PATCH 36 34 37 35 38 @onsetup -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testConfiglet.py
r2447 r3128 1 import re, string 1 import re 2 import string 2 3 from base import * 4 3 5 4 6 class TestConfiglet(ptc.FunctionalTestCase): … … 6 8 def afterSetUp(self): 7 9 self.sp = self.portal.portal_properties.site_properties 8 self.basic_auth = ':'.join((portal_owner, default_password))10 self.basic_auth = ':'.join((portal_owner, default_password)) 9 11 self.loginAsPortalOwner() 10 12 self.addProduct(PRODUCT_NAME) 11 13 12 14 self.capprops = self.portal.portal_properties[PROPERTY_SHEET] 13 15 self.save_url = self.portal.id + \ … … 20 22 for skin in skins.getSkinSelections(): 21 23 path = skins.getSkinPath(skin) 22 path = map( string.strip, string.split( path,','))24 path = map(string.strip, string.split(path, ',')) 23 25 if not layer in path: 24 26 return False … … 29 31 self.publish(self.save_url + '&static_captchas=static', 30 32 self.basic_auth) 31 33 32 34 self.assertTrue(self.layerInSkins(LAYER_STATIC_CAPTCHAS), 33 35 "No '%s' skin layer in some skins" % LAYER_STATIC_CAPTCHAS) … … 36 38 res = self.publish(self.save_url + '&static_captchas=dynamic', 37 39 self.basic_auth).getBody() 38 40 39 41 self.assertTrue(self.layerInSkins(LAYER_DYNAMIC_CAPTCHAS), 40 42 "No '%s' skin layer in some skins" % LAYER_DYNAMIC_CAPTCHAS) … … 99 101 self.loginAsPortalOwner() 100 102 self.addProduct(PRODUCT_NAME) 101 self.view = self.publish(self.portal.id+'/prefs_captchas_setup_form', 102 portal_owner+":"+default_password).getBody() 103 103 captcha_pref_path = self.portal.id + '/prefs_captchas_setup_form' 104 basic_auth = portal_owner + ":" + default_password 105 self.view = self.publish(captcha_pref_path, basic_auth).getBody() 106 104 107 def matchinput(self, name): 105 108 return re.match('.*<input\s+[^\>]*name=\"%s\"[^>]*>' % name, 106 self.view, re.I |re.S)109 self.view, re.I | re.S) 107 110 108 111 def test_basic_form(self): 109 form = re.match('.*<form\s+[^\>]*action=\"[^\"]*?prefs_captchas_setup_form\"[^>]*>', 110 self.view, re.I|re.S) 112 reg_expr = '.*<form\s+[^\>]*action=\"[^\"]*?'\ 113 'prefs_captchas_setup_form\"[^>]*>' 114 form = re.match(reg_expr, self.view, re.I | re.S) 111 115 self.assertNotEqual(form, None, 112 116 "No 'Plone Captchas Setup' form present on the configlet view") … … 122 126 self.assertNotEqual(self.matchinput(param), None, 123 127 "'%s' form element absence on the configlet form" % param) 124 128 125 129 126 130 def test_suite(): -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testDynamic.py
r2450 r3128 12 12 from PIL import ImageFont 13 13 fontspath = abspath(dirname(dirname(__file__))) + '/data/fonts/vera/' 14 font = ImageFont.truetype(fontspath +'VeraBd.ttf', 27)14 font = ImageFont.truetype(fontspath + 'VeraBd.ttf', 27) 15 15 except ImportError: 16 16 DYNAMIC_WORKABLE = False … … 24 24 for skin in skins.getSkinSelections(): 25 25 path = skins.getSkinPath(skin) 26 path = map( string.strip, string.split( path,','))26 path = map(string.strip, string.split(path, ',')) 27 27 try: 28 28 i = path.index(LAYER_STATIC_CAPTCHAS) … … 31 31 except ValueError: 32 32 pass 33 path = string.join( path, ', ')34 skins.addSkinSelection( skin, path)33 path = string.join(path, ', ') 34 skins.addSkinSelection(skin, path) 35 35 self._refreshSkinData() 36 36 37 37 38 38 class TestPIL(unittest.TestCase): 39 39 40 40 def testPILImageFont(self): 41 41 if not DYNAMIC_WORKABLE: … … 69 69 # index start from 0 and lower or equals to captchas count 70 70 index = int(parsed_key['key']) 71 self.assertTrue(index >= 0 and index <= len(utils.basic_english.words.split())) 71 words = utils.basic_english.words.split() 72 self.assertTrue(index >= 0 and index <= len(words)) 72 73 # encrypted key must be equals to word from the dictionary, 73 74 # under index position and must be not empty string … … 76 77 def test_GetImage(self): 77 78 # getCaptchaImage function must return image coded in hashkey same to 78 # image get by 'key' after parsing decrypted key 79 # image get by 'key' after parsing decrypted key 79 80 decrypted_key = decrypt(self.captcha_key, self.hashkey) 80 81 parsed_key = parseKey(decrypted_key) 81 82 82 83 img_html = self.publish( 83 self.portal.absolute_url(1) +"/getCaptchaImage/%s" % self.hashkey)84 self.portal.absolute_url(1) + "/getCaptchaImage/%s" % self.hashkey) 84 85 85 86 img_ctype = img_html.getHeader('content-type') -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testInstallation.py
r1957 r3128 1 1 from base import * 2 2 3 3 4 class TestInstallation(ptc.FunctionalTestCase): … … 15 16 def testPropertysheetInstall(self): 16 17 pp = getToolByName(self.portal, 'portal_properties') 17 self.assert_(PROPERTY_SHEET in pp.objectIds(), 'Property sheet isn\'t found') 18 msg = 'Property sheet isn\'t found' 19 self.assert_(PROPERTY_SHEET in pp.objectIds(), msg) 18 20 19 21 def testPropertysheetUninstall(self): … … 24 26 25 27 def testConfigletInstall(self): 26 self.assert_(CONFIGLET_ID in [a.getId() for a in self.cp.listActions()], 'Configlet not found') 28 list_ids = [] 29 for action in self.cp.listActions(): 30 list_ids.append(action.getId()) 31 self.assert_(CONFIGLET_ID in list_ids, 'Configlet not found') 27 32 28 33 def testConfigletUninstall(self): 29 34 self.qi.uninstallProducts([PRODUCT_NAME]) 30 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True,'%s is already installed' % PRODUCT_NAME) 31 self.assert_(not CONFIGLET_ID in [a.getId() for a in self.cp.listActions()], 'Configlet found after uninstallation') 35 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 36 '%s is already installed' % PRODUCT_NAME) 37 list_ids = [] 38 for action in self.cp.listActions(): 39 list_ids.append(action.getId()) 40 msg = 'Configlet found after uninstallation' 41 self.assert_(not CONFIGLET_ID in list_ids, msg) 32 42 33 43 def testSkinsInstall(self): … … 38 48 path = map(str.strip, path.split(',')) 39 49 for layer in layers: 40 self.assert_(layer.split('/')[0] in skinstool.objectIds(), '%s directory view not found in portal_skins after installation' % layer) 41 self.assert_(layer in path, '%s layer not found in %s' % (PRODUCT_NAME, skin)) 50 msg = '%s directory view not found in'\ 51 'portal_skins after installation' % layer 52 self.assert_(layer.split('/')[0] in skinstool.objectIds(), msg) 53 msg = '%s layer not found in %s' % (PRODUCT_NAME, skin) 54 self.assert_(layer in path, msg) 42 55 43 56 def testSkinsUninstall(self): 44 57 self.qi.uninstallProducts([PRODUCT_NAME]) 45 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True,'%s is already installed' % PRODUCT_NAME) 58 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 59 '%s is already installed' % PRODUCT_NAME) 46 60 skinstool = self.st 47 61 layers = self.getLayers() … … 50 64 path = map(str.strip, path.split(',')) 51 65 for layer in layers: 52 self.assert_(not layer.split('/')[0] in skinstool.objectIds(), '%s directory view found in portal_skins after uninstallation' % layer) 53 self.assert_(not layer in path, '%s layer found in %s after uninstallation' % (layer, skin)) 66 msg = '%s directory view found in'\ 67 'portal_skins after uninstallation' % layer 68 skins_tool_ids = skinstool.objectIds() 69 self.assert_(not layer.split('/')[0] in skins_tool_ids, msg) 70 msg = '%s layer found in'\ 71 '%s after uninstallation' % (layer, skin) 72 self.assert_(not layer in path, msg) 54 73 55 74 def testToolInstall(self): … … 58 77 def testToolUninstall(self): 59 78 self.qi.uninstallProducts([PRODUCT_NAME]) 60 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 79 self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 61 80 '%s is already installed' % PRODUCT_NAME) 62 81 self.assert_(not TOOL_ID in self.portal.objectIds()) … … 69 88 self.assert_(not self.portal.hasProperty(CAPTCHA_KEY)) 70 89 90 71 91 def test_suite(): 72 92 suite = unittest.TestSuite() -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testStatic.py
r2542 r3128 4 4 from DateTime import DateTime 5 5 from Products.CMFFormController.ControllerState import ControllerState 6 6 7 7 8 class TestStatic(ptc.FunctionalTestCase): … … 19 20 for skin in self.skins.getSkinSelections(): 20 21 path = self.skins.getSkinPath(skin) 21 path = map( string.strip, string.split( path,','))22 path = map(string.strip, string.split(path, ',')) 22 23 self.assertTrue(LAYER_STATIC_CAPTCHAS in path) 23 24 … … 26 27 static = self.skins.restrictedTraverse('captchas') 27 28 static_ids = static.objectIds() 28 for i in range(1, CAPTCHAS_COUNT +1):29 for i in range(1, CAPTCHAS_COUNT + 1): 29 30 self.assertTrue("%s.jpg" % i in static_ids, 30 "No %s.jpg in static, %s" % (i, static_ids))31 "No %s.jpg in static, %s" % (i, static_ids)) 31 32 32 33 def test_GetCaptcha_Date(self): … … 45 46 self.assertTrue(index >= 1 and index <= CAPTCHAS_COUNT) 46 47 # encrypted key must be equals to title of the image 47 key = getWord( index-1)48 key = getWord(index - 1) 48 49 img = getattr(self.portal, '%s.jpg' % index) 49 50 self.assertTrue(encrypt1(key) == img.title) … … 51 52 def test_GetImage(self): 52 53 # getCaptchaImage function must return image coded in hashkey same to 53 # image get by 'key' after parsing decrypted key 54 # image get by 'key' after parsing decrypted key 54 55 req, resp = self.app.REQUEST, self.app.REQUEST.RESPONSE 55 56 decrypted_key = decrypt(self.captcha_key, self.hashkey) 56 57 parsed_key = parseKey(decrypted_key) 57 img = self.portal.restrictedTraverse(parsed_key['key'] +'.jpg')58 img = self.portal.restrictedTraverse(parsed_key['key'] + '.jpg') 58 59 img_html = img.index_html(req, resp) 59 60 60 obj_html = self.publish( 61 self.portal.absolute_url(1)+"/getCaptchaImage/%s" % self.hashkey).getBody() 62 self.assertTrue(obj_html == img_html, "Image get by getCaptchaImage script " \ 63 "is differ from image get by index (after parsing decrypted key)") 64 61 portal = self.portal.absolute_url(1) 62 captcha_path = portal + "/getCaptchaImage/%s" % self.hashkey 63 obj_html = self.publish(captcha_path).getBody() 64 msg = "Image get by getCaptchaImage script is differ from"\ 65 "image get by index (after parsing decrypted key)" 66 self.assertTrue(obj_html == img_html, msg) 67 65 68 66 69 class TestStaticValidator(ptc.PloneTestCase): … … 80 83 def testGoodData(self): 81 84 hashkey = self.portal.getCaptcha() 82 key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 85 decrypted_key = decrypt(self.captcha_key, hashkey) 86 key = getWord(int(parseKey(decrypted_key)['key']) - 1) 83 87 self.req.form['hashkey'] = hashkey 84 self.req.form['key'] = key +'1'88 self.req.form['key'] = key + '1' 85 89 86 cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 87 self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 90 cstate = self.pfc.validate(self.dummycs, self.req, 91 ['captcha_validator', ]) 92 error_msg = 'Please re-enter validation code.' 93 self.assertTrue(cstate.getErrors()['key'] == error_msg, 88 94 "Static captcha validator validate wrong key") 89 95 90 96 def testBadKey(self): 91 97 hashkey = self.portal.getCaptcha() 92 key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 98 decrypted_key = decrypt(self.captcha_key, hashkey) 99 key = getWord(int(parseKey(decrypted_key)['key']) - 1) 93 100 self.req.form['hashkey'] = hashkey 94 101 self.req.form['key'] = 'bad key' 95 96 cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 97 self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 102 103 cstate = self.pfc.validate(self.dummycs, self.req, 104 ['captcha_validator', ]) 105 error_msg = 'Please re-enter validation code.' 106 self.assertTrue(cstate.getErrors()['key'] == error_msg, 98 107 "Static captcha validator validate wrong key") 99 108 … … 103 112 now = DateTime().timeTime() 104 113 DateTime.timeTime = lambda s: now - float(3601) 105 114 106 115 hashkey = self.portal.getCaptcha() 107 key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 116 117 decrypted_key = decrypt(self.captcha_key, hashkey) 118 key = getWord(int(parseKey(decrypted_key)['key']) - 1) 108 119 self.req.form['hashkey'] = hashkey 109 120 self.req.form['key'] = key 110 121 # Return original Date 111 122 DateTime.timeTime = origDTTT 112 cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 113 self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 123 cstate = self.pfc.validate(self.dummycs, self.req, 124 ['captcha_validator', ]) 125 error_msg = 'Please re-enter validation code.' 126 self.assertTrue(cstate.getErrors()['key'] == error_msg, 114 127 "Static captcha validator validate wrong key") 115 128 -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testWidget.py
r2542 r3128 12 12 testPatch() 13 13 14 14 15 def addTestLayer(self): 15 16 # Install test_captcha skin layer … … 19 20 skinName = skins.getDefaultSkin() 20 21 paths = map(string.strip, skins.getSkinPath(skinName).split(',')) 21 paths.insert(paths.index('custom') +1, 'test_captcha')22 paths.insert(paths.index('custom') + 1, 'test_captcha') 22 23 skins.addSkinSelection(skinName, ','.join(paths)) 23 24 self._refreshSkinData() … … 34 35 self.absolute_url = self.portal['index_html'].absolute_url_path() 35 36 36 self.basic_auth = ':'.join((portal_owner, default_password))37 self.basic_auth = ':'.join((portal_owner, default_password)) 37 38 self.captcha_key = self.portal.captcha_key 38 39 39 40 def testImage(self): 40 41 path = '%s/test_form' % self.absolute_url 41 response = self.publish(path, self.basic_auth, request_method='GET').getBody() 42 response = self.publish(path, self.basic_auth, 43 request_method='GET').getBody() 42 44 patt = re.compile(IMAGE_PATT % self.portal.absolute_url()) 43 45 match_obj = patt.search(response) 44 46 45 47 img_url = match_obj.group(1) 46 content_type = self.publish('/plone' + img_url, self.basic_auth).getHeader('content-type') 48 res = self.publish('/plone' + img_url, self.basic_auth) 49 content_type = res.getHeader('content-type') 47 50 self.assert_(content_type.startswith('image')) 48 51 49 52 def testSubmitRightCaptcha(self): 50 53 hashkey = self.portal.getCaptcha() 51 # index of word number starts from 1, but index of dictionary starts from 0 52 key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 54 # index of word number starts from 1, 55 # but index of dictionary starts from 0 56 decrypted_key = decrypt(self.captcha_key, hashkey) 57 key = getWord(int(parseKey(decrypted_key)['key']) - 1) 53 58 parameters = 'form.submitted=1&key=%s' % key 54 59 path = '%s/test_form?%s' % (self.absolute_url, parameters) 55 60 extra = {'hashkey': hashkey, 56 61 'form.button.Save': 'Save'} 57 response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 62 response = self.publish(path, self.basic_auth, extra=extra, 63 request_method='GET').getBody() 58 64 self.assert_(not NOT_VALID.search(response)) 59 65 … … 64 70 extra = {'hashkey': hashkey, 65 71 'form.button.Save': 'Save'} 66 response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 72 response = self.publish(path, self.basic_auth, extra=extra, 73 request_method='GET').getBody() 67 74 self.assert_(NOT_VALID.search(response)) 68 75 69 76 def testSubmitRightCaptchaTwice(self): 70 77 hashkey = self.portal.getCaptcha() 71 key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1) 72 parameters = 'form.submitted=1&key=%s'%key 73 path = '%s/test_form?%s'%(self.absolute_url, parameters) 78 decrypted_key = decrypt(self.captcha_key, hashkey) 79 key = getWord(int(parseKey(decrypted_key)['key']) - 1) 80 parameters = 'form.submitted=1&key=%s' % key 81 path = '%s/test_form?%s' % (self.absolute_url, parameters) 74 82 extra = {'hashkey': hashkey, 75 83 'form.button.Save': 'Save'} 76 84 self.publish(path, self.basic_auth, extra=extra, request_method='GET') 77 response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 85 response = self.publish(path, self.basic_auth, extra=extra, 86 request_method='GET').getBody() 78 87 79 88 self.assert_(NOT_VALID.search(response)) … … 82 91 # captcha core related issue, described in 83 92 # in http://plone.org/products/plone-comments/issues/5 84 resp = self.publish(self.portal.absolute_url(1) +"/captcha_widget")93 resp = self.publish(self.portal.absolute_url(1) + "/captcha_widget") 85 94 self.assertEqual(resp.status / 100, 2) 95 86 96 87 97 def test_suite(): -
quintagroup.captcha.core/trunk/quintagroup/captcha/core/utils.py
r3097 r3128 19 19 import Crypto 20 20 21 21 22 def encrypt1(s): 22 23 return md5.md5(s).hexdigest().upper() 23 24 25 24 26 def getTransform(x, y, a, p, o): 25 return (math.sin( (y+o[0])*p )*a + x, math.sin( (x+o[1])*p )*a + y) 27 return (math.sin((y + o[0]) * p) * a + x, math.sin((x + o[1]) * p) * a + y) 28 26 29 27 30 def gen_captcha(**kwargs): … … 57 60 58 61 #select font for captcha text 59 ALL_FONTS=('Bd', 'It', 'MoBI', 'Mono', 'Se', 'BI', 'MoBd', 'MoIt', 'SeBd', '') 62 ALL_FONTS = ('Bd', 'It', 'MoBI', 'Mono', 'Se', 63 'BI', 'MoBd', 'MoIt', 'SeBd', '') 60 64 rand_font = random.choice(ALL_FONTS) 61 font = ImageFont.truetype(FONT_PATH+'/vera/Vera%s.ttf'%rand_font, fnt_sz) 65 rand_font_path = FONT_PATH + '/vera/Vera%s.ttf' % rand_font 66 font = ImageFont.truetype(rand_font_path, fnt_sz) 62 67 textSize = font.getsize(text) 63 68 64 69 #------------------------------render background1 ----------------------- 65 image = Image.new('RGB', (textSize[0] +7,textSize[1]+7), bkground)70 image = Image.new('RGB', (textSize[0] + 7, textSize[1] + 7), bkground) 66 71 image.paste(bkground) 67 72 #------------------------------render Text2 ------------------------ 68 73 draw = ImageDraw.Draw(image) 69 alignment = (random.uniform(0, 1), random.uniform(0,1))74 alignment = (random.uniform(0, 1), random.uniform(0, 1)) 70 75 x = int((image.size[0] - textSize[0]) * alignment[0] + 0.5) 71 76 y = int((image.size[1] - textSize[1]) * alignment[1] + 0.5) 72 77 73 draw.text((x, y), text, font=font, fill=font_color)78 draw.text((x, y), text, font=font, fill=font_color) 74 79 75 80 #------------------------------render Distortion ----------------------- … … 85 90 yRow = [] 86 91 for i in xrange(xPoints): 87 x, y = getTransform(i *r, j*r, amplitude, period, offset)92 x, y = getTransform(i * r, j * r, amplitude, period, offset) 88 93 89 94 # Clamp the edges so we don't get black undefined areas 90 x = max(0, min(image.size[0] -1, x))91 y = max(0, min(image.size[1] -1, y))95 x = max(0, min(image.size[0] - 1, x)) 96 y = max(0, min(image.size[1] - 1, y)) 92 97 93 98 xRow.append(x) … … 99 104 # each square between points on the grid 100 105 mesh = [] 101 for j in xrange(yPoints -1):102 for i in xrange(xPoints -1):106 for j in xrange(yPoints - 1): 107 for i in xrange(xPoints - 1): 103 108 mesh.append(( 104 109 # Destination rectangle 105 (i *r, j*r,106 (i +1)*r, (j+1)*r),110 (i * r, j * r, 111 (i + 1) * r, (j + 1) * r), 107 112 # Source quadrilateral 108 (xRows[j ][i ], yRows[j ][i],109 xRows[j +1][i ], yRows[j+1][i],110 xRows[j +1][i+1], yRows[j+1][i+1],111 xRows[j ][i+1], yRows[j ][i+1]),113 (xRows[j][i], yRows[j][i], 114 xRows[j + 1][i], yRows[j + 1][i], 115 xRows[j + 1][i + 1], yRows[j + 1][i + 1], 116 xRows[j][i + 1], yRows[j][i + 1]), 112 117 )) 113 118 … … 120 125 size = len(src) 121 126 sys.modules['ImageFile'] = ImageFile 122 return {'src': src, 'size':size}127 return {'src': src, 'size': size} 123 128 124 129 … … 127 132 return words[index] 128 133 134 129 135 def getIndex(word): 130 136 words = basic_english.words.split() … … 132 138 res = words.index(word) 133 139 except ValueError: 134 res = getLen() +1140 res = getLen() + 1 135 141 return res 142 136 143 137 144 def getCaptchasCount(dynamic): … … 141 148 return CAPTCHAS_COUNT 142 149 150 143 151 def formKey(num): 144 152 def normalize(s): 145 return (not len(s) %8 and s) or normalize(s+str(randint(0, 9)))153 return (not len(s) % 8 and s) or normalize(s + str(randint(0, 9))) 146 154 147 return normalize('%s_%i_'%(str(DateTime().timeTime()), num)) 155 return normalize('%s_%i_' % (str(DateTime().timeTime()), num)) 156 148 157 149 158 def encrypt(key, s): 150 159 return toHex(Crypto.new(key).encrypt(s)) 151 160 161 152 162 def decrypt(key, s): 153 163 return Crypto.new(key).decrypt(toStr(s)) 164 154 165 155 166 def parseKey(s): … … 157 168 if ps is None: 158 169 return {'date': '', 'key': ''} 159 return {'date': ps.group(1), 'key':ps.group(2)} 170 return {'date': ps.group(1), 'key': ps.group(2)} 171 160 172 161 173 def toHex(s): … … 164 176 hv = hex(ord(ch)).replace('0x', '') 165 177 if len(hv) == 1: 166 hv = '0' +hv178 hv = '0' + hv 167 179 lst.append(hv) 168 180 169 return reduce(lambda x,y:x+y, lst) 181 return reduce(lambda x, y: x + y, lst) 182 170 183 171 184 def toStr(s): -
quintagroup.captcha.core/trunk/setup.py
r2820 r3128 9 9 long_description=open("README.txt").read() + "\n" + 10 10 open(os.path.join("docs", "HISTORY.txt")).read(), 11 # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers12 11 classifiers=[ 13 12 "Framework :: Plone",
Note: See TracChangeset
for help on using the changeset viewer.