Example #1
0
def dealWithArticle(request, post_id=0):
	'''
	если post_id = 0 => аргумент был не передан и мы создаем статью
	иначе редактируем статью с id = post_id
	надо будет прикрутить куки, чтобы... после редактирования статьи возвращать
	на страницу, откуда статья редактировалась.
	а после создания статьи возвращать страницу новосозданной статьи
	'''
	if post_id == 0:
		#добавление статьи
		mode = 0
	else:
		#редактирование статьи
		mode = 1
	try:
		article = Article.objects.get(pk = post_id)
		article_form = ArticleForm(instance = article)
		article = article_form.save(commit = False)
	except Article.DoesNotExist:
		article = Article()
		
		
	if request.POST:
		post = request.POST.copy()
		new_article_form = ArticleForm(post)
		if new_article_form.is_valid():
			new_article = new_article_form.save(commit = False)
			
			article.title = new_article.title
			article.bb_text = new_article.bb_text
			article.main_text = render_bbcode(new_article.bb_text)
			article.desc_text = render_bbcode(get_desc(new_article.bb_text))
			article.pub_date = timezone.now()
			article.is_big = is_big(article.main_text)
			
			article.save()
			return HttpResponseRedirect(reverse('blog.views.post',kwargs={'post_id':article.id}))
		else:
			return render_to_response('article_form.html',{'article_form': new_article_form, 
														   'mode':mode,
														   'url_ref': ref_for_article_form},
															context_instance=RequestContext(request))
	else:
		#добавляем статью
		if mode == 0:
			article_form = ArticleForm()
			return render_to_response('article_form.html',{'article_form': article_form,
													   'mode':mode,
													   'url_ref': ref_for_article_form},
														context_instance=RequestContext(request))
		if mode == 1:
			return render_to_response('article_form.html',{'article_form': article_form,
														   'mode':mode,
														   'url_ref': ref_for_article_form,
														   'article_id':article.id},
															context_instance=RequestContext(request))
Example #2
0
def post():
    conn = sqlite3.connect("posts.db")
    c = conn.cursor()
    ##universal dict to easen the coding
    ud = dict(request.args.items() +
                         request.form.items())
    q = "select author,title,post from posts where postid='"+ud["postID"]+"'"
    result=c.execute(q)
    op = "" ##op = original poster in interwebz talk
    title=""
    for r in result:
        op = "<td width='15%'>"+r[0]+"</td><td width='85%'>"+render_bbcode(r[2]).replace("\n","<br>")+"</td>"
        title=r[1]
    comments = []
    print request.method +"!!!!!!!!!!!!!!!\n\n\n"
    q = "select postid,commentid, comment, author from comments where postid='"+ud["postID"]+"'"
    result = c.execute(q)
    conn.commit()      
    for r in result:
        comments.append(r)
    print comments
    topic = ud["topic"]
    postid = ud["postID"]
    commentid=0 ##the current number of comments
    ##prepare the html string
    q = "select Count(*) from comments where postid='"+ud["postID"]+"'"
    commentid = c.execute(q)
    ##this just takes the first and only item.
    for i in commentid:
        commentid=i[0]

    if ("comment" in request.form):
        body = ud["body"]
        print "BODY: "+body
        author = ud["username"]
        if (author!="" and body!=""):
            q = '''insert into comments values("'''+postid+'''","'''+ str(commentid) +'''","'''+body+'''","'''+author+'''")'''
            c.execute(q)
            conn.commit()
            commentid+=1
    tablestr=""
    i=0
    while (i<commentid):
        q = "select comment, author from comments where postid='"+ud["postID"]+"' and commentid='"+str(i)+"'"
        result=c.execute(q)
        for item in result:
            tablestr=tablestr+"<tr><td>"+item[1]+"</td><td>"+render_bbcode(item[0]).replace("\n","<br>")+"</td><tr>"
        i+=1

    return render_template("post.html",comments=tablestr,topic=topic,postid=postid,op=op,title=title)
Example #3
0
 def render(self, data):
   # FIXME dirty hack
   # we do this because cleditor performs escaping of html entities (<, >, &, ...)
   # as this is unreliable and unsafe anyway (since it's javascript and can be overwritten by the user)
   # and render_bbcode performs the same escaping, we need to unescape it first
   data = HTMLParser.HTMLParser().unescape(data)
   return render_bbcode(data)
def index():
    base = get_base_vars()
    mems = get_members_by_rank()
    #news = requests.get("http://logunners.shivtr.com/news_entries.json")
    news = requests.get("https://raw.githubusercontent.com/mynameis7/League-of-Gunners-Flask-App/master/src/app/static/news_entries.json")
    print type(news.json())
    news_json = news.json()
    entries = news_json["news_entries"]
    for i in xrange(len(entries)):
        entry = entries[i]
        entry["entry"] = render_bbcode(entry["entry"])
        date = entry["created_at"]
        date = dt.strptime(date[0:-6], "%Y-%m-%dT%H:%M:%S.%f")
        date = date.strftime("%b %d, %Y")
        entry["date"] = date
    print len(entries)
    return render_template(template + "index.html",
                title='Home',
                                name=base["name"],
                                short_name=base["short"],
                                members=mems,
                                template=template,
                                news=entries,
                                member_ids=news_json["members"]
                )
Example #5
0
def blogedit(blogid):
    if 'logged_in' not in session:
        abort(403)
    if request.method == 'POST':
        title = request.form['title'].strip()
        text  = request.form['blogpost'].strip()

        error = 0
        if title == "":
            error = 1
            flash("You must make a title","error")
        if text == "":
            error = 1
            flash("You must make the blogpost","error")
        if 'Preview Blog' in request.form.values():
            renderedblog = render_bbcode(text)
            return render_template("blogedit.html",blogid=blogid,title=title,blogpost=text,recover=1,preview="1",renderedblog=renderedblog)
        if error:
            return render_template('blogedit.html',blogid=blogid,title=title,blogpost=text,recover=1)

        g.db.execute("""
UPDATE post SET title=?, text=?, lastedit=? WHERE id=?
""",(title,text,unixtime(),blogid))
        g.db.commit()
        flash("You successfully changed your blogpost","message")
        return redirect(url_for('blogpost',blogid=blogid))
    g.blog = query_db("""
SELECT * FROM post WHERE id=?
""", [str(blogid)], True,False)
    return render_template('blogedit.html',blogid=blogid)
Example #6
0
def bbcode(value):
    """
    Generates (X)HTML from string with BBCode "markup".
    By using the postmark lib from:
    @see: http://code.google.com/p/postmarkup/
    """ 
    return render_bbcode(value)
Example #7
0
def convert_text_to_html(text, markup):
    if markup == 'bbcode':
        text = render_bbcode(text)
    elif markup == 'markdown':
        text = markdown.markdown(text, safe_mode='escape')
    else:
        raise Exception('Invalid markup property: %s' % markup)
    return urlize(text)
Example #8
0
def convert_text_to_html(text, markup):
    if markup == 'bbcode':
        text = render_bbcode(text)
    elif markup == 'markdown':
        text = markdown.markdown(text, safe_mode='escape')
    else:
        raise Exception('Invalid markup property: %s' % markup)
    return urlize(text)
 def __call__(self, message):
     try:
         import postmarkup
     except ImportError:
         if not settings.DEBUG:
             return force_unicode(message).strip()
         raise
     return force_unicode(postmarkup.render_bbcode(message)).strip()
Example #10
0
    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.author = self.request.user

        instance.rendered_text = render_bbcode(form.cleaned_data['text'])

        instance.save()
        return redirect(reverse('detail_article', args=[instance.id]))
Example #11
0
def convert_text_to_html(text, markup):
    if markup == "bbcode":
        text = render_bbcode(text)
    elif markup == "markdown":
        text = markdown.markdown(text, safe_mode="escape")
    else:
        raise Exception("Invalid markup property: %s" % markup)
    return urlize(text)
Example #12
0
def render_markup(text):
    """Renders the given text as bbcode

    :param text: The text that should be rendered as bbcode
    """
    if flaskbb_config['MARKUP_TYPE'] == 'bbcode':
        return render_bbcode(text)
    elif flaskbb_config['MARKUP_TYPE'] == 'markdown':
        return render_markdown(text, extras=['tables'])
    return text
Example #13
0
def render_markup(text):
    """Renders the given text as bbcode

    :param text: The text that should be rendered as bbcode
    """
    if flaskbb_config['MARKUP_TYPE'] == 'bbcode':
        return render_bbcode(text)
    elif flaskbb_config['MARKUP_TYPE'] == 'markdown':
        return render_markdown(text, extras=['tables'])
    return text
Example #14
0
def editPost(request):
    if request.POST and request.POST.get('text') and request.GET.get('id'):
        id = int(request.GET.get('id'))
        post = Post.objects.get(id=id)
        post.text = request.POST.get('text')
        post.editor = request.user
        post.save()
        xhtml = render_bbcode(request.POST.get('text'))
        return HttpResponse(xhtml+"<br/><br/>Last edited by <a href='/users/"+request.user.username+"'>"+request.user.username+"</a> just now")
    return HttpResponse("")
Example #15
0
def query_db(query, args=(), one=False,renderbbcode=True):
    """Queries the database and returns a list of dictionaries."""
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    if rv and renderbbcode:
        for d in rv:
            if 'text' in d and 'title' in d:
                d['text'] = render_bbcode(unicode(d['text']))
    return (rv[0] if rv else None) if one else rv
Example #16
0
    def save(self, *args, **kwargs):
        if not self.created:
            self.created = datetime.now()

        if not self.uuid:
            self.uuid           = uuid()

        if not self.body_html:
            self.body_html      = render_bbcode(self.body)

        super(Post, self).save(*args, **kwargs)
Example #17
0
def convert_text_to_html(text, markup):
    if markup == 'bbcode':
        text = render_bbcode(text)
    elif markup == 'markdown':
        text = markdown.markdown(text, safe_mode='escape')
    else:
        raise Exception('Invalid markup property: %s' % markup)
    text = urlize(text)
    if forum_settings.NOFOLLOW_LINKS:
        text = add_rel_nofollow(text)
    return text
Example #18
0
def convert_text_to_html(text, markup):
    if markup == 'bbcode':
        text = render_bbcode(text)
    elif markup == 'markdown':
        text = markdown.markdown(text, safe_mode='escape')
    else:
        raise Exception('Invalid markup property: %s' % markup)
    text = urlize(text)
    if forum_settings.NOFOLLOW_LINKS:
        text = add_rel_nofollow(text)
    return text
def bbcode(value):
    """BBcode template filter
    
    Runs the passed text through the bbcode parser
        
    """
    
    try:
        return mark_safe(render_bbcode(value))
    except:
        return value
Example #20
0
    def save(self, *args, **kwargs):
        if not self.created:
            self.created = datetime.now()

        if not self.uuid:
            self.uuid = uuid()

        if not self.body_html:
            self.body_html = render_bbcode(self.body)

        super(Post, self).save(*args, **kwargs)
Example #21
0
def editdraft(draftid):
    if 'logged_in' not in session:
        abort(403)

    if request.method == "POST":
        blogpost = request.form['blogpost']

        title = request.form['title']
        if 'Preview Draft' in request.form.values():
            return render_template("editdraft.html",preview="1",renderedblog=render_bbcode(blogpost),title=title,blogpost=blogpost,recover=1)
        elif 'Submit Draft' in request.form.values():
            g.db.execute("""
UPDATE draft SET
title=?,
text=?,
lastedit=?
WHERE id=?
""",[title,blogpost,unixtime(),draftid])
            g.db.commit()
            flash("You have saved your draft","message")
            return redirect(url_for('drafts'))

        elif 'Publish Draft' in request.form.values():

            error = 0
            if title == "":
                error = 1
                flash("You must make a title","error")
            if blogpost == "":
                error = 1
                flash("You must make the blogpost","error")
            if error:
                return render_template('editdraft.html',title=title,blogpost=blogpost,recover=1)
            time_var = unixtime()
            g.db.execute("""
INSERT INTO post (title, text, removed,unixtime,views) VALUES (?,?,0,?,0)
""",(title,blogpost,time_var))
            g.db.commit()
            blogid = query_db("""SELECT id FROM post WHERE unixtime=?""",[time_var],True)['id']
            g.db.execute("""
DELETE FROM draft WHERE id=?
""",[draftid])
            g.db.commit()
            flash("You have published a draft","message")

            return redirect(url_for('blogpost',blogid=blogid))
            
    g.blog = query_db("""
SELECT * FROM draft WHERE id=? AND removed=0
""",[draftid],True,False)
            
    return render_template("editdraft.html")
Example #22
0
 def rendered_body(self):
     if not self.body_cache:
         # SMF seemed to half render the content before it went to the db.
         # Clean it up.
         body = self.body
         body = body.replace('<br />', '\n')
         body = body.replace('&nbsp;', ' ')
         body = body.replace('&quot;', "'")
         body = body.replace('&#039;', "'")
         body = body.replace('&amp;', '&')
         self.body_cache = render_bbcode(body)
         self.save()
     return self.body_cache
Example #23
0
def bbcode(value):
    """Generates (X)HTML from string with BBCode "markup".
    By using the postmark lib from:
    @see: http://code.google.com/p/postmarkup/
    """ 
    try:
        from postmarkup import render_bbcode
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
        return force_unicode(value)
    else:
        return mark_safe(render_bbcode(value))
Example #24
0
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        self.content_r = render_bbcode(self.content)

        if not self.slug:
            self.slug = slugify(self.title, instance=self)

        if self.pk:
            self.modified_at = datetime.now()
        else:
            self.created_at = datetime.now()

        super(Entry, self).save(
            force_insert, force_update, using, update_fields)
Example #25
0
def convert_bbcode_to_html(bbcode_content, escape=True, exclude_tags=()):
	'''
	Convert BBCode to HTML

	@type bbcode_content: str or unicode
	@param bbcode_content: the BBCode content

	@type escape: bool
	@param escape: whether escape '<', '>' and '"' to HTML entity

	@type exclude_tags: str or unicode
	@param exclude_tags: the BBCode tags which shouldn't be parsed
	'''
	return render_bbcode(bbcode_content, auto_urls=False, clean=False, exclude_tags=exclude_tags, escape=escape)
Example #26
0
def convert_bbcode_to_html(bbcode_content, escape=True, exclude_tags=()):
	'''
	将BBCode转换成HTML

	@type bbcode_content: str or unicode
	@param bbcode_content: 用于转换的BBCode内容

	@type escape: bool
	@param escape: 是否进行HTML实体转义

	@type exclude_tags: str or unicode
	@param exclude_tags: 不进行解析的BBCode标签
	'''
	return render_bbcode(bbcode_content, auto_urls=False, clean=False, exclude_tags=exclude_tags, escape=escape)
Example #27
0
def render_quote(input, strip=False):
	patterns = {
			'&[rl]dquo;': '"',
			'&lt;': '<',
			'&gt;': '>'
			}
	if strip:
		input = strip_bbcode(spoiler(input, True))
		for pat, repl in patterns.items():
			input = re.sub(pat, '', input)
	else:
		input = render_bbcode(spoiler(input))
		for pat, repl in patterns.items():
			input = re.sub(pat, repl, input)
	return input.strip()
Example #28
0
def bbcode(value):
    """
    Generates (X)HTML from string with BBCode "markup".
    By using the postmark lib from:
    @see: http://code.google.com/p/postmarkup/
    
    """
    try:
        from postmarkup import render_bbcode
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
        return force_unicode(value)
    else:
        return mark_safe(render_bbcode(value))
Example #29
0
def markup_parser(request):
    resp = Response()
    # markup preview helper
    resp.charset = 'utf-8'
    markup = request.GET.get('markup', 'textile')
    value = request.POST.get('data', '')
    if markup == 'textile':
        value = textile(value)
    elif markup == 'markdown':
        value = markdown.markdown(value)
    elif markup == 'bbcode':
        value = render_bbcode(value)
    if isinstance(value, unicode):
        value = value.encode('utf-8')
    resp.body = value
    return resp
Example #30
0
def markup_parser(request):
    resp = Response()
    # markup preview helper
    resp.charset = 'utf-8'
    markup = request.GET.get('markup', 'textile')
    value = request.POST.get('data', '')
    if markup == 'textile':
        value = textile(value)
    elif markup == 'markdown':
        value = markdown.markdown(value)
    elif markup == 'bbcode':
        value = render_bbcode(value)
    if isinstance(value, unicode):
        value = value.encode('utf-8')
    resp.body = value
    return resp
Example #31
0
def bbcode(value):
    """
    Generates (X)HTML from string with BBCode "markup".
    By using the postmark lib from:
    @see: http://code.google.com/p/postmarkup/

    """
    try:
        import postmarkup
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
        return force_unicode(value)
    else:
        postmarkup.LinkTag.annotate_link = lambda self, domain: u""
        return mark_safe(postmarkup.render_bbcode(value, paragraphs=True))
Example #32
0
def add_blog():
    if 'logged_in' in session:
        if not request.args.get("recover") == "1":
            return render_template("addpost.html")
        else:
            title = request.args.get('title')
            blogpost = request.args.get('blogpost')
            preview = request.args.get("preview")
            if preview == "1":
                renderedblog = render_bbcode(blogpost)
                return render_template("addpost.html",preview=preview,title=title,blogpost=blogpost,renderedblog=renderedblog)
            else:
                return render_template("addpost.html",preview=preview,title=title,blogpost=blogpost)

    else:
        return abort(403);
def application(environ, start_response):
    fs = OSFS(join(dirname(__file__), "static"))
    path = environ["PATH_INFO"]      
    if path in ("", "/"):        
        path = "index.html"
    if path == "/getbbcode":
        bbcode = unicode(environ["wsgi.input"].read(), 'utf-8')
        html = render_bbcode(bbcode, clean=True, paragraphs=True, render_unknown_tags=True)
        start_response("200 OK", [("Content-type", "text/html; charset=utf-8")])
        return [html.encode("utf-8")]
    mime_type, _encoding = mimetypes.guess_type(basename(path))
    if not fs.isfile(path):
        start_response("404 NOT FOUND", [])
        return ["Nobody here but us chickens: %s" % path]
    start_response("200 OK", [("Content-type", mime_type)])    
    return [fs.getcontents(path)]
Example #34
0
def ajax_edit(pid):
    if not check_login():
        return "False"

    token = session['token']

    nt = nordict.Nordict()

    message = request.form['message']

    postvar = {'message': message}

    path = "public/forums/post/{0}/edit".format(pid)
    call = nt.call_api(token, path, postvar).json()

    from postmarkup import render_bbcode
    return render_bbcode(call['data']['body'])
Example #35
0
def editabout():
    if "logged_in" not in session:
        abort(403)
    if request.method == "POST":
        blogpost = request.form['blogpost']
        if 'Preview Aboutpage' in request.form.values():
            return render_template("editabout.html",preview="1",renderedblog=render_bbcode(blogpost),blogpost=blogpost,recover=1)

        g.db.execute("""
UPDATE about SET text=?, unixtime=?
""",[blogpost,unixtime()])
        g.db.commit()
        flash("You have successfully edited the aboutpage","message")
        return redirect(url_for("about"))

    g.orig_about = query_db("""
SELECT text FROM about LIMIT 1
""",(),True)['text']
    return render_template("editabout.html")
Example #36
0
def application(environ, start_response):
    fs = OSFS(join(dirname(__file__), "static"))
    path = environ["PATH_INFO"]
    if path in ("", "/"):
        path = "index.html"
    if path == "/getbbcode":
        bbcode = unicode(environ["wsgi.input"].read(), 'utf-8')
        html = render_bbcode(bbcode,
                             clean=True,
                             paragraphs=True,
                             render_unknown_tags=True)
        start_response("200 OK",
                       [("Content-type", "text/html; charset=utf-8")])
        return [html.encode("utf-8")]
    mime_type, _encoding = mimetypes.guess_type(basename(path))
    if not fs.isfile(path):
        start_response("404 NOT FOUND", [])
        return ["Nobody here but us chickens: %s" % path]
    start_response("200 OK", [("Content-type", mime_type)])
    return [fs.getcontents(path)]
Example #37
0
 def __call__(self, environ, start_response):
     req = Request(environ)
     if '/markup_parser.html' in req.path_info:
         resp = Response()
         # markup preview helper
         resp.charset = 'utf-8'
         markup = req.GET.get('markup', 'textile')
         value = req.POST.get('data')
         if markup == 'textile':
             value = textile(value)
         elif markup == 'markdown':
             value = markdown.markdown(value)
         elif markup == 'bbcode':
             value = render_bbcode(value)
         if isinstance(value, unicode):
             value = value.encode('utf-8')
         resp.body = value
     else:
         resp = req.get_response(self.static_app)
     resp.headers['X-Salade'] = 'none'
     return resp(environ, start_response)
Example #38
0
 def __call__(self, environ, start_response):
     req = Request(environ)
     if '/markup_parser.html' in req.path_info:
         resp = Response()
         # markup preview helper
         resp.charset = 'utf-8'
         markup = req.GET.get('markup', 'textile')
         value = req.POST.get('data')
         if markup == 'textile':
             value = textile(value)
         elif markup == 'markdown':
             value = markdown.markdown(value)
         elif markup == 'bbcode':
             value = render_bbcode(value)
         if isinstance(value, unicode):
             value = value.encode('utf-8')
         resp.body = value
     else:
         resp = req.get_response(self.static_app)
     resp.headers['X-Salade'] = 'none'
     return resp(environ, start_response)
Example #39
0
 def render_bbcode(self, **kwargs):
     value = self.raw_value
     return value and render_bbcode(value) or ''
Example #40
0
def convert_text_to_html(text):
    text = render_bbcode(text, encoding='utf-8')
    text = text.replace('http:///', '/')
    if forum_settings.SMILES_SUPPORT:
        text = smiles(text)
    return urlize(text)
Example #41
0
 def markup(self, input):
     input = render_bbcode(input)
     return input
Example #42
0

def smile_it(str):
    s = str
    for smile, url in PYBB_SMILES.items():
        s = s.replace(
            smile, '<img src="%s%s%s" alt="smile" />' %
            (settings.STATIC_URL, PYBB_SMILES_PREFIX, url))
    return s


PYBB_MARKUP_ENGINES = getattr(
    settings, 'PYBB_MARKUP_ENGINES', {
        'bbcode':
        lambda str: urlize(
            smile_it(render_bbcode(str, exclude_tags=['size', 'center']))),
        'markdown':
        lambda str: urlize(smile_it(Markdown(safe_mode='escape').convert(str)))
    })

PYBB_QUOTE_ENGINES = getattr(
    settings, 'PYBB_QUOTE_ENGINES', {
        'bbcode':
        lambda text, username="": '[quote="%s"]%s[/quote]\n' %
        (username, text),
        'markdown':
        lambda text, username="": '>' + text.replace('\n', '\n>').replace(
            '\r', '\n>') + '\n'
    })

PYBB_MARKUP = getattr(settings, 'PYBB_MARKUP', 'bbcode')
Example #43
0
    ':)': 'smile.png',
    ':P': 'tongue.png',
    ';)': 'wink.png'
})

#MEDIA_URL = getattr(settings, 'MEDIA_URL', '/media/')
#STATIC_URL = getattr(settings, 'STATIC_URL', '')

def smile_it(str):
    s = str
    for smile, url in PYBB_SMILES.items():
        s = s.replace(smile, '<img src="%s%s%s" alt="smile" />' % (settings.STATIC_URL, PYBB_SMILES_PREFIX, url))
    return s

PYBB_MARKUP_ENGINES = getattr(settings, 'PYBB_MARKUP_ENGINES', {
    'bbcode': lambda str: urlize(smile_it(render_bbcode(str.strip(), exclude_tags=['size', 'center']))),
    'markdown': lambda str: urlize(smile_it(Markdown(safe_mode='escape').convert(str)))
})

PYBB_QUOTE_ENGINES = getattr(settings, 'PYBB_QUOTE_ENGINES', {
    'bbcode': lambda text, username="": '[quote="%s"]%s[/quote]\n' % (username, text),
    'markdown': lambda text, username="": '>'+text.replace('\n','\n>').replace('\r','\n>') + '\n'
})

PYBB_MARKUP = getattr(settings, 'PYBB_MARKUP', 'bbcode')
PYBB_BUTTONS = getattr(settings, 'PYBB_BUTTONS', {})
#Dict of buttons that will be used, instead of text links if defined
#Currently supported buttons:
#  new_topic
#  submit
#  save
Example #44
0
def bbcode(s):
    return mark_safe(render_bbcode(s))
def bbcode(text):
    from postmarkup import render_bbcode
    return render_bbcode(text)
Example #46
0
def render_markup(text):
    """Renders the given text as bbcode

    :param text: The text that should be rendered as bbcode
    """
    return render_bbcode(text)
Example #47
0
def render(markup, markup_type):

    markup = markup or ""

    if markup_type == "postmarkup":

        tag_data = {}
        html = post_render(markup,
                           paragraphs=True,
                           clean=True,
                           tag_data=tag_data)

        text = postmarkup.textilize(html)
        output = tag_data.get('output', {})
        sections = output.get("sections", {})
        for key, value in sections.items():
            sections[key] = [
                post_markup(s, paragraphs=True, clean=True) for s in value
            ]
        data = output

        summary_markup = output.get("summary", "")
        summary_html = ""
        if summary_markup.strip():
            summary = post_markup(output.get("summary", ""),
                                  paragraphs=True,
                                  clean=True)
            summary_html = summary

    elif markup_type == "emarkup":

        sections = extendedmarkup.parse(markup)

        html = extendedmarkup.chunks_to_html(sections['main'])
        summary_html = html
        text = postmarkup.textilize(html)
        data = dict(sections=sections)

    elif markup_type == "comment_bbcode":

        html = postmarkup.render_bbcode(markup, paragraphs=True, clean=True)
        text = postmarkup.textilize(html)
        return html, html, text, {}

    elif markup_type == "comment_wordpress":

        html = markup
        summary_html = html
        text = postmarkup.textilize(html)
        data = {}

    elif markup_type == "text":

        html = "<p>%s</p>" % postmarkup._escape(markup)
        summary_html = html
        text = postmarkup.textilize(markup)
        data = {}

    else:

        html = markup
        summary_html = html
        text = postmarkup.textilize(html)
        data = {}

    more_i = html.find('<!--more-->')
    if more_i == -1:
        more_i = html.find('<!-- more -->')

    if more_i != -1:
        summary_html = html[:more_i]
        summary_html = unicode(BeautifulSoup(summary_html))

    return html, summary_html, text, data
Example #48
0
 def process_html(self, archive, context, text, target, options):
     html = postmarkup.render_bbcode(text)
     return HTML(html)