Exemple #1
0
def pate_create():
    content = flask.request.form.get('content', None)
    if not content:
        flask.abort(400)

    try:
        timeout = int(flask.request.form.get('timeout', 60))
    except (ValueError, TypeError):
        return 'invalid "timeout" value', 400
    if timeout < 1:
        return 'timeout has to be greater than 0', 400

    # convert to minutes
    if timeout > 60 * 60 * 24 * 2:
        return 'timeout has to be smaller than 2 days', 400

    paste = Paste(content=content)
    paste.save(timeout)

    app.logger.info('page created by %s, size %s', flask.request.remote_addr,
                    len(paste.content))

    # context negotiation does not work well here
    user_agent = flask.request.headers.get('user-agent')
    if user_agent and user_agent.startswith('curl'):
        url = 'http://{}/{}\n'.format(flask.request.host, paste.key)
        return flask.Response(url, content_type='text/plain; charset=utf-8')

    return flask.redirect(flask.url_for('.paste_show', key=paste.key))
Exemple #2
0
def main(request):
    previous = request.POST.get('paste', '')
    
    if previous:
        try:
            import hashlib
            id = hashlib.md5(previous).hexdigest()
        except:
            import md5
            id = md5.new(previous).hexdigest()
        
        try:
            Paste.objects.get(url=id)
        except:
            p = Paste(content=previous, url=id)
            p.save()
        
        previous = 'http://%s/%s' % (request.get_host(), id)
            
    t = loader.get_template('index.html')
    c = Context({
        'previous': previous
    })
    
    return http.HttpResponse(t.render(c))
Exemple #3
0
def create(request):
    form = CreationForm(request.POST)
    if not form.is_valid():
        return render_to_response('pastebin/create.html', {
            'url': reverse(create),
            'form': form.as_ul(),
        }, RequestContext(request))

    paste = Paste(
        content=form.cleaned_data['content'],
        lang=form.cleaned_data['lang'],
    )
    paste.save()
    return HttpResponseRedirect(reverse(view, args=[paste.key]))
Exemple #4
0
def new(request):
    while True:
        paste_hash = "".join([random.choice(string.digits+string.ascii_lowercase)
                        for i in range(6)])
        try:
            Paste.objects.get(paste_hash=paste_hash)
        except Paste.DoesNotExist:
            paste = Paste(create_time=timezone.now(),
                        modified_time=timezone.now(), 
                        paste_hash=paste_hash)
            paste.save()
            return HttpResponseRedirect(reverse('paste:edit', args=(paste.paste_hash, )))
        else:
            pass
Exemple #5
0
def new(request):
    while True:
        paste_hash = "".join([
            random.choice(string.digits + string.ascii_lowercase)
            for i in range(6)
        ])
        try:
            Paste.objects.get(paste_hash=paste_hash)
        except Paste.DoesNotExist:
            paste = Paste(create_time=timezone.now(),
                          modified_time=timezone.now(),
                          paste_hash=paste_hash)
            paste.save()
            return HttpResponseRedirect(
                reverse('paste:edit', args=(paste.paste_hash, )))
        else:
            pass
Exemple #6
0
def create_paste(request):
    error_msg = u"No data sent."
    if request.method == "GET":
        get = request.GET.copy()
        if get.has_key('title') and get.has_key('text') and get.has_key('nickname') and get.has_key('exp_time'):
            ttl = get['title']
            txt = get['text']
            usr = get['nickname']

            try:
                exp = datetime.strptime(get['exp_time'],'%d/%m/%Y %H:%M')           
            except:
                msg = 2

            if len(txt) > 100000: # utf-8 100kB
                msg = 0
            else:
                p = Paste(randString(15),usr,ttl,txt,exp)
                p.save()
                msg = 1
            return HttpResponse(msg)
        else:
            error_msg = u"Insufficient data"
    return HttpResponseServerError(error_msg) 
Exemple #7
0
def new_paste(request, id=None):
    text_form = file_form = link_form = None

    if id:
        try:
            paste = Paste.objects.get(pk=id)
        except Paste.DoesNotExist:
            return HttpResponseRedirect(url('pastes.new'))
        parent = paste.parent or paste
    else:
        parent = paste = None

    if request.method == 'POST':
        paste_type = int(request.POST.get('type', 0))
        if paste_type == PASTE_TYPE_TEXT:
            text_form = PasteTextForm(request.POST, prefix="text")
            text_form.is_active = True
            form = text_form
        elif paste_type == PASTE_TYPE_FILE:
            file_form = PasteFileForm(request.POST, request.FILES, prefix="file")
            file_form.is_active = True
            form = file_form
        elif paste_type == PASTE_TYPE_LINK:
            link_form = PasteLinkForm(request.POST, prefix="link")
            link_form.is_active = True
            form = link_form
        if form.is_valid():
            key = form.cleaned_data['slug']
            if not key:
                length = 5
                while 1:
                    key = Paste.generate_key(length)
                    try:
                        Paste.objects.get(pk=key)
                    except Paste.DoesNotExist:
                        break
                    length += 1

            new_paste = Paste(
                id=key,
                parent=parent,
                type=paste_type,
                status=form.cleaned_data.get('public') and 1 or 0,
                title=form.cleaned_data.get('title', None),
                ip=request.META['REMOTE_ADDR'],
                author=request.user.is_authenticated() and request.user or None,
                group=request.group,
            )
            if form is text_form:
                new_paste.text = text_form.cleaned_data['text']
                if not text_form.cleaned_data['syntax']:
                    # Automatic detection
                    try:
                        lexer = lexers.guess_lexer(new_paste.text)
                        syntax = Syntax.objects.filter(lexer=lexer.__class__.__name__)[0:1].get()
                    except (Syntax.DoesNotExist, ClassNotFound), exc:
                        syntax = Syntax.objects.get(name="Plaintext")
                    new_paste.syntax = syntax
                else:
                    new_paste.syntax = text_form.cleaned_data['syntax']
            elif form is link_form:
                new_paste.text = link_form.cleaned_data['text']
            elif form is file_form:
                content = form.cleaned_data['file'].read()
                filename = form.cleaned_data['file'].name
                if not new_paste.title:
                    new_paste.title = filename
                if IMAGE_TYPES.search(filename):
                    new_paste.type = PASTE_TYPE_IMAGE
                else:
                    syntax = None
                    if len(content) < 1024*25: # 10 kb
                        try:
                            lexer = lexers.guess_lexer_for_filename(filename, content)
                            syntax = Syntax.objects.filter(lexer=lexer.__class__.__name__)[0:1].get()
                        except (Syntax.DoesNotExist, ClassNotFound):
                            pass
                    if syntax:
                        new_paste.syntax = syntax
                        new_paste.type = PASTE_TYPE_TEXT
                        new_paste.text = content
                new_paste.file.save(filename, form.cleaned_data['file'])
                request.session.setdefault('pastes', []).append(str(new_paste.id))
                request.session.save()
            new_paste.save()
            return HttpResponseRedirect(new_paste.get_absolute_url())
Exemple #8
0
def main(request):
    previous = request.POST.get('paste', '')

    user_name = ''

    user_name_post = request.POST.get('user_name', '')

    if 'user_name' in request.COOKIES :
        user_name = sanitize_username(request.COOKIES['user_name'])
    
    if user_name_post :
        user_name = sanitize_username(user_name_post)

    ucookie = False

    if previous:
        try:
            import hashlib
            hash = hashlib.md5(previous).hexdigest()
        except:
            import md5
            hash = md5.new(previous).hexdigest()

        id = None

        for idsize in range(1, len(hash) + 1) :
            useid = hash[0:idsize]

            try :
                Paste.objects.get(url=useid)
            except :
                id = useid
                break

        if id :
            id = 'p' + id
            p = Paste(content=previous, url=id)
            p.save()
        
        host = sanitize_nasty(request.get_host())
        if hasattr(settings, 'SIMPYL_SEARCH_PATH_OK') :
            if host.endswith('.' + settings.SIMPYL_SEARCH_PATH_OK) :
                host = host[0:-len(settings.SIMPYL_SEARCH_PATH_OK)-1]
        
        previous = 'http://%s/%s' % (host, id)

        if hasattr(settings, 'SIMPYL_PASTEBIN_ZMQ_URL') :
            import zmq
            ztx = zmq.Context()
            pub = ztx.socket(zmq.PUB)
            pub.connect(settings.SIMPYL_PASTEBIN_ZMQ_URL)

            if not user_name :
                try :
                    user_name = sanitize_username(request.META['HTTP_X_REAL_IP'])
                except :
                    user_name = request.META['REMOTE_ADDR']
            else :
                ucookie = user_name

            pub.send("action::paste by %s: %s" % (user_name, previous))
            
    t = loader.get_template('index.html')

    cdict = {
        'title': titl,
        'title_low': titl.lower(),
        'previous': previous,
        'user_name': user_name
    }

    if hasattr(settings, 'SIMPYL_PASTEBIN_NOTELINE') :
        cdict['noteline'] = settings.SIMPYL_PASTEBIN_NOTELINE

    if hasattr(settings, 'GA_ID') :
        cdict['GA_ID'] = settings.GA_ID

    c = Context(cdict)
    
    resp = http.HttpResponse(t.render(c))
    if ucookie :
        set_cookie(resp, 'user_name', ucookie, days_expire=365)
    return resp
def main(request):
    previous = request.POST.get("paste", "")

    user_name = ""

    user_name_post = request.POST.get("user_name", "")

    if "user_name" in request.COOKIES:
        user_name = sanitize_username(request.COOKIES["user_name"])

    if user_name_post:
        user_name = sanitize_username(user_name_post)

    ucookie = False

    if previous:
        if not user_name:
            try:
                user_name = sanitize_username(request.META["HTTP_X_REAL_IP"])
            except:
                user_name = request.META["REMOTE_ADDR"]
        else:
            ucookie = user_name

        title = to_ascii_lazy(request.POST.get("title", "untitled"))
        tsms = long(time.time() * 1000)

        hash_inputs = [previous.encode("utf-8"), user_name + "-" + str(tsms)]
        try:
            import hashlib

            hasher = lambda hash_input: hashlib.md5(hash_input).hexdigest()
        except:
            import md5

            hasher = lambda hash_input: md5.new(hash_input).hexdigest()

        hash = "".join([hasher(hash_input) for hash_input in hash_inputs])

        id = None

        for idsize in range(1, len(hash) + 1):
            useid = "p" + hash[0:idsize]

            try:
                Paste.objects.get(url=useid)
            except:
                id = useid
                break

        if id:
            p = Paste(content=previous, url=id, user_name=user_name, title=title, tsms=tsms)
            p.save()

            host = sanitize_nasty(request.get_host())
            if hasattr(settings, "SIMPYL_SEARCH_PATH_OK"):
                if host.endswith("." + settings.SIMPYL_SEARCH_PATH_OK):
                    host = host[0 : -len(settings.SIMPYL_SEARCH_PATH_OK) - 1]

            previous = "http://%s/%s" % (host, id)

            if hasattr(settings, "SIMPYL_PASTEBIN_ZMQ_URL"):
                import zmq

                ztx = zmq.Context()
                pub = ztx.socket(zmq.PUB)
                pub.connect(settings.SIMPYL_PASTEBIN_ZMQ_URL)

                zm_action = "action::paste '%s' by %s: %s" % (title, user_name, previous)
                pub.send(zm_action)

    cdict = {"title": titl, "title_low": titl.lower(), "previous": previous, "user_name": user_name}

    resp = shared_rr("index.html", cdict)

    if ucookie:
        set_cookie(resp, "user_name", ucookie, days_expire=365)
    return resp