Ejemplo n.º 1
0
def execute(pagename, request):
    form = values_to_form(request.values)

    template = form.get('template', [''])[0]

    if template and not request.page.exists():
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            editor = PageEditor(request, template_page)
            editor.user = request.user
            text = editor.get_raw_body()
            editor.page_name = pagename
            request.page.set_raw_body(editor._expand_variables(text))
            newdata = parse_text(request, request.page,
                                 request.page.get_raw_body())

            # Add prototype metas (^ something::\s*$) as keys
            protokeys = [y for x,y in dl_proto_re.findall(text)]
            for key in protokeys:
                if not (key in newdata[pagename].get('out', dict()) or 
                        key in newdata[pagename].get('meta', dict())):
                    newdata[pagename].setdefault('meta', dict())[key] = list()

            # I'll lie, cheat, do anything to make this work
            newdata[pagename]['saved'] = True

            # Add the template metas to cache so that they'd show
            request.graphdata.cacheset(pagename, newdata.get(pagename, dict()))

    MetaEdit.execute(pagename, request)
Ejemplo n.º 2
0
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]

    try:
        metas = get_metas2(request, args)
    except ImportError:
        request.status_code = 501
        request.write(u"abusehelper package not available")
        return
    except ValueError:
        request.status_code = 400
        request.write(u"invalid query '" + args + u"'")
        return

    if form.get('formatted', [None])[0]:
        formatted = {}
        values = []
        for page, vals in metas.items():
            values.extend(vals.keys())
            for val in vals.values():
                values.extend(val)

        for value in values:
            f = format_wikitext(request, value)
            if f != value and value not in formatted:
                formatted[value] = f

        metas = {'metas': metas, 'formatted': formatted}

    json.dump(metas, request, indent=2)
Ejemplo n.º 3
0
def execute(pagename, request):
    request.headers["Content-Type"] = "text/plain; charset=ascii"
    if request.environ['REQUEST_METHOD'] != 'POST':
        return

    form = values_to_form(request.values)

    content = form.get('content', [None])[0]
    if not content:
        sendfault(request,  "Missing page content")
        return

    pagename = normalize_pagename(pagename, request.cfg)
    if not pagename:
        sendfault(request, "No page name entered")
        return

    if not request.user.may.write(pagename):
        sendfault(request, "You are not allowed to edit this page")
        return

    page = PageEditor(request, pagename)
    if page.exists():
        sendfault(request, "Page already exists.")
        return

    msg = ""
    try:
        msg = page.saveText(content, 0)
    except page.SaveError, msg:
        sendfault(request, "Failed to save page: %s" % pagename)
        return
Ejemplo n.º 4
0
def execute(pagename, request):
    request.headers["Content-Type"] = "text/plain; charset=ascii"
    if request.environ['REQUEST_METHOD'] != 'POST':
        return

    form = values_to_form(request.values)

    content = form.get('content', [None])[0]
    if not content:
        sendfault(request, "Missing page content")
        return

    pagename = normalize_pagename(pagename, request.cfg)
    if not pagename:
        sendfault(request, "No page name entered")
        return

    if not request.user.may.write(pagename):
        sendfault(request, "You are not allowed to edit this page")
        return

    page = PageEditor(request, pagename)
    if page.exists():
        sendfault(request, "Page already exists.")
        return

    msg = ""
    try:
        msg = page.saveText(content, 0)
    except page.SaveError, msg:
        sendfault(request, "Failed to save page: %s" % pagename)
        return
Ejemplo n.º 5
0
def execute(pagename, request):
    # Strip non-ascii chars in header
    pagename_header = '%s.csv' % (pagename)
    pagename_header = pagename_header.encode('ascii', 'ignore')

    request.content_type = 'text/csv; charset=UTF-8'
    request.headers['Content-Disposition'] = \
        'attachment; filename="%s"' % pagename_header
    GetMeta = wikiutil.importPlugin(request.cfg, 'xmlrpc', 'GetMeta',
                                    'do_action')

    form = values_to_form(request.values)

    try:
        args = form['args'][0]
    except (KeyError, IndexError):
        args = u''

    table = GetMeta(request, args, keysonly=False)
    table = getmeta_to_table(table)
    if 0:
        print '--', table, '--'
        print 'args', args
        print 'pagename', pagename

    writer = csv.writer(request, delimiter=';')

    for row in table:
        writer.writerow(map(encode_page, row))
Ejemplo n.º 6
0
def execute(pagename, request):
    form = values_to_form(request.values)
    query = form.get('q', [None])[0]
    output_format = form.get('type', [""])[0]
    try:
        json_rows = metas_to_json(request, query)

        accepts = unicode(request.request.accept_mimetypes)

        if output_format == "stream" or "text/event-stream" in accepts:
            request.content_type = "text/event-stream"

            ## send_file seems to be the least hacky way
            ## for sending streamed content in MoinMoin
            request.send_file(MetaStreamer(json_rows))
        else:
            request.content_type = "application/json;boundary=NL"

            for row in json_rows:
                request.write(row + "\n")

    except ImportError:
        request.status_code = 501
        request.write(u"abusehelper package not available")
    except ValueError:
        request.status_code = 400
        request.write(u"invalid query '" + query + u"'")
Ejemplo n.º 7
0
def execute(pagename, request):
    # Strip non-ascii chars in header
    pagename_header = '%s.csv' % (pagename)
    pagename_header = pagename_header.encode('ascii', 'ignore')
    
    request.content_type = 'text/csv; charset=UTF-8'
    request.headers['Content-Disposition'] = \
        'attachment; filename="%s"' % pagename_header
    GetMeta = wikiutil.importPlugin(request.cfg, 'xmlrpc', 'GetMeta', 'do_action')

    form = values_to_form(request.values)

    try:
        args = form['args'][0]
    except (KeyError, IndexError):
        args = u''

    table = GetMeta(request, args, keysonly=False)
    table = getmeta_to_table(table)
    if 0:
        print '--', table, '--'
        print 'args', args
        print 'pagename', pagename

    writer = csv.writer(request, delimiter=';')

    for row in table:
        writer.writerow(map(encode_page, row))
Ejemplo n.º 8
0
def execute(pagename, request):
    form = values_to_form(request.values)

    template = form.get('template', [''])[0]

    if template and not request.page.exists():
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            editor = PageEditor(request, template_page)
            editor.user = request.user
            text = editor.get_raw_body()
            editor.page_name = pagename
            request.page.set_raw_body(editor._expand_variables(text))
            newdata = parse_text(request, request.page,
                                 request.page.get_raw_body())

            # Add prototype metas (^ something::\s*$) as keys
            protokeys = [y for x,y in dl_proto_re.findall(text)]
            for key in protokeys:
                if not (key in newdata[pagename].get('out', dict()) or 
                        key in newdata[pagename].get('meta', dict())):
                    newdata[pagename].setdefault('meta', dict())[key] = list()

            # I'll lie, cheat, do anything to make this work
            newdata[pagename]['saved'] = True

            # Add the template metas to cache so that they'd show
            request.graphdata.cacheset(pagename, newdata.get(pagename, dict()))

    MetaEdit.execute(pagename, request)
Ejemplo n.º 9
0
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]

    try:
        metas = get_metas2(request, args)
    except ImportError:
        request.status_code = 501
        request.write(u"abusehelper package not available")
        return
    except ValueError:
        request.status_code = 400
        request.write(u"invalid query '" + args + u"'")
        return

    if form.get('formatted', [None])[0]:
        formatted = {}
        values = []
        for page, vals in metas.items():
            values.extend(vals.keys())
            for val in vals.values():
                values.extend(val)

        for value in values:
            f = format_wikitext(request, value)
            if f != value and value not in formatted:
                formatted[value] = f

        metas = {'metas': metas, 'formatted': formatted}

    json.dump(metas, request, indent=2)
Ejemplo n.º 10
0
def execute(pagename, request):
    if 'metasearch' in request.values: 
        form = values_to_form(request.values)
        form['action'] = [u'MetaSearch']
        val = form.get('value', [''])
        form['q'] = val
        request.values = CombinedMultiDict([MultiDict(form)])
        return ms_execute(pagename, request)

    return fs_execute(pagename, request)
Ejemplo n.º 11
0
    def do_action(self):
        _ = self.request.getText

        pdata = self.request.graphdata.getpage(self.pagename)
        oldpagename = self.pagename

        success, msgs = RenamePageBasic.do_action(self)

        form = values_to_form(self.request.values)

        rename_links = 0
        if 'rename_links' in form:
            try:
                rename_links = int(form['rename_links'][0])
            except:
                pass

        if rename_links and success:
            newpagename = form.get('newpagename', [u''])[0]
            newpagename = wikiutil.normalize_pagename(newpagename, self.cfg)

            comment = form.get('comment', [u''])[0]
            comment = wikiutil.clean_input(comment)
            comment = "%s (%s)" % (comment, _("changed links:") +
                                   " %s -> %s" % (self.pagename, newpagename))

            # List pages that link to the renamed page
            pages = set()
            inlinks = self.request.graphdata.get_in(self.pagename)
            for type in inlinks:
                pages.update(inlinks[type])

            # Update listed pages
            for page in pages:
                # User rights _ARE_ checked here!
                if not self.request.user.may.write(page):
                    continue

                # If inlink rename of a single page does not work,
                # continue but make sure to emit a warning
                success_single, msg = self._inlink_rename(page, newpagename,
                                                          oldpagename, comment)
                if not success_single:
                    success = False

                if msg:
                    msgs = self._add_msg(msgs, msg)

            if not success:
                msgs = self._add_msg(msgs,
                         _(u'Other pages with inlinks renamed successfully.'))

        return success, msgs
Ejemplo n.º 12
0
    def __init__(self, pagename, request, **kw):
        ActionBase.__init__(self, pagename, request)
        self.getText = request.getText
        self.request = request
        self.use_ticket = True
        self.form_trigger = 'requestinvite'
        self.form_trigger_label = wikiutil.escape(kw.get('button_text', [self.getText('Send Request')])[0], True)
        self.querytext = kw.get('text', [self.getText('Send invite request for collab')])[0]

        form = values_to_form(self.request.values)
        collab = form.get('collab', [u''])[0]
        self.collab = wikiutil.clean_input(collab).strip()
Ejemplo n.º 13
0
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]
    if not args:
        args = pagename

    handle = form.get('handle', [None])[0]
    if handle:
        handle = str(handle)

    getvalues = form.get('getvalues', [None])[0]
    if getvalues:
        args = "%s=/.+/" % getvalues

    inc_get_metas = wikiutil.importPlugin(request.cfg, "xmlrpc", "IncGetMeta",
                                          "inc_get_metas")
    out = inc_get_metas(request, args, handle)

    if getvalues:
        changed = out[2][1]
        filtered = dict()
        for page, metas in changed.items():
            for key, vals in metas.items():
                if key == getvalues:
                    filtered[page] = {key: vals}

        out[2] = (out[2][0], filtered)
    
    if form.get('formatted', [None])[0]:
        formatted = dict()

        for page, metas in out[2][1].items():
            vals = list()
            for key, values in metas.items():
                vals.append(key)
                vals.extend(values[1])
           
            request.page = Page(request, page)

            for val in vals:
                f = format_wikitext(request, val)
                if val != f:
                    formatted[val] = f

        out.append(formatted)


    json.dump(out, request, indent=2)
Ejemplo n.º 14
0
    def do_action(self):
        form = values_to_form(self.request.values)

        template = form.get('template', [''])[0]
        template = wikiutil.clean_input(template).strip().split(',')
        new_template = old_template = None
        if len(template) > 0:
            new_template = template[0]
            if len(template) > 1:
                old_template = template[1]

        email = form.get('email', [u''])[0]
        email = wikiutil.clean_input(email).strip()
        if len(email) == 0:
            return False, "Please specify an email address."

        pagename = self.pagename
        try:
            if wikiutil.isGroupPage(pagename, self.request.cfg):
                myuser = invite_user_to_wiki(self.request, pagename, email,
                                             new_template, old_template)
                mygrouppage = pagename
            else:
                myuser = invite_user_to_page(self.request, pagename, email,
                                             new_template, old_template)
                mygrouppage = getattr(self.request.cfg, GROUP_DEFAULT_VARIABLE,
                                      GROUP_DEFAULT_DEFAULT)

            if mygrouppage:
                mycomment = "invited {0}.".format(myuser.email)
                try:
                    add_user_to_group(self.request,
                                      myuser,
                                      mygrouppage,
                                      comment=mycomment)
                except GroupException, ge:
                    tmp = "User invitation mail sent to address '%s', but could not add the user to group '%s': %s"
                    if myuser.email != email:
                        tmp += " Please note that the email address was converted to lowercase!"
                    return True, wikiutil.escape(
                        tmp % (email, mygrouppage, unicode(ge)))

                tmp = "User invitation mail sent to address '%s' and the user was added to group '%s'."
                if myuser.email != email:
                    tmp += " Please note that the email address was converted to lowercase!"

                return True, wikiutil.escape(tmp % (email, mygrouppage))

        except InviteException, ie:
            return False, wikiutil.escape(unicode(ie).encode(config.charset))
Ejemplo n.º 15
0
def execute(pagename, request):
    if request.environ["REQUEST_METHOD"] != "POST":
        return_page(request, pagename)
        return

    params = values_to_form(request.values)
    meta_keys = params.get("meta_key", list())
    if not meta_keys or not meta_keys[0]:
        return_page(request, pagename, "Timestamping failed. Missing meta_key", "error")
        return

    success, msg = write_timestamps(request, pagename, meta_keys)
    if success:
        return_page(request, pagename)
    else:
        return_page(request, pagename, msg, "error")
Ejemplo n.º 16
0
def execute(pagename, request):
    silent = False

    form = values_to_form(request.values)

    if "gwikisilent" in form:
        silent = True

    editlink = True
    if "noeditlink" in form:
        editlink = False

    args = form.get('args', [""])[0]

    macro = wikiutil.importPlugin(request.cfg, "macro", "MetaTable","do_macro")
    request.write(macro(request, args, silent=silent, editlink=editlink))
Ejemplo n.º 17
0
def execute(pagename, request):
    silent = False

    form = values_to_form(request.values)

    if "gwikisilent" in form:
        silent = True

    editlink = True
    if "noeditlink" in form:
        editlink = False

    args = form.get('args', [""])[0]

    macro = wikiutil.importPlugin(request.cfg, "macro", "MetaTable",
                                  "do_macro")
    request.write(macro(request, args, silent=silent, editlink=editlink))
Ejemplo n.º 18
0
def execute(pagename, request):
    if request.environ["REQUEST_METHOD"] != "POST":
        return_page(request, pagename)
        return

    params = values_to_form(request.values)
    meta_keys = params.get("meta_key", list())
    if not meta_keys or not meta_keys[0]:
        return_page(request, pagename, "Timestamping failed. Missing meta_key",
                    "error")
        return

    success, msg = write_timestamps(request, pagename, meta_keys)
    if success:
        return_page(request, pagename)
    else:
        return_page(request, pagename, msg, "error")
Ejemplo n.º 19
0
def macro_MetaSlideshow(macro, slidekey=u'next'):

    request = macro.request
    formatter = macro.formatter
    pagename = macro.request.page.page_name
    page = macro.request.page

    parameters = dict()

    form = values_to_form(request.values)

    if form.get('action', [None])[0]:
        parameters['action'] = wikiutil.escape(form['action'][0])

    if form.get('media', [None])[0]:
        parameters['media'] = wikiutil.escape(form['media'][0])

    result = list()
    result.append(formatter.table(True, {"tableclass": "navigation"}))
    result.append(formatter.table_row(True))
    result.append(formatter.table_cell(True))

    if parameters.get('action', str()) == 'print':
        if parameters.get('media', str()) != 'projection':
            return None
        else:
            result.append(
                page.link_to(request,
                             text='Edit ',
                             querystr={'action': 'edit'}))
            result.append(page.link_to(request, text='Wiki ', querystr=dict()))
    else:
        result.append(
            page.link_to(request,
                         text='Slideshow ',
                         querystr={
                             'action': 'print',
                             'media': 'projection'
                         }))
        parameters = dict()

    try:
        slideshow = get_slideshow(request, pagename, slidekey)
    except SlideshowException, e:
        return "Slideshow error: " + e.args
Ejemplo n.º 20
0
    def do_action(self):
        form = values_to_form(self.request.values)

        template = form.get('template', [''])[0]
        template = wikiutil.clean_input(template).strip().split(',')
        new_template = old_template = None
        if len(template) > 0:
            new_template = template[0]
            if len(template) > 1:
                old_template = template[1]

        email = form.get('email', [u''])[0]
        email = wikiutil.clean_input(email).strip()
        if len(email) == 0:
            return False, "Please specify an email address."

        pagename = self.pagename
        try:
            if wikiutil.isGroupPage(pagename, self.request.cfg):
                myuser = invite_user_to_wiki(self.request, pagename, email, new_template, old_template)
                mygrouppage = pagename
            else:
                myuser = invite_user_to_page(self.request, pagename, email, new_template, old_template)
                mygrouppage = getattr(self.request.cfg, GROUP_DEFAULT_VARIABLE, GROUP_DEFAULT_DEFAULT)

            if mygrouppage:
                mycomment = "invited {0}.".format(myuser.email)
                try:
                    add_user_to_group(self.request, myuser, mygrouppage, comment=mycomment)
                except GroupException, ge:
                    tmp = "User invitation mail sent to address '%s', but could not add the user to group '%s': %s"
                    if myuser.email != email:
                        tmp += " Please note that the email address was converted to lowercase!"
                    return True, wikiutil.escape(tmp % (email, mygrouppage, unicode(ge)))

                tmp = "User invitation mail sent to address '%s' and the user was added to group '%s'."
                if myuser.email != email:
                    tmp += " Please note that the email address was converted to lowercase!"

                return True, wikiutil.escape(tmp % (email, mygrouppage))

        except InviteException, ie:
            return False, wikiutil.escape(unicode(ie).encode(config.charset))
Ejemplo n.º 21
0
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]
    key = form.get('getvalues', [None])[0]
    formatted = form.get('formatted', [None])[0]

    do_action = wikiutil.importPlugin(request.cfg, "xmlrpc", "GetMetaStruct",
                                      "do_action")

    if not args:
        if key:
            results = do_action(request, "%s=/.+/" % key)
            metas = dict()
            for page in results:
                values = results[page].get(key, [])
                if values:
                    metas.setdefault(page, list())
                    metas[page].extend(values)
        else:
            metas = do_action(request, pagename)
    else:
        metas = do_action(request, args)

    if formatted:
        formatted = {}
        values = []
        for page, vals in metas.items():
            values.extend(vals.keys())
            for val in vals.values():
                values.extend(val)

        for value in values:
            f = format_wikitext(request, value)
            if f != value and value not in formatted:
                formatted[value] = f

        metas = {'metas': metas, 'formatted': formatted}

    json.dump(metas, request, indent=2)
Ejemplo n.º 22
0
def execute(pagename, request):
    request.content_type = "application/json"

    form = values_to_form(request.values)

    args = form.get('args', [None])[0]
    key = form.get('getvalues', [None])[0]
    formatted = form.get('formatted', [None])[0]

    do_action = wikiutil.importPlugin(request.cfg, "xmlrpc", "GetMetaStruct",
                                      "do_action")

    if not args:
        if key:
            results = do_action(request, "%s=/.+/" % key)
            metas = dict()
            for page in results:
                values = results[page].get(key, [])
                if values:
                    metas.setdefault(page, list())
                    metas[page].extend(values)
        else:
            metas = do_action(request, pagename)
    else:
        metas = do_action(request, args)

    if formatted:
        formatted = {}
        values = []
        for page, vals in metas.items():
            values.extend(vals.keys())
            for val in vals.values():
                values.extend(val)

        for value in values:
            f = format_wikitext(request, value)
            if f != value and value not in formatted:
                formatted[value] = f

        metas = {'metas' : metas, 'formatted': formatted}

    json.dump(metas, request, indent=2)
Ejemplo n.º 23
0
def execute(pagename, request):
    form = values_to_form(request.values)

    # Editaction allows for arbitrary action to be used for editing target page
    editaction = form.get('editfunc', [''])[0]
    # Edit actions assumed to be all in lower case
    editaction = editaction.lower()

    if editaction:
        # MoinMoin.action.newpage left no choice but to edit the URL
        # action on-the-fly in request.http_redirect
        request.http_redirect_real = request.http_redirect
        
        def redirect_editaction(url):
            url = url.replace('action=edit', 'action=%s' % editaction)
            request.http_redirect_real(url)

        request.http_redirect = redirect_editaction

    return NewPage(request, pagename).render()
Ejemplo n.º 24
0
def execute(pagename, request):
    form = values_to_form(request.values)

    # Editaction allows for arbitrary action to be used for editing target page
    editaction = form.get("editfunc", [""])[0]
    # Edit actions assumed to be all in lower case
    editaction = editaction.lower()

    if editaction:
        # MoinMoin.action.newpage left no choice but to edit the URL
        # action on-the-fly in request.http_redirect
        request.http_redirect_real = request.http_redirect

        def redirect_editaction(url):
            url = url.replace("action=edit", "action=%s" % editaction)
            request.http_redirect_real(url)

        request.http_redirect = redirect_editaction

    return NewPage(request, pagename).render()
Ejemplo n.º 25
0
def execute(pagename, request):
    if request.environ["REQUEST_METHOD"] != "POST":
        return_page(request, pagename)
        return

    for key in values_to_form(request.values):
        if len(key) == 10 and key.startswith("stress_"):
            try:
                control = {"0":"yes", "1":"no"}[key[7]]
                activity = {"0":"low","1":"medium","2":"high"}[key[9]]
            except IndexError:
                continue

            success, msg = save_report(request, control, activity)
            if success:
                return_page(request, pagename, msg)
            else:
                return_page(request, pagename, msg, "error")
            return
        
    return_page(request, pagename)
Ejemplo n.º 26
0
def execute(pagename, request):
    if request.environ["REQUEST_METHOD"] != "POST":
        return_page(request, pagename)
        return

    for key in values_to_form(request.values):
        if len(key) == 10 and key.startswith("stress_"):
            try:
                control = {"0": "yes", "1": "no"}[key[7]]
                activity = {"0": "low", "1": "medium", "2": "high"}[key[9]]
            except IndexError:
                continue

            success, msg = save_report(request, control, activity)
            if success:
                return_page(request, pagename, msg)
            else:
                return_page(request, pagename, msg, "error")
            return

    return_page(request, pagename)
Ejemplo n.º 27
0
def execute(pagename, request):
    _ = request.getText
    request.content_type = "application/json"

    if request.environ['REQUEST_METHOD'] != 'POST':
        return

    # normalization is performed in set_metas, this check is retained
    # to provide early feedback to the user.
    pagename = wikiutil.normalize_pagename(pagename, request.cfg)
    if not pagename:
        sendfault(request, 2, _("No page name entered"))
        return

    form = values_to_form(request.values)

    indata = form.get('args', [None])[0]
    if not indata:
        return

    indata = json.loads(indata)

    if 'metas' not in indata:
        msg = []
        for xpagename, metadict in indata.items():
            r = doit(request, xpagename, {'metas': metadict, 'action': 'set'})
            if not r:
                continue
            if type(r) is list:
                msg += r
            else:
                msg.append(r)
    else:
        msg = doit(request, pagename, indata)

    if msg:
        json.dump(dict(status="ok", msg=msg), request)

    return
Ejemplo n.º 28
0
def execute(pagename, request):
    _ = request.getText
    request.content_type = "application/json"

    if request.environ['REQUEST_METHOD'] != 'POST':
        return

    # normalization is performed in set_metas, this check is retained
    # to provide early feedback to the user.
    pagename = wikiutil.normalize_pagename(pagename, request.cfg)
    if not pagename:
        sendfault(request, 2, _("No page name entered"))
        return

    form = values_to_form(request.values)

    indata = form.get('args', [None])[0]
    if not indata:
        return

    indata = json.loads(indata)

    if 'metas' not in indata:
        msg = []
        for xpagename, metadict in indata.items():
            r = doit(request, xpagename, {'metas': metadict, 'action': 'set'})
            if not r:
                continue
            if type(r) is list:
                msg += r
            else:
                msg.append(r)
    else:
        msg = doit(request, pagename, indata)

    if msg:
        json.dump(dict(status="ok", msg=msg), request)

    return
Ejemplo n.º 29
0
    def do_action(self):
        form = values_to_form(self.request.values)
        days = form.get('days', [u''])[0]
        days = wikiutil.clean_input(days)

        try:
            days = int(days)
        except ValueError:
            return False, "Invalid number: %s" % days

        fake = FakeXmlrpcObj()
        fake.request = self.request
        cookie = generateCookie(fake, str(self.pagename), days * SECONDS_IN_DAY)
        if isinstance(cookie, xmlrpclib.Fault):
            return False, cookie.faultString

        default_filename = self.pagename + ".cookie"
        filename = form.get('filename', [default_filename])[0]

        self.filename = filename.encode("ascii", "ignore")
        self.cookie = cookie.data

        return True, ""
Ejemplo n.º 30
0
def macro_MetaSlideshow(macro, slidekey=u"next"):

    request = macro.request
    formatter = macro.formatter
    pagename = macro.request.page.page_name
    page = macro.request.page

    parameters = dict()

    form = values_to_form(request.values)

    if form.get("action", [None])[0]:
        parameters["action"] = wikiutil.escape(form["action"][0])

    if form.get("media", [None])[0]:
        parameters["media"] = wikiutil.escape(form["media"][0])

    result = list()
    result.append(formatter.table(True, {"tableclass": "navigation"}))
    result.append(formatter.table_row(True))
    result.append(formatter.table_cell(True))

    if parameters.get("action", str()) == "print":
        if parameters.get("media", str()) != "projection":
            return None
        else:
            result.append(page.link_to(request, text="Edit ", querystr={"action": "edit"}))
            result.append(page.link_to(request, text="Wiki ", querystr=dict()))
    else:
        result.append(page.link_to(request, text="Slideshow ", querystr={"action": "print", "media": "projection"}))
        parameters = dict()

    try:
        slideshow = get_slideshow(request, pagename, slidekey)
    except SlideshowException, e:
        return "Slideshow error: " + e.args
Ejemplo n.º 31
0
def execute(pagename, request):
    _ = request.getText
    form = values_to_form(request.values)
    msgs = list()

    newpage = form['name'][0]
    if not newpage:
        request.theme.add_msg(_("IOCList page name not set!"), 'error')
        request.page.send_page()
        return
    template = form['template'][0]
    if not template:
        template = "IOCListTemplate"
    allow_overlap = form['allow_overlap'][0]
    if not allow_overlap:
        allow_overlap = "no"
    
    ips = IPV4_RE.findall(form['data'][0])
    ips = filter(is_ipv4, ips)
    ips = set(ips)

    ipv6 = IPV6_RE.findall(form['data'][0])
    ipv6 = filter(is_ipv6, ipv6)
    ips.update(set(ipv6))

    ips = list(ips)
    domains = set(DOMAIN_RE.findall(form['data'][0]))
    urls = set(URL_RE.findall(form['data'][0]))
    emails = set(EMAIL_RE.findall(form['data'][0]))
    hashes = set(HASH_RE.findall(form['data'][0]))

    data = {'ip': list(ips),
            'domain name': list(domains),
            'url': list(urls),
            'email address': list(emails),
            'artifact hash': list(hashes)}
    dataset = set()
    for key in data:
        dataset.update(data[key])

    graphdata = request.graphdata
    vals_on_keys = graphdata.get_vals_on_keys()

    new_data = dict((key, list()) for (key, value) in data.iteritems())

    for ip in ips:
        if ip not in vals_on_keys.get('ip', list()):
           new_data['ip'].append(ip)
    for domain in domains:
        if domain not in vals_on_keys.get('domain name', list()):
           new_data['domain name'].append(domain)
    for url in urls:
        if url not in vals_on_keys.get('url', list()):
           new_data['url'].append(url)
    for email in emails:
        if email not in vals_on_keys.get('email address', list()):
           new_data['email address'].append(email)
    for h in hashes:
        if h not in vals_on_keys.get('artifact hash', list()):
           new_data['artifact hash'].append(h)

    newdataset = list()
    for key in new_data:
        newdataset.extend(new_data[key])

    old_data = dataset.difference(newdataset)
    if old_data:
        vals_on_pages = graphdata.get_vals_on_pages()

        if allow_overlap == 'no':
            for ioc in old_data:
                msgs.append(_("The following IOC already listed: %s (%s).") % 
                            (ioc, ', '.join(vals_on_pages[ioc])))
        else:
            for ioc in old_data:
                if newpage in vals_on_pages[ioc]:
                    for key in data.keys():
                        if ioc in data[key]:
                            data[key].remove(ioc)
                else:
                    msgs.append(
                        _("The following IOC already listed: %s (%s).") % 
                        (ioc, ', '.join(vals_on_pages[ioc])) + " " +
                        _("Adding anyway."))

    if allow_overlap != 'no':
        new_data = data

    if not new_data:
        request.theme.add_msg(_("No new IOC!"), 'error')
        request.page.send_page()
        return

    if not Page(request, newpage).exists():
        msgs.append(_("Creating page %s with template %s") % 
                              (newpage, template))
        msgs.append(save_template(request, newpage, template))

    ioccount = 0
    for key in new_data:
        ioccount += len(new_data[key])
    msgs.append(_("Added %s IOC to list %s") % (ioccount,
                                                newpage))

    edit_meta(request, newpage, {}, new_data)
    msg = ''
    for line in msgs:
        msg += line + request.formatter.linebreak(0)

    request.theme.add_msg(msg)
    do_show(pagename, request)
Ejemplo n.º 32
0
def execute(pagename, request):
    _ = request.getText
    form = values_to_form(request.values)
    msgs = list()

    newpage = form['name'][0]
    if not newpage:
        request.theme.add_msg(_("IOCList page name not set!"), 'error')
        request.page.send_page()
        return
    template = form['template'][0]
    if not template:
        template = "IOCListTemplate"
    allow_overlap = form['allow_overlap'][0]
    if not allow_overlap:
        allow_overlap = "no"

    ips = IPV4_RE.findall(form['data'][0])
    ips = filter(is_ipv4, ips)
    ips = set(ips)

    ipv6 = IPV6_RE.findall(form['data'][0])
    ipv6 = filter(is_ipv6, ipv6)
    ips.update(set(ipv6))

    ips = list(ips)
    domains = set(DOMAIN_RE.findall(form['data'][0]))
    urls = set(URL_RE.findall(form['data'][0]))
    emails = set(EMAIL_RE.findall(form['data'][0]))
    hashes = set(HASH_RE.findall(form['data'][0]))

    data = {
        'ip': list(ips),
        'domain name': list(domains),
        'url': list(urls),
        'email address': list(emails),
        'artifact hash': list(hashes)
    }
    dataset = set()
    for key in data:
        dataset.update(data[key])

    graphdata = request.graphdata
    vals_on_keys = graphdata.get_vals_on_keys()

    new_data = dict((key, list()) for (key, value) in data.iteritems())

    for ip in ips:
        if ip not in vals_on_keys.get('ip', list()):
            new_data['ip'].append(ip)
    for domain in domains:
        if domain not in vals_on_keys.get('domain name', list()):
            new_data['domain name'].append(domain)
    for url in urls:
        if url not in vals_on_keys.get('url', list()):
            new_data['url'].append(url)
    for email in emails:
        if email not in vals_on_keys.get('email address', list()):
            new_data['email address'].append(email)
    for h in hashes:
        if h not in vals_on_keys.get('artifact hash', list()):
            new_data['artifact hash'].append(h)

    newdataset = list()
    for key in new_data:
        newdataset.extend(new_data[key])

    old_data = dataset.difference(newdataset)
    if old_data:
        vals_on_pages = graphdata.get_vals_on_pages()

        if allow_overlap == 'no':
            for ioc in old_data:
                msgs.append(
                    _("The following IOC already listed: %s (%s).") %
                    (ioc, ', '.join(vals_on_pages[ioc])))
        else:
            for ioc in old_data:
                if newpage in vals_on_pages[ioc]:
                    for key in data.keys():
                        if ioc in data[key]:
                            data[key].remove(ioc)
                else:
                    msgs.append(
                        _("The following IOC already listed: %s (%s).") %
                        (ioc, ', '.join(vals_on_pages[ioc])) + " " +
                        _("Adding anyway."))

    if allow_overlap != 'no':
        new_data = data

    if not new_data:
        request.theme.add_msg(_("No new IOC!"), 'error')
        request.page.send_page()
        return

    if not Page(request, newpage).exists():
        msgs.append(
            _("Creating page %s with template %s") % (newpage, template))
        msgs.append(save_template(request, newpage, template))

    ioccount = 0
    for key in new_data:
        ioccount += len(new_data[key])
    msgs.append(_("Added %s IOC to list %s") % (ioccount, newpage))

    edit_meta(request, newpage, {}, new_data)
    msg = ''
    for line in msgs:
        msg += line + request.formatter.linebreak(0)

    request.theme.add_msg(msg)
    do_show(pagename, request)
Ejemplo n.º 33
0
    def execute(self):
        request = self.request
        _ = request.getText

        pagename = request.page.page_name
        if not request.user.may.read(pagename):
            fault = _(u'Can not read page') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        form = values_to_form(request.values)
        self.formargs(form)

        if self.help or not self.attachment:
            enter_page(request, pagename, 'View .gv attachment')

            self.sendForm()

            if self.help:
                # This is the URL addition to the nodes that have graph data
                self.urladd = url_parameters(form)
                self.urladd = self.urladd.replace('&help=Inline', '')
                request.write('<<ViewDot(' + self.urladd + ')>>')

            exit_page(request, pagename)
            return

        if not self.attachment[:10].lower() == 'attachment':
            fault = _(u'No attachment defined') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        self.attachment = self.attachment[11:]

        pagename, filename = AttachFile.absoluteName(self.attachment,
                                                     self.pagename)
        if not request.user.may.read(pagename):
            fault = _(u'Can not read attachment page') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        fname = wikiutil.taintfilename(filename)
        fpath = AttachFile.getFilename(request, pagename, fname)

        try:
            data = file(fpath, 'r').read()
        except IOError:
            fault = _(u'Can not read attachment') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        if not gv_found:
            fault = _(u"ERROR: Graphviz Python extensions not installed. " +\
                      u"Not performing layout.")
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        self.cache_key = cache_key(self.request,
                                   [data, self.graphengine, self.format])
        key = "%s-%s" % (self.cache_key, self.format)

        if self.format in ['zgr', 'svg']:
            formatcontent = 'svg+xml'
        else:
            formatcontent = self.format

        if not cache_exists(request, key):
            graphviz = Graphviz(engine=self.graphengine, string=data)
            data = self.getLayoutInFormat(graphviz, self.format)

            cache.put(self.request, key, data, content_type=formatcontent)

        if self.format in ['zgr', 'svg']:
            # Display zgr graphs as applets
            if self.format == 'zgr':
                image_p = lambda url, text: \
                    '<applet code="net.claribole.zgrviewer.ZGRApplet.class"'+ \
                    ' archive="%s/gwikicommon/zgrviewer/zvtm.jar,' % \
                    (self.request.cfg.url_prefix_static) + \
                    '%s/gwikicommon/zgrviewer/zgrviewer.jar" ' % \
                    (self.request.cfg.url_prefix_static) + \
                    'width="%s" height="%s">' % (form_escape(self.width), form_escape(self.height))+\
                    '<param name="type" ' + \
                    'value="application/x-java-applet;version=1.4" />' + \
                    '<param name="scriptable" value="false" />' + \
                    '<param name="svgURL" value="%s" />' % (url) + \
                    '<param name="title" value="ZGRViewer - Applet" />'+ \
                    '<param name="appletBackgroundColor" value="#DDD" />' + \
                    '<param name="graphBackgroundColor" value="#DDD" />' + \
                    '<param name="highlightColor" value="red" />' + \
                    ' </applet><br>\n'
            else:
                image_p = lambda url, text: \
                    '<object data="%s" alt="%s" ' % (url, text) + \
                    'type="image/svg+xml">\n' + \
                    '<embed src="%s" alt="%s" ' % (url, text) + \
                    'type="image/svg+xml"/>\n</object>'
        else:
            image_p = lambda url, text: \
                '<img src="%s" alt="%s">\n' % (url, text)

        image_uri = cache.url(self.request, key)

        if not self.inline:
            if self.format == 'zgr':
                request.write('<html><body>')

        request.write(image_p(image_uri, _('visualisation')))

        if not self.inline and self.format == 'zgr':
            request.write('</html></body>')
        else:
            pass  # No footer
Ejemplo n.º 34
0
def _do_diff(pagename, request):
    # return attachment list
    _ = request.getText

    form = values_to_form(request.values)

    att1 = form.get('att1', [''])[0]
    att2 = form.get('att2', [''])[0]
    sort = form.get('sort', ['normal'])[0]

    if (not (att1 and att2) or not 
        (AttachFile.exists(request, pagename, att1) and 
         AttachFile.exists(request, pagename, att2))):
        AttachFile.error_msg(pagename, request, 
                             _('Could not diff, attachments not selected or nonexisting'))
        return

    form['target'] = [att1]
    request.values = CombinedMultiDict([MultiDict(form)])
    pagename, filename, fpath = AttachFile._access_file(pagename, request)

    att1data = open(fpath, 'r').read()

    form['target'] = [att2]
    request.values = CombinedMultiDict([MultiDict(form)])
    pagename, filename, fpath = AttachFile._access_file(pagename, request)
    att2data = open(fpath, 'r').read()

    if sort == 'sort':
        att1data = '\n'.join(sorted(att1data.split('\n')))
        att2data = '\n'.join(sorted(att2data.split('\n')))
    elif sort == 'uniq':
        att1data = '\n'.join(sorted(set(att1data.split('\n'))))
        att2data = '\n'.join(sorted(set(att2data.split('\n'))))
    elif sort == 'cnt':
        att1tmp = list()
        for line in sorted(set(att1data.split('\n'))):
            if not line:
                continue
            att1tmp.append("%s %s" % (att1data.count(line), line))
        att2tmp = list()
        for line in sorted(set(att2data.split('\n'))):
            if not line:
                continue
            att2tmp.append("%s %s" % (att2data.count(line), line))
        att1data = '\n'.join(att1tmp)
        att2data = '\n'.join(att2tmp)

    # Use user interface language for this generated page
    request.setContentLanguage(request.lang)
    request.theme.send_title(_('Diff of %s and %s') % (att1, att2), 
                             pagename=pagename)
    request.write('<div id="content">\n') # start content div

    if request.user.show_fancy_diff:
        from MoinMoin.util import diff_html
        request.write(request.formatter.rawHTML(diff_html.diff(request, 
                                                               att1data, 
                                                               att2data)))
    else:
        from MoinMoin.util import diff_text
        lines = diff_text.diff(att1data.split("\n"), att2data.split("\n"))

        request.write(request.formatter.preformatted(1))
        for line in lines:
                if line[0] == "@":
                    request.write(request.formatter.rule(1))
                request.write(request.formatter.text(line + '\n'))
        request.write(request.formatter.preformatted(0))

    AttachFile.send_uploadform(pagename, request)
    request.write('</div>\n') # end content div
    request.theme.send_footer(pagename)
    request.theme.send_closing_html()
Ejemplo n.º 35
0
def show_editform(wr, request, pagename, args):
    formatter = request.formatter

    # Note that metatable_parseargs handles read permission checks
    pagelist, metakeys, _ = metatable_parseargs(request, args,
                                                get_all_keys=True)

    uneditable_pages = list()
    # See that the user can write each page
    for page in pagelist:
        if not request.user.may.write(page):
            uneditable_pages.append(page)
    for page in uneditable_pages:
        pagelist.remove(page)

    _ = request.getText

    if uneditable_pages:
        reason = _("No save permission to some pages (%s)" %
                   ','.join(uneditable_pages))
        request.write(render_warning(reason))

    if not pagelist:
        reason = _("No pages to edit.")
        request.write(render_error(reason))
        return

    wr(u'<form method="POST" action="%s" enctype="multipart/form-data">\n',
       actionname(request))
    wr(u'<input type="hidden" name="action" value="%s">\n', action_name)
    wr(formatter.table(1))
    wr(formatter.table_row(1, {'rowclass': 'meta_header'}))
    wr(formatter.table_cell(1, {'class': 'meta_page'}))

    form = values_to_form(request.values)

    template = form.get('template', [''])[0]
    if template:
        wr('<input type="hidden" name="template" value="%s">', template)

    # Filter out uneditables, such as inlinks
    metakeys = editable_p(metakeys)

    _ = request.getText

    for key in metakeys + ['']:
        wr(formatter.table_cell(1, {'class': 'meta_header'}))
        wr(u'<input class="metakey" type="text" name="%s" value="%s">',
           u':: %s' % key, key)
    wr(formatter.table_row(0))

    values = dict()
    valnos = dict()

    for frompage in pagelist:
        values[frompage] = dict()

        for key in metakeys + ['']:
            values[frompage][key] = list()
            # If the page has no values for this key, it'll
            # have one in the table to add a value
            if not valnos.has_key(frompage):
                valnos[frompage] = 1

            keydata = get_metas(request, frompage, [key],
                                abs_attach=False, includeGenerated=False)

            for i, val in enumerate(keydata[key]):
                values[frompage][key].append(val)
                # Enumerate starts from 0: #values++
                # One to add a value: #values++
                if valnos[frompage] < i + 2:
                    valnos[frompage] = i + 2

            values[frompage][key].append('')


    for frompage in pagelist:
        wr(formatter.table_row(1))
        wr(formatter.table_cell(1, {'class': 'meta_page',
                                    'rowspan': str(valnos[frompage])}))
        wr(u'%s', frompage)

        for i in range(valnos[frompage]):
            # Add <tr>:s for additional values also
            if i > 0:
                wr(formatter.table_row(1))

            for key in metakeys + ['']:
                inputname = frompage + SEPARATOR + key

                if len(values[frompage][key]) >= (i + 1):
                    val = values[frompage][key][i]
                else:
                    val = ''

                # Skip default labels
                if key == 'label' and val == frompage:
                    val = ''

                wr(formatter.table_cell(1, {'class': 'meta_cell'}))
                wr(u'<textarea class="metavalue dynamic"  rows="1" name="%s">%s</textarea>',
                   inputname, val)

                #print frompage, key, inputname, values, '<br>'
            wr(formatter.table_row(0))

        wr(formatter.table_row(1))
        wr(formatter.table_cell(1, {'class': 'meta_cell'}))
        for key in metakeys + ['']:
            inputname = frompage + SEPARATOR + key

            if len(values[frompage][key]) >= (i + 1):
                val = values[frompage][key][i]
            else:
                val = ''

            # Skip default labels
            if key == 'label' and val == frompage:
                val = ''

            wr(formatter.table_cell(1))
            wr(u'<input class="metavalue" type="file" name="%s">\n', inputname)

        wr(formatter.table_row(0))

# Proto JS code to warn on leaving an empty key name
# <script language="JavaScript" type="text/javascript">
#    function myvalid(me) {
#      if (me.form.subject.value == "") {
#        if (confirm("Empty subject, send anyway?"))
#          return true;
#        else
#          return false;
#      }
#      return true;
#    }
# </script>
# <input type="submit" name="send" value="Send" class="button1"tabindex="7"
# onClick="return myvalid(this);" />

    wr(formatter.table(0))
    wr(u'<input type="submit" name="save" value="%s">\n', _('Save'))
    wr(u'<input type="submit" name="cancel" value="%s">\n', _('Cancel'))
    wr(u'</form>\n')
Ejemplo n.º 36
0
def execute(pagename, request):
    pagename_header = '%s-%s.zip' % (pagename, datetime.now().isoformat()[:10])
    pagename_header = pagename_header.encode('ascii', 'ignore')

    request.content_type = 'application/zip'
    request.headers['Content-Disposition'] = \
        'attachment; filename="%s"' % pagename_header

    args = values_to_form(request.values)

    try:
        args = args['args'][0]
    except (KeyError, IndexError):
        args = u''

    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)

    renameDict = dict()

    for page in pagelist:
        metas = get_metas(request,
                          page, ["gwikirename"],
                          abs_attach=False,
                          checkAccess=False)
        renameList = metas["gwikirename"]
        if renameList:
            renameDict[page] = renameList

    output = StringIO()
    zip = zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED)

    userid = user.getUserIdentification(request)
    script = [
        packLine(['MoinMoinPackage', '1']),
    ]
    counter = 0

    for pagename in pagelist:
        counter += 1
        page = Page(request, pagename)
        timestamp = wikiutil.version2timestamp(page.mtime_usecs())
        # Underlay pages are in epoch 0, zipfile in python 2.7 does
        # not support this.
        if not timestamp:
            pagefile, rev, exists = page.get_rev()
            if rev == 99999999:
                # We should never get here
                log.error("Page %s neither in pages or underlay, skipping." %
                          (pagename))
                continue
            timestamp = os.path.getctime(pagefile)
        pagetext = page.get_raw_body().encode("utf-8")
        filename = str(counter)
        zinfo = zipfile.ZipInfo(
            filename=filename,
            date_time=datetime.fromtimestamp(timestamp).timetuple()[:6])
        zinfo.compress_type = zipfile.ZIP_DEFLATED
        zip.writestr(zinfo, pagetext)

        targetNameList = renameDict.get(pagename, [pagename])
        for targetName in targetNameList:
            script.append(
                packLine(["AddRevision", filename, targetName, userid, ""]))

        for attachment in _get_files(request, pagename):
            counter += 1
            sourcefile = AttachFile.getFilename(request, pagename, attachment)
            filename = str(counter) + "-attachment"
            zip.write(sourcefile, filename)
            script.append(
                packLine([
                    "AddAttachment", filename, attachment, pagename, userid, ""
                ]))

    zip.writestr(MOIN_PACKAGE_FILE, u"\n".join(script).encode("utf-8"))
    zip.close()

    request.write(output.getvalue())
Ejemplo n.º 37
0
def execute(pagename, request):
    _ = request.getText

    form = values_to_form(request.values)

    if not request.user.may.write(pagename):
        request.reset()
        backto = form.get('backto', [None])[0]
        if backto:
            request.page = Page(request, backto)

        request.theme.add_msg(_('You are not allowed to edit this page.'),
                              "error")
        request.page.send_page()
        return

    frm = wr(
        u'<form id="metaformedit" method="POST" enctype="multipart/form-data" action="%s">\n',
             actionname(request))+\
          wr(u'<input form="metaformedit" type="hidden" name="action" value="MetaEdit">\n')+\
          wr(u'<input form="metaformedit" type="hidden" name="gwikiseparator" value="%s">\n',
             SEPARATOR)

    btn = '<div class="saveform"><p class="savemessage">' + \
          wr('<input type=submit name=saveform form="metaformedit" value="%s">',
             _(form.get('saveBtnText', ['Save Changes'])[0])) + \
             wr('<input form="metaformedit" type=submit name=cancel value="%s">',
                _('Cancel')) +'</p></div>'

    # Template to use for any new pages
    template = form.get('template', [''])[0]
    if template:
        frm += wr('<input form="metaformedit" type="hidden" name="template" value="%s">', template)
    # Where to after saving page
    backto = form.get('backto', [''])[0]
    if backto:
        frm += wr('<input form="metaformedit" type="hidden" name="backto" value="%s">', backto)

    old_header = request.cfg.page_header2
    old_footer = request.cfg.page_footer1
    # The post-header and pre-footer texts seem to be implemented in themes.
    # Using post-header instead of page msg to avoid breaking header forms.
    request.cfg.page_header2 += frm + btn
    request.cfg.page_footer1 += btn + '</form>'

    old_page = request.page
    request.page = FormPage(request, pagename)

    error = ''
    newpage = False
    template_text = ''
    # If the page does not exist but we'd know how to construct it,
    # replace the Page content with template and pretend it exists
    if template and not request.page.exists():
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            editor = PageEditor(request, template_page)
            editor.user = request.user
            text = editor.get_raw_body()
            editor.page_name = pagename
            template_text = editor._expand_variables(text)
            request.page.set_raw_body(template_text)
            request.page.exists = lambda **kw: True
            request.page.lastEditInfo = lambda: {}
            newpage = True
        else:
            error = '<div class="saveform"><p class="savemessage">' + \
                    _("Cannot read template") + '</p></div>'

    elif not template and not request.page.exists():
        error = '<div class="saveform"><p class="savemessage">' + \
                _("No template specified, cannot edit") + '</p></div>'


    if error:
        request.cfg.page_header2 = request.cfg.page_header2 + error
        request.cfg.page_footer1 = request.cfg.page_footer1

    # Extra spaces from formatter need to be removed, that's why the
    # page is not sent as it is
    out = StringIO.StringIO()
    request.redirect(out)
    request.sent_headers = True
    request.page.send_page()
    request.redirect()

    graphdata = request.graphdata
    vals_on_keys = graphdata.get_vals_on_keys()

    # If we're making a new page based on a template, make sure that
    # the values from the evaluated template are included in the form editor
    if newpage:
        templatePage = Page(request, template)
        data = parse_text(request, templatePage, template_text)
        for page in data:
            for key in data[page].get('meta', list()):
                for val in data[page]['meta'][key]:
                    vals_on_keys.setdefault(key, set()).add(val)
            for key in data[page].get('out', list()):
                for val in data[page]['out'][key]:
                    vals_on_keys.setdefault(key, set()).add(val)

            pagemeta = graphdata.get_meta(page)

            for key in pagemeta:
                for val in pagemeta[key]:
                    vals_on_keys.setdefault(key, set()).add(val)

    # Form types
    def form_selection(request, pagekey, curval, values, description=''):
        msg = wr('<select form="metaformedit" name="%s">', pagekey)
        msg += wr('<option value=""> </option>')

        for keyval, showval in values:
            msg += wr('<option value="%s"%s>%s</option>',
                      keyval, curval == keyval and ' selected' or '',
                      showval)

        msg += '</select>'

        return msg

    def form_checkbox(request, pagekey, curval, values, description=''):
        msg = ''

        for keyval, showval in values:
            msg += wr(
                '<input form="metaformedit" type="checkbox" name="%s" value="%s"%s>',
                pagekey, keyval, curval == keyval and ' checked' or '') + \
                '<label>' + format_wikitext(request, showval) +'</label>'

        return msg

    def form_radio(request, pagekey, curval, values, description=''):
        msg = ''

        for keyval, showval in values:
            msg += wr(
                '<input form="metaformedit" type="radio" name="%s" value="%s"%s>',
                pagekey, keyval, curval == keyval and ' checked' or '') + \
                '<label>' + format_wikitext(request, showval) +'</label>'

        return msg

    def form_textbox(request, pagekey, curval, values, description=''):
        return wr('<textarea form="metaformedit" name="%s">%s</textarea>',
                  pagekey, curval)

    def form_date(request, pagekey, curval, values, description=''):
        return wr('<input form="metaformedit" type="text" class="date" name="%s" value="%s">',
                pagekey, curval)

    def form_file(request, pagekey, curval, values, description=''):
        if curval:
            return wr(
                '<input form="metaformedit" class="file" type="text" name="%s" value="%s" readonly>'
                , pagekey, curval)
        else:
            return wr(
                '<input form="metaformedit" class="file" type="file" name="%s%s0" value="" readonly>',
                pagekey, SEPARATOR)

    formtypes = {'selection': form_selection,
                 'checkbox': form_checkbox,
                 'textbox': form_textbox,
                 'textarea': form_textbox,
                 'radio': form_radio,
                 'date': form_date,
                 'file': form_file}

    def repl_subfun(mo):
        dt, pagekey, val = mo.groups()

        pagekey = form_unescape(pagekey)
        msg = dt
        key = pagekey.split(SEPARATOR)[1]

        properties = get_properties(request, key)

        values = list()

        # Placeholder key key
        if key in vals_on_keys:
            for keyval in sorted(vals_on_keys[key]):
                keyval = keyval.strip()
# Is this really needed? If so, probably should make the length configurable..
#                if len(keyval) > 30:
#                    showval = keyval[:27] + '...'
#                else:
#                    showval = keyval
                showval = keyval

                values.append((keyval, showval))

        formtype = properties.get('hint')
        constraint = properties.get('constraint')
        desc = properties.get('description')
        default = properties.get('default', '')
        hidden = False

        if formtype == "hidden":
            hidden = True

        if not formtype in formtypes:
            formtype = "selection"

        if (not formtype == "radio" and
            not (formtype == "checkbox" and constraint == "existing")):
            cloneable = "true"
        else:
            cloneable = "false"

        if desc:
            msg = msg.replace('</dt>', ' %s</dt>' % \
                                  request.formatter.icon('info'))
            msg = msg.replace('<dt>', wr(
                    '<dt class="mt-tooltip" title="%s" rel="%s">', key, desc))

        msg = msg.replace('<dd>', wr('<dd class="metaformedit" data-cloneable="%s" data-default="%s">',  cloneable, default))

        msg += formtypes[formtype](request, pagekey, val, values)


        if (not constraint == 'existing' and
            not formtype in ['textbox', 'textarea', 'file', 'date']):
            msg += wr('<textarea form="metaformedit" name="%s"></textarea>', pagekey)

        if hidden:
            msg = request.formatter.div(1, css_class='comment') + msg + \
                request.formatter.div(0)
        return msg

    data = out.getvalue()
    data = value_re.sub(repl_subfun, data)
    request.write(data)
    request.page = old_page
    request.cfg.page_header2 = old_header
    request.cfg.page_footer1 = old_footer
Ejemplo n.º 38
0
    def execute(self):
        request = self.request
        _ = request.getText

        pagename = request.page.page_name
        if not request.user.may.read(pagename):
            fault = _(u'Can not read page') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        form = values_to_form(request.values)
        self.formargs(form)

        if self.help or not self.attachment:
            enter_page(request, pagename, 'View .gv attachment')

            self.sendForm()

            if self.help:
                # This is the URL addition to the nodes that have graph data
                self.urladd = url_parameters(form)
                self.urladd = self.urladd.replace('&help=Inline', '')
                request.write('&lt;&lt;ViewDot(' + self.urladd + ')&gt;&gt;')

            exit_page(request, pagename)
            return

        if not self.attachment[:10].lower() == 'attachment':
            fault = _(u'No attachment defined') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        self.attachment = self.attachment[11:]

        pagename, filename = AttachFile.absoluteName(self.attachment,
                                                     self.pagename)
        if not request.user.may.read(pagename):
            fault = _(u'Can not read attachment page') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        fname = wikiutil.taintfilename(filename)
        fpath = AttachFile.getFilename(request, pagename, fname)

        try:
            data = file(fpath, 'r').read()
        except IOError:
            fault = _(u'Can not read attachment') + u'\n'
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        if not have_gv():
            fault = _(u"ERROR: Graphviz Python extensions not installed. " +\
                      u"Not performing layout.")
            if self.inline:
                request.write(request.formatter.text(fault))
                return
            request.content_type = 'text/plain'
            request.write(fault)
            return

        self.cache_key = cache_key(self.request,
                                   [data, self.graphengine, self.format])
        key = "%s-%s" % (self.cache_key, self.format)

        if self.format in ['zgr', 'svg']:
            formatcontent = 'svg+xml'
        else:
            formatcontent = self.format

        if not cache_exists(request, key):
            graphviz = Graphviz(engine=self.graphengine, string=data)
            data = self.getLayoutInFormat(graphviz, self.format)

            cache.put(self.request, key, data, content_type=formatcontent)

        if self.format in ['zgr', 'svg']:
            # Display zgr graphs as applets
            if self.format == 'zgr':
                image_p = lambda url, text: \
                    '<applet code="net.claribole.zgrviewer.ZGRApplet.class"'+ \
                    ' archive="%s/gwikicommon/zgrviewer/zvtm.jar,' % \
                    (self.request.cfg.url_prefix_static) + \
                    '%s/gwikicommon/zgrviewer/zgrviewer.jar" ' % \
                    (self.request.cfg.url_prefix_static) + \
                    'width="%s" height="%s">' % (form_escape(self.width), form_escape(self.height))+\
                    '<param name="type" ' + \
                    'value="application/x-java-applet;version=1.4" />' + \
                    '<param name="scriptable" value="false" />' + \
                    '<param name="svgURL" value="%s" />' % (url) + \
                    '<param name="title" value="ZGRViewer - Applet" />'+ \
                    '<param name="appletBackgroundColor" value="#DDD" />' + \
                    '<param name="graphBackgroundColor" value="#DDD" />' + \
                    '<param name="highlightColor" value="red" />' + \
                    ' </applet><br>\n'
            else:
                image_p = lambda url, text: \
                    '<object data="%s" alt="%s" ' % (url, text) + \
                    'type="image/svg+xml">\n' + \
                    '<embed src="%s" alt="%s" ' % (url, text) + \
                    'type="image/svg+xml"/>\n</object>'
        else:
            image_p = lambda url, text: \
                '<img src="%s" alt="%s">\n' % (url, text)

        image_uri = cache.url(self.request, key)

        if not self.inline:
            if self.format == 'zgr':
                request.write('<html><body>')

        request.write(image_p(image_uri, _('visualisation')))

        if not self.inline and self.format == 'zgr':
            request.write('</html></body>')
        else:
            pass # No footer
Ejemplo n.º 39
0
def execute(pagename, request):
    form = values_to_form(request.values)

    util = form.get('util', [None])[0]

    if util == "format":
        txt = form.get('text', [None])[0]
        request.write(format_wikitext(request, txt))

    elif util == "getTemplate":
        template = form.get('name', [None])[0]
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            Page(request, template_page).send_raw()

    elif util == "newPage":
        page = form.get('page', [None])[0]
        content = form.get('content', [""])[0]
        request.content_type = "application/json"

        if request.environ['REQUEST_METHOD'] != 'POST':
            return

        if not page:
            msg = "Page name not defined!"
            json.dump(dict(status="error", msg=msg), request)
            return

        if not request.user.may.write(page):
            msg = "You are not allowed to edit this page"
            json.dump(dict(status="error", msg=msg), request)
            return

        p = Page(request, page)
        if p.exists():
            msg = "Page already exists"
            json.dump(dict(status="error", msg=msg), request)
            return

        editor = PageEditor(request, page)
        msg = editor.saveText(content, p.get_real_rev())
        json.dump(dict(status="ok", msg=msg), request)


    elif util == "getProperties":
        request.content_type = "application/json"
        key = form.get('key', [''])[0]
        json.dump(get_properties(request, key), request)
        return

    elif util == "uploadFile":
        request.content_type = "application/json"

        if not request.user.may.write(pagename):
            msg = u"You are not allowed to edit this page!"
            json.dump(dict(status="error", msg=msg), request)
            request.status_code = 403
            return

        from MoinMoin.action.AttachFile import add_attachment, AttachmentAlreadyExists

        try:
            overwrite = int(form.get('overwrite', ['0'])[0])
        except:
            overwrite = 0

        response = dict(success=list(), failed=list())
        for name in request.files:
            _file = request.files.get(name)
            filename = _file.filename
            try:
                t,s = add_attachment(request, pagename, filename, _file.stream, overwrite=overwrite)
                response['success'].append(filename)
            except AttachmentAlreadyExists:
                response['failed'].append(filename)

        json.dump(response, request)
        return

    elif util == "getAttachments":
        request.content_type = "application/json"
        from MoinMoin.action.AttachFile import _get_files, getAttachUrl

        files = _get_files(request, pagename)
        response = []
        for name in files:
            response.append(dict(url=getAttachUrl(pagename, name, request),name=name))

        json.dump(response, request)

    return
Ejemplo n.º 40
0
def _do_diff(pagename, request):
    # return attachment list
    _ = request.getText

    form = values_to_form(request.values)

    att1 = form.get('att1', [''])[0]
    att2 = form.get('att2', [''])[0]
    sort = form.get('sort', ['normal'])[0]

    if (not (att1 and att2)
            or not (AttachFile.exists(request, pagename, att1)
                    and AttachFile.exists(request, pagename, att2))):
        AttachFile.error_msg(
            pagename, request,
            _('Could not diff, attachments not selected or nonexisting'))
        return

    form['target'] = [att1]
    request.values = CombinedMultiDict([MultiDict(form)])
    pagename, filename, fpath = AttachFile._access_file(pagename, request)

    att1data = open(fpath, 'r').read()

    form['target'] = [att2]
    request.values = CombinedMultiDict([MultiDict(form)])
    pagename, filename, fpath = AttachFile._access_file(pagename, request)
    att2data = open(fpath, 'r').read()

    if sort == 'sort':
        att1data = '\n'.join(sorted(att1data.split('\n')))
        att2data = '\n'.join(sorted(att2data.split('\n')))
    elif sort == 'uniq':
        att1data = '\n'.join(sorted(set(att1data.split('\n'))))
        att2data = '\n'.join(sorted(set(att2data.split('\n'))))
    elif sort == 'cnt':
        att1tmp = list()
        for line in sorted(set(att1data.split('\n'))):
            if not line:
                continue
            att1tmp.append("%s %s" % (att1data.count(line), line))
        att2tmp = list()
        for line in sorted(set(att2data.split('\n'))):
            if not line:
                continue
            att2tmp.append("%s %s" % (att2data.count(line), line))
        att1data = '\n'.join(att1tmp)
        att2data = '\n'.join(att2tmp)

    # Use user interface language for this generated page
    request.setContentLanguage(request.lang)
    request.theme.send_title(_('Diff of %s and %s') % (att1, att2),
                             pagename=pagename)
    request.write('<div id="content">\n')  # start content div

    if request.user.show_fancy_diff:
        from MoinMoin.util import diff_html
        request.write(
            request.formatter.rawHTML(
                diff_html.diff(request, att1data, att2data)))
    else:
        from MoinMoin.util import diff_text
        lines = diff_text.diff(att1data.split("\n"), att2data.split("\n"))

        request.write(request.formatter.preformatted(1))
        for line in lines:
            if line[0] == "@":
                request.write(request.formatter.rule(1))
            request.write(request.formatter.text(line + '\n'))
        request.write(request.formatter.preformatted(0))

    AttachFile.send_uploadform(pagename, request)
    request.write('</div>\n')  # end content div
    request.theme.send_footer(pagename)
    request.theme.send_closing_html()
Ejemplo n.º 41
0
def execute(pagename, request):
    _ = request.getText

    form = values_to_form(request.values)

    if not request.user.may.write(pagename):
        request.reset()
        backto = form.get('backto', [None])[0]
        if backto:
            request.page = Page(request, backto)

        request.theme.add_msg(_('You are not allowed to edit this page.'),
                              "error")
        request.page.send_page()
        return

    frm = wr(
        u'<form id="metaformedit" method="POST" enctype="multipart/form-data" action="%s">\n',
             actionname(request))+\
          wr(u'<input form="metaformedit" type="hidden" name="action" value="MetaEdit">\n')+\
          wr(u'<input form="metaformedit" type="hidden" name="gwikiseparator" value="%s">\n',
             SEPARATOR)

    btn = '<div class="saveform"><p class="savemessage">' + \
          wr('<input type=submit name=saveform form="metaformedit" value="%s">',
             _(form.get('saveBtnText', ['Save Changes'])[0])) + \
             wr('<input form="metaformedit" type=submit name=cancel value="%s">',
                _('Cancel')) +'</p></div>'

    # Template to use for any new pages
    template = form.get('template', [''])[0]
    if template:
        frm += wr(
            '<input form="metaformedit" type="hidden" name="template" value="%s">',
            template)
    # Where to after saving page
    backto = form.get('backto', [''])[0]
    if backto:
        frm += wr(
            '<input form="metaformedit" type="hidden" name="backto" value="%s">',
            backto)

    old_header = request.cfg.page_header2
    old_footer = request.cfg.page_footer1
    # The post-header and pre-footer texts seem to be implemented in themes.
    # Using post-header instead of page msg to avoid breaking header forms.
    request.cfg.page_header2 += frm + btn
    request.cfg.page_footer1 += btn + '</form>'

    old_page = request.page
    request.page = FormPage(request, pagename)

    error = ''
    newpage = False
    template_text = ''
    # If the page does not exist but we'd know how to construct it,
    # replace the Page content with template and pretend it exists
    if template and not request.page.exists():
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            editor = PageEditor(request, template_page)
            editor.user = request.user
            text = editor.get_raw_body()
            editor.page_name = pagename
            template_text = editor._expand_variables(text)
            request.page.set_raw_body(template_text)
            request.page.exists = lambda **kw: True
            request.page.lastEditInfo = lambda: {}
            newpage = True
        else:
            error = '<div class="saveform"><p class="savemessage">' + \
                    _("Cannot read template") + '</p></div>'

    elif not template and not request.page.exists():
        error = '<div class="saveform"><p class="savemessage">' + \
                _("No template specified, cannot edit") + '</p></div>'

    if error:
        request.cfg.page_header2 = request.cfg.page_header2 + error
        request.cfg.page_footer1 = request.cfg.page_footer1

    # Extra spaces from formatter need to be removed, that's why the
    # page is not sent as it is
    out = StringIO.StringIO()
    request.redirect(out)
    request.sent_headers = True
    request.page.send_page()
    request.redirect()

    graphdata = request.graphdata
    vals_on_keys = graphdata.get_vals_on_keys()

    # If we're making a new page based on a template, make sure that
    # the values from the evaluated template are included in the form editor
    if newpage:
        templatePage = Page(request, template)
        data = parse_text(request, templatePage, template_text)
        for page in data:
            for key in data[page].get('meta', list()):
                for val in data[page]['meta'][key]:
                    vals_on_keys.setdefault(key, set()).add(val)
            for key in data[page].get('out', list()):
                for val in data[page]['out'][key]:
                    vals_on_keys.setdefault(key, set()).add(val)

            pagemeta = graphdata.get_meta(page)

            for key in pagemeta:
                for val in pagemeta[key]:
                    vals_on_keys.setdefault(key, set()).add(val)

    # Form types
    def form_selection(request, pagekey, curval, values, description=''):
        msg = wr('<select form="metaformedit" name="%s">', pagekey)
        msg += wr('<option value=""> </option>')

        for keyval, showval in values:
            msg += wr('<option value="%s"%s>%s</option>', keyval,
                      curval == keyval and ' selected' or '', showval)

        msg += '</select>'

        return msg

    def form_checkbox(request, pagekey, curval, values, description=''):
        msg = ''

        for keyval, showval in values:
            msg += wr(
                '<input form="metaformedit" type="checkbox" name="%s" value="%s"%s>',
                pagekey, keyval, curval == keyval and ' checked' or '') + \
                '<label>' + format_wikitext(request, showval) +'</label>'

        return msg

    def form_radio(request, pagekey, curval, values, description=''):
        msg = ''

        for keyval, showval in values:
            msg += wr(
                '<input form="metaformedit" type="radio" name="%s" value="%s"%s>',
                pagekey, keyval, curval == keyval and ' checked' or '') + \
                '<label>' + format_wikitext(request, showval) +'</label>'

        return msg

    def form_textbox(request, pagekey, curval, values, description=''):
        return wr('<textarea form="metaformedit" name="%s">%s</textarea>',
                  pagekey, curval)

    def form_date(request, pagekey, curval, values, description=''):
        return wr(
            '<input form="metaformedit" type="text" class="date" name="%s" value="%s">',
            pagekey, curval)

    def form_file(request, pagekey, curval, values, description=''):
        if curval:
            return wr(
                '<input form="metaformedit" class="file" type="text" name="%s" value="%s" readonly>',
                pagekey, curval)
        else:
            return wr(
                '<input form="metaformedit" class="file" type="file" name="%s%s0" value="" readonly>',
                pagekey, SEPARATOR)

    formtypes = {
        'selection': form_selection,
        'checkbox': form_checkbox,
        'textbox': form_textbox,
        'textarea': form_textbox,
        'radio': form_radio,
        'date': form_date,
        'file': form_file
    }

    def repl_subfun(mo):
        dt, pagekey, val = mo.groups()

        pagekey = form_unescape(pagekey)
        msg = dt
        key = pagekey.split(SEPARATOR)[1]

        properties = get_properties(request, key)

        values = list()

        # Placeholder key key
        if key in vals_on_keys:
            for keyval in sorted(vals_on_keys[key]):
                keyval = keyval.strip()
                # Is this really needed? If so, probably should make the length configurable..
                #                if len(keyval) > 30:
                #                    showval = keyval[:27] + '...'
                #                else:
                #                    showval = keyval
                showval = keyval

                values.append((keyval, showval))

        formtype = properties.get('hint')
        constraint = properties.get('constraint')
        desc = properties.get('description')
        default = properties.get('default', '')
        hidden = False

        if formtype == "hidden":
            hidden = True

        if not formtype in formtypes:
            formtype = "selection"

        if (not formtype == "radio"
                and not (formtype == "checkbox" and constraint == "existing")):
            cloneable = "true"
        else:
            cloneable = "false"

        if desc:
            msg = msg.replace('</dt>', ' %s</dt>' % \
                                  request.formatter.icon('info'))
            msg = msg.replace(
                '<dt>',
                wr('<dt class="mt-tooltip" title="%s" rel="%s">', key, desc))

        msg = msg.replace(
            '<dd>',
            wr(
                '<dd class="metaformedit" data-cloneable="%s" data-default="%s">',
                cloneable, default))

        msg += formtypes[formtype](request, pagekey, val, values)

        if (not constraint == 'existing'
                and not formtype in ['textbox', 'textarea', 'file', 'date']):
            msg += wr('<textarea form="metaformedit" name="%s"></textarea>',
                      pagekey)

        if hidden:
            msg = request.formatter.div(1, css_class='comment') + msg + \
                request.formatter.div(0)
        return msg

    data = out.getvalue()
    data = value_re.sub(repl_subfun, data)
    request.write(data)
    request.page = old_page
    request.cfg.page_header2 = old_header
    request.cfg.page_footer1 = old_footer
Ejemplo n.º 42
0
def execute(pagename, request):
    _ = request.getText

    def wr(fmt, *args):
        request.write(form_writer(fmt, *args))

    # This action generates data using the user language
    request.setContentLanguage(request.lang)
    form = values_to_form(request.values)

    if form.has_key('cancel'):
        request.reset()
        backto = form.get('backto', [None])[0]
        request.theme.add_msg(_('Edit was cancelled.'), "error")
        if backto:
            page = Page(request, backto)
            request.http_redirect(page.url(request))
            request.page = page

        request.page.send_page()
    elif form.has_key('save') or form.has_key('saveform'):
        if request.environ['REQUEST_METHOD'] != 'POST':
            request.page.send_page()
            return

        template = form.get('template', [None])[0]

        # MetaFormEdit is much closer to set_meta in function
        if form.has_key('saveform'):
            added, cleared = {pagename: dict()}, {pagename: list()}

            # Pre-create page if it does not exist, using the template specified
            if template:
                added[pagename]['gwikitemplate'] = template

            # Ignore form clutter
            ignore = set()
            files = dict()
            for key in request.files:
                ignore.add(key)
                _file = request.files.get(key)
                filename = _file.filename
                fileobj = _file.stream

                #                    if type(fileobj) != file:
                #                        continue

                banana = key.split(SEPARATOR)
                keys = files.setdefault(banana[0], dict())
                values = keys.setdefault(banana[1], list())
                values.append((filename, fileobj))

            keys = list()
            for key in form:
                if key not in ignore and SEPARATOR in key:
                    keys.append(key.split(SEPARATOR)[1])


#            keys = [x.split(SEPARATOR)[1] for x in form if SEPARATOR in x]

            for key in keys:
                cleared[pagename].append(key)
                vals = [
                    x.strip() for x in form[pagename + SEPARATOR + key]
                    if x.strip()
                ]
                if vals:
                    added[pagename].setdefault(key, list()).extend(vals)

            msgs = list()
            # Add attachments
            for pname in files:
                for key in files[pname]:
                    for value in files[pname][key]:
                        name = value[0]
                        try:
                            t, s = add_attachment(request, pname, name,
                                                  value[1])
                            added.setdefault(pname, dict()).setdefault(
                                key, list()).append("[[attachment:%s]]" % name)
                        except AttachmentAlreadyExists:
                            msgs = ["Attachment '%s' already exists." % name]

            _, msgss = set_metas(request, cleared, dict(), added)
            msgs.extend(msgss)

        else:
            # MetaEdit
            pages, msgs, files = parse_editform(request, form)

            if pages:
                saved_templates = False

                for page, _ in pages.iteritems():
                    # Save the template if needed
                    if not Page(request, page).exists() and template:
                        msgs.append(save_template(request, page, template))
                        saved_templates = True

                # If new pages were changed we need to redo parsing
                # the form to know what we really need to edit
                if saved_templates:
                    pages, newmsgs, files = parse_editform(request, form)

                for page, (oldMeta, newMeta) in pages.iteritems():
                    msgs.append('%s: ' % page +
                                edit_meta(request, page, oldMeta, newMeta))

                for page in files:
                    for key in files[page]:
                        name, content = files[page][key]
                        t, s = add_attachment(request, page, name, content)
            else:
                msgs.append(request.getText('No pages changed'))

        msg = ''
        for line in msgs:
            msg += line + request.formatter.linebreak(0)

        request.reset()
        backto = form.get('backto', [None])[0]
        if backto:
            page = Page(request, backto)
            request.http_redirect(page.url(request))
        else:
            page = Page(request, pagename)

        request.theme.add_msg(msg)
        request.page = page
        page.send_page()
    elif form.has_key('args'):
        enter_page(request, pagename, 'Metatable editor')
        formatter = request.page.formatter

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit metatable")))
        request.write(formatter.heading(0, 2))
        args = ', '.join(form['args'])
        show_editform(wr, request, pagename, args)

        exit_page(request, pagename)
    else:
        enter_page(request, pagename, 'Metatable editor')
        formatter = request.page.formatter

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit current page")))
        request.write(formatter.heading(0, 2))
        show_editform(wr, request, pagename, pagename)

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit metatable")))
        request.write(formatter.heading(0, 2))
        show_queryform(wr, request, pagename)

        exit_page(request, pagename)
    return
Ejemplo n.º 43
0
def execute(pagename, request):
    form = values_to_form(request.values)

    util = form.get('util', [None])[0]

    if util == "format":
        txt = form.get('text', [None])[0]
        request.write(format_wikitext(request, txt))

    elif util == "getTemplate":
        template = form.get('name', [None])[0]
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            Page(request, template_page).send_raw()

    elif util == "newPage":
        page = form.get('page', [None])[0]
        content = form.get('content', [""])[0]
        request.content_type = "application/json"

        if request.environ['REQUEST_METHOD'] != 'POST':
            return

        if not page:
            msg = "Page name not defined!"
            json.dump(dict(status="error", msg=msg), request)
            return

        if not request.user.may.write(page):
            msg = "You are not allowed to edit this page"
            json.dump(dict(status="error", msg=msg), request)
            return

        p = Page(request, page)
        if p.exists():
            msg = "Page already exists"
            json.dump(dict(status="error", msg=msg), request)
            return

        editor = PageEditor(request, page)
        msg = editor.saveText(content, p.get_real_rev())
        json.dump(dict(status="ok", msg=msg), request)

    elif util == "getProperties":
        request.content_type = "application/json"
        key = form.get('key', [''])[0]
        json.dump(get_properties(request, key), request)
        return

    elif util == "uploadFile":
        request.content_type = "application/json"

        if not request.user.may.write(pagename):
            msg = u"You are not allowed to edit this page!"
            json.dump(dict(status="error", msg=msg), request)
            request.status_code = 403
            return

        from MoinMoin.action.AttachFile import add_attachment, AttachmentAlreadyExists

        try:
            overwrite = int(form.get('overwrite', ['0'])[0])
        except:
            overwrite = 0

        response = dict(success=list(), failed=list())
        for name in request.files:
            _file = request.files.get(name)
            filename = _file.filename
            try:
                t, s = add_attachment(request,
                                      pagename,
                                      filename,
                                      _file.stream,
                                      overwrite=overwrite)
                response['success'].append(filename)
            except AttachmentAlreadyExists:
                response['failed'].append(filename)

        json.dump(response, request)
        return

    elif util == "getAttachments":
        request.content_type = "application/json"
        from MoinMoin.action.AttachFile import _get_files, getAttachUrl

        files = _get_files(request, pagename)
        response = []
        for name in files:
            response.append(
                dict(url=getAttachUrl(pagename, name, request), name=name))

        json.dump(response, request)

    return
Ejemplo n.º 44
0
def show_editform(wr, request, pagename, args):
    formatter = request.formatter

    # Note that metatable_parseargs handles read permission checks
    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)

    uneditable_pages = list()
    # See that the user can write each page
    for page in pagelist:
        if not request.user.may.write(page):
            uneditable_pages.append(page)
    for page in uneditable_pages:
        pagelist.remove(page)

    _ = request.getText

    if uneditable_pages:
        reason = _("No save permission to some pages (%s)" %
                   ','.join(uneditable_pages))
        request.write(render_warning(reason))

    if not pagelist:
        reason = _("No pages to edit.")
        request.write(render_error(reason))
        return

    wr(u'<form method="POST" action="%s" enctype="multipart/form-data">\n',
       actionname(request))
    wr(u'<input type="hidden" name="action" value="%s">\n', action_name)
    wr(formatter.table(1))
    wr(formatter.table_row(1, {'rowclass': 'meta_header'}))
    wr(formatter.table_cell(1, {'class': 'meta_page'}))

    form = values_to_form(request.values)

    template = form.get('template', [''])[0]
    if template:
        wr('<input type="hidden" name="template" value="%s">', template)

    # Filter out uneditables, such as inlinks
    metakeys = editable_p(metakeys)

    _ = request.getText

    for key in metakeys + ['']:
        wr(formatter.table_cell(1, {'class': 'meta_header'}))
        wr(u'<input class="metakey" type="text" name="%s" value="%s">',
           u':: %s' % key, key)
    wr(formatter.table_row(0))

    values = dict()
    valnos = dict()

    for frompage in pagelist:
        values[frompage] = dict()

        for key in metakeys + ['']:
            values[frompage][key] = list()
            # If the page has no values for this key, it'll
            # have one in the table to add a value
            if not valnos.has_key(frompage):
                valnos[frompage] = 1

            keydata = get_metas(request,
                                frompage, [key],
                                abs_attach=False,
                                includeGenerated=False)

            for i, val in enumerate(keydata[key]):
                values[frompage][key].append(val)
                # Enumerate starts from 0: #values++
                # One to add a value: #values++
                if valnos[frompage] < i + 2:
                    valnos[frompage] = i + 2

            values[frompage][key].append('')

    for frompage in pagelist:
        wr(formatter.table_row(1))
        wr(
            formatter.table_cell(1, {
                'class': 'meta_page',
                'rowspan': str(valnos[frompage])
            }))
        wr(u'%s', frompage)

        for i in range(valnos[frompage]):
            # Add <tr>:s for additional values also
            if i > 0:
                wr(formatter.table_row(1))

            for key in metakeys + ['']:
                inputname = frompage + SEPARATOR + key

                if len(values[frompage][key]) >= (i + 1):
                    val = values[frompage][key][i]
                else:
                    val = ''

                # Skip default labels
                if key == 'label' and val == frompage:
                    val = ''

                wr(formatter.table_cell(1, {'class': 'meta_cell'}))
                wr(
                    u'<textarea class="metavalue dynamic"  rows="1" name="%s">%s</textarea>',
                    inputname, val)

                #print frompage, key, inputname, values, '<br>'
            wr(formatter.table_row(0))

        wr(formatter.table_row(1))
        wr(formatter.table_cell(1, {'class': 'meta_cell'}))
        for key in metakeys + ['']:
            inputname = frompage + SEPARATOR + key

            if len(values[frompage][key]) >= (i + 1):
                val = values[frompage][key][i]
            else:
                val = ''

            # Skip default labels
            if key == 'label' and val == frompage:
                val = ''

            wr(formatter.table_cell(1))
            wr(u'<input class="metavalue" type="file" name="%s">\n', inputname)

        wr(formatter.table_row(0))


# Proto JS code to warn on leaving an empty key name
# <script language="JavaScript" type="text/javascript">
#    function myvalid(me) {
#      if (me.form.subject.value == "") {
#        if (confirm("Empty subject, send anyway?"))
#          return true;
#        else
#          return false;
#      }
#      return true;
#    }
# </script>
# <input type="submit" name="send" value="Send" class="button1"tabindex="7"
# onClick="return myvalid(this);" />

    wr(formatter.table(0))
    wr(u'<input type="submit" name="save" value="%s">\n', _('Save'))
    wr(u'<input type="submit" name="cancel" value="%s">\n', _('Cancel'))
    wr(u'</form>\n')
Ejemplo n.º 45
0
def execute(pagename, request):
    _ = request.getText

    def wr(fmt, *args):
        request.write(form_writer(fmt, *args))

    # This action generates data using the user language
    request.setContentLanguage(request.lang)
    form = values_to_form(request.values)

    if form.has_key('cancel'):
        request.reset()
        backto = form.get('backto', [None])[0]
        request.theme.add_msg(_('Edit was cancelled.'), "error")
        if backto:
            page = Page(request, backto)
            request.http_redirect(page.url(request))
            request.page = page

        request.page.send_page()
    elif form.has_key('save') or form.has_key('saveform'):
        if request.environ['REQUEST_METHOD'] != 'POST':
            request.page.send_page()
            return

        template = form.get('template', [None])[0]

        # MetaFormEdit is much closer to set_meta in function
        if form.has_key('saveform'):
            added, cleared = {pagename: dict()}, {pagename: list()}

            # Pre-create page if it does not exist, using the template specified
            if template:
                added[pagename]['gwikitemplate'] = template

            # Ignore form clutter
            ignore = set()
            files = dict()
            for key in request.files:
                ignore.add(key)
                _file = request.files.get(key)
                filename = _file.filename
                fileobj = _file.stream

#                    if type(fileobj) != file:
#                        continue

                banana = key.split(SEPARATOR)
                keys = files.setdefault(banana[0], dict())
                values = keys.setdefault(banana[1], list())
                values.append((filename, fileobj))

            keys = list()
            for key in form:
                if key not in ignore and SEPARATOR in key:
                    keys.append(key.split(SEPARATOR)[1])
#            keys = [x.split(SEPARATOR)[1] for x in form if SEPARATOR in x]

            for key in keys:
                cleared[pagename].append(key)
                vals = [x.strip() for x in form[pagename + SEPARATOR + key]
                            if x.strip()]
                if vals:
                    added[pagename].setdefault(key, list()).extend(vals)

            msgs = list()
            # Add attachments
            for pname in files:
                for key in files[pname]:
                    for value in files[pname][key]:
                        name = value[0]
                        try:
                            t, s = add_attachment(request, pname,
                                                  name, value[1])
                            added.setdefault(pname, dict()).setdefault(
                                key, list()).append("[[attachment:%s]]" % name)
                        except AttachmentAlreadyExists:
                            msgs = ["Attachment '%s' already exists." % name]

            _, msgss = set_metas(request, cleared, dict(), added)
            msgs.extend(msgss)

        else:
            # MetaEdit
            pages, msgs, files = parse_editform(request, form)

            if pages:
                saved_templates = False

                for page, _ in pages.iteritems():
                    # Save the template if needed
                    if not Page(request, page).exists() and template:
                        msgs.append(save_template(request, page, template))
                        saved_templates = True

                # If new pages were changed we need to redo parsing
                # the form to know what we really need to edit
                if saved_templates:
                    pages, newmsgs, files = parse_editform(request, form)

                for page, (oldMeta, newMeta) in pages.iteritems():
                    msgs.append('%s: ' % page +
                                edit_meta(request, page, oldMeta, newMeta))

                for page in files:
                    for key in files[page]:
                        name, content = files[page][key]
                        t, s = add_attachment(request, page, name, content)
            else:
                msgs.append(request.getText('No pages changed'))

        msg = ''
        for line in msgs:
            msg += line + request.formatter.linebreak(0)

        request.reset()
        backto = form.get('backto', [None])[0]
        if backto:
            page = Page(request, backto)
            request.http_redirect(page.url(request))
        else:
            page = Page(request, pagename)

        request.theme.add_msg(msg)
        request.page = page
        page.send_page()
    elif form.has_key('args'):
        enter_page(request, pagename, 'Metatable editor')
        formatter = request.page.formatter

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit metatable")))
        request.write(formatter.heading(0, 2))
        args = ', '.join(form['args'])
        show_editform(wr, request, pagename, args)

        exit_page(request, pagename)
    else:
        enter_page(request, pagename, 'Metatable editor')
        formatter = request.page.formatter

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit current page")))
        request.write(formatter.heading(0, 2))
        show_editform(wr, request, pagename, pagename)

        request.write(formatter.heading(1, 2))
        request.write(formatter.text(_("Edit metatable")))
        request.write(formatter.heading(0, 2))
        show_queryform(wr, request, pagename)

        exit_page(request, pagename)
    return
Ejemplo n.º 46
0
def get_url_params(request):
    try:
        return values_to_form(request.values)
    except Exception as ex:
        return {'body': "no request body", 'debug': str(ex)}
Ejemplo n.º 47
0
    def get_form_html(self, buttons_html):
        _ = self._

        form = values_to_form(self.request.values)

        if self.subpages:
            subpages = ' '.join(map(wikiutil.escape, self.subpages))

            d = {
                'subpage': subpages,
                'subpages_checked': ('', 'checked')[form.get('subpages_checked', ['0'])[0] == '1'],
                'subpage_label': _('Rename all /subpages too?'),
                'links_label': _('Rename links to page too?'),
                'links_checked': ('checked', '')[form.get('subpages_checked', ['0'])[0] == '1'],
                'pagename': wikiutil.escape(self.pagename, True),
                'newname_label': _("New name"),
                'comment_label': _("Optional reason for the renaming"),
                'buttons_html': buttons_html,
                'querytext': _('Really rename this page?')
                }

            return '''
<strong>%(querytext)s</strong>
<br>
<br>
<table>
    <tr>
    <dd>
        %(subpage_label)s<input type="checkbox" name="rename_subpages" value="1" %(subpages_checked)s>
    </dd>
    <dd>
        <class="label"><subpage> %(subpage)s</subpage>
    </dd>
    </tr>
</table>
<table>
    <tr>
        <td class="label"><label>%(newname_label)s</label></td>
        <td class="content">
            <input type="text" name="newpagename" value="%(pagename)s" size="80">
        </td>
    </tr>
    <tr>
        <td class="label"><label>%(comment_label)s</label></td>
        <td class="content">
            <input type="text" name="comment" size="80" maxlength="200">
        </td>
    </tr>
    <tr>
    <td>
    <dd>
        %(links_label)s<input type="checkbox" name="rename_links" value="1" %(links_checked)s>
    </dd>
    </td>
    </tr>
    <tr>
        <td></td>
        <td class="buttons">
            %(buttons_html)s
        </td>
    </tr>
</table>
''' % d

        else:
            d = {
                'pagename': wikiutil.escape(self.pagename, True),
                'newname_label': _("New name"),
                'comment_label': _("Optional reason for the renaming"),
                'links_label': _('Rename links to page too?'),
                'links_checked': ('checked', '')[form.get('subpages_checked', ['0'])[0] == '1'],
                'buttons_html': buttons_html,
                }
            return '''
<table>
    <tr>
        <td class="label"><label>%(newname_label)s</label></td>
        <td class="content">
            <input type="text" name="newpagename" value="%(pagename)s" size="80">
        </td>
    </tr>
    <tr>
        <td class="label"><label>%(comment_label)s</label></td>
        <td class="content">
            <input type="text" name="comment" size="80" maxlength="200">
        </td>
    </tr>
    <tr>
    <td>
    <dd>
        %(links_label)s<input type="checkbox" name="rename_links" value="1" %(links_checked)s>
    </dd>
    </td>
    </tr>
    <tr>
        <td></td>
        <td class="buttons">
            %(buttons_html)s
        </td>
    </tr>
</table>
''' % d
Ejemplo n.º 48
0
def execute(pagename, request):
    pagename_header = "%s-%s.zip" % (pagename, datetime.now().isoformat()[:10])
    pagename_header = pagename_header.encode("ascii", "ignore")

    request.content_type = "application/zip"
    request.headers["Content-Disposition"] = 'attachment; filename="%s"' % pagename_header

    args = values_to_form(request.values)

    try:
        args = args["args"][0]
    except (KeyError, IndexError):
        args = u""

    pagelist, metakeys, _ = metatable_parseargs(request, args, get_all_keys=True)

    renameDict = dict()

    for page in pagelist:
        metas = get_metas(request, page, ["gwikirename"], abs_attach=False, checkAccess=False)
        renameList = metas["gwikirename"]
        if renameList:
            renameDict[page] = renameList

    output = StringIO()
    zip = zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED)

    userid = user.getUserIdentification(request)
    script = [packLine(["MoinMoinPackage", "1"])]
    counter = 0

    for pagename in pagelist:
        counter += 1
        page = Page(request, pagename)
        timestamp = wikiutil.version2timestamp(page.mtime_usecs())
        # Underlay pages are in epoch 0, zipfile in python 2.7 does
        # not support this.
        if not timestamp:
            pagefile, rev, exists = page.get_rev()
            if rev == 99999999:
                # We should never get here
                log.error("Page %s neither in pages or underlay, skipping." % (pagename))
                continue
            timestamp = os.path.getctime(pagefile)
        pagetext = page.get_raw_body().encode("utf-8")
        filename = str(counter)
        zinfo = zipfile.ZipInfo(filename=filename, date_time=datetime.fromtimestamp(timestamp).timetuple()[:6])
        zinfo.compress_type = zipfile.ZIP_DEFLATED
        zip.writestr(zinfo, pagetext)

        targetNameList = renameDict.get(pagename, [pagename])
        for targetName in targetNameList:
            script.append(packLine(["AddRevision", filename, targetName, userid, ""]))

        for attachment in _get_files(request, pagename):
            counter += 1
            sourcefile = AttachFile.getFilename(request, pagename, attachment)
            filename = str(counter) + "-attachment"
            zip.write(sourcefile, filename)
            script.append(packLine(["AddAttachment", filename, attachment, pagename, userid, ""]))

    zip.writestr(MOIN_PACKAGE_FILE, u"\n".join(script).encode("utf-8"))
    zip.close()

    request.write(output.getvalue())