import urllib
import re
import random
import hashlib

class CapatchaController:

#--- Captcha ----------------------------------------------
re_all_img = re.compile('<img.+?>')
re_img_src = re.compile('src="(.+?)"')
def _getPictures(self, type, count):
page = random.randint(0, 35)

if type == 'birds':
url = 'http://www.flickr.com/groups/beautifulbirdscom/pool/page%s' % page
elif type == 'cats':
url = 'http://www.flickr.com/photos/tags/kitty/clusters/cat-kitten-cute/page%s' % page
else:
raise Exception('Invalid type arugment, should be "birds" or "cats", you gave %s' % type)

result = []
html = urllib.urlopen(url).read()

img_tags = list(self.re_all_img.finditer(html))
random.shuffle(img_tags)

for img_tag in img_tags:
img_tag = img_tag.group(0)
if 'class="pc_img"' in img_tag:
result.append( self.re_img_src.search(img_tag).group(1) )

if len(result) >= count:
break

return result

@amiweb.expose
def getCaptchaHTML(self):
matches = self._getPictures('birds', 5)

cats = self._getPictures('cats', 1)
session()['captcha_current_url'] = cats[0]

matches.extend(cats)
random.shuffle(matches)

form_html = []
form_html.append('<form><table>')

li_item = '<td><input type="radio" name="c_match" value="%s" /> <img src="%s" /></td>'
for i in range(0, len(matches), 2):
img_1 = matches[i]
img_2 = matches[i+1]
form_html.append('<tr>')
form_html.append(li_item % (img_1, img_1))
form_html.append(li_item % (img_2, img_2))
form_html.append('</tr>')

form_html.append('</table></form>')
return ' '.join(form_html)

@amiweb.expose
def validateCaptcha(self, url, content):
cur_url = session().get('captcha_current_url')
if url == cur_url:
session()['captcha_ok_for'] = hashlib.md5(content).hexdigest()
return 'ok'

#Only one guess
if cur_url:
del session()['captcha_current_url']

return 'error'

@amiweb.expose
def showCaptcha(self):
ns = {
'template': self.template
}
return render("site_plugins/blog/view/show_captcha.tmpl", ns)