Exemple #1
0
def feed(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()
    cname = to_canonical(name)
    wiki_name = current_app.config['SITE_TITLE']
    start = 0
    length = int(request.args.get('length', 20))

    the_feed = AtomFeed(
        title="{} - Recent changes for page '{}'".format(wiki_name, cname),
        url=url_for('wiki.page', name=cname, _external=True),
        id="{}_pagefeed_{}".format(to_canonical(wiki_name), cname),
        feed_url=url_for('wiki.feed', name=cname, _external=True),
        generator=("Realms wiki", 'https://github.com/scragg0x/realms-wiki', __version__)
    )

    page = g.current_wiki.get_page(cname)
    items = list(itertools.islice(page.history, start, start + length))  # type: list[dict]

    for item in items:
        the_feed.add(
            title="Commit '{}'".format(item['sha']),
            content=item['message'],
            url=url_for('wiki.commit', name=name, sha=item['sha'], _external=True),
            id="{}/{}".format(item['sha'], cname),
            author=item['author'],
            updated=datetime.fromtimestamp(item['time'])
        )

    response = make_response((the_feed.to_string(), {'Content-type': 'application/atom+xml; charset=utf-8'}))
    response.add_etag()
    return response.make_conditional(request)
Exemple #2
0
def create(name):
    if request.method == 'POST':
        cname = to_canonical(request.form['name'])

        if cname in app.config['WIKI_LOCKED_PAGES']:
            return redirect(url_for("wiki.create"))

        if not cname:
            return redirect(url_for("wiki.create"))

        g.current_wiki.write_page(request.form['name'],
                                  request.form['content'],
                                  message=request.form['message'],
                                  create=True,
                                  username=current_user.username)
    else:
        cname = to_canonical(name) if name else ""
        if cname and g.current_wiki.get_page(cname):
            # Page exists, edit instead
            return redirect(url_for('wiki.edit', name=cname))

        g.assets['js'].append('editor.js')
        return render_template('wiki/edit.html',
                               name=cname,
                               content="",
                               info={})
Exemple #3
0
def edit(name):
    data = wiki.get_page(name)
    cname = to_canonical(name)
    if request.method == 'POST':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in config.LOCKED:
            return redirect(url_for(config.ROOT_ENDPOINT))

        if edit_cname.lower() != cname.lower():
            wiki.rename_page(cname, edit_cname)

        """
        wiki.write_page(edit_cname,
                        request.form['content'],
                        message=request.form['message'],
                        username=current_user.username)"""
    else:
        if data:
            name = remove_ext(data['name'])

            content = data.get('data')
            g.assets['js'].append('editor.js')
            return render_template('wiki/edit.html', name=name, content=content, partials=data.get('partials'))
        else:
            return redirect(url_for('wiki.create', name=cname))
Exemple #4
0
def edit(name):
    data = wiki.get_page(name)
    cname = to_canonical(name)
    if request.method == 'POST':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in config.LOCKED:
            return redirect(url_for(config.ROOT_ENDPOINT))

        if edit_cname.lower() != cname.lower():
            wiki.rename_page(cname, edit_cname)

        wiki.write_page(edit_cname,
                        request.form['content'],
                        message=request.form['message'],
                        username=current_user.username)
    else:
        if data:
            name = remove_ext(data['name'])

            content = data.get('data')
            g.assets['js'].append('editor.js')
            return render_template('wiki/edit.html',
                                   name=name,
                                   content=content,
                                   partials=data.get('partials'))
        else:
            return redirect(url_for('wiki.create', name=cname))
Exemple #5
0
def edit(name):
    data = g.current_wiki.get_page(name)
    cname = to_canonical(name)
    if request.method == 'POST':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in app.config['WIKI_LOCKED_PAGES']:
            return redirect(url_for(app.config['ROOT_ENDPOINT']))

        if edit_cname != cname.lower():
            g.current_wiki.rename_page(cname, edit_cname)

        g.current_wiki.write_page(edit_cname,
                                  request.form['content'],
                                  message=request.form['message'],
                                  username=current_user.username)
    else:
        if data:
            name = remove_ext(data['name'])
            content = data.get('data')
            g.assets['js'].append('editor.js')
            return render_template('wiki/edit.html',
                                   name=name,
                                   content=content,
                                   info=data.get('info'),
                                   sha=data.get('sha'),
                                   partials=data.get('partials'))
        else:
            return redirect(url_for('wiki.create', name=cname))
Exemple #6
0
def feed(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()
    cname = to_canonical(name)
    wiki_name = current_app.config['SITE_TITLE']
    start = 0
    length = int(request.args.get('length', 20))

    the_feed = AtomFeed(
        title="{} - Recent changes for page '{}'".format(wiki_name, cname),
        url=url_for('wiki.page', name=cname, _external=True),
        id="{}_pagefeed_{}".format(to_canonical(wiki_name), cname),
        feed_url=url_for('wiki.feed', name=cname, _external=True),
        generator=("Realms wiki", 'https://github.com/scragg0x/realms-wiki', __version__)
    )

    page = g.current_wiki.get_page(cname)
    items = list(itertools.islice(page.history, start, start + length))  # type: list[dict]

    for item in items:
        the_feed.add(
            title="Commit '{}'".format(item['sha']),
            content=item['message'],
            url=url_for('wiki.commit', name=name, sha=item['sha'], _external=True),
            id="{}/{}".format(item['sha'], cname),
            author=item['author'],
            updated=datetime.fromtimestamp(item['time'])
        )

    response = make_response((the_feed.to_string(), {'Content-type': 'application/atom+xml; charset=utf-8'}))
    response.add_etag()
    return response.make_conditional(request)
Exemple #7
0
def page_write(name):
    cname = to_canonical(name)

    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get("ALLOW_ANON") and current_user.is_anonymous():
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == "POST":
        # Create
        if cname in current_app.config.get("WIKI_LOCKED_PAGES"):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.write_page(
            cname,
            request.form["content"],
            message=request.form["message"],
            create=True,
            username=current_user.username,
            email=current_user.email,
        )

    elif request.method == "PUT":
        edit_cname = to_canonical(request.form["name"])

        if edit_cname in current_app.config.get("WIKI_LOCKED_PAGES"):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname.lower():
            g.current_wiki.rename_page(cname, edit_cname)

        sha = g.current_wiki.write_page(
            edit_cname,
            request.form["content"],
            message=request.form["message"],
            username=current_user.username,
            email=current_user.email,
        )

        return dict(sha=sha)

    else:
        # DELETE
        if cname in current_app.config.get("WIKI_LOCKED_PAGES"):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.delete_page(name, username=current_user.username, email=current_user.email)

    return dict(sha=sha)
Exemple #8
0
def page_write(name):
    cname = to_canonical(name)

    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(
    ):
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == 'POST':
        # Create
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.write_page(cname,
                                        request.form['content'],
                                        message=request.form['message'],
                                        create=True,
                                        username=current_user.username,
                                        email=current_user.email)

    elif request.method == 'PUT':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname.lower():
            g.current_wiki.rename_page(cname, edit_cname)

        sha = g.current_wiki.write_page(edit_cname,
                                        request.form['content'],
                                        message=request.form['message'],
                                        username=current_user.username,
                                        email=current_user.email)

        return dict(sha=sha)

    else:
        # DELETE
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.delete_page(name,
                                         username=current_user.username,
                                         email=current_user.email)

    return dict(sha=sha)
Exemple #9
0
def page_write(name):
    cname = to_canonical(name)

    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous():
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == 'POST':
        # Create
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.write_page(cname,
                                        request.form['content'],
                                        message=request.form['message'],
                                        create=True,
                                        username=current_user.username,
                                        email=current_user.email)

    elif request.method == 'PUT':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname:
            g.current_wiki.rename_page(cname, edit_cname)

        sha = g.current_wiki.write_page(edit_cname,
                                        request.form['content'],
                                        message=request.form['message'],
                                        username=current_user.username,
                                        email=current_user.email)

        return dict(sha=sha)

    elif request.method == 'DELETE':
        # DELETE
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.delete_page(cname,
                                         username=current_user.username,
                                         email=current_user.email)

    return dict(sha=sha)
Exemple #10
0
    def write_page(self, name, content, message=None, create=False, username=None, email=None):
        """Write page to git repo

        :param name: Name of page.
        :param content: Content of page.
        :param message: Commit message.
        :param create: Perform git add operation?
        :param username: Commit Name.
        :param email: Commit Email.
        :return: Git commit sha1.
        """

        cname = to_canonical(name)
        filename = cname_to_filename(cname)

        with open(self.path + "/" + filename, 'w') as f:
            f.write(content)

        if create:
            self.gittle.add(filename)

        if not message:
            message = "Updated %s" % name

        username, email = self._get_user(username, email)

        ret = self.gittle.commit(name=username,
                                 email=email,
                                 message=message,
                                 files=[filename])

        cache.delete(cname)

        return ret
Exemple #11
0
def _build_sidebar(path=""):
    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"
    # append always as first element the back link (go up by one level of directory)
    parts = path.split("/")
    # build the link for the back button in the sidebar
    back_link = "/_index/" + "/".join(parts[0:(len(parts) - 2)])
    sidebar = [dict(name='Back', dir=False, link=back_link)]
    # get the tree for the current directory (the files belonging to the current subdir plus the subdir of level 1)
    for item in _tree_index(items, path=path):
        name = ''
        link = ''
        # if we are analyzing a directory
        if item['dir']:
            # the name is the last word before the last '/' (we have to take the last but one because the returned name has the form /sub1/sub2/sub3/,
            # if we would take the last the result will be '')
            name = item["name"].split('/')[-2]
            # append the home keyword in order to redirect the user at tjhehomepage of the chosen subdir
            link = "/_index/" + item["name"]
        # if we are analyzing a file
        else:
            # the name i simly the last word after the last "/""
            name = item["name"].split('/')[-1]
            link = "/" + item["name"]
        sidebar.append(dict(name=name, dir=item['dir'], link=link))
    return sidebar
Exemple #12
0
def revert():
    cname = to_canonical(request.form.get('name'))
    commit = request.form.get('commit')
    message = request.form.get('message', "Reverting %s" % cname)

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(
    ):
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
        return dict(error=True, message="Page is locked"), 403

    try:
        sha = g.current_wiki.revert_page(cname,
                                         commit,
                                         message=message,
                                         username=current_user.username,
                                         email=current_user.email)
    except PageNotFound as e:
        return dict(error=True, message=e.message), 404

    if sha:
        flash("Page reverted")

    return dict(sha=sha)
Exemple #13
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    path = cname
    # get the path to the current file without its name
    if '/' in cname:
        path = cname[:cname.rfind("/")]
    # build the sidebar for the retreived path
    sidebar = _build_sidebar(path=path)
    # build the breadcrumb for the current page
    breadcrumb = _build_breadcrumb(rel_url=cname)

    if data:
        return render_template('wiki/page.html',
                               name=cname,
                               page=data,
                               sidebar=sidebar,
                               breadcrumb=breadcrumb,
                               partials=data.get('partials'),
                               path=path)
    else:
        abort(404)
Exemple #14
0
def add_source(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    page = g.current_wiki.get_page(cname)
    if not page:
        return redirect(url_for('wiki.page', name='home'))

    new_source = urllib.unquote_plus(request.args.get('source')).decode('utf8')
    if not new_source or not urlsplit(new_source).netloc == 'www.data.gouv.fr':
        return redirect(url_for('wiki.page', name=cname))
    lines = page.data.split('\n')
    content = """{}

::: source
{}
:::

{}
""".format("\n".join(lines[0:2]), new_source, "\n".join(lines[2:]))
    sha = page.write(content,
                     message='Add source automatically',
                     username=current_user.username,
                     email=current_user.email)

    return redirect(url_for('wiki.page', name=cname))
Exemple #15
0
    def write_page(self, name, content, message=None, create=False, username=None, email=None):
        """Write page to git repo

        :param name: Name of page.
        :param content: Content of page.
        :param message: Commit message.
        :param create: Perform git add operation?
        :param username: Commit Name.
        :param email: Commit Email.
        :return: Git commit sha1.
        """

        cname = to_canonical(name)
        filename = cname_to_filename(cname)

        with open(self.path + "/" + filename, 'w') as f:
            f.write(content)

        if create:
            self.gittle.add(filename)

        if not message:
            message = "Updated %s" % name

        username, email = self._get_user(username, email)

        ret = self.gittle.commit(name=username,
                                 email=email,
                                 message=message,
                                 files=[filename])

        cache.delete(cname)

        return ret
Exemple #16
0
def _build_sidebar(path = ""):
    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"
    # append always as first element the back link (go up by one level of directory)
    parts = path.split("/")
    # build the link for the back button in the sidebar
    back_link = "/_index/" + "/".join( parts[0:(len(parts) - 2)] )
    sidebar = [ dict(name = 'Back', dir = False, link = back_link) ]
    # get the tree for the current directory (the files belonging to the current subdir plus the subdir of level 1)
    for item in _tree_index(items, path=path):
        name = ''
        link = ''
        # if we are analyzing a directory 
        if item['dir']:
            # the name is the last word before the last '/' (we have to take the last but one because the returned name has the form /sub1/sub2/sub3/, 
            # if we would take the last the result will be '')
            name = item["name"].split('/')[-2]
            # append the home keyword in order to redirect the user at tjhehomepage of the chosen subdir
            link = "/_index/" + item["name"]
        # if we are analyzing a file
        else:
            # the name i simly the last word after the last "/""
            name = item["name"].split('/')[-1]
            link = "/" + item["name"]          
        sidebar.append(dict(name = name, dir = item['dir'], link = link))
    return sidebar   
Exemple #17
0
    def write_page(self, name, content, message=None, create=False, username=None, email=None):
        def escape_repl(m):
            if m.group(1):
                return "```" + escape(m.group(1)) + "```"

        def unescape_repl(m):
            if m.group(1):
                return "```" + unescape(m.group(1)) + "```"

        cname = to_canonical(name)

        # prevents p tag from being added, we remove this later
        content = "<div>" + content + "</div>"
        content = re.sub(r"```(.*?)```", escape_repl, content, flags=re.DOTALL)

        tree = lxml.html.fromstring(content)

        cleaner = Cleaner(remove_unknown_tags=False, kill_tags=set(["style"]), safe_attrs_only=False)
        tree = cleaner.clean_html(tree)

        content = lxml.html.tostring(tree, encoding="utf-8", method="html")

        # remove added div tags
        content = content[5:-6]

        # FIXME this is for block quotes, doesn't work for double ">"
        content = re.sub(r"(\n&gt;)", "\n>", content)
        content = re.sub(r"(^&gt;)", ">", content)

        # Handlebars partial ">"
        content = re.sub(r"\{\{&gt;(.*?)\}\}", r"{{>\1}}", content)

        # Handlebars, allow {{}} inside HTML links
        content = content.replace("%7B", "{")
        content = content.replace("%7D", "}")

        content = re.sub(r"```(.*?)```", unescape_repl, content, flags=re.DOTALL)

        filename = self.cname_to_filename(cname)
        with open(self.path + "/" + filename, "w") as f:
            f.write(content)

        if create:
            self.repo.add(filename)

        if not message:
            message = "Updated %s" % name

        if not username:
            username = self.default_committer_name

        if not email:
            email = self.default_committer_email

        ret = self.repo.commit(name=username, email=email, message=message, files=[filename])

        cache.delete(cname)

        return ret
Exemple #18
0
def create(name):
    cname = to_canonical(name) if name else ""
    if cname and g.current_wiki.get_page(cname):
        # Page exists, edit instead
        return redirect(url_for('wiki.edit', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html', name=cname, content="", info={})
Exemple #19
0
def create(name):
    cname = to_canonical(name) if name else ""
    if cname and g.current_wiki.get_page(cname):
        # Page exists, edit instead
        return redirect(url_for("wiki.edit", name=cname))

    g.assets["js"].append("editor.js")
    return render_template("wiki/edit.html", name=cname, content="", info={})
Exemple #20
0
def commit(name, sha):
    cname = to_canonical(name)

    data = wiki.get_page(cname, sha=sha)
    if data:
        return render_template('wiki/page.html', name=name, page=data, commit=sha)
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #21
0
def revert():
    name = request.form.get('name')
    commit = request.form.get('commit')
    cname = to_canonical(name)
    wiki.revert_page(name, commit, message="Reverting %s" % cname,
                     username=current_user.username)
    flash('Page reverted', 'success')
    return redirect(url_for('wiki.page', name=cname))
Exemple #22
0
def commit(name, sha):
    cname = to_canonical(name)

    data = g.current_wiki.get_page(cname, sha=sha)

    if not data:
        abort(404)

    return render_template('wiki/page.html', name=name, page=data, commit=sha)
Exemple #23
0
def commit(name, sha):
    cname = to_canonical(name)

    data = g.current_wiki.get_page(cname, sha=sha)

    if not data:
        abort(404)

    return render_template('wiki/page.html', name=name, page=data, commit=sha)
Exemple #24
0
def index(path):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"

    return render_template('wiki/index.html', index=_tree_index(items, path=path), path=path)
Exemple #25
0
def page(name):
    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)
    if data:
        return render_template('wiki/page.html', name=cname, page=data, partials=data.get('partials'))
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #26
0
def create(name):
    cname = to_canonical(name) if name else ""
    if cname and g.current_wiki.get_page(cname):
        # Page exists, edit instead
        return redirect(url_for('wiki.edit', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html',
                           name=cname + '/',
                           content="",
                           info={})
Exemple #27
0
def commit(name, sha):
    cname = to_canonical(name)

    data = wiki.get_page(cname, sha=sha)
    if data:
        return render_template('wiki/page.html',
                               name=name,
                               page=data,
                               commit=sha)
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #28
0
def index(path):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"

    return render_template('wiki/index.html',
                           index=_tree_index(items, path=path),
                           path=path)
Exemple #29
0
def commit(name, sha):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)

    data = g.current_wiki.get_page(cname, sha=sha)

    if not data:
        abort(404)

    return render_template('wiki/page.html', name=name, page=data, commit=sha)
Exemple #30
0
def index(path):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"
        items = filter(lambda x: x['name'].startswith(path), items)
    if not request.args.get('flat', '').lower() in ['yes', '1', 'true']:
        items = _tree_index(items, path=path)

    return render_template('wiki/index.html', index=items, path=path)
Exemple #31
0
def commit(name, sha):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)

    data = g.current_wiki.get_page(cname, sha=sha)

    if not data:
        abort(404)

    return render_template('wiki/page.html', name=name, page=data, commit=sha)
Exemple #32
0
def index(path):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"
        items = filter(lambda x: x['name'].startswith(path), items)
    if not request.args.get('flat', '').lower() in ['yes', '1', 'true']:
        items = _tree_index(items, path=path)

    return render_template('wiki/index.html', index=items, path=path)
Exemple #33
0
def page(name):
    cname = to_canonical(name)
    print("Name: %s, cname: %s" % (name, cname))
    if cname != name:
        return redirect(url_for("wiki.page", name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        return render_template("wiki/page.html", name=cname, page=data, partials=data.get("partials"))
    else:
        return redirect(url_for("wiki.create", name=cname))
Exemple #34
0
def upload(name):
    page_cname = to_canonical(name)
    page = g.current_wiki.get_page(page_cname)

    front_matter = page.get_front_matter() if page else {}

    if "attachments" in front_matter.keys():
        attachments = front_matter["attachments"]
    else:
        attachments = []

    S3_ACCESS_KEY = current_app.config.get('S3_ACCESS_KEY')
    S3_SECRET_KEY = current_app.config.get('S3_SECRET_KEY')
    S3_BUCKET = current_app.config.get('S3_BUCKET')

    bucket_name = S3_BUCKET
    s3 = boto3.client("s3",
                      aws_access_key_id=S3_ACCESS_KEY,
                      aws_secret_access_key=S3_SECRET_KEY)

    for key, f in request.files.iteritems():
        if key.startswith('file'):
            filename = f.filename

            file_folder = datetime.strftime(datetime.utcnow(),
                                            "%Y%m%d%H%M") + "_" + str(
                                                shortuuid.uuid())[:6]
            file_key = "wiki/files/" + file_folder + "/" + filename

            attachments.append({
                "filename": str(filename),
                "handler": "S3",
                "key": str(file_key)
            })

            s3.upload_fileobj(f, bucket_name, file_key)

    front_matter["attachments"] = attachments

    # Get page again to reduce odds of race condition issue
    page = g.current_wiki.get_page(page_cname)

    page_content = page.data if page else ""

    page_content = page.update_front_matter(page_content, front_matter)

    sha = page.write(page_content,
                     message="Attached file to " + page_cname,
                     username=current_user.username,
                     email=current_user.email)

    return "Success"
Exemple #35
0
def revert():
    name = request.form.get('name')
    commit = request.form.get('commit')
    cname = to_canonical(name)

    if cname in config.LOCKED:
        flash("Page is locked")
        return redirect(url_for(config.ROOT_ENDPOINT))

    wiki.revert_page(name, commit, message="Reverting %s" % cname,
                     username=current_user.username)
    flash('Page reverted', 'success')
    return redirect(url_for('wiki.page', name=cname))
Exemple #36
0
def create(name):
    if request.method == 'POST':
        cname = to_canonical(request.form['name'])

        if cname in config.LOCKED:
            return redirect(url_for("wiki.create"))

        if not cname:
            return redirect(url_for("wiki.create"))

        wiki.write_page(request.form['name'],
                        request.form['content'],
                        message=request.form['message'],
                        create=True,
                        username=current_user.username)
    else:
        cname = to_canonical(name) if name else ""
        if cname and wiki.get_page(cname):
            # Page exists, edit instead
            return redirect(url_for('wiki.edit', name=cname))

        g.assets['js'].append('editor.js')
        return render_template('wiki/edit.html', name=cname, content="")
Exemple #37
0
def page(name):
    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = wiki.get_page(cname)

    if data:
        return render_template('wiki/page.html',
                               name=cname,
                               page=data,
                               partials=data.get('partials'))
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #38
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        return render_template('wiki/page.html', name=cname, page=data, partials=data.get('partials'))
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #39
0
    def get_page(self, name, sha='HEAD'):
        """Get page data, partials, commit info.

        :param name: Name of page.
        :param sha: Commit sha.
        :return: dict

        """
        cached = cache.get(name)
        if cached:
            return cached

        # commit = gittle.utils.git.commit_info(self.repo[sha])
        filename = cname_to_filename(name).encode('latin-1')
        sha = sha.encode('latin-1')

        namespace_path = os.path.join(self.path, os.path.splitext(filename)[0])
        namespace_cname = to_canonical(os.path.splitext(filename)[0])
        if not os.path.exists(os.path.join(
                self.path, filename)) and os.path.isdir(namespace_path):
            files = [
                "[%s](%s_%s)" % (x, namespace_cname, filename_to_cname(x))
                for x in os.listdir(namespace_path)
            ]
            print(files)
            return {
                'data':
                "# Namespace %s \n\n This is an automatically generated list of pages in this namespace.\n\n %s"
                % (os.path.splitext(filename)[0], '\n'.join(files))
            }

        try:
            data = self.gittle.get_commit_files(sha,
                                                paths=[filename]).get(filename)
            if not data:
                return None
            partials = {}
            if data.get('data'):
                meta = self.get_meta(data['data'])
                if meta and 'import' in meta:
                    for partial_name in meta['import']:
                        partials[partial_name] = self.get_page(partial_name)
            data['partials'] = partials
            data['info'] = self.get_history(name, limit=1)[0]

            return data

        except KeyError:
            # HEAD doesn't exist yet
            return None
Exemple #40
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(cname)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html',
                           name=cname,
                           content=page.get('data'),
                           info=page.get('info'),
                           sha=page.get('sha'),
                           partials=page.get('partials'))
Exemple #41
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        return render_template('wiki/page.html', name=cname, page=data,
                               partials=_partials(data.imports))
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #42
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(cname)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html',
                           name=cname,
                           content=page.data,
                           # TODO: Remove this? See #148
                           info=next(page.history),
                           sha=page.sha)
Exemple #43
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(cname)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html',
                           name=cname,
                           content=page.get('data'),
                           info=page.get('info'),
                           sha=page.get('sha'),
                           partials=page.get('partials'))
Exemple #44
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(cname)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    g.assets['js'].append('editor.js')
    return render_template('wiki/edit.html',
                           name=cname,
                           content=page.data.decode(),
                           # TODO: Remove this? See #148
                           info=next(page.history),
                           sha=page.sha)
Exemple #45
0
def revert():
    name = request.form.get('name')
    commit = request.form.get('commit')
    cname = to_canonical(name)

    if cname in config.LOCKED:
        flash("Page is locked")
        return redirect(url_for(config.ROOT_ENDPOINT))

    wiki.revert_page(name,
                     commit,
                     message="Reverting %s" % cname,
                     username=current_user.username)
    flash('Page reverted', 'success')
    return redirect(url_for('wiki.page', name=cname))
Exemple #46
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(name)

    if not page:
        # Page doesn't exist
        return redirect(url_for("wiki.create", name=cname))

    name = remove_ext(page["name"])
    g.assets["js"].append("editor.js")
    return render_template(
        "wiki/edit.html",
        name=name,
        content=page.get("data"),
        info=page.get("info"),
        sha=page.get("sha"),
        partials=page.get("partials"),
    )
Exemple #47
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(name)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    name = remove_ext(page['path'])
    g.assets['js'].append('editor.js')
    # get the list of the images present in the current page
    img_list = re.findall("src\s*=\s*'(.+?)'", page.get('data'))
    return render_template('wiki/edit.html',
                           name=name,
                           content=page.get('data'),
                           info=page.get('info'),
                           sha=page.get('sha'),
                           partials=page.get('partials'),
                           img_list=img_list)
Exemple #48
0
def edit(name):
    cname = to_canonical(name)
    page = g.current_wiki.get_page(name)

    if not page:
        # Page doesn't exist
        return redirect(url_for('wiki.create', name=cname))

    name = remove_ext(page['path'])
    g.assets['js'].append('editor.js')
    # get the list of the images present in the current page
    img_list = re.findall("src\s*=\s*'(.+?)'", page.get('data'))
    return render_template('wiki/edit.html',
                           name=name,
                           content=page.get('data'),
                           info=page.get('info'),
                           sha=page.get('sha'),
                           partials=page.get('partials'),
                           img_list=img_list)
Exemple #49
0
def filedata(name):
    page_cname = to_canonical(name)
    page = g.current_wiki.get_page(page_cname)

    file_key = request.form['pk']
    attr_name = request.form['name']
    value = request.form['value']

    if attr_name == "description":
        front_matter = page.get_front_matter() if page else {}

        if "attachments" in front_matter.keys():
            attachments = front_matter["attachments"]
        else:
            attachments = []

        found_key = False
        updated_attachments = []

        for attachment in attachments:
            if file_key == attachment.get("key"):
                attachment["description"] = value
                found_key = True

            updated_attachments.append(attachment)

        front_matter["attachments"] = updated_attachments

        page_content = page.data if page else ""
        page_content = page.update_front_matter(page_content, front_matter)

        sha = page.write(page_content,
                         message="Updated file data for " + file_key,
                         username=current_user.username,
                         email=current_user.email)

        return value
    else:
        # In the future this endpoint can be used to edit filenames (only the
        # key needs to stay the same) or other file attributes.
        raise NotImplementedError
Exemple #50
0
    def get_page(self, name, sha='HEAD'):
        """Get page data, partials, commit info.

        :param name: Name of page.
        :param sha: Commit sha.
        :return: dict

        """
        cached = cache.get(name)
        if cached:
            return cached

        # commit = gittle.utils.git.commit_info(self.repo[sha])
        filename = cname_to_filename(name).encode('latin-1')
        sha = sha.encode('latin-1')

        namespace_path = os.path.join(self.path, os.path.splitext(filename)[0])
        namespace_cname = to_canonical(os.path.splitext(filename)[0])
        if not os.path.exists(os.path.join(self.path, filename)) and os.path.isdir(namespace_path):
            files = ["[%s](%s_%s)" % (x, namespace_cname, filename_to_cname(x)) for x in os.listdir(namespace_path)]
            print(files)
            return {'data': "# Namespace %s \n\n This is an automatically generated list of pages in this namespace.\n\n %s" % (os.path.splitext(filename)[0], '\n'.join(files))}

        try:
            data = self.gittle.get_commit_files(sha, paths=[filename]).get(filename)
            if not data:
                return None
            partials = {}
            if data.get('data'):
                meta = self.get_meta(data['data'])
                if meta and 'import' in meta:
                    for partial_name in meta['import']:
                        partials[partial_name] = self.get_page(partial_name)
            data['partials'] = partials
            data['info'] = self.get_history(name, limit=1)[0]

            return data

        except KeyError:
            # HEAD doesn't exist yet
            return None
Exemple #51
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        front_matter = data.get_front_matter()
        enable_files = current_app.config.get('FILE_MANAGER_ENABLE')

        return render_template('wiki/page.html',
                               name=cname,
                               page=data,
                               partials=_partials(data.imports),
                               front_matter=front_matter,
                               enable_files=enable_files)
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #52
0
def revert():
    cname = to_canonical(request.form.get("name"))
    commit = request.form.get("commit")
    message = request.form.get("message", "Reverting %s" % cname)

    if not current_app.config.get("ALLOW_ANON") and current_user.is_anonymous():
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if cname in current_app.config.get("WIKI_LOCKED_PAGES"):
        return dict(error=True, message="Page is locked"), 403

    try:
        sha = g.current_wiki.revert_page(
            cname, commit, message=message, username=current_user.username, email=current_user.email
        )
    except PageNotFound as e:
        return dict(error=True, message=e.message), 404

    if sha:
        flash("Page reverted")

    return dict(sha=sha)
Exemple #53
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous():
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    path = cname
    # get the path to the current file without its name
    if '/' in cname:
        path = cname[:cname.rfind("/")]
    # build the sidebar for the retreived path
    sidebar = _build_sidebar(path=path)
    # build the breadcrumb for the current page
    breadcrumb = _build_breadcrumb(rel_url=cname)

    if data:
        return render_template('wiki/page.html', name=cname, page=data, sidebar=sidebar, breadcrumb=breadcrumb, partials=data.get('partials'), path=path)
    else:
         abort(404)
Exemple #54
0
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        if is_markdown(cname):
            return render_template('wiki/page.html',
                                   name=cname,
                                   page=data,
                                   partials=_partials(data.imports))
        else:
            response = make_response(data.data)
            response.headers['Content-Type'] = 'image/png'
            response.headers[
                'Content-Disposition'] = 'attachment; filename=img.png'
            return response
    else:
        return redirect(url_for('wiki.create', name=cname))
Exemple #55
0
def page_write(name):
    cname = to_canonical(name)

    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(
    ):
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == 'POST':
        # Create
        create_cname = to_canonical(request.form['name'])

        # if the page already exist we don't want an override
        if g.current_wiki.get_page(create_cname):
            return dict(error=True, message="Page already exists"), 403

        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        #image management
        content = _image_management(request.form['content'])
        if not content:
            return dict(error=True,
                        message="Error during images management"), 500
        #end image management

        sha = g.current_wiki.write_page(create_cname,
                                        content,
                                        message=request.form['message'],
                                        create=True,
                                        username=current_user.username,
                                        email=current_user.email)

    elif request.method == 'PUT':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname:
            g.current_wiki.rename_page(cname, edit_cname)

        #image management
        content = _image_management(request.form['content'])
        if not content:
            return dict(error=True,
                        message="Error during images management"), 500
        #end image management

        # get the list of the images present in the current page
        img_list = _find_images_in_page(content)
        #return dict(response = request.form.getlist('img_list[]'))
        # get the list of images that were present befor the edit
        old_image_list = request.form.getlist('img_list[]')
        # retrieve the difference (images to be deleted)
        images_to_delete = [
            img for img in old_image_list if img not in img_list
        ]
        # delete those images
        _delete_images(images_to_delete)

        sha = g.current_wiki.write_page(edit_cname,
                                        content,
                                        message=request.form['message'],
                                        username=current_user.username,
                                        email=current_user.email)

        return dict(sha=sha)

    elif request.method == 'DELETE':
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403
        #get the imges present in the current page
        page = g.current_wiki.get_page(cname)
        img_list = _find_images_in_page(page['data'])
        # delete those images
        _delete_images(img_list)
        #secondo me e' sbagliato
        sha = g.current_wiki.delete_page(cname,
                                         username=current_user.username,
                                         email=current_user.email)

    return dict(sha=sha)
Exemple #56
0
def page_write(name):
    cname = to_canonical(name)
    
    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous():
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == 'POST':
        # Create
        create_cname = to_canonical(request.form['name'])

        # if the page already exist we don't want an override
        if g.current_wiki.get_page(create_cname):
            return dict(error=True, message="Page already exists"), 403

        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        #image management
        content = _image_management(request.form['content'])
        if not content:
            return dict(error=True, message="Error during images management"), 500
        #end image management

        sha = g.current_wiki.write_page(create_cname,
                                        content,
                                        message=request.form['message'],
                                        create=True,
                                        username=current_user.username,
                                        email=current_user.email)

    elif request.method == 'PUT':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname:
            g.current_wiki.rename_page(cname, edit_cname)


        #image management
        content = _image_management(request.form['content'])
        if not content:
            return dict(error=True, message="Error during images management"), 500
        #end image management
        
        # get the list of the images present in the current page
        img_list = _find_images_in_page(content)
        #return dict(response = request.form.getlist('img_list[]'))
        # get the list of images that were present befor the edit
        old_image_list = request.form.getlist('img_list[]')
        # retrieve the difference (images to be deleted)
        images_to_delete = [img for img in old_image_list if img not in img_list]
        # delete those images
        _delete_images(images_to_delete)

        sha = g.current_wiki.write_page(edit_cname,
                                        content,
                                        message=request.form['message'],
                                        username=current_user.username,
                                        email=current_user.email)

        return dict(sha=sha)

    elif request.method == 'DELETE':
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403
        #get the imges present in the current page
        page = g.current_wiki.get_page(cname) 
        img_list = _find_images_in_page(page['data'])
        # delete those images
        _delete_images(img_list)
        #secondo me e' sbagliato
        sha = g.current_wiki.delete_page(cname,
                                         username=current_user.username,
                                         email=current_user.email)

    return dict(sha=sha)