Example #1
0
    def process_request(self, req):
        self.check_config()
        action = req.args.get('action')

        if req.method == 'POST' and action == 'create':
            response = captcha.submit(
                req.args['recaptcha_challenge_field'],
                req.args['recaptcha_response_field'],
                self.private_key,
                req.remote_addr,
            )
            if not response.is_valid:
                data = {}
                data[
                    'registration_error'] = 'Captcha incorrect. Please try again.'
                data['recaptcha_javascript'] = captcha.displayhtml(
                    self.public_key)
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, None
            else:
                ret = super(RecaptchaRegistrationModule,
                            self).process_request(req)
                h, data, n = ret
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, n
        else:
            ret = super(RecaptchaRegistrationModule, self).process_request(req)
            h, data, n = ret
            data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
            data['recaptcha_theme'] = self.theme
            return "recaptcharegister.html", data, n
Example #2
0
def entry_form(request):
    captcha_error = None
    html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    
    if request.method == 'POST':
        captcha_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None),  
                  request.POST.get("recaptcha_response_field", None),  
                  settings.RECAPTCHA_PRIVATE_KEY,  
                  request.META.get("REMOTE_ADDR", None))
        form = EntryForm(request.POST)
        if form.is_valid():
            if not captcha_response.is_valid:
                captcha_error = True
                html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
                return render_to_response('nest_bizplan/entry_form.html', {'form': form, 'captcha_error': captcha_error, 'html_captcha': html_captcha}, context_instance=RequestContext(request))
            new_entry = form.save()
            
            # Send e-mail to applicant
            subject = 'Education Business Plan Competition - Application Received '
            body = 'Thank you for entering the Milken-PennGSE Education Business Plan Competition! We have received your application. All applications will be reviewed by a panel of judges. Some applicants will then be invited to continue to the next round of the competition, as semi-finalists. We expect that semi-finalists will be announced by January 25, 2011. We will be in touch then - thank you, and best of luck!'
            send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [new_entry.email])
            
            return HttpResponseRedirect('/business-plan-competition-thanks/')
    else:
        form = EntryForm()
    
    return render_to_response('nest_bizplan/entry_form_closed.html', {'form': form, 'html_captcha': html_captcha}, context_instance=RequestContext(request))
Example #3
0
    def process_request(self, req):
        self.check_config()
        action = req.args.get('action')

        if req.method == 'POST' and action == 'create':
            response = captcha.submit(
                req.args['recaptcha_challenge_field'],
                req.args['recaptcha_response_field'],
                self.private_key,
                req.remote_addr,
                )
            if not response.is_valid:
                data = {}
                data['registration_error'] = 'Captcha incorrect. Please try again.'
                data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, None
            else:
                ret = super(RecaptchaRegistrationModule, self).process_request(req)
                h, data, n = ret
                data['recaptcha_theme'] = self.theme
                return "recaptcharegister.html", data, n
        else:
            ret = super(RecaptchaRegistrationModule, self).process_request(req)
            h, data, n = ret
            data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
            data['recaptcha_theme'] = self.theme
            return "recaptcharegister.html", data, n
Example #4
0
def webit():
	import os,cgi
	from exceptions import Exception
	from recaptcha.client import captcha
	
	try:
		scriptname=os.environ['SCRIPT_NAME']
	except: 
		raise Exception,'Program should run as a cgi'
	if DEBUG_TO_WEB:
		import cgitb; cgitb.enable()
	
	print 'Content-type: text/html; charset=utf-8\n\n'
	form = cgi.FieldStorage()
	if os.environ['REQUEST_METHOD']=='GET':
		print FORM_PAGE_TEMPLATE % {
			'scriptname':scriptname,
			'errorhtml':'',
			'captcha':captcha.displayhtml(RECAPTCHA_PUBLIC_KEY),
		}
		
	
	
	else: # POST
		errors=[]
		captcha_error=''

		captcha_response = captcha.submit(
			form.getvalue('recaptcha_challenge_field'),
			form.getvalue('recaptcha_response_field'),
			RECAPTCHA_PRIVATE_KEY,
			os.environ['REMOTE_ADDR'])	
		if not captcha_response.is_valid:
			errors.append("You've failed the captcha test. Convince me again that you're not a robot.")
			captcha_error=captcha_response.error_code
		if errors:
			errorhtml='<ul class="error-list">%s</ul>' % ('\n'.join(['<li>%s</li>' % e for e in errors]))
			print FORM_PAGE_TEMPLATE % {
				'scriptname':scriptname,
				'errorhtml':errorhtml,
				'captcha':captcha.displayhtml(RECAPTCHA_PUBLIC_KEY,error=captcha_error),
			}
		else:
			try:
				title = 'Action completed'
				response = 'Thank you.  The form has been submitted to a moderator for review.'
			except Exception,e:
				title = 'Failed'
				response = '<strong>Error:</strong> %s' % str(e)
			print RESPONSE_PAGE_TEMPLATE % {'title':title,'response':response}
Example #5
0
def view_form(request, hash, not_active_template = 'tnycnt/tnycnt_not_active.html', 
              form_template = 'tnycnt/tnycnt_mailform.html',
              message_template = 'tnycnt/tnycnt_message.txt',
              ):
    """
    View and send a user created contact form.
    Uses recaptcha lib. If captcha is wrong a message is shown above form.  
    Mail message body can be edit in 'tnycnt/tnycnt_message.txt' and the message
    subject needs TNYCNT_MAIL_SUBJECT in settings file.
    """
    object = get_object_or_404(Contact, hash=hash)
    message = '' 
    if object.is_active == False:
        return render_to_response(not_active_template,
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        # Captcha check
        check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'],
                        request.POST['recaptcha_response_field'],
                        RECAPTCHA_PRIVATE_KEY,
                        request.META['REMOTE_ADDR'])
        form = ContactMailForm(request.POST)
        html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)
        if check_captcha.is_valid is False:
            #captcha is wrong
            message = _('Captcha failed')
        else:    
            if form.is_valid():
                from django.core.mail import send_mail		
                current_site = Site.objects.get_current()            
                subject = settings.TNYCNT_MAIL_SUBJECT        
                message = render_to_string(message_template,
                                           {'site_name':current_site,
                                            'title':object.title,
                                            'subject':form.cleaned_data['subject'],
                                            'email':form.cleaned_data['email'],
                                            'body': form.cleaned_data['body'] })            
                send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                          [object.user.email])
                return HttpResponseRedirect(reverse('tnycnt_sent'))
    else:
        form = ContactMailForm()
        html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    return render_to_response(form_template,
                             {'form': form,
                              'html_captcha': html_captcha,
                              'object':object,
                              'message':message},
                              context_instance=RequestContext(request))
Example #6
0
def user_creation(request, template_name='registration/create_user.html'):
    "Displays user creation form and handles its action"
    if request.method == "POST":
        if recaptcha is not None:
            if not ('recaptcha_challenge_field' in request.POST
                    and 'recaptcha_response_field' in request.POST
                    and recaptcha.submit(request.POST['recaptcha_challenge_field'],
                                         request.POST['recaptcha_response_field'],
                                         settings.RECAPTCHA_PRIVATE_KEY,
                                         request.remote_addr).is_valid):
                from django.http import HttpResponseForbidden
                return HttpResponseForbidden("invalid captcha")

        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            # log in the user automatically
            user = authenticate(username=form.cleaned_data["username"],
                                password=form.cleaned_data["password1"])
            perform_login(request, user)
            return redirect("ductus.wiki.views.view_frontpage")
    else:
        form = UserCreationForm()

    captcha_html = ""
    if recaptcha is not None:
        captcha_html = recaptcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                                             use_ssl=request.is_secure())
        captcha_html = captcha_html.replace('frameborder="0"',
                                            'style="border: 0"')

    return render_to_response(template_name, {
        'form': form,
        'captcha': mark_safe(captcha_html),
    }, context_instance=RequestContext(request))
Example #7
0
 def render(self, name, value, attrs=None):
     use_ssl = False
     if 'RECAPTCHA_USE_SSL' in settings.__members__:
         use_ssl = settings.RECAPTCHA_USE_SSL
     return mark_safe(u'%s' %
                      captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                                          use_ssl=use_ssl))
Example #8
0
def add():
    if request.method == 'GET':
        template = templates.get_template("add.html")
        return template.render(captcha_html=recaptcha.displayhtml(RECAPTCHA_PUBLIC_KEY))
    elif request.method == 'POST':
        # validate captcha
        recaptcha_response = recaptcha.submit(request.form['recaptcha_challenge_field'], request.form['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY, request.remote_addr)
        if not recaptcha_response.is_valid:
            template = templates.get_template("recaptcha_failed.html")
            return template.render()

        time_start = time.strptime("%s %s" % (request.form['date'], request.form['time']), '%A %d %B, %Y %H:%M')
        time_start = datetime.datetime.fromtimestamp(time.mktime(time_start))
        venue = request.form['venue']
        artists = [artist for artist in request.form.getlist('artists')if artist]
        gigname = request.form['gigname']
        gigdesc = request.form['gigdesc']
        if not venue or not artists:
            abort(400)

        if not model.get_venue_by_name(venue):
            model.add_venue(venue)
        venue_id = model.get_venue_by_name(venue).id
        for artist in artists:
            if not model.get_artist_by_name(artist):
                model.add_artist(artist)
        artist_ids = [model.get_artist_by_name(artist).id for artist in artists]
        gig_id = model.add_gig(time_start, venue_id, artist_ids, name=gigname, description = gigdesc)

        return redirect('/gig/%s' % gig_id)
    else: # unknown request method
        assert False
Example #9
0
def problem(request, slug=None):
    show_comments = request.GET.get('show')
    problem = get_object_or_404(Problem, slug=slug)
    form = CommentForm(request.POST or None)
    if request.method == 'POST':
        success = save_comment(request, form, problem)

        # Save name
        if success:
            show_comments = True
            if request.user.is_anonymous():
                form = CommentForm(initial={'name': form.data['name']})

    #Users don't need to pass a captcha
    html_captcha = ''
    if request.user.is_anonymous() and settings.RECAPTCHA_ENABLED:
        html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)
    comment_tree = Comment.objects.select_related('user').filter(problem=problem, spam=False).order_by('path').extra(select={'provider': 'SELECT provider FROM social_auth_usersocialauth WHERE social_auth_usersocialauth.user_id = core_comment.user_id'})

    return render(request, 'core/home.html', {'problem': problem,
                                              'comment_tree': comment_tree,
                                              'form': form,
                                              'html_captcha': html_captcha,
                                              'request': request,
                                              'show_comments': show_comments})
Example #10
0
def contactForm(request):
    """Contact Form"""
    title = _('Contact')
    message = ''

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            contact_text = form.cleaned_data['contact_text']
            check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
            if check_captcha.is_valid is False:
                # Captcha is wrong show a error ...
                message = _('Error with captcha number. Copy the same number.')
            else:
                subject = _('Contact - %(name)s') % {'name':SITE_TITLE}
                body = _('This email is generated with Contact Module from %(site)s\n\n%(name)s - %(email)s\n%(message)s') % {'site':SITE_TITLE,'name':name,'email':email,'message':contact_text}

                email = EmailMessage(subject, body, to=CONTACT_EMAIL)
                email.send()

                message = _('Thanks for your message. We will respond soon.')
        else:
            message = _('Sorry! This form is not valid. Try again.')

    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    return render_to_response("contact/form.html", locals(), context_instance=RequestContext(request))
Example #11
0
 def render(self, *args, **kwargs):
     from recaptcha.client import captcha as recaptcha
     recaptcha_options = """<script type="text/javascript"> var RecaptchaOptions = { theme: '""" + self.theme + \
                         "', lang: '" + get_language()[0:2] + \
                         ("', custom_theme_widget: 'recaptcha_widget'" if self.theme == 'custom' else "'") + " }; </script>\n"
     return mark_safe(recaptcha_options +
                      recaptcha.displayhtml(self.public_key))
Example #12
0
    def get(self, ids=None):
        try:
            s = Stream.get_by_id(int(ids))
        except:
            s = None

        if s:  # stream exists
            chtml = captcha.displayhtml(public_key=RECAPTCHA_PUBLIC_KEY, use_ssl=False, error=None)
            template_values = {
                "title": "Stream " + str(s.key().id()),
                "title2": "Modifying stream",
                "description": s.description,
                "onload": "document.stream.e_pass.focus()",
                "stream": s,
                "captcha": chtml,
                "admin": users.is_current_user_admin(),
                "logout": users.create_logout_url("/"),
                "lang": self.get_lang(),
            }
            path = os.path.join(os.path.dirname(__file__), "templates/modify_stream.html")
            self.response.out.write(template.render(path, template_values))
        elif ids:  # stream selected but not found
            self.redirect("/error/404")
        else:  # no stream selected
            self.redirect("/new")
Example #13
0
    def get(self, idr=None):
        try:
            r = Request.get_by_id(int(idr))
        except:
            r = None

        if r:  # request exists
            chtml = captcha.displayhtml(public_key=RECAPTCHA_PUBLIC_KEY, use_ssl=False, error=None)
            template_values = {
                "title": "Request " + str(r.key().id()),
                "title2": "Modifying request",
                "description": r.description,
                "onload": "document.request.e_pass.focus()",
                "request": r,
                "comments": r.get_comments(),
                "captcha": chtml,
                "admin": users.is_current_user_admin(),
                "logout": users.create_logout_url("/"),
                "lang": self.get_lang(),
            }
            path = os.path.join(os.path.dirname(__file__), "templates/modify_request.html")
            self.response.out.write(template.render(path, template_values))
        elif idr:  # request selected but not found
            self.redirect("/error/404")
        else:  # no request selected
            self.redirect("/new")
Example #14
0
    def form(self, template=CAPTCHA_TMPL):
        """returns the captcha form"""
        if not self.use:
            return ""

        return template % captcha.displayhtml(self.public_key,
                                              use_ssl=self.use_ssl)
Example #15
0
    def get(self):
        """
        Logged in users not allowed here.
        """
        if self.get_current_user():
            return self.redirect("/")

        if options.disable_signups:
            return self.write("Sorry! Signups Are Closed.")

        # voucher key
        key_value = self.get_argument('key', '')

        promotions = Promotion.active()

        # If we're using mltshp-cdn.com, we know that we can use
        # https; if something else is configured, check the
        # X-Forwarded-Proto header and fallback to the protocol
        # of the request
        using_https = options.cdn_ssl_host == "mltshp-cdn.com" or \
            self.request.headers.get("X-Forwarded-Proto",
                self.request.protocol) == "https"

        #recaptcha hot fix
        if options.recaptcha_public_key:
            captcha_string = captcha.displayhtml(options.recaptcha_public_key,
                                                 use_ssl=using_https)
        else:
            captcha_string = ""
        return self.render("account/create.html",
                           name="",
                           email="",
                           key=key_value,
                           promotions=promotions,
                           recaptcha=captcha_string)
Example #16
0
 def change_password(self, check):
     """ """
     user = check_verify_remember(check)
     if user:
         g.chtml = ''
         chtml = captcha.displayhtml(
           public_key = "6Ldph8cSAAAAAGJK1OCZwgqWxctr6gS2FTCM3B1r",
           use_ssl = False,
           error = None)
         g.chtml = Markup(chtml)
         g.check = check
         if request.method == 'POST':
             valid = self.recaptcha()
             if valid:
                 new_password = request.form['new_password'] 
                 new_password_two = request.form['new_password_two'] 
                 if len(new_password) < 6:
                     message = g.users_msg('error_password_1')
                     status = 'msg msg-error'
                 elif new_password != new_password_two:
                     message = g.users_msg('error_password_2')
                     status = 'msg msg-error'
                 else:
                     g.db.users.update({"_id": user['_id']}, {"$set": { "password": create_password(new_password) } })
                     message = g.users_msg('success_update_password')
                     status = 'msg msg-success'
             else:
                 message = g.login_msg('captcha_error')
                 status = 'msg msg-error'
         return render_template('{}/change_password.html'.format(MODULE_DIR), **locals())
     else:
         message = g.login_msg('not_change_password')
         status = 'msg msg-error'
         return render_template('{}/verify.html'.format(MODULE_DIR), **locals())
Example #17
0
    def get(self, idr=None):
        try:
            r = Request.get_by_id(int(idr))
        except:
            r = None

        if r:  # request exists
            chtml = captcha.displayhtml(public_key=RECAPTCHA_PUBLIC_KEY,
                                        use_ssl=False,
                                        error=None)
            template_values = {
                'title': 'Request ' + str(r.key().id()),
                'title2': 'Modifying request',
                'description': r.description,
                'onload': 'document.request.e_pass.focus()',
                'request': r,
                'comments': r.get_comments(),
                'captcha': chtml,
                'admin': users.is_current_user_admin(),
                'logout': users.create_logout_url('/'),
                'lang': self.get_lang()
            }
            path = os.path.join(os.path.dirname(__file__),
                                'templates/modify_request.html')
            self.response.out.write(template.render(path, template_values))
        elif idr:  # request selected but not found
            self.redirect('/error/404')
        else:  # no request selected
            self.redirect('/new')
Example #18
0
    def get(self, ids=None):
        try:
            s = Stream.get_by_id(int(ids))
        except:
            s = None

        if s:  # stream exists
            chtml = captcha.displayhtml(public_key=RECAPTCHA_PUBLIC_KEY,
                                        use_ssl=False,
                                        error=None)
            template_values = {
                'title': 'Stream ' + str(s.key().id()),
                'title2': 'Modifying stream',
                'description': s.description,
                'onload': 'document.stream.e_pass.focus()',
                'stream': s,
                'captcha': chtml,
                'admin': users.is_current_user_admin(),
                'logout': users.create_logout_url('/'),
                'lang': self.get_lang()
            }
            path = os.path.join(os.path.dirname(__file__),
                                'templates/modify_stream.html')
            self.response.out.write(template.render(path, template_values))
        elif ids:  # stream selected but not found
            self.redirect('/error/404')
        else:  # no stream selected
            self.redirect('/new')
Example #19
0
 def get(self):
     Pagina.get(self)
     # el captcha
     if users.get_current_user():
         chtml = ""
     else:
         chtml = captcha.displayhtml(public_key=RECAPTCHA_PUBLIC_KEY, use_ssl=False, error=None)
     if self.request.get("tipo") == "pregunta":
         foco = "pregunta"
     elif self.request.get("tipo") == "enlace":
         foco = "enlace"
     else:
         foco = "pensamiento"
     template_values = {
         "titulo": "Publicar...",
         "descripcion": u"Formulario de publicación de Ubuntu FAQ. " + APP_DESCRIPTION,
         "tags": "ubuntu, kubuntu, xubuntu, lubuntu, problema, ayuda, linux, karmic, lucid, maverick, natty, ocelot",
         "url": self.url,
         "url_linktext": self.url_linktext,
         "mi_perfil": self.mi_perfil,
         "usuario": users.get_current_user(),
         "notis": self.get_notificaciones(),
         "formulario": self.formulario,
         "error_dominio": self.error_dominio,
         "captcha": chtml,
         "tipo": self.request.get("tipo"),
         "contenido": self.request.get("contenido"),
         "url2": self.request.get("url"),
         "foco": foco,
     }
     path = os.path.join(os.path.dirname(__file__), "templates/nueva.html")
     self.response.out.write(template.render(path, template_values))
Example #20
0
 def get_context_data(self, **kwargs):
     context_data = super(CBIReservationView, self).get_context_data(**kwargs)
     context_data['recaptcha_html'] = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)
     reservation = CBIReservation()
     reservation.product = self._product()
     context_data['object'] = reservation
     return context_data
Example #21
0
 def render(self, *args, **kwargs):
     from recaptcha.client import captcha as recaptcha
     custom_translations_str = ''
     if self.custom_translations:
         custom_translations_str = 'custom_translations : {\n'
         for key, value in self.custom_translations.items():
             custom_translations_str += '\n%s: "%s",' % (key, force_unicode(value))
         custom_translations_str = custom_translations_str[:-1]  # Remove the last comma
         custom_translations_str += '},'
     recaptcha_options = """
     <script>
         var RecaptchaOptions = {
             theme: '%s',
             lang: '%s',
             %s
             custom_theme_widget: '%s'
         };
     </script>
     """ % (
         self.theme,
         get_language()[0:2],
         custom_translations_str,
         'recaptcha_widget' if self.theme == 'custom' else ''
         )
     return mark_safe(recaptcha_options + recaptcha.displayhtml(self.public_key))
Example #22
0
    def displayhtml(self, use_ssl=False, error=None):
        """Return HTML string for inserting recaptcha into a form."""
	if not self._initialized:
		self._configure()

        from recaptcha.client.captcha import displayhtml
        return literal(displayhtml(self._public_key, use_ssl = use_ssl, error = error))
Example #23
0
    def get(self):
        """
        Logged in users not allowed here.
        """
        if self.get_current_user():
            return self.redirect("/")

        if options.disable_signups:
            return self.write("Sorry! Signups Are Closed.")

        # voucher key
        key_value = self.get_argument('key', '')

        promotions = Promotion.active()

        # Amazon's ELB will set this header to inform us what scheme is in use
        # Fallback to checking Tornado's protocol if it is absent
        using_https = self.request.headers.get(
            "X-Forwarded-Proto", self.request.protocol) == "https"

        #recaptcha hot fix
        captcha_string = captcha.displayhtml(options.recaptcha_public_key,
                                             use_ssl=using_https)
        return self.render("account/create.html",
                           name="",
                           email="",
                           key=key_value,
                           promotions=promotions,
                           recaptcha=captcha_string)
Example #24
0
  def post(self):
    if self.get_logged_in_person():
      p = self.get_logged_in_person() 
      challenge = self.request.get('recaptcha_challenge_field')
      response  = self.request.get('recaptcha_response_field')
      remoteip  = environ['REMOTE_ADDR']

      cResponse = captcha.submit(
                     challenge,
                     response,
                     recaptcha_keys.recaptcha_private_key,
                     remoteip)

      if cResponse.is_valid:
          # response was valid
          p.ishuman = True
          p.put()
          self.render('confirm')
      else:
        error = cResponse.error_code

        chtml = captcha.displayhtml(
          public_key = recaptcha_keys.recaptcha_public_key,
          use_ssl = False,
          error = cResponse.error_code)

        template_values = {
          'captchahtml': chtml
        }
        self.render('home', template_values)

    else:
      self.redirect('/')
Example #25
0
    def form(self, template=CAPTCHA_TMPL):
        """returns the captcha form"""
        if not self.use:
            return ""

        return template % captcha.displayhtml(self.public_key,
                                              use_ssl=self.use_ssl)
Example #26
0
def register(request):
    if request.method == "POST":
        if "recaptcha_challenge_field" in request.POST:
            check_captcha = captcha.submit(
                request.POST["recaptcha_challenge_field"],
                request.POST["recaptcha_response_field"],
                settings.RECAPTCHA_PRIVATE_KEY,
                request.META["REMOTE_ADDR"],
            )
            if not check_captcha.is_valid:
                messages.error(request, "Captcha didn't pan out! '%s'" % check_captcha.error_code)
                return HttpResponseRedirect(reverse("register"))

        form = RegisterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username, email, password = cd["username"], cd["email"], cd["password"]
            new_user = User.objects.create_user(username=username, email=email, password=password)
            profile = UserProfile.objects.create(user=new_user)
            messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)

            authed_user = authenticate(username=username, password=password)
            login(request, authed_user)
            return HttpResponseRedirect(reverse("profile"))
    else:
        form = RegisterForm()
    return render_to_response(
        "registration/register.html",
        {"form": form, "captcha": mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))},
        context_instance=RequestContext(request),
    )
Example #27
0
class WikiPageText(WikiPage):
    """Pages of mime type text/* use this for display."""
    def content_iter(self, lines):
        yield '<pre>'
        for line in lines:
            yield werkzeug.html(line)
        yield '</pre>'

    def plain_text(self):
        """
        Get the content of the page with all markup removed, used for
        indexing.
        """

        return self.storage.page_text(self.title)

    def view_content(self, lines=None):
        """
        Read the page content from storage or preview and return iterator.
        """

        if lines is None:
            f = self.storage.open_page(self.title)
            lines = self.storage.page_lines(f)
        return self.content_iter(lines)

    def render_editor(self, preview=None, captcha_error=None):
        """Generate the HTML for the editor."""

        _ = self.wiki.gettext
        author = self.request.get_author()
        lines = []
        try:
            page_file = self.storage.open_page(self.title)
            lines = self.storage.page_lines(page_file)
            (rev, old_date, old_author,
             old_comment) = self.storage.page_meta(self.title)
            comment = _(u'modified')
            if old_author == author:
                comment = old_comment
        except error.NotFoundErr:
            comment = _(u'created')
            rev = -1
        except error.ForbiddenErr, e:
            return werkzeug.html.p(werkzeug.html(unicode(e)))
        if preview:
            lines = preview
            comment = self.request.form.get('comment', comment)
        if captcha and self.wiki.recaptcha_public_key:
            recaptcha_html = captcha.displayhtml(
                self.wiki.recaptcha_public_key, error=captcha_error)
        else:
            recaptcha_html = None
        return self.template('edit_text.html',
                             comment=comment,
                             preview=preview,
                             recaptcha_html=recaptcha_html,
                             author=author,
                             parent=rev,
                             lines=lines)
Example #28
0
 def render(self, name, value, attrs=None):
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     html = u"<script type='text/javascript'>var RecaptchaOptions = {theme : \
            '%s'};</script>" % (
         final_attrs.get('theme', 'clean'))
     html += captcha.displayhtml(settings.RECAPTCHA_PUBLIC)
     return mark_safe(html)
Example #29
0
 def render(self, name, value, attrs=None):
     return mark_safe(
         u'%s' % captcha.displayhtml(
             settings.RECAPTCHA_PUBLIC_KEY,
             use_ssl=settings.RECAPTCHA_USE_SSL
         )
     )
Example #30
0
    def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs)
        error = final_attrs.get('error', None)
        html = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY, error=error, use_ssl=True)

        return mark_safe(u"""<script type="text/javascript">
        var RecaptchaOptions = {
            custom_translations : {
                instructions_visual : "%s",
                instructions_audio : "%s",
                play_again : "%s",
                cant_hear_this : "%s",
                visual_challenge : "%s",
                audio_challenge : "%s",
                refresh_btn : "%s",
                help_btn : "%s",
                incorrect_try_again : "%s",
            },
            theme : 'clean'
        };
        </script>
        %s
        """ % (_('Type the two words:'),
               _('Type what you hear:'),
               _('Play sound again'),
               _('Download sound as MP3'),
               _('Get a visual challenge'),
               _('Get an audio challenge'),
               _('Get a new challenge'),
               _('Help'),
               _('Incorrect. Try again.'),
                html))
Example #31
0
 def render(self, *args, **kwargs):
     from recaptcha.client import captcha as recaptcha
     recaptcha_options = u"<script> var RecaptchaOptions = { theme: '" + self.theme + \
                         "', lang: '" + get_language()[0:2] + \
                         ("', custom_theme_widget: 'recaptcha_widget'" if self.theme == 'custom' else "'") + " }; </script>\n"
     return mark_safe(recaptcha_options + recaptcha.displayhtml(
         self.public_key, use_ssl=self.use_ssl))
Example #32
0
 def GET(self):
     l.info('GET adduser')
     expire_cookie()
     cap = captcha.displayhtml(web.captcha_public_key,
                               use_ssl=True,
                               error="Something broke.")
     return render.adduser(cap)
Example #33
0
def register(request):
    if request.method == 'POST':
        if 'recaptcha_challenge_field' in request.POST:
            check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
            if not check_captcha.is_valid:
                messages.error(request, "Captcha was incorrect!") #% check_captcha.error_code)
                return HttpResponseRedirect(reverse('register'))

        form = RegisterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username,email,password = cd['username'], cd['email'], cd['password']   
            
            new_user = User.objects.create_user(username = username, email = email, password = password)  

            #TODO: fix this, weird postgres issue in django 1.3 see trac issue #15682
            user = User.objects.get(username=new_user.username)
            profile = UserProfile.objects.create(user=user)
            
            messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)
            
            authed_user = authenticate(username=username, password=password)
            login(request, authed_user)
            return HttpResponseRedirect(reverse('profile'))    
    else:
        form = RegisterForm(initial=request.POST)
    return render_to_response('registration/register.html', {
        'form': form,
        'captcha': mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)),
    }, context_instance=RequestContext(request))
Example #34
0
 def _new_captcha(self):
     captcha = self._get_recaptcha()
     if captcha == None: return
     myhtml = captcha.displayhtml(config.recaptcha_public_key,
                                  use_ssl=config.is_https(request))
     c.recaptcha_html = myhtml
     return myhtml
Example #35
0
    def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs)
        error = final_attrs.get('error', None)
        html = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                                   error=error,
                                   use_ssl=True)

        return mark_safe(u"""<script type="text/javascript">
        var RecaptchaOptions = {
            custom_translations : {
                instructions_visual : "%s",
                instructions_audio : "%s",
                play_again : "%s",
                cant_hear_this : "%s",
                visual_challenge : "%s",
                audio_challenge : "%s",
                refresh_btn : "%s",
                help_btn : "%s",
                incorrect_try_again : "%s",
            },
            theme : 'clean'
        };
        </script>
        %s
        """ % (_('Type the two words:'), _('Type what you hear:'),
               _('Play sound again'), _('Download sound as MP3'),
               _('Get a visual challenge'), _('Get an audio challenge'),
               _('Get a new challenge'), _('Help'), _('Incorrect. Try again.'),
               html))
Example #36
0
File: page.py Project: happytk/moin
 def render_editor(self, preview=None, captcha_error=None):
     _ = self.wiki.gettext
     author = self.request.get_author()
     if self.title in self.storage:
         comment = _(u'changed')
         (rev, old_date, old_author,
             old_comment) = self.storage.page_meta(self.title)
         if old_author == author:
             comment = old_comment
     else:
         comment = _(u'uploaded')
         rev = -1
     if captcha and self.wiki.recaptcha_public_key:
         recaptcha_html = captcha.displayhtml(
                 self.wiki.recaptcha_public_key, error=captcha_error)
     else:
         recaptcha_html = None
     context = {
         'comment': comment,
         'author': author,
         'parent': rev,
         'recaptcha_html': recaptcha_html,
         'help': self.get_edit_help(),
     }
     return self.template('edit_file.html', **context)
Example #37
0
 def render_editor(self, preview=None, captcha_error=None):
     _ = self.wiki.gettext
     author = self.request.get_author()
     if self.title in self.storage:
         comment = _('changed')
         (rev, old_date, old_author,
          old_comment) = self.storage.page_meta(self.title)
         if old_author == author:
             comment = old_comment
     else:
         comment = _('uploaded')
         rev = -1
     if captcha and self.wiki.recaptcha_public_key:
         recaptcha_html = captcha.displayhtml(
             self.wiki.recaptcha_public_key, error=captcha_error)
     else:
         recaptcha_html = None
     context = {
         'comment': comment,
         'author': author,
         'parent': rev,
         'recaptcha_html': recaptcha_html,
         'help': self.get_edit_help(),
     }
     return self.template('edit_file.html', **context)
Example #38
0
 def get(self, username):
     gexf = "twitter_com_"+username.lower()+".gexf"
     path = os.path.join("static", gexf)
     if os.path.exists(path):
         self.render("template/view-twitter.html", username=username, gexf=gexf)
     else:
         recaptcha = captcha.displayhtml(CONFIG.WEB.captcha_public_key)
         self.render("template/request-twitter.html", username=username, error=None, captcha=recaptcha)
Example #39
0
 def render(self, name, value, attrs=None):
     plugin = get_plugin('contactform')
     pubkey = plugin.get_config().get('rpubk', None)
     if pubkey:
         pubkey = pubkey.value
     else:
         pubkey = ''
     return captcha.displayhtml(pubkey)
Example #40
0
 def render(self, name, value, attrs=None):
     plugin = get_plugin('contactform')
     pubkey = plugin.get_config().get('rpubk', None)
     if pubkey:
         pubkey = pubkey.value
     else:
         pubkey = ''
     return captcha.displayhtml(pubkey)
Example #41
0
 def render(self, *args, **kwargs):
     conf = settings.RECAPTCHA_OPTIONS
     recaptcha_conf = ('<script type="text/javascript">' "var RecaptchaOptions = %s" "</script>") % json.dumps(conf)
     custom_widget_html = render_to_string("im/captcha.html", {"conf": "Bob"})
     return mark_safe(
         recaptcha_conf
         + custom_widget_html
         + captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY, use_ssl=settings.RECAPTCHA_USE_SSL)
     )
Example #42
0
def contacts(request):
    data = shared_context(request, tags=["contacts"])
    # load all pins without page (aka news)
    data["pins"] = Pin.objects.filter(language=data["language"], page__isnull=True).order_by("-id")

    # recaptcha settings
    public_key = settings.RECAPTCHA_PUBLIC_KEY
    script = displayhtml(public_key=public_key)

    return render_to_response("%s/contacts.html" % data["template"], {"script": script}, RequestContext(request, data))
Example #43
0
    def get(self):
        from recaptcha.client import captcha
        captcha_error_code = self.get_argument('captcha_error', None)

        captcha_html = captcha.displayhtml(
            public_key = configuration.RECAPTCHA_PUBLIC_KEY,
            use_ssl = False,
            error = captcha_error_code
            )
        self.render('feedback.html', captcha_html=captcha_html)
Example #44
0
 def render(self, *args, **kwargs):
     conf = settings.RECAPTCHA_OPTIONS
     recaptcha_conf = ('<script type="text/javascript">'
                       'var RecaptchaOptions = %s'
                       '</script>') % json.dumps(conf)
     custom_widget_html = render_to_string("im/captcha.html",
                                           {'conf': 'Bob'})
     return mark_safe(
         recaptcha_conf + custom_widget_html +
         captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                             use_ssl=settings.RECAPTCHA_USE_SSL))
Example #45
0
 def render(self, name, value, attrs=None):
     final_attrs = self.build_attrs(attrs)
     error = final_attrs.get('error', None)
     html = captcha.displayhtml(askbot_settings.RECAPTCHA_KEY, error=error)
     options = u',\n'.join([u'%s: "%s"' % (k, conditional_escape(v)) \
                for k, v in final_attrs.items() if k in self.options])
     return mark_safe(u"""<script type="text/javascript">
     var RecaptchaOptions = {
         %s
     };
     </script>
     %s
     """ % (options, html))
Example #46
0
 def recovery(self, fields={}):
     "забыли пароль"
     #self.baseurl = cherrypy.request.base
     # если нужна Captcha - сгенерим скрипт для вставки в шаблон
     if self.useCaptcha == 1:
         fields['CaptchaHtml'] = captcha.displayhtml(
             scfg.reCaptchaPublicKey, use_ssl=True)
     return self.drawTemplate(
         templ=forgot_passwd,
         data=[fields, {
             'baseurl': cherrypy.request.base
         }],
         draw_wo_login=True)
Example #47
0
 def render(self, *args, **kwargs):
     from recaptcha.client import captcha as recaptcha
     recaptcha_options = ("""<script type="text/javascript"> """
                          """var RecaptchaOptions = { theme: '%(theme)s', """
                             """lang: '%(language)s', """
                             """custom_theme_widget: '%(widget)s'}; """
                          """</script>\n"""%{
                 'theme': self.theme,
                 'language': get_language()[0:2],
                 'widget': ('recaptcha_widget' if self.theme == 'custom'
                            else '')})
     return mark_safe(recaptcha_options + 
                      recaptcha.displayhtml(self.public_key))
Example #48
0
def request_form(request):
    if request.method == 'POST':
        form = SessionRequestForm(request.POST)
    else:
        form = SessionRequestForm()

    html_captcha = "reCAPTCHA disabled"

    if settings.RECAPTCHA_ENABLED:
        html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)

    return render(request, 'request.html',
                  {'form': form, 'html_captcha': html_captcha})
Example #49
0
    def image_tag(self):
        lang = pref_lang()
        options = {
            "ca":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    custom_translations : {
                                            instructions_visual : "Escriu les dues paraules:",
                                            instructions_audio : "Transcriu el que sentis:",
                                            play_again : "Torna a escoltar l'\u00e0udio",
                                            cant_hear_this : "Descarrega la pista en MP3",
                                            visual_challenge : "Modalitat visual",
                                            audio_challenge : "Modalitat auditiva",
                                            refresh_btn : "Demana dues noves paraules",
                                            help_btn : "Ajuda",
                                            incorrect_try_again : "Incorrecte. Torna-ho a provar.",
                                    },
                                    lang : '%s',
                                    theme : 'clean'
                                };
                        </script>
                        """ % lang,
            "es":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang,
            "en":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang
        }

        if not self.settings.public_key:
            raise ValueError(
                'No recaptcha public key configured. Go to path/to/site/@@recaptcha-settings to configure.'
            )
        use_ssl = self.request['SERVER_URL'].startswith('https://')
        error = IRecaptchaInfo(self.request).error
        return options.get(lang, '') + displayhtml(
            self.settings.public_key, use_ssl=use_ssl, error=error)
Example #50
0
class UserProfileFormRegister(forms.Form):
    """
    User profile registration form.
    """

    REGISTRATION_REQUIRE_CAPTCHA = settings.REGISTRATION_REQUIRE_CAPTCHA
    RECAPTCHA_PUBLIC_KEY = settings.RECAPTCHA_PUBLIC_KEY
    RECAPTCHA_HTML = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY,
                                         use_ssl=settings.RECAPTCHA_USE_SSL)

    first_name = forms.CharField(widget=forms.TextInput(),
                                 required=True,
                                 max_length=255)
    last_name = forms.CharField(widget=forms.TextInput(),
                                required=False,
                                max_length=255)
    city = forms.CharField(widget=forms.TextInput(),
                           required=False,
                           max_length=255)
    country = forms.ChoiceField(widget=forms.Select(),
                                required=False,
                                choices=COUNTRIES,
                                initial='ZZ')
    organization = forms.CharField(widget=forms.TextInput(),
                                   required=False,
                                   max_length=255)
    home_page = forms.CharField(widget=forms.TextInput(),
                                required=False,
                                max_length=255)
    twitter = forms.CharField(widget=forms.TextInput(),
                              required=False,
                              max_length=255)

    recaptcha_challenge_field = forms.CharField(required=False, max_length=512)
    recaptcha_response_field = forms.CharField(
        max_length=100, required=settings.REGISTRATION_REQUIRE_CAPTCHA)

    def save_user_profile(self, new_user):
        """
        Creates and returns a new_user profile.
        """
        new_profile = \
            UserProfile(user=new_user, name=self.cleaned_data['first_name'],
                        city=self.cleaned_data['city'],
                        country=self.cleaned_data['country'],
                        organization=self.cleaned_data['organization'],
                        home_page=self.cleaned_data['home_page'],
                        twitter=self.cleaned_data['twitter'])
        new_profile.save()
        return new_profile
    def display_recaptcha(self, *args, **kwargs):
        public = "6Lf98eASAAAAAMARWX5AXv33iiHwS6E6I3tkVOFT"
        captcha_html = captcha.displayhtml(public,
                                           use_ssl=False,
                                           error="Something broke!")

        # You'll probably want to add error message handling here if you
        # have been redirected from a failed attempt
        return """
        <form action="validate">
        %s
        <input type=submit value="Submit Captcha Text" \>
        </form>
        """ % captcha_html
Example #52
0
    def get(self):
        (forum, siteroot,
         tmpldir) = forum_siteroot_tmpldir_from_url(self.request.path_info)
        if not forum or forum.is_disabled:
            return self.redirect("/")

        if not users.get_current_user():
            return self.redirect(users.create_login_url(self.request.url))

        ip = get_remote_ip()
        if ip in BANNED_IPS:
            return fake_error(self.response)

        self.send_cookie()

        rememberChecked = ""
        prevUrl = "http://"
        prevEmail = ""
        prevName = ""
        user = self.get_fofou_user()
        if user and user.remember_me:
            rememberChecked = "checked"
            prevUrl = user.homepage
            if not prevUrl:
                prevUrl = "http://"
            prevName = user.name
            prevEmail = user.email
        forum.title_or_url = forum.title or forum.url
        chtml = captcha.displayhtml(public_key=forum.recaptcha_public,
                                    use_ssl=False,
                                    error=None)
        tvals = {
            'siteroot': siteroot,
            'forum': forum,
            'captchahtml': chtml,
            'rememberChecked': rememberChecked,
            'prevUrl': prevUrl,
            'prevEmail': prevEmail,
            'prevName': prevName,
            'log_in_out': get_log_in_out(self.request.url)
        }
        topic_id = self.request.get('id')
        if topic_id:
            topic = db.get(db.Key.from_path('Topic', int(topic_id)))
            if not topic: return self.redirect(siteroot)
            tvals['prevTopicId'] = topic_id
            tvals['prevSubject'] = topic.subject
        tmpl = os.path.join(tmpldir, "post.html")
        self.template_out(tmpl, tvals)
Example #53
0
 def add_ip_in_black_list(self, ip):
     """ """
     g.chtml = ''
     value = time()
     black_ip = {
                 'ip' : ip,
               'time' : value
     }
     g.db.black_ip.insert(black_ip)
     if self.check_ip_in_black_list(ip):
         chtml = captcha.displayhtml(
           public_key = "6Ldph8cSAAAAAGJK1OCZwgqWxctr6gS2FTCM3B1r",
           use_ssl = False,
           error = None)
         g.chtml = Markup(chtml)
Example #54
0
def layout_submit(request):
    if request.method == 'POST':
        form = StationLayoutQuarantineForm(request.POST)
    else:
        form = StationLayoutQuarantineForm()

    html_captcha = "reCAPTCHA disabled"

    if settings.RECAPTCHA_ENABLED:
        html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)

    return render(request, 'layout_submit.html', {
        'form': form,
        'html_captcha': html_captcha
    })
Example #55
0
def register(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    email = request.POST.get('email', '')
    result = check_captcha(request)
    public_key = settings.RECAPTCHA_PUBLIC_KEY
    script = displayhtml(public_key=public_key)

    if result.is_valid:
        #Gravatar image
        #image = ''.join(['http://www.gravatar.com/avatar/',hashlib.md5(email).hexdigest(),'.jpg'])
        if User.objects.filter(username=username).count() == 0:
            try:
                validate_email(email)
                user = User.objects.create_user(username=username,
                                                email=email,
                                                password=password)
                user.save()
                user = auth.authenticate(username=username, password=password)
                if user is not None and user.is_active:
                    auth.login(request, user)
                    return HttpResponseRedirect("/")
                else:
                    return render_to_response(
                        'website_qanswr/login-register.html', {
                            'script': script,
                            "loginError": True
                        },
                        context_instance=RequestContext(request))
            except ValidationError:
                return render_to_response(
                    'website_qanswr/login-register.html', {
                        'script': script,
                        "invalidEmail": True
                    },
                    context_instance=RequestContext(request))
        else:
            return render_to_response('website_qanswr/login-register.html', {
                'script': script,
                "nameTaken": True
            },
                                      context_instance=RequestContext(request))
    else:
        return render_to_response('website_qanswr/login-register.html', {
            'script': script,
            "captchaFail": True
        },
                                  context_instance=RequestContext(request))
Example #56
0
def recaptcha_html():
    """Inserts a ReCaptcha widget, using settings.RECAPTCHA_PUBLIC_KEY.
    If that's not set, outputs an empty string.

    Usage:

    .. code-block:: html+django

      {% recaptcha_html %}

    """
    if not getattr(settings, 'RECAPTCHA_PUBLIC_KEY', None):
        return u''
    html = u'<script type="text/javascript">var RecaptchaOptions = {theme : "white"};</script>'
    html += captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)
    return html
Example #57
0
    def default(self, *args, **kwargs):
        if cherrypy.session.get("userid", None):
            raise cherrypy.HTTPRedirect("/")
        captcha_html = captcha.displayhtml(
            cherrypy.request.app.config["captcha"]["public"],
            use_ssl=False,
            error="Dadgummit")

        error = None
        if "error" in kwargs:
            error = kwargs["error"]

        if error in cherrypy.request.app.config["captcha errors"]:
            error = cherrypy.request.app.config["captcha errors"][error]

        return {"captcha": captcha_html, "error": error}
Example #58
0
    def POST_edit(self, page_name=''):
        i = web.input('spinner', recaptcha=False)
        spinner, recaptcha_p = i.spinner, i.recaptcha
        error_to_use = None
        if recaptcha_p:
            c = recaptcha.submit(i.recaptcha_challenge_field,
                                 i.recaptcha_response_field,
                                 os.environ['RECAPTCHA_PRIVKEY'], web.ctx.ip)
            if not c.is_valid: error_to_use = c.error_code
        i = auth.unspuninput(page_name,
                             'content',
                             'scroll_pos',
                             'caret_pos',
                             'current_revision',
                             save=False,
                             delete=False)
        page = db.get_page(page_name)
        content = re.sub(r'(\r\n|\r)', '\n', i.content)
        if (jt.site.security == 'open' and
                not auth.logged_in()) and (not recaptcha_p or error_to_use):
            captcha = recaptcha.displayhtml(os.environ['RECAPTCHA_PUBKEY'],
                                            use_ssl=True,
                                            error=error_to_use)
            timestamp, spinner, spinfield = auth.spinner(page_name)
            return render('captcha', vars=locals())
        if not page:
            db.new_page(page_name, content, i.scroll_pos, i.caret_pos)
            page = db.get_page(page_name)

        revision = db.get_revision(page.id)
        if i.current_revision and revision.revision != int(
                i.current_revision
        ) and not page.deleted and revision.content != content:
            timestamp, spinner, spinfield = auth.spinner(page_name)
            orig = db.get_revision(page.id, i.current_revision)
            diff = better_diff(orig.content, content)
            return render('edit_conflict', vars=locals())

        if i.delete and page_name:
            db.delete_page(page.id)
            return web.seeother(page.url)

        db.update_page(page.id, content, i.scroll_pos, i.caret_pos)
        if page.deleted:
            db.undelete_page(page.id, page_name)

        web.seeother(page.url)