Exemplo n.º 1
0
def show(ID):
    timestamp = request.args.get('timestamp')
    if timestamp is not None:
        timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp, showing=True)
    if k.exists():
        r = render_knowl(ID, footer="0", raw=True)
        title = k.title or "'%s'" % k.id
    else:
        if current_user.is_admin() and k.exists(allow_deleted=True):
            k = Knowl(ID, showing=True, allow_deleted=True)
            r = render_knowl(ID, footer="0", raw=True, allow_deleted=True)
            title = (k.title or "'%s'" % k.id) + " (DELETED)"
        else:
            return abort(404, "No knowl found with the given id")
    for elt in k.edit_history:
        # We will be printing these within a javascript ` ` string
        # so need to escape backticks
        elt['content'] = json.dumps(elt['content'])
    # Modify the comments list to add information on whether this user can delete
    if k.type != -2:
        for i, (cid, author, timestamp) in enumerate(k.comments):
            can_delete = (current_user.is_admin() or current_user.get_id() == author)
            author_name = userdb.lookup(author)["full_name"]
            k.comments[i] = (cid, author_name, timestamp, can_delete)
    b = get_bread([(k.category, url_for('.index', category=k.category)), ('%s' % title, url_for('.show', ID=ID))])

    return render_template(u"knowl-show.html",
                           title=title,
                           k=k,
                           cur_username=current_user.get_id(),
                           render=r,
                           bread=b)
Exemplo n.º 2
0
def content(ID, timestamp):
    if timestamp is not None:
        timestamp = timestamp_in_ms_to_datetime(timestamp)
    data = Knowl(ID, timestamp=timestamp).content
    resp = make_response(data)
    # cache and allow CORS
    resp.headers['Cache-Control'] = 'max-age=%d, public' % (_cache_time, )
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Exemplo n.º 3
0
def content(ID, timestamp):
    if timestamp is not None:
        timestamp = timestamp_in_ms_to_datetime(timestamp)
    data = Knowl(ID, timestamp=timestamp).content
    resp = make_response(data)
    # cache and allow CORS
    resp.headers['Cache-Control'] = 'max-age=%d, public' % (_cache_time,)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Exemplo n.º 4
0
Arquivo: main.py Projeto: LMFDB/lmfdb
def show(ID):
    timestamp = request.args.get('timestamp')
    if timestamp is not None:
        timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp, showing=True)
    if k.exists():
        r = render_knowl(ID, footer="0", raw=True)
        title = k.title or "'%s'" % k.id
        if not is_beta():
            if k.status == 0:
                title += " (awaiting review)"
            else:
                title += " (reviewed)"
    else:
        if current_user.is_admin() and k.exists(allow_deleted=True):
            k = Knowl(ID, showing=True, allow_deleted=True)
            r = render_knowl(ID, footer="0", raw=True, allow_deleted=True)
            title = (k.title or "'%s'" % k.id) + " (DELETED)"
        else:
            return abort(404, "No knowl found with the given id")
    for elt in k.edit_history:
        # We will be printing these within a javascript ` ` string
        # so need to escape backticks
        elt['content'] = json.dumps(elt['content'])
    # Modify the comments list to add information on whether this user can delete
    if k.type != -2:
        for i, (cid, author, timestamp) in enumerate(k.comments):
            can_delete = (current_user.is_admin() or current_user.get_id() == author)
            author_name = userdb.lookup(author)["full_name"]
            k.comments[i] = (cid, author_name, timestamp, can_delete)
    b = get_bread([(k.category, url_for('.index', category=k.category)), ('%s' % title, url_for('.show', ID=ID))])

    return render_template(u"knowl-show.html",
                           title=title,
                           k=k,
                           cur_username=current_user.get_id(),
                           render=r,
                           bread=b)
Exemplo n.º 5
0
def render_knowl(ID,
                 footer=None,
                 kwargs=None,
                 raw=False,
                 k=None,
                 allow_deleted=False,
                 timestamp=None):
    """
    this method renders the given Knowl (ID) to insert it
    dynamically in a website. It is intended to be used
    by an AJAX call, but should do a similar job server-side
    only, too.

    Note, that the used knowl-render.html template is *not*
    based on any globally defined website and just creates
    a small and simple html snippet!

    the keyword 'raw' is used in knowledge.show and knowl_inc to
    include *just* the string and not the response object.
    """
    # logger.debug("kwargs: %s", request.args)
    kwargs = kwargs or dict(((k, v) for k, v in request.args.items()))
    # logger.debug("kwargs: %s" , kwargs)
    if timestamp is None:
        # fetch and convert the ms timestamp to datetime
        try:
            timestamp = timestamp_in_ms_to_datetime(int(kwargs['timestamp']))
        except KeyError:
            pass

    if k is None:
        try:
            k = Knowl(ID, allow_deleted=allow_deleted, timestamp=timestamp)
        except Exception:
            logger.critical("Failed to render knowl %s" % ID)
            errmsg = "Sorry, the knowledge database is currently unavailable."
            return errmsg if raw else make_response(errmsg)

        # If we are rendering a reviewed knowl on nonbeta,
        # we always include the timestamp
        if timestamp is None and k.status == 1 and not is_beta():
            kwargs['timestamp'] = k.ms_timestamp

    # kw_params is inserted *verbatim* into the url_for(...) function inside the template
    # the idea is to pass the keyword arguments of the knowl further along the chain
    # of links, in this case the title and the permalink!
    # so, this kw_params should be plain python, e.g. "a=1, b='xyz'"
    kw_params = ', '.join(('%s="%s"' % (k, v) for k, v in kwargs.items()))
    logger.debug("kw_params: %s" % kw_params)

    # this is a very simple template based on no other template to render one single Knowl
    # for inserting into a website via AJAX or for server-side operations.
    if request.method == "POST":
        con = request.form['content']
        foot = footer or request.form['footer']
    elif request.method == "GET":
        con = request.args.get("content", k.content)
        foot = footer or request.args.get("footer", "1")

    # authors = []
    # for a in k.author_links():
    #  authors.append("<a href='%s'>%s</a>" %
    #    (url_for('users.profile', userid=a['_id']), a['full_name'] or a['_id'] ))
    # authors = ', '.join(authors)

    render_me = u"""\
  {%% include "knowl-defs.html" %%}
  {%% from "knowl-defs.html" import KNOWL with context %%}
  {%% from "knowl-defs.html" import KNOWL_LINK with context %%}
  {%% from "knowl-defs.html" import KNOWL_INC with context %%}
  {%% from "knowl-defs.html" import TEXT_DATA with context %%}

  <div class="knowl">"""
    if foot == "1":
        render_me += """\
  <div class="knowl-header">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s ) }}">%(title)s</a>
  </div>""" % {
            'ID': k.id,
            'title': (k.title or k.id),
            'kw_params': kw_params
        }

    render_me += """<div><div class="knowl-content">%(content)s</div></div>"""

    review_status = ""
    if foot == "1":
        render_me += """\
  <div class="knowl-footer">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s) }}">permalink</a>
    {%% if user_is_authenticated %%}
      &middot;
      <a href="{{ url_for('.edit', ID='%(ID)s') }}">edit</a>
    {%% endif %%}
    %(review_status)s
  </div>"""
        # """ &middot; Authors: %(authors)s """
        if k.status == 0 and k.type != -2:
            review_status = """&middot; (awaiting review)"""
    render_me += "</div>"
    # render_me = render_me % {'content' : con, 'ID' : k.id }
    con = md_preprocess(con)

    # markdown enabled
    render_me = render_me % {
        'content': md.convert(con),
        'ID': k.id,
        'review_status': review_status,
        'kw_params': kw_params
    }  #, 'authors' : authors }
    # Pass the text on to markdown.  Note, backslashes need to be escaped for
    # this, but not for the javascript markdown parser

    # logger.debug("rendering template string:\n%s" % render_me)

    # TODO improve the error message
    # so that the user has a clue. Most likely, the {{ KNOWL('...') }} has the wrong syntax!
    try:
        data = render_template_string(render_me, k=k, **kwargs)
        if raw:
            # note, this is just internally for the .show method, raw rendering
            # doesn't exist right now and will wrap this into a make_reponse!
            return data
        resp = make_response(data)
        # cache if it is a usual GET
        if request.method == 'GET':
            resp.headers['Cache-Control'] = 'max-age=%d, public' % (
                _cache_time, )
            resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
    except Exception as e:
        return "ERROR in the template: %s. Please edit it to resolve the problem." % e
Exemplo n.º 6
0
def demote(ID, timestamp):
    timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp)
    k.review(who=current_user.get_id(), set_beta=True)
    flash(Markup("Knowl %s has been returned to beta." % ID))
    return redirect(url_for(".show", ID=ID))
Exemplo n.º 7
0
def review(ID, timestamp):
    timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp)
    k.review(who=current_user.get_id())
    flash(Markup("Knowl %s has been positively reviewed." % ID))
    return redirect(url_for(".show", ID=ID))
Exemplo n.º 8
0
def render_knowl(ID, footer=None, kwargs=None,
        raw=False, k=None, allow_deleted=False, timestamp=None):
    """
    this method renders the given Knowl (ID) to insert it
    dynamically in a website. It is intended to be used
    by an AJAX call, but should do a similar job server-side
    only, too.

    Note, that the used knowl-render.html template is *not*
    based on any globally defined website and just creates
    a small and simple html snippet!

    the keyword 'raw' is used in knowledge.show and knowl_inc to
    include *just* the string and not the response object.
    """
    # logger.debug("kwargs: %s", request.args)
    kwargs = kwargs or dict(((k, v) for k, v in request.args.iteritems()))
    # logger.debug("kwargs: %s" , kwargs)
    if timestamp is None:
        # fetch and convert the ms timestamp to datetime
        try:
            timestamp = timestamp_in_ms_to_datetime(int(kwargs['timestamp']))
        except KeyError:
            pass

    if k is None:
        try:
            k = Knowl(ID, allow_deleted=allow_deleted, timestamp=timestamp)
        except Exception:
            logger.critical("Failed to render knowl %s"%ID)
            errmsg = "Sorry, the knowledge database is currently unavailable."
            return errmsg if raw else make_response(errmsg)

        # If we are rendering a reviewed knowl on nonbeta,
        # we always include the timestamp
        if timestamp is None and k.status == 1 and not is_beta():
            kwargs['timestamp'] = k.ms_timestamp;



    # kw_params is inserted *verbatim* into the url_for(...) function inside the template
    # the idea is to pass the keyword arguments of the knowl further along the chain
    # of links, in this case the title and the permalink!
    # so, this kw_params should be plain python, e.g. "a=1, b='xyz'"
    kw_params = ', '.join(('%s="%s"' % (k, v) for k, v in kwargs.iteritems()))
    logger.debug("kw_params: %s" % kw_params)

    # this is a very simple template based on no other template to render one single Knowl
    # for inserting into a website via AJAX or for server-side operations.
    if request.method == "POST":
        con = request.form['content']
        foot = footer or request.form['footer']
    elif request.method == "GET":
        con = request.args.get("content", k.content)
        foot = footer or request.args.get("footer", "1")

    # authors = []
    # for a in k.author_links():
    #  authors.append("<a href='%s'>%s</a>" %
    #    (url_for('users.profile', userid=a['_id']), a['full_name'] or a['_id'] ))
    # authors = ', '.join(authors)

    render_me = u"""\
  {%% include "knowl-defs.html" %%}
  {%% from "knowl-defs.html" import KNOWL with context %%}
  {%% from "knowl-defs.html" import KNOWL_LINK with context %%}
  {%% from "knowl-defs.html" import KNOWL_INC with context %%}
  {%% from "knowl-defs.html" import TEXT_DATA with context %%}

  <div class="knowl">"""
    if foot == "1":
        render_me += """\
  <div class="knowl-header">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s ) }}">%(title)s</a>
  </div>""" % {'ID': k.id, 'title': (k.title or k.id), 'kw_params': kw_params}

    render_me += """<div><div class="knowl-content">%(content)s</div></div>"""

    review_status = ""
    if foot == "1":
        render_me += """\
  <div class="knowl-footer">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s) }}">permalink</a>
    {%% if user_is_authenticated %%}
      &middot;
      <a href="{{ url_for('.edit', ID='%(ID)s') }}">edit</a>
    {%% endif %%}
    %(review_status)s
  </div>"""
        # """ &middot; Authors: %(authors)s """
        if k.status == 0 and k.type != -2:
            review_status = """&middot; (awaiting review)"""
    render_me += "</div>"
    # render_me = render_me % {'content' : con, 'ID' : k.id }
    con = md_preprocess(con)

    # markdown enabled
    render_me = render_me % {'content': md.convert(con), 'ID': k.id, 'review_status': review_status,
                             'kw_params': kw_params} #, 'authors' : authors }
    # Pass the text on to markdown.  Note, backslashes need to be escaped for
    # this, but not for the javascript markdown parser

    # logger.debug("rendering template string:\n%s" % render_me)

    # TODO improve the error message
    # so that the user has a clue. Most likely, the {{ KNOWL('...') }} has the wrong syntax!
    try:
        data = render_template_string(render_me, k=k, **kwargs)
        if raw:
            # note, this is just internally for the .show method, raw rendering
            # doesn't exist right now and will wrap this into a make_reponse!
            return data
        resp = make_response(data)
        # cache if it is a usual GET
        if request.method == 'GET':
            resp.headers['Cache-Control'] = 'max-age=%d, public' % (_cache_time,)
            resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
    except Exception, e:
        return "ERROR in the template: %s. Please edit it to resolve the problem." % e
Exemplo n.º 9
0
def demote(ID, timestamp):
    timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp)
    k.review(who=current_user.get_id(), set_beta=True)
    flash("Knowl %s has been returned to beta." % ID)
    return redirect(url_for(".show", ID=ID))
Exemplo n.º 10
0
def review(ID, timestamp):
    timestamp = timestamp_in_ms_to_datetime(timestamp)
    k = Knowl(ID, timestamp=timestamp)
    k.review(who=current_user.get_id())
    flash("Knowl %s has been positively reviewed." % ID)
    return redirect(url_for(".show", ID=ID))