Ejemplo n.º 1
0
def submit_contact_us_page(request):   
    errors = {}

    try:
        if request.method == 'POST':
            if (request.user.has_perm('CONTACT_US')):
                captcha_response = captcha.submit(request.POST.get('recaptcha_challenge_field', ''), 
                                                  request.POST.get('recaptcha_response_field', ''), 
                                                  settings.CAPTCHA_PRIVATE_KEY, 
                                                  request.META.get('REMOTE_ADDR', ''))
                                                  
            if not captcha_response.is_valid:
                errors['contact_us_captcha']="Invalid captcha text.  Try again!"
            else:
                contactUsForm = ContactUsForm(request.POST)
                
                if (contactUsForm.is_valid()):
                    name = purgeHtml(contactUsForm.cleaned_data.get('name'))
                    email = purgeHtml(contactUsForm.cleaned_data.get('email'))
                    subject = purgeHtml(contactUsForm.cleaned_data.get('subject'))
                    message = purgeHtml(contactUsForm.cleaned_data.get('message'))
                    
                    email = EmailMessage(subject, "\n".join((name, email, message)), settings.CONTACT_US_EMAIL, 
                                         [settings.CONTACT_US_EMAIL], [],
                                         headers= {'Reply-To': email})
                    
                    email.send(False)
                    return HttpResponseRedirect('/contact-us-success')
                else:
                    for attr, value in contactUsForm.errors.iteritems():
                        logger.info("Invalid contact-us form submitted: " + unicode(attr) + ": " + unicode(value))
                        errors[attr] = value                

    except smtplib.SMTPException:
        logger.error("Mail sending exception when submitting contact us page:") 
        logger.error(traceback.print_exc(8))
        messages.error("Sorry!  Reckonbot is having trouble with the Contact Us form.  I'm on it! - DK")               
    except Exception:
        logger.error("Exception when submitting contact us page:") 
        logger.error(traceback.print_exc(8))
        raise Exception 

    request.session['errors'] = errors    
    return HttpResponseRedirect('/contact-us')                
Ejemplo n.º 2
0
def post_content(request):
    
    if request.user.has_perm('POST_CONTENT'):  
        try:
            # Check to see if we're coming here from a POST.  If so, process it.  If not, give 'em a fresh form.
            if request.method == 'POST' :
                form = PostContentForm(request.POST, content_types=client_get_content_types(request.user.session_id).data,
                                                     media_types=client_get_media_types(request.user.session_id).data)
                
                # Check form validation -- kick the form back out with error messages if failed.
                valid = form.is_valid()
                if valid:
                    if (form.cleaned_data['content_type'] == "PODCAST"):
                        valid = False
                        media = Media(media_type=form.cleaned_data['media_type'],
                                      name=form.cleaned_data['name'],
                                      url=form.cleaned_data['url'],
                                      duration=form.cleaned_data['duration'])
                        
                        if (not media.url or not verifyUrl(media.url)):
                            messages.error(request, "Invalid or nonexistent podcast URL specified.", extra_tags='validation')
                        elif (not media.media_type and not media.media_type == 'AUDIO'):
                            messages.error(request, "Attached content needs to be audio.", extra_tags='validation')
                        elif (not media.name):
                            messages.error(request, "Podcast name needs to be specified.", extra_tags='validation')
                        elif (not media.duration):
                            messages.error(request, "Podcast duration needs to be specified.", extra_tags='validation')
                        else:
                            media.size = getUrlDownloadSize(media.url)
                            media.file_type = getUrlMimeType(media.url)
                            valid = True
                    else:
                        media = None
                            
                    if valid:
                        content=Content(content_type=(form.cleaned_data['content_type']),
                                            title=purgeHtml(form.cleaned_data['title']),
                                            body=(form.cleaned_data['body']),
                                            summary=(form.cleaned_data['summary']),
                                            tag_csv=purgeHtml(form.cleaned_data['tags']),
                                            submitter_id=request.user.reckoner_id,
                                            media_items=[media])
                    
                        # Submit to the API
                        response = client_post_content(content, request.user.session_id)
                        
                        # Check to see if the API submission was a success.  If not, clean the error and display.  Otherwise, great!
                        if not response.success:
                            logger.error("Error from post attempt: " + response.message)
                            raise Exception
                        else:                    
                            return HttpResponseRedirect('/blog')
            else:
                form = PostContentForm(content_types=client_get_content_types(request.user.session_id).data,
                                       media_types=client_get_media_types(request.user.session_id).data)
            
            c = RequestContext(request,{'form' : form,})
            return render_to_response('post-content.html', c)
        except Exception:      
            logger.error("Exception when showing and processing the Submit-Content form:") 
            logger.error(traceback.print_exc(8))
            raise Exception  
    else:
        return HttpResponseRedirect("/")      
Ejemplo n.º 3
0
def update_content_ajax(request):
    site_response = AjaxServiceResponse(success=False,
                                        message="whoops", 
                                        message_description='No go. Try again later.')
    
    if (request.user.has_perm('UPDATE_ALL_CONTENT')):
        try:
            if request.method == 'POST':
                content_id = (request.POST.get('content-id', None))
                
                commentary = sanitizeDescriptionHtml(request.POST.get('commentary', None))
                if (commentary):
                    commentary_user_id = request.user.reckoner_id
                else:
                    commentary_user_id = None                  
                
                title = purgeHtml(request.POST.get('title', None))
                body = request.POST.get('body', None)
                summary = request.POST.get('summary', None)
                tag_csv = purgeHtml(request.POST.get('tags', None))
                
                media_id = (request.POST.get('media-id', None))
                media_url = (request.POST.get('url', None))
                media_type = (request.POST.get('media-type', None))
                name = (request.POST.get('name', None))
                url = (request.POST.get('url', None))
                duration = (request.POST.get('duration', None))
                
                if ((commentary and len(commentary) > 3000) or (title and len(title) > 300) or 
                    (body and len(body) > 50000) or (tag_csv and len(tag_csv) > 200) or
                    (summary and len(summary) > 4000)):
                    site_response = AjaxServiceResponse(success=False,
                                                        message="too_long",
                                                        message_description="Saved field is too long.")  
                elif (url is not None) and not verifyUrl(url):
                    site_response = AjaxServiceResponse(success=False,
                                                        message="bad_media_url",
                                                        message_description="Specified Media URL is invalid.")  
                elif ((name is not None and name == "") or (duration is not None and duration == "")):
                    site_response = AjaxServiceResponse(success=False,
                                                        message="missing_required_field",
                                                        message_description="Missing Required Field.")                      
                    
                elif (content_id): 
                    if (media_id and url):
                        media_items = [Media(id = media_id,
                                      media_type=media_type,
                                      name=name,
                                      url=url,
                                      file_type=getUrlMimeType(url),
                                      duration=duration,
                                      size=getUrlDownloadSize(url))]
                    else:
                        media_items = None
                        
                    contentUpdate = Content(id=content_id, commentary=commentary, commentary_user_id=commentary_user_id, media_items=media_items,
                                                summary=summary, title=title, body=body, tag_csv=tag_csv)
                    
                    service_response = client_update_content(contentUpdate,
                                                          request.user.session_id)                    
                    
                    if (service_response.success):
                        site_response = AjaxServiceResponse(success=True,
                                                            message="success",
                                                            message_description="Updated!")
                
        except Exception:
            logger.error("Exception when updating content:") 
            logger.error(traceback.print_exc(8))    

    
    return HttpResponse(site_response.getXMLString())
Ejemplo n.º 4
0
def reckoning_approval_page(request):
    if request.user.has_perm('APPROVAL'):    
        try:
            reckoningQueueFormPrefix = "reckqueue"
            approveReckoningFormPrefix = "reckapp"
            errors={}
            
            if request.method == 'POST':
                if 'getreck' in request.POST:
                    pendingReckonings = client_get_reckoning_approval_queue(request.user.session_id)
                    reckoningQueueForm = ReckoningQueueForm(request.POST, prefix=reckoningQueueFormPrefix, 
                                                            reckonings=pendingReckonings.reckonings)
                    
                    if (reckoningQueueForm.is_valid()):
                        reckoningId = reckoningQueueForm.cleaned_data.get('pendingselect')
                        request.session["admin_approve_reckoning"] = reckoningId
                    else:
                        for attr, value in reckoningQueueForm.errors.iteritems():
                            errors[attr] = value
                                                      
                elif ('save' in request.POST) or ('approve' in request.POST):
                    approveReckoningForm = ApproveReckoningForm(request.POST, prefix=approveReckoningFormPrefix)
                    
                    if (approveReckoningForm.is_valid()):
                        if (approveReckoningForm.cleaned_data['edit_commentary']):
                            commentary = sanitizeDescriptionHtml(approveReckoningForm.cleaned_data['commentary'].strip())
                            commentary_user_id = request.user.reckoner_id
                        else:
                            commentary = settings.RECKONING_UPDATE_DELETE_SENTINEL
                            commentary_user_id = settings.RECKONING_UPDATE_DELETE_SENTINEL
                            
                        if (approveReckoningForm.cleaned_data['description']):
                            description = sanitizeDescriptionHtml(approveReckoningForm.cleaned_data['description'])
                        else:
                            description = settings.RECKONING_UPDATE_DELETE_SENTINEL
                            
                        answers = [Answer(index=0), Answer(index=1)]
                        for key, attr in approveReckoningForm.cleaned_data.iteritems():
                            if (key.startswith("answer")):
                                index = key.split('_')[1]
                                answers[int(index)-1].text = purgeHtml(attr)
                            elif (key.startswith("subtitle")):
                                index = key.split('_')[1]
                                answers[int(index)-1].subtitle = purgeHtml(attr)
                                
                        media = []
                        if (request.POST.get('attached-files', None)):
                            urls = request.POST.get('attached-files', None).split(";")
                            for url in urls:
                                media.append(parseReckoningImageFromUploadUrl(url))

                        savedReckoning=Reckoning(id=request.session["admin_approve_reckoning"],
                                                 question=purgeHtml(approveReckoningForm.cleaned_data['question']),
                                                 description=description,
                                                 answers=answers,
                                                 interval=approveReckoningForm.cleaned_data['interval'],
                                                 highlighted=approveReckoningForm.cleaned_data['highlighted'],
                                                 commentary=commentary,
                                                 commentary_user_id=commentary_user_id,
                                                 tag_csv=purgeHtml(approveReckoningForm.cleaned_data['tags']),
                                                 media_items=media)
                        
                        response = client_update_reckoning(savedReckoning, request.user.session_id)
                        if (not response.success):
                            logger.error("Error when updating a Reckoning: " + response.message)
                            messages.error(request, "Failed to save reckoning " + request.session["admin_approve_reckoning"])
                        else:
                            messages.info(request, "Saved reckoning " + request.session["admin_approve_reckoning"] + "!")
                    
                        if ('approve' in request.POST):
                            response = client_approve_reckoning(request.session["admin_approve_reckoning"], request.user.session_id)
                            if (not response.success):
                                logger.error("Error when approving a Reckoning: " + response.message)
                                messages.error(request, "Failed to approve reckoning " + request.session["admin_approve_reckoning"])
                            else:
                                messages.info(request, "Approved reckoning " + request.session["admin_approve_reckoning"] + "!")
                                request.session["admin_approve_reckoning"] = None
                    else:
                        for attr, value in approveReckoningForm.errors.iteritems():
                            errors[attr] = value
                    
                elif 'reject' in request.POST:
                    response = client_reject_reckoning(request.session["admin_approve_reckoning"], request.user.session_id)
                    if (not response.success):
                        logger.error("Error when rejecting a Reckoning: " + response.message)
                        messages.error(request, "Failed to approve reckoning " + request.session["admin_approve_reckoning"])
                    else:
                        messages.info(request, "Rejected reckoning " + request.session["admin_approve_reckoning"] + "!")
                        request.session["admin_approve_reckoning"] = None                                              
                        
            pendingReckonings = client_get_reckoning_approval_queue(request.user.session_id)
            reckoningQueueForm = ReckoningQueueForm(prefix=reckoningQueueFormPrefix, reckonings=pendingReckonings.reckonings)            
            
            currentReckoning = None
            approveReckoningForm = None
            postingUser = None
            reckoningId = request.session.get('admin_approve_reckoning', None)
            if (reckoningId):
                reckoningResponse = client_get_reckoning(reckoningId, request.user.session_id, True)
                if (reckoningResponse.status.success and len(reckoningResponse.reckonings) > 0):
                    currentReckoning=reckoningResponse.reckonings[0]
                    postingUser = reckonerauthbackend.get_user(request.user.session_id, currentReckoning.submitter_id)
                    approveReckoningForm = ApproveReckoningForm(prefix=approveReckoningFormPrefix,reckoning=currentReckoning)
                else:
                    request.session['admin_approve_reckoning'] = None
            
            c = RequestContext(request, {'reckoningQueueForm': reckoningQueueForm, 
                                         'approveReckoningForm' : approveReckoningForm,
                                         'currentReckoning' : currentReckoning,
                                         'postingUser' : postingUser,
                                         'errors' : errors})
            
            return render_to_response('approve_reckonings.html', c)            
            
        except Exception:      
            logger.error("Exception when rending reckoning approval screen:") 
            logger.error(traceback.print_exc(8))
            raise Exception
    else:
        return HttpResponseRedirect('/')