def execute(macro, args):
    _ = macro.request.getText
    silent = False

    if args is None:
        args = ''
    else:
        args = args.strip().split(',')
        if args[-1].strip() == 'gwikisilent':
            silent = True
            args = args[:-1]

        args = ','.join(args)

    pagelist, metakeys, styles = metatable_parseargs(macro.request, args,
                                                     get_all_keys=True)

    if silent:
        return "{0}".format(len(pagelist))

    if not pagelist:
        return _("No matches for") + " '{0}'".format(text_escape(args))

    return "{0} {1} '{2}'".format(len(pagelist), _("matches for"),
                                  text_escape(args))
Beispiel #2
0
def execute(macro, args):
    _ = macro.request.getText
    silent = False

    if args is None:
        args = ''
    else:
        args = args.strip().split(',')
        if args[-1].strip() == 'gwikisilent':
            silent = True
            args = args[:-1]

        args = ','.join(args)

    pagelist, metakeys, styles = metatable_parseargs(macro.request,
                                                     args,
                                                     get_all_keys=True)

    if silent:
        return "{0}".format(len(pagelist))

    if not pagelist:
        return _("No matches for") + " '{0}'".format(text_escape(args))

    return "{0} {1} '{2}'".format(len(pagelist), _("matches for"),
                                  text_escape(args))
def execute(macro, args):
    if args is None:
        args = ''

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, styles = \
                metatable_parseargs(macro.request, args,
                                    get_all_keys=True)

    request = macro.request
    _ = request.getText

    # No data -> bail out quickly, Scotty
    if not pagelist:
        request.write(macro.formatter.linebreak() +
                      u'<div class="metatable">' +
                      macro.formatter.table(1))
        t_cell(macro, "%s (%s)" % (_("Metatable has no contents"), args))
        request.write(macro.formatter.table(0) + 
                      u'</div>')

        return ""

    # We're sure the user has the access to the page, so don't check
    construct_table(macro, pagelist, metakeys,
                    checkAccess=False, styles=styles)

    return ""
Beispiel #4
0
def execute(macro, args):
    # Parse arguments
    if args is None:
        args = ''

    args = [x.strip() for x in args.split(',')]
    metatableargs = ''
    includeargs = ''

    split = None
    try:
        split = args.index('')
    except ValueError:
        metatableargs = ','.join(args)

    if split:
        metatableargs = ','.join(args[:split])
        includeargs = ','.join(args[split + 1:])

    # Get pages
    pagelist, metakeys, styles = metatable_parseargs(macro.request,
                                                     metatableargs,
                                                     get_all_keys=True)

    if not pagelist:
        return "No match for '{0}'".format(text_escape(metatableargs))

    # Use MoinMoin's include to print the pages
    return moinInclude.execute(macro, make_pagelist(pagelist) + includeargs)
def execute(xmlrpcobj, args, keysonly=True):
    request = xmlrpcobj.request
    _ = request.getText
    args = xmlrpcobj._instr(args)

    # Expects MetaTable arguments
    pagelist, metakeys, _ = metatable_parseargs(request, args, 
                                                get_all_keys=True)
    # If we only want the keys as specified by the args
    if keysonly:
        return list(metakeys), list(pagelist)

    # Keys to the first row
    out = []
    out.append(metakeys)

    # Go through the pages, give list that has
    # the name of the page followed by the values of the keys
    for page in pagelist:
        # We're pretty sure the user has the read access to the pages,
        # so don't check again
        metas = get_metas(request, page, metakeys, checkAccess=False)
        row = [page]
        for key in metakeys:
            row.append([value for value in metas[key]])
        out.append(row)

    return out
Beispiel #6
0
def do_action(request, args, keysonly=True):
    # Expects MetaTable arguments
    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)
    # If we only want the keys as specified by the args
    if keysonly:
        return list(metakeys), list(pagelist)

    # Keys to the first row
    out = []
    out.append(metakeys)

    # Go through the pages, give list that has
    # the name of the page followed by the values of the keys
    for page in pagelist:
        # We're pretty sure the user has the read access to the pages,
        # so don't check again
        metas = get_metas(request, page, metakeys, checkAccess=False)
        row = [page]
        for key in metakeys:
            row.append([value for value in metas[key]])
        out.append(row)

    return out
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request

    if not args:
        return ''

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, styles = metatable_parseargs(request, args,
                                                     get_all_keys=True)

    namekey = ''
    if metakeys and '%s||' % metakeys[0] in args:
        namekey = metakeys[0]

    out = list()

    for page in pagelist:
        text = ''
        if namekey:
            metas = get_metas(request, page, [namekey],
                              checkAccess=False, formatLinks=True)
            text = ', '.join(metas[namekey])

        if not text:
            text = page

        out.append(Page(request, page).link_to(request, text=text))

    return ', '.join(out)
def execute(self, args):
    if args is None:
        args = ''

    addpagename = False

    if args.strip().endswith('addpagename'):
        addpagename = True
        args = ','.join(args.split(',')[:-1])

    # Note, metatable_parseargs deals with permissions
    pages, keys, styles = metatable_parseargs(self.request,
                                              args,
                                              get_all_keys=True)

    if len(keys) < 2:
        return _sysmsg % (
            'error',
            self.request.getText('Need a minimum of two keys to build matrix'))

    legend = "%s/%s" % (keys[0], keys[1])

    return construct_table(self,
                           pages,
                           keys,
                           legend=legend,
                           checkAccess=False,
                           styles=styles,
                           addpagename=addpagename)
Beispiel #9
0
def do_macro(request, args, **kw):
    formatter = request.formatter
    _ = request.getText
    out = list()
    pagename = request.page.page_name

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, styles = metatable_parseargs(request,
                                                     args,
                                                     get_all_keys=True)

    # No data -> bail out quickly, Scotty
    if not pagelist:
        out.append(formatter.linebreak() + u'<div class="metatable">' +
                   formatter.table(1))
        if kw.get('silent'):
            out.extend(t_cell(request, request.page, ["%s" % _("No matches")]))
        else:
            out.extend(
                t_cell(request, request.page,
                       ["%s '%s'" % (_("No matches for"), args)]))
        out.append(formatter.table(0) + u'</div>')
        return "".join(out)

    parser = Parser('', request)

    options = dict({'args': args}.items() + kw.items())
    divfmt = {'class': "metatable", 'data-options': quote(json.dumps(options))}
    out.append(formatter.div(1, **divfmt))
    # We're sure the user has the access to the page, so don't check
    out.extend(
        construct_table(request,
                        pagelist,
                        metakeys,
                        checkAccess=False,
                        styles=styles,
                        options=options,
                        parser=parser))

    def action_link(action, linktext, args):
        req_url = request.script_root + "/" + \
            url_escape(request.page.page_name) + \
            '?action=' + action + '&amp;args=' + url_escape(args)
        return '<a href="%s" class="meta_footer_link">[%s]</a>\n' % \
            (req_url, _(linktext))

    # If the user has no write access to this page, omit editlink
    if kw.get('editlink', True):
        out.append(action_link('MetaEdit', 'edit', args))

    out.append(action_link('metaCSV', 'csv', args))
    out.append(action_link('metaPackage', 'zip', args))
    out.append(formatter.div(0))
    return "".join(out)
def do_action(request, args):
    # Expects MetaTable arguments
    pagelist, metakeys, _ = metatable_parseargs(request, args,
                                                get_all_keys=True)

    out = {}
    # We're pretty sure the user has the read access to the pages,
    # so don't check again
    for page in pagelist:
        metas = get_metas(request, page, metakeys, checkAccess=False)
        out[page] = dict(metas)
    return out
Beispiel #11
0
def do_action(request, args):
    # Expects MetaTable arguments
    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)

    out = {}
    # We're pretty sure the user has the read access to the pages,
    # so don't check again
    for page in pagelist:
        metas = get_metas(request, page, metakeys, checkAccess=False)
        out[page] = dict(metas)
    return out
def execute(self, args):
    if args is None:
        args = ''

    addpagename = False

    if args.strip().endswith('addpagename'):
        addpagename = True
        args = ','.join(args.split(',')[:-1])

    # Note, metatable_parseargs deals with permissions
    pages, keys, styles = metatable_parseargs(self.request,
                                              args, get_all_keys=True)
    return formatMetaSelection(self.request, pages, keys, styles, addpagename)
def do_macro(request, args, **kw):
    formatter = request.formatter
    _ = request.getText
    out = list()
    pagename = request.page.page_name

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, styles = metatable_parseargs(request, args, get_all_keys=True)

    # No data -> bail out quickly, Scotty
    if not pagelist:
        out.append(formatter.linebreak() + u'<div class="metatable">' + formatter.table(1))
        if kw.get("silent"):
            out.extend(t_cell(request, request.page, ["%s" % _("No matches")]))
        else:
            out.extend(t_cell(request, request.page, ["%s '%s'" % (_("No matches for"), args)]))
        out.append(formatter.table(0) + u"</div>")
        return "".join(out)

    parser = Parser("", request)

    options = dict({"args": args}.items() + kw.items())
    divfmt = {"class": "metatable", "data-options": quote(json.dumps(options))}
    out.append(formatter.div(1, **divfmt))
    # We're sure the user has the access to the page, so don't check
    out.extend(
        construct_table(request, pagelist, metakeys, checkAccess=False, styles=styles, options=options, parser=parser)
    )

    def action_link(action, linktext, args):
        req_url = (
            request.script_root
            + "/"
            + url_escape(request.page.page_name)
            + "?action="
            + action
            + "&amp;args="
            + url_escape(args)
        )
        return '<a href="%s" class="meta_footer_link">[%s]</a>\n' % (req_url, _(linktext))

    # If the user has no write access to this page, omit editlink
    if kw.get("editlink", True):
        out.append(action_link("MetaEdit", "edit", args))

    out.append(action_link("metaCSV", "csv", args))
    out.append(action_link("metaPackage", "zip", args))
    out.append(formatter.div(0))
    return "".join(out)
def execute(self, args):
    if args is None:
        args = ''

    addpagename = False

    if args.strip().endswith('addpagename'):
        addpagename = True
        args = ','.join(args.split(',')[:-1])

    # Note, metatable_parseargs deals with permissions
    pages, keys, styles = metatable_parseargs(self.request,
                                              args,
                                              get_all_keys=True)
    return formatMetaSelection(self.request, pages, keys, styles, addpagename)
def execute(macro, args):
    request = macro.request

    if not args:
        return u''

    args = args.strip().split(',')

    sort_order = 'value'
    if args[-1].strip().lower() == 'value':
        args = args[:-1]
    elif args[-1].strip().lower() == 'count':
        sort_order = 'count'
        args = args[:-1]
    args = ','.join(args)

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = \
        metatable_parseargs(request, args, get_all_keys=True)

    if not pagelist:
        show_error(macro, args, "No content")
        return ""

    if len(metakeys) != 1:
        show_error(macro, args, "Too many keys")
        return ""

    key = metakeys[0]

    if sort_order not in ["value", "count"]:
        show_error(
            macro, args,
            "Bad sort order (should be either '''value''' or '''count''')")
        return ""

    # We're sure the user has the access to the page, so don't check
    construct_table(macro, pagelist, key, sort_order)

    return ''
def inc_get_metas(request, args, handle=None):
    pages, keys, _ = metatable_parseargs(request, args, get_all_keys=True)

    current = dict()
    for page in pages:
        request.page = Page(request, page)
        # metatable_parseargs checks read permissions, no need to do it again
        metas = get_metas(request, page, keys, checkAccess=False)

        current[page] = dict()
        for key in keys:
            values = set(metas[key])
            current[page][key] = values

    cachedir = os.path.join(request.cfg.cache_dir, "getmetas")
    if not os.path.exists(cachedir):
        os.makedirs(cachedir)

    lock = WriteLock(cachedir, timeout=60.0)
    success = lock.acquire()

    path = os.path.join(cachedir, request.cfg.siteid + ".shelve")
    db = shelve.open(path)

    incremental = True
    try:
        if not handle or handle not in db:
            incremental = False
            handle = create_new_handle(db)
        previous = db.get(handle, dict())
        db[handle] = current
    finally:
        db.close()

    if lock.isLocked():
        lock.release()

    return [incremental, handle, diff(previous, current)]
def execute(macro, args):
    request = macro.request

    if not args:
        return u''

    args = args.strip().split(',')

    sort_order = 'value'
    if args[-1].strip().lower() == 'value':
        args = args[:-1]
    elif args[-1].strip().lower() == 'count':
        sort_order = 'count'
        args = args[:-1]
    args = ','.join(args)

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = \
        metatable_parseargs(request, args, get_all_keys=True)

    if not pagelist:
        show_error(macro, args, "No content")
        return ""

    if len(metakeys) != 1:
        show_error(macro, args, "Too many keys")
        return ""

    key = metakeys[0]

    if sort_order not in ["value", "count"]:
        show_error(macro, args, "Bad sort order (should be either '''value''' or '''count''')")
        return ""

    # We're sure the user has the access to the page, so don't check
    construct_table(macro, pagelist, key, sort_order)

    return ''
def execute(self, args):
    if args is None:
        args = ''

    addpagename = False

    if args.strip().endswith('addpagename'):
        addpagename = True
        args = ','.join(args.split(',')[:-1])

    # Note, metatable_parseargs deals with permissions
    pages, keys, styles = metatable_parseargs(self.request,
                                              args, get_all_keys=True)

    if len(keys) < 2:
        return _sysmsg % ('error',
                          self.request.getText('Need a minimum of two keys to build matrix'))

    legend = "%s/%s" % (keys[0], keys[1])

    return construct_table(self, pages, keys, legend=legend,
                           checkAccess=False, styles=styles,
                           addpagename=addpagename)
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')
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())
def draw_topology(request, args, key):
    args = [x.strip() for x in args.split(',')]

    topology, flowfile, color = '', '', ''
    rotate, width = '', ''
    graph = GraphShower(request.page.page_name, request)

    # take flow file specification from arguments as flow=k.csv,
    # otherwise assume that the argument specifies the topology
    for arg in args:
        if '=' in arg:
            key, val = [x.strip() for x in arg.split('=', 1)]
            if key == 'color':
                color = val
            if key == 'flow':
                flowfile = val
            if key == 'rotate':
                rotate = True
            if key == 'width':
                try:
                    width = float(val)
                except ValueError:
                    pass
        else:
            topology = arg

    _ = request.getText

    # Get all containers
    args = 'CategoryContainer, %s=/.+/' % (topology)

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, styles = metatable_parseargs(request, args,
                                                     get_all_keys=True)

    if not pagelist:
        return (False, "", render_error("%s: %s" %
                (_("No such topology or empty topology"), topology)))

    coords = dict()
    images = dict()
    aliases = dict()
    areas = dict()
    colors = dict()

    # Make a context to calculate font sizes with
    # There must be a better way to do this, I just don't know it!
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)

    ctx = cairo.Context(surface)
    ctx.select_font_face("Times-Roman", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)
    ctx.set_font_size(12)

    allcoords = list()
    for page in pagelist:
        data = get_metas(request, page,
                         [topology, 'gwikishapefile', 'tia-name', color],
                         checkAccess=False, formatLinks=True)

        crds = [x.split(',') for x in data.get(topology, list)]

        if not crds:
            continue
        crds = [x.strip() for x in crds[0]]
        if not len(crds) == 2:
            continue

        try:
            start_x, start_y = int(crds[0]), int(crds[1])
        except ValueError:
            continue

        coords[page] = start_x, start_y
        allcoords.append((start_x, start_y))

        img = data.get('gwikishapefile', list())
        if color:
            clr = data.get(color, list())
            if clr:
                colors[page] = clr[0]

        alias = data.get('tia-name', list())
        # Newer versions of analyzer do not use aliases anymore
        if not alias:
            alias = [page]

        aliases[page] = alias[0]

        if img:
            # Get attachment name, name of the page it's on, strip
            # link artifacts, find filesys name
            img = img[0].split(':')[1]
            pname = '/'.join(img.split('/')[:-1])
            img = img.split('/')[-1]
            img = img.split('|')[0]
            img = img.rstrip('}').rstrip(']]')
            imgname = AttachFile.getFilename(request, pname, img)
            try:
                images[page] = cairo.ImageSurface.create_from_png(imgname)
                end_x = start_x + images[page].get_width()
                end_y = start_y + images[page].get_height()
            except cairo.Error:
                end_x = start_x
                end_y = start_y
                pass

        text_len = ctx.text_extents(aliases[page])[4]
        text_end = start_x + text_len
        if text_end > end_x:
            end_x = text_end

        # If there was no image or a problem with loading the image
        if page not in images:
            # Lack of image -> black 10x10 rectangle is drawn
            end_x, end_y = start_x + 10, start_y + 10

        allcoords.append((end_x, end_y))

    if flowfile:
        flowcoords = list()
        flowname = AttachFile.getFilename(request, topology, flowfile)
        try:
            flows = csv.reader(file(flowname, 'r').readlines(), delimiter=';')
        except IOError:
            return (False, "", render_error("%s: %s" %
                    (_("No such flowfile as attachment on topology page"),
                     flowfile)))

        flows.next()
        for line in flows:
            if not line:
                continue
            try:
                flowcoords.append((line[0], line[6]))
            except IndexError:
                # Pasted broken lines?
                pass

    max_x = max([x[0] for x in allcoords])
    min_x = min([x[0] for x in allcoords])
    max_y = max([x[1] for x in allcoords])
    min_y = min([x[1] for x in allcoords])

    # Make room for text under pictures
    if rotate:
        surface_y = max_y - min_y
        surface_x = max_x - min_x + 25
    else:
        surface_y = max_y - min_y + 25
        surface_x = max_x - min_x

    try:
        # Get background image, if any
        toponame = AttachFile.getFilename(request, topology, 'shapefile.png')
        background = cairo.ImageSurface.create_from_png(toponame)

        h = background.get_height()
        w = background.get_width()
        diff_x = w - surface_x
        diff_y = h - surface_y

        if diff_x > 0:
            surface_x = w
        else:
            diff_x = 0

        if diff_y > 0:
            surface_y = h
        else:
            diff_y = 0

    except cairo.Error:
        background = None
        diff_x = 0
        diff_y = 0
        pass

    # Setup Cairo
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                 int(surface_x), int(surface_y))

    # request.write(repr([surface_x, surface_y]))
    ctx = cairo.Context(surface)
    ctx.select_font_face("Times-Roman", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)
    ctx.set_font_size(12)

    ctx.set_source_rgb(1.0, 1.0, 1.0)
    ctx.rectangle(0, 0, surface_x, surface_y)
    ctx.fill()

    if background:
        # Center background if not large. Again, I'm just guessing
        # where the background image should be, and trying to mimic
        # analyzer.
        h = background.get_height()
        w = background.get_width()
        start_x, start_y = 0, 0
        if w < surface_x:
            start_x = start_x - min_x - w/2
        if h < surface_y:
            start_y = start_y - min_y - h/2
        ctx.set_source_surface(background, start_x, start_y)
        ctx.rectangle(start_x, start_y, w, h)
        ctx.fill()

    midcoords = dict()
    for page in pagelist:
        if page not in coords:
            continue

        x, y = coords[page]

        # FIXME need more data to align different backgrounds
        # correctly, this is just guessing
        start_x = x - min_x + (diff_x / 2)
        start_y = y - min_y + (diff_y / 3)

        w, h = 10, 10
        if page not in images:
            ctx.set_source_rgb(0, 0, 0)
        else:
            h = images[page].get_height()
            w = images[page].get_width()
            if page in colors:
                clr = graph.hashcolor(colors[page])
                r, g, b = [int(''.join(i), 16) / 255.0 for i in
                           zip(clr[1::2], clr[2::2])]
                ctx.set_source_rgb(r, g, b)
            else:
                ctx.set_source_rgb(1, 1, 1)

        midcoords[page] = (start_x + w / 2, start_y + h / 2)
        ctx.rectangle(start_x, start_y, w, h)
        ctx.fill()

        if page in images:
            ctx.set_source_surface(images[page], start_x, start_y)
            ctx.rectangle(start_x, start_y, w, h)
            ctx.fill()

        text = make_tooltip(request, page)

        areas["%s,%s,%s,%s" % (start_x, start_y, start_x + w, start_y + h)] = \
            [page, text, 'rect']

        if page in aliases:
            ctx.set_source_rgb(0, 0, 0)
            if rotate:
                ctx.move_to(start_x + w + 10, start_y + h)
            else:
                ctx.move_to(start_x, start_y + h + 10)

            # FIXME, should parse links more nicely, now just removes
            # square brackets
            text = aliases[page].lstrip('[').rstrip(']')

            if rotate:
                ctx.rotate(-90.0*math.pi/180.0)

            ctx.show_text(text)

            if rotate:
                ctx.rotate(90.0*math.pi/180.0)

    if flowfile:
        ctx.set_line_width(1)
        ctx.set_source_rgb(0, 0, 0)
        for start, end in flowcoords:
            if (start not in midcoords) or (end not in midcoords):
                continue

            sx, sy = midcoords[start]
            ex, ey = midcoords[end]
            ctx.move_to(sx, sy)
            ctx.line_to(ex, ey)
            ctx.stroke()

    s2 = surface

    if width:
        # For scaling
        new_surface_y = width
        factor = surface_y/new_surface_y
        new_surface_x = surface_x / factor

        # Recalculate image map data
        newareas = dict()
        for coords, data in areas.iteritems():
            corners = [float(i) for i in coords.split(',')]
            corners = tuple(i / factor for i in corners)
            newareas['%s,%s,%s,%s' % corners] = data
        areas = newareas
    else:
        new_surface_y = surface_y
        new_surface_x = surface_x

    if rotate:
        temp = new_surface_x
        new_surface_x = new_surface_y
        new_surface_y = temp
        temp = surface_x
        surface_x = surface_y
        surface_y = temp

    s2 = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                            int(new_surface_x), int(new_surface_y))

    ctx = cairo.Context(s2)

    if rotate:
        ctx.rotate(90.0*math.pi/180.0)

        # Recalculate image map data
        newareas = dict()
        for coords, data in areas.iteritems():
            corners = coords.split(',')
            corners = [float(i) for i in coords.split(',')]
            corners = tuple([new_surface_x - corners[1], corners[0],
                             new_surface_x - corners[3], corners[2]])
            newareas['%s,%s,%s,%s' % corners] = data
        areas = newareas

    if width:
        ctx.scale(new_surface_x/surface_x, new_surface_y/surface_y)

    if rotate:
        ctx.translate(0, -surface_x)

    ctx.set_source_surface(surface, 0, 0)
    ctx.paint()

    data = cairo_surface_to_png(s2)

    map = ''
    for coords in areas:
        name, text, shape = areas[coords]
        pagelink = request.script_root + u'/' + name

        tooltip = "%s\n%s" % (name, text)

        map += u'<area href="%s" shape="%s" coords="%s" title="%s">\n' % \
            (form_escape(pagelink), shape, coords, tooltip)

    return True, data, map
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request
    _ = request.getText

    if not have_cairo():
        return _sysmsg % ('error', _(\
                "ERROR: Cairo Python extensions not installed. " +\
                    "Not performing layout."))

    url_args, args = radarchart_args(args)

    # For multiple radar charts per table row
    try:
        height = ''.join(url_args.get('height', list()))
        width = ''.join(url_args.get('width', list()))
        if not height: 
            height = MAX_WIDTH
        if not width:
            width = MAX_WIDTH
        height, width = int(height), int(width)
    except ValueError:
        pass

    # MAX_WIDTH is the assumed max_width here
    amount = MAX_WIDTH / min(height, width)
    if amount < 1:
        amount = 1

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = metatable_parseargs(request, args,
                                                get_all_keys=True)

    values = set()
    for page in pagelist:
        metas = get_metas(request, page, metakeys)
        for key in metas:
            # Get the maximum value of each key on a page
            if metas[key]:
                numberedvals = dict()
                for i, val in enumerate(map(ordervalue, metas[key])):
                    numberedvals[val] = i
                maxval = max(numberedvals.keys())
                i = numberedvals[maxval]
                # This contraption is here because we need to deliver
                # unparsed (textual) values in urls
                values.add(metas[key][i])
    for val in values:
        if val.startswith('attachment'):
            # A bit ugly fix for a weird corner case
            val = "attachment:%s" % (val[11:])
        url_args.setdefault('value', list()).append(val)

    out = StringIO.StringIO()
    out.write(macro.formatter.linebreak() +
              u'<div class="metaradartable">' +
              macro.formatter.table(1))

    rowcount = (len(pagelist) / amount)
    if len(pagelist) % amount:
        rowcount += 1
    # Iterate over the number of rows
    for i in range(rowcount):

        out.write(macro.formatter.table_row(1))

        pages = pagelist[i*amount:(i+1)*amount]

        # First enter page names to first row
        for page in pages:
            out.write(macro.formatter.table_cell(1, {'class': 'meta_page'}))
            out.write(macro.formatter.pagelink(1, page))
            out.write(macro.formatter.text(page))
            out.write(macro.formatter.pagelink(0))
            out.write(macro.formatter.linebreak())
        # Don't make extra squares for the first row
        if i:
            for j in range(amount - len(pages)):
                out.write(macro.formatter.table_cell(1))

        out.write(macro.formatter.table_row(1))

        # Chart images to the other row
        for page in pages:
            out.write(macro.formatter.table_cell(1, {'class': 'meta_radar'}))
            out.write(u'<img src="%s">' % 
                      (url_construct(request, url_args, page)))
            out.write(macro.formatter.linebreak())
        if i:
            for j in range(amount - len(pages)):
                out.write(macro.formatter.table_cell(1))

    out.write(macro.formatter.table(0) + u'</div>')

    return out.getvalue()
Beispiel #23
0
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request
    _ = request.getText

    if not have_cairo():
        return _sysmsg % ('error', _(\
                "ERROR: Cairo Python extensions not installed. " +\
                    "Not performing layout."))

    url_args, args = radarchart_args(args)

    # For multiple radar charts per table row
    try:
        height = ''.join(url_args.get('height', list()))
        width = ''.join(url_args.get('width', list()))
        if not height:
            height = MAX_WIDTH
        if not width:
            width = MAX_WIDTH
        height, width = int(height), int(width)
    except ValueError:
        pass

    # MAX_WIDTH is the assumed max_width here
    amount = MAX_WIDTH / min(height, width)
    if amount < 1:
        amount = 1

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)

    values = set()
    for page in pagelist:
        metas = get_metas(request, page, metakeys)
        for key in metas:
            # Get the maximum value of each key on a page
            if metas[key]:
                numberedvals = dict()
                for i, val in enumerate(map(ordervalue, metas[key])):
                    numberedvals[val] = i
                maxval = max(numberedvals.keys())
                i = numberedvals[maxval]
                # This contraption is here because we need to deliver
                # unparsed (textual) values in urls
                values.add(metas[key][i])
    for val in values:
        if val.startswith('attachment'):
            # A bit ugly fix for a weird corner case
            val = "attachment:%s" % (val[11:])
        url_args.setdefault('value', list()).append(val)

    out = StringIO.StringIO()
    out.write(macro.formatter.linebreak() + u'<div class="metaradartable">' +
              macro.formatter.table(1))

    rowcount = (len(pagelist) / amount)
    if len(pagelist) % amount:
        rowcount += 1
    # Iterate over the number of rows
    for i in range(rowcount):

        out.write(macro.formatter.table_row(1))

        pages = pagelist[i * amount:(i + 1) * amount]

        # First enter page names to first row
        for page in pages:
            out.write(macro.formatter.table_cell(1, {'class': 'meta_page'}))
            out.write(macro.formatter.pagelink(1, page))
            out.write(macro.formatter.text(page))
            out.write(macro.formatter.pagelink(0))
            out.write(macro.formatter.linebreak())
        # Don't make extra squares for the first row
        if i:
            for j in range(amount - len(pages)):
                out.write(macro.formatter.table_cell(1))

        out.write(macro.formatter.table_row(1))

        # Chart images to the other row
        for page in pages:
            out.write(macro.formatter.table_cell(1, {'class': 'meta_radar'}))
            out.write(u'<img src="%s">' %
                      (url_construct(request, url_args, page)))
            out.write(macro.formatter.linebreak())
        if i:
            for j in range(amount - len(pages)):
                out.write(macro.formatter.table_cell(1))

    out.write(macro.formatter.table(0) + u'</div>')

    return out.getvalue()
def execute(pagename, request):
    if not have_cairo():
        error = request.getText(
            "ERROR: Cairo Python extensions not installed. " +
            "Not performing layout."
        )
        request.content_type = 'text/plain'
        request.write(error)
        return

    request.content_type = "image/png"

    # Grab arguments
    args = ', '.join(x for x in request.values.getlist('arg'))

    params = {'height': 0, 'width': 0}

    # Height and Width
    for attr in ['height', 'width']:
        if request.values.has_key(attr):
            val = ''.join(request.values.getlist(attr))
            try:
                params[attr] = int(val)
            except ValueError:
                pass

    # Aggregate set of included values of a page
    values = set()
    if request.values.has_key('value'):
        values.update(map(ordervalue, request.values.getlist('value')))

    # Values that need to be included to form a complete scale, say 1-10
    scale = list()
    if request.values.has_key('scale'):
        scale = request.values['scale']

    if not params['height'] and params['width']:
        params['height'] = params['width']
    elif params['height'] and not params['width']:
        params['width'] = params['height']
    elif not params['height'] and not params['width']:
        params['width'] = params['height'] = 1000

    # calculate center and radius, leave some room for text and stuff
    center = (params['height'] / 2, params['width'] / 2)
    radius = min(center)
    if radius > 50:
        radius -= 50

    # Setup Cairo
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                 params['height'], params["width"])
    ctx = cairo.Context(surface)
    ctx.select_font_face("Times-Roman", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)
    ctx.set_font_size(12)

    ctx.set_source_rgb(1.0, 1.0, 1.0)
    ctx.rectangle(0, 0, params['width'], params['height'])
    ctx.fill()

    ctx.set_source_rgb(0.0, 0.0, 0.0)

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = metatable_parseargs(request, args,
                                                get_all_keys=True)
    metakeys = filter(lambda x: x not in SPECIAL_ATTRS, metakeys)

    # If no keys, print nothing
    if not pagelist:
        request.write(plot_error(request))
        return

    # Populate data to the radar chart
    data = dict()
    for page in pagelist:
        # On links, we want a list of page names, not their markup
        metas = get_metas(request, page, metakeys, checkAccess=False)

        # Get the maximum value of each key on a page
        for key in metakeys:
            data.setdefault(key, list())
            if metas[key]:
                scale.extend(map(ordervalue, metas[key]))
                if page == pagename:
                    data[key].append(max(map(ordervalue, metas[key])))

    # Get values for the chart axes
    data_per_axis = dict()
    for axis, key in enumerate(metakeys):
        data_per_axis[axis] = key

    if not values:
        for x in data.values():
            values.update(x)

    if scale:
        values.update(scale)

    values = sorted(values)

    # Refuse to draw if no values for any key
    if not len(values):
        request.write(plot_error(request))
        return

    no_values = len(values) + 1
    per_value = radius / no_values

    sectors = len(data)
    angle = 2*math.pi/sectors

    cur_radius = per_value
    # Make the base grid
    for x in range(1, no_values):
        ctx, gridpoints = spider_radius(ctx, center, cur_radius, sectors)
        cur_radius += per_value

    # Apply ink from strokes so far
    ctx.stroke()

    # Now start to make chart on top of the base
    ctx.set_source_rgb(50/255.0,137/255.0,37/255.0)
    ctx.set_line_width(5)

    endpoints = list()

    # Find coords for each value
    for i in range(sectors):
        val = data[data_per_axis[i]]
        if val:
            val = val.pop()
            radius = values.index(val) + 1
        else:
            # If no values exist, it's in the bottom
            radius = 0
        x, y = spider_coords(radius * per_value, i*angle)

        endpoints.append(add_to_center(center, (x, y)))

    draw_path(ctx, endpoints)

    # Draw path filling the contents
    ctx.stroke_preserve()
    ctx.set_source_rgba(150/255.0,190/255.0,13/255.0, 0.2)
    ctx.fill()

    # Write axis names on top of it all
    for point, axis in zip(gridpoints, data_per_axis.keys()):
        text = data_per_axis[axis]

        ctx.set_source_rgba(1, 1, 1, 0.9)
        width, height = ctx.text_extents(text)[2:4]

        # Move texts on the left side a bit left
        if point[0] < center[0]:
            point = (point[0] - width, point[1])

        width, height = width * 1.2, -height * 1.2
        x, y = point[0] - 0.1 * width, point[1] + 0.1 * height
        ctx.rectangle(x, y, width, height)
        ctx.fill()

        ctx.set_source_rgb(0, 0, 0)
        ctx.move_to(*point)
        ctx.show_text(text)

    request.write(cairo_surface_to_png(surface))
def execute(macro, args):
    mode = 'keys'

    request = macro.request

    # get params
    if args:
        args = [x.strip() for x in args.split(',')]
    else:
        args = []

    kw = {}
    for arg in args:
        if '=' in arg:
            key, value = arg.split('=', 1)
            if key == "metaMaxTags":
                kw[str(key.strip())] = value
            if key == "metaShowMode":
                if value in ['keys', 'values']:
                    mode = value

    args = filter(
        lambda x: x.split('=')[0] not in ["metaMaxTags", "metaShowMode"],
        args
    )

    try:
        maxTags = int(kw["metaMaxTags"])
    except (KeyError, ValueError):
        maxTags = 50

    # [(hits, fontsize), (hits, fontsize), ...]
    levels = [
        (4, "0.65em"),
        (7, "0.75em"),
        (12, "0.9em"),
        (18, "1.0em"),
        (25, "1.05em"),
        (35, "1.1em"),
        (50, "1.15em"),
        (60, "1.2em"),
        (90, "1.25em"),
        (None, "1.3em")
    ]

    tags = []

    if not args:
        args = ''
    else:
        args = ','.join(args)

    pagelist, metakeys, _ = metatable_parseargs(
        macro.request,
        args,
        get_all_pages=True
    )

    if not hasattr(request.graphdata, 'keys_on_pages'):
        request.graphdata.reverse_meta()

    for name in pagelist:
        page = request.graphdata.getpage(name)
        if mode == 'keys':
            tags.extend(x for x in page.get('meta', {}).keys())
            tags.extend(x for x in page.get('out', {}).keys() if x != NO_TYPE)
        else:
            for key in page.get('meta', {}).keys():
                if key in ['label', 'URL']:
                    continue
                tags.extend(x.strip('"') for x in page['meta'][key])
            for key in page.get('out', {}).keys():
                if key == NO_TYPE:
                    continue
                tags.extend(page['out'][key])

    taglist = frozenset(tags)

    def sort(t):
        return t[1]

    show = []
    for tag in taglist:
        cnt = tags.count(tag)
        show.append((tag, cnt, tag))
    show.sort(key=sort, reverse=True)
    show = show[0:maxTags]
    show.sort()

    html = []

    for tag in show:
        if mode == 'keys':
            data = request.graphdata.keys_on_pages.get(tag[2])
        else:
            data = request.graphdata.vals_on_pages.get(tag[2])

        if not data:
            data = []
        title = '\n'.join(sorted(data, key=unicode.lower))

        pagename = tag[0]
        hits = tag[1]
        url = url_construct(request, {
            "action": ["MetaSearch"],
            "q": [pagename]
        }, request.page.page_name)

        fontsize = "0.1em"
        for _hits, _fontsize in levels:
            if _hits is None or hits < _hits:
                fontsize = _fontsize
                break

        html.append(
            u'<span style="font-size:%s;"><a title="%s" href="%s"> %s</a></span>' % (
                form_escape(fontsize),
                form_escape(title),
                form_escape(url),
                wikiutil.escape(pagename)
            )
        )

    return ''.join(html)
Beispiel #26
0
def execute(pagename, request):
    if not have_cairo():
        error = request.getText(
            "ERROR: Cairo Python extensions not installed. " +
            "Not performing layout.")
        request.content_type = 'text/plain'
        request.write(error)
        return

    request.content_type = "image/png"

    # Grab arguments
    args = ', '.join(x for x in request.values.getlist('arg'))

    params = {'height': 0, 'width': 0}

    # Height and Width
    for attr in ['height', 'width']:
        if request.values.has_key(attr):
            val = ''.join(request.values.getlist(attr))
            try:
                params[attr] = int(val)
            except ValueError:
                pass

    # Aggregate set of included values of a page
    values = set()
    if request.values.has_key('value'):
        values.update(map(ordervalue, request.values.getlist('value')))

    # Values that need to be included to form a complete scale, say 1-10
    scale = list()
    if request.values.has_key('scale'):
        scale = request.values['scale']

    if not params['height'] and params['width']:
        params['height'] = params['width']
    elif params['height'] and not params['width']:
        params['width'] = params['height']
    elif not params['height'] and not params['width']:
        params['width'] = params['height'] = 1000

    # calculate center and radius, leave some room for text and stuff
    center = (params['height'] / 2, params['width'] / 2)
    radius = min(center)
    if radius > 50:
        radius -= 50

    # Setup Cairo
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, params['height'],
                                 params["width"])
    ctx = cairo.Context(surface)
    ctx.select_font_face("Times-Roman", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)
    ctx.set_font_size(12)

    ctx.set_source_rgb(1.0, 1.0, 1.0)
    ctx.rectangle(0, 0, params['width'], params['height'])
    ctx.fill()

    ctx.set_source_rgb(0.0, 0.0, 0.0)

    # Note, metatable_parseargs deals with permissions
    pagelist, metakeys, _ = metatable_parseargs(request,
                                                args,
                                                get_all_keys=True)
    metakeys = filter(lambda x: x not in SPECIAL_ATTRS, metakeys)

    # If no keys, print nothing
    if not pagelist:
        request.write(plot_error(request))
        return

    # Populate data to the radar chart
    data = dict()
    for page in pagelist:
        # On links, we want a list of page names, not their markup
        metas = get_metas(request, page, metakeys, checkAccess=False)

        # Get the maximum value of each key on a page
        for key in metakeys:
            data.setdefault(key, list())
            if metas[key]:
                scale.extend(map(ordervalue, metas[key]))
                if page == pagename:
                    data[key].append(max(map(ordervalue, metas[key])))

    # Get values for the chart axes
    data_per_axis = dict()
    for axis, key in enumerate(metakeys):
        data_per_axis[axis] = key

    if not values:
        for x in data.values():
            values.update(x)

    if scale:
        values.update(scale)

    values = sorted(values)

    # Refuse to draw if no values for any key
    if not len(values):
        request.write(plot_error(request))
        return

    no_values = len(values) + 1
    per_value = radius / no_values

    sectors = len(data)
    angle = 2 * math.pi / sectors

    cur_radius = per_value
    # Make the base grid
    for x in range(1, no_values):
        ctx, gridpoints = spider_radius(ctx, center, cur_radius, sectors)
        cur_radius += per_value

    # Apply ink from strokes so far
    ctx.stroke()

    # Now start to make chart on top of the base
    ctx.set_source_rgb(50 / 255.0, 137 / 255.0, 37 / 255.0)
    ctx.set_line_width(5)

    endpoints = list()

    # Find coords for each value
    for i in range(sectors):
        val = data[data_per_axis[i]]
        if val:
            val = val.pop()
            radius = values.index(val) + 1
        else:
            # If no values exist, it's in the bottom
            radius = 0
        x, y = spider_coords(radius * per_value, i * angle)

        endpoints.append(add_to_center(center, (x, y)))

    draw_path(ctx, endpoints)

    # Draw path filling the contents
    ctx.stroke_preserve()
    ctx.set_source_rgba(150 / 255.0, 190 / 255.0, 13 / 255.0, 0.2)
    ctx.fill()

    # Write axis names on top of it all
    for point, axis in zip(gridpoints, data_per_axis.keys()):
        text = data_per_axis[axis]

        ctx.set_source_rgba(1, 1, 1, 0.9)
        width, height = ctx.text_extents(text)[2:4]

        # Move texts on the left side a bit left
        if point[0] < center[0]:
            point = (point[0] - width, point[1])

        width, height = width * 1.2, -height * 1.2
        x, y = point[0] - 0.1 * width, point[1] + 0.1 * height
        ctx.rectangle(x, y, width, height)
        ctx.fill()

        ctx.set_source_rgb(0, 0, 0)
        ctx.move_to(*point)
        ctx.show_text(text)

    request.write(cairo_surface_to_png(surface))
Beispiel #27
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')
Beispiel #28
0
def execute(macro, args):
    mode = 'keys'

    request = macro.request

    # get params
    if args:
        args = [x.strip() for x in args.split(',')]
    else:
        args = []

    kw = {}
    for arg in args:
        if '=' in arg:
            key, value = arg.split('=', 1)
            if key == "metaMaxTags":
                kw[str(key.strip())] = value
            if key == "metaShowMode":
                if value in ['keys', 'values']:
                    mode = value

    args = filter(
        lambda x: x.split('=')[0] not in ["metaMaxTags", "metaShowMode"], args)

    try:
        maxTags = int(kw["metaMaxTags"])
    except (KeyError, ValueError):
        maxTags = 50

    # [(hits, fontsize), (hits, fontsize), ...]
    levels = [(4, "0.65em"), (7, "0.75em"), (12, "0.9em"), (18, "1.0em"),
              (25, "1.05em"), (35, "1.1em"), (50, "1.15em"), (60, "1.2em"),
              (90, "1.25em"), (None, "1.3em")]

    tags = []

    if not args:
        args = ''
    else:
        args = ','.join(args)

    pagelist, metakeys, _ = metatable_parseargs(macro.request,
                                                args,
                                                get_all_pages=True)

    if not hasattr(request.graphdata, 'keys_on_pages'):
        request.graphdata.reverse_meta()

    for name in pagelist:
        page = request.graphdata.getpage(name)
        if mode == 'keys':
            tags.extend(x for x in page.get('meta', {}).keys())
            tags.extend(x for x in page.get('out', {}).keys() if x != NO_TYPE)
        else:
            for key in page.get('meta', {}).keys():
                if key in ['label', 'URL']:
                    continue
                tags.extend(x.strip('"') for x in page['meta'][key])
            for key in page.get('out', {}).keys():
                if key == NO_TYPE:
                    continue
                tags.extend(page['out'][key])

    taglist = frozenset(tags)

    def sort(t):
        return t[1]

    show = []
    for tag in taglist:
        cnt = tags.count(tag)
        show.append((tag, cnt, tag))
    show.sort(key=sort, reverse=True)
    show = show[0:maxTags]
    show.sort()

    html = []

    for tag in show:
        if mode == 'keys':
            data = request.graphdata.keys_on_pages.get(tag[2])
        else:
            data = request.graphdata.vals_on_pages.get(tag[2])

        if not data:
            data = []
        title = '\n'.join(sorted(data, key=unicode.lower))

        pagename = tag[0]
        hits = tag[1]
        url = url_construct(request, {
            "action": ["MetaSearch"],
            "q": [pagename]
        }, request.page.page_name)

        fontsize = "0.1em"
        for _hits, _fontsize in levels:
            if _hits is None or hits < _hits:
                fontsize = _fontsize
                break

        html.append(
            u'<span style="font-size:%s;"><a title="%s" href="%s"> %s</a></span>'
            % (form_escape(fontsize), form_escape(title), form_escape(url),
               wikiutil.escape(pagename)))

    return ''.join(html)
def execute(xmlrpcobj, page, ttl=None, version=""):
    request = xmlrpcobj.request

    cfg = dict()
    for key, value in DEFAULTS.iteritems():
        cfg[key] = getattr(request.cfg, "cookie_" + key, value)

    if ttl is None:
        ttl = cfg["min_ttl"] * SECONDS_IN_DAY

    # Check if user has right to read page
    if not request.user.may.read(page):
        return xmlrpclib.Fault(1, "You are not allowed get this license.")

    # Encode the pagename and username properly (?)
    username = request.user.name
    pagename = page

    if not username:
        return xmlrpclib.Fault(1, "Unknown user")

    pagelist, metakeys, _ = metatable_parseargs(request, page, get_all_keys=True)
    metas = get_metas(request, page, metakeys, checkAccess=False)

    typeValue = metas.get("Type", [])
    if len(typeValue) == 0:
        licenseType = "cookie"
    else:
        licenseType = typeValue[0]

    if licenseType == "capped":
        usedCookies = countUsage(request, username + "/Bookkeeping", page)
        ownedCookies = countOwned(request, username + "/Shopkeeping", page)
        availableCookies = ownedCookies - usedCookies

    minTTL = getIntMeta(metas, "Minimum check-out period (days)", cfg["min_ttl"])
    maxTTL = getIntMeta(metas, "Maximum check-out period (days)", cfg["max_ttl"])

    minTTL *= SECONDS_IN_DAY
    maxTTL *= SECONDS_IN_DAY

    # Cap the cookie ttl between minTTL and maxTTL
    ttl = min(max(ttl, minTTL), maxTTL)

    if licenseType == "capped":
        ttl = min(ttl, availableCookies * SECONDS_IN_DAY)
        availableCookies -= ttl / SECONDS_IN_DAY

    if ttl <= 0:
        return xmlrpclib.Fault(1, "You don't have any cookies left!")

    if licenseType == "traditional":
        first, last = getPurchases(request, username + "/Shopkeeping", page)
        if first == 0 and last == 0:
            return xmlrpclib.Fault(1, "No purchased licenses found!")

        duration = getIntMeta(metas, "Duration (days)", cfg["default_duration"])
        issued = first
        expires = last + duration * SECONDS_IN_DAY
    else:
        # Start and end times for the cookie
        issued = int(time.time())
        expires = issued + ttl

    cookieData = reformatMetaDict(metas)
    cookieData["collabname"] = request.cfg.interwikiname
    cookieData["pagename"] = pagename
    cookieData["username"] = username
    cookieData["issued"] = int(issued)
    cookieData["expires"] = int(expires)

    if licenseType == "capped":
        cookieData["availableCookies"] = "%.02f" % availableCookies

    cookie = createCookieString(cookieData)

    failure = logCookieRequest(request, cfg, username, (issued, expires, pagename), version)
    if failure:
        return failure

    return signCookie(cfg, cookie)