Example #1
0
    def _add_msg(self, msgs, msg):
        if not msg:
            return msgs

        if msgs is None:
            msgs = msg
        else:
            msgs = "%s<br>%s" % (msgs, form_escape(msg))

        return msgs
Example #2
0
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request
    _ = request.getText

    # Import the plugin action to print out the graph html form
    graphshower = wikiutil.importPlugin(request.cfg, 'action', 'ShowGraph',
                                        'execute')

    if not args:
        return ""

    uri, args = uri_params(args.strip())

    if not args:
        return ""

    # Legacy fix
    args['action'] = ['ShowGraph']
    pagename = uri

    # Check out if the start page exists, if not, we'll just bail out
    if not request.user.may.read(pagename):
        return _("InlineGraph: User may not read page %s" %
                 form_escape(pagename))

    old_page = request.page
    old_values = request.values
    old_url = getattr(request, 'url', '')

    request.page = Page(request, pagename)
    request.formatter.page = request.page
    request.values = CombinedMultiDict([MultiDict(args)])

    req_url = url_construct(request, args, pagename)
    urladd = '?' + req_url.split('?')[1]
    request.url = req_url

    request.write(u'<div class="inlinegraph">')
    graphshower(request.page.page_name,
                request,
                urladd=urladd,
                app_page=request.page.page_name,
                inline=1)

    request.page = old_page
    request.formatter.page = old_page
    request.values = old_values
    del request.url
    if old_url:
        request.url = old_url

    return u'<a href="%s" class="graph-link">[%s]</a>\n' % \
           (req_url, _('examine')) + u'</div>'
Example #3
0
def execute(macro, args):
    formatter = macro.formatter
    macro.request.page.formatter = formatter
    request = macro.request
    _ = request.getText

    # Import the plugin action to print out the graph html form
    graphshower = wikiutil.importPlugin(request.cfg,
                                        'action', 'ShowGraph',
                                        'execute')

    if not args:
        return ""

    uri, args = uri_params(args.strip())

    if not args:
        return ""

    # Legacy fix
    args['action'] = ['ShowGraph']
    pagename = uri

    # Check out if the start page exists, if not, we'll just bail out
    if not request.user.may.read(pagename):
        return _("InlineGraph: User may not read page %s" %
                 form_escape(pagename))

    old_page = request.page
    old_values = request.values
    old_url = getattr(request, 'url', '')

    request.page = Page(request, pagename)
    request.formatter.page = request.page
    request.values = CombinedMultiDict([MultiDict(args)])

    req_url = url_construct(request, args, pagename)
    urladd = '?' + req_url.split('?')[1]
    request.url = req_url

    request.write(u'<div class="inlinegraph">')
    graphshower(request.page.page_name, request,
                urladd=urladd, app_page=request.page.page_name, inline=1)

    request.page = old_page
    request.formatter.page = old_page
    request.values = old_values
    del request.url
    if old_url:
        request.url = old_url

    return u'<a href="%s" class="graph-link">[%s]</a>\n' % \
           (req_url, _('examine')) + u'</div>'
Example #4
0
    def _dl_repl(self, match, groups):
        dt = match[1:-3].lstrip(' ')
        if dt != "":
            self.curdef=dt
        else:
            self.curdef=self.prevdef
        dt = self.curdef
        self.ddline = self.lineno

        return apply(wikiParser._dl_repl, (self, match, groups)) + \
               '\n<input class="metavalue" type="text" name="' + \
               form_escape('%s%s%s' % (self.pagename, SEPARATOR, dt)) + \
               '" value="'
Example #5
0
    def _dl_repl(self, match, groups):
        dt = match[1:-3].lstrip(' ')
        if dt != "":
            self.curdef = dt
        else:
            self.curdef = self.prevdef
        dt = self.curdef
        self.ddline = self.lineno

        return apply(wikiParser._dl_repl, (self, match, groups)) + \
               '\n<input class="metavalue" type="text" name="' + \
               form_escape('%s%s%s' % (self.pagename, SEPARATOR, dt)) + \
               '" value="'
Example #6
0
def execute(macro, args):
    f = macro.formatter
    macro.request.page.formatter = f
    request = macro.request
    _ = request.getText

    allow_overlap = 'no'
    template = 'IOCListTemplate'

    if args:
        args = [x.strip() for x in args.split(',')]
        if len(args) == 2:
            template, overlap = args
            if overlap in ['no', 'yes']:
                allow_overlap = overlap
        elif len(args) == 1:
            template = args[0]

    html = [
        u'<form class="macro" method="POST" action="%s">' %
        (request.href(f.page.page_name)),
        u'<div class="ioclist">',
        u'<input type="hidden" name="action" value="ioclist">',
        u'<input type="hidden" name="allow_overlap" value="%s">' %
        form_escape(allow_overlap),
        u'<input type="hidden" name="template" value="%s">' %
        form_escape(template),
        u'<p class="ioctext">Enter IOC:s in the text box below</p>',
        u'<textarea rows=10 cols=80 name="data"></textarea>',
        u'<p class="ioctext">List name',
        u'<input type="text" name="name">',
        u'<input type="submit" value="%s"></p>' % _("Create IOCList"),
        u'</div></form>',
    ]

    return macro.formatter.rawHTML('\n'.join(html))
Example #7
0
def execute(macro, args):
    f = macro.formatter
    macro.request.page.formatter = f
    request = macro.request
    _ = request.getText

    allow_overlap = 'no'
    template = 'IOCListTemplate'

    if args:
        args = [x.strip() for x in args.split(',')]
        if len(args) == 2:
            template, overlap = args
            if overlap in ['no', 'yes']:
                allow_overlap = overlap
        elif len(args) == 1:
            template = args[0]

    html = [
        u'<form class="macro" method="POST" action="%s">' %
        (request.href(f.page.page_name)),
        u'<div class="ioclist">',
        u'<input type="hidden" name="action" value="ioclist">',
        u'<input type="hidden" name="allow_overlap" value="%s">' %
        form_escape(allow_overlap),
        u'<input type="hidden" name="template" value="%s">' %
        form_escape(template),
        u'<p class="ioctext">Enter IOC:s in the text box below</p>',
        u'<textarea rows=10 cols=80 name="data"></textarea>',
        u'<p class="ioctext">List name',
        u'<input type="text" name="name">',
        u'<input type="submit" value="%s"></p>' % _("Create IOCList"),
        u'</div></form>',
        ]

    return macro.formatter.rawHTML('\n'.join(html))
Example #8
0
    def sendForm(self):
        request = self.request
        _ = request.getText

        ## Begin form
        request.write(u'<form method="GET" action="%s">\n' %
                      actionname(request))
        request.write(u'<input type=hidden name=action value="ViewDot">')

        request.write(u"<table>\n<tr>\n")

        # format
        request.write(u"<td>\n" + _('Output format') + u"<br>\n")
        for type in self.available_formats:
            request.write(
                u'<input type="radio" name="format" ' +
                u'value="%s"%s%s<br>\n' %
                (form_escape(type), type == self.format and " checked>" or ">",
                 wikiutil.escape(type)))

        # graphengine
        request.write(u"<td>\n" + _('Output graphengine') + u"<br>\n")
        for type in self.available_graphengines:
            request.write(u'<input type="radio" name="graphengine" ' +
                          u'value="%s"%s%s<br>\n' %
                          (form_escape(type), type == self.graphengine
                           and " checked>" or ">", wikiutil.escape(type)))

        request.write(
            _("Dot file") + "<br>\n" + u'<select name="attachment">\n')

        # Use request.rootpage, request.page has weird failure modes
        for page in request.rootpage.getPageList():
            # Page#getPageList filters out pages to which the user doesn't have
            # read access.

            files = AttachFile._get_files(request, page)
            for file in files:
                if file.endswith('.dot') or file.endswith('.gv'):
                    request.write(
                        '<option label="%s" value="%s">%s</option>\n' %
                        (form_escape(file),
                         form_escape("attachment:%s/%s" % (page, file)),
                         wikiutil.escape("%s/%s" % (page, file))))
        request.write('</select>\n</table>\n')
        request.write(u'<input type=submit name=view ' +
                      'value="%s">\n' % form_escape(_('View')))
        request.write(u'<input type=submit name=help ' +
                      'value="%s"><br>\n' % form_escape(_('Inline')))
        request.write(u'</form>\n')
Example #9
0
    def sendForm(self):
        request = self.request
        _ = request.getText

        ## Begin form
        request.write(u'<form method="GET" action="%s">\n' %
                      actionname(request))
        request.write(u'<input type=hidden name=action value="ViewDot">')

        request.write(u"<table>\n<tr>\n")

        # format
        request.write(u"<td>\n" + _('Output format') + u"<br>\n")
        for type in self.available_formats:
            request.write(u'<input type="radio" name="format" ' +
                          u'value="%s"%s%s<br>\n' %
                          (form_escape(type),
                           type == self.format and " checked>" or ">",
                           wikiutil.escape(type)))

        # graphengine
        request.write(u"<td>\n" + _('Output graphengine') + u"<br>\n")
        for type in self.available_graphengines:
            request.write(u'<input type="radio" name="graphengine" ' +
                          u'value="%s"%s%s<br>\n' %
                          (form_escape(type),
                           type == self.graphengine and " checked>" or ">",
                           wikiutil.escape(type)))

        request.write(_("Dot file") + "<br>\n" +
                      u'<select name="attachment">\n')

        # Use request.rootpage, request.page has weird failure modes
        for page in request.rootpage.getPageList():
            # Page#getPageList filters out pages to which the user doesn't have
            # read access.

            files = AttachFile._get_files(request, page)
            for file in files:
                if file.endswith('.dot') or file.endswith('.gv'):
                    request.write('<option label="%s" value="%s">%s</option>\n'
                                  % (form_escape(file), form_escape("attachment:%s/%s" % (page, file)),
                                     wikiutil.escape("%s/%s" % (page, file))))
        request.write('</select>\n</table>\n')
        request.write(u'<input type=submit name=view ' +
                      'value="%s">\n' % form_escape(_('View')))
        request.write(u'<input type=submit name=help ' +
                      'value="%s"><br>\n' % form_escape(_('Inline')))
        request.write(u'</form>\n')
Example #10
0
def elemlist(request, formatter, elems, text):
    _ = request.getText
    if not elems:
        return
    request.write(formatter.paragraph(1))
    request.write(formatter.text(_("The following") + " %s " % form_escape(text)
                                 + _("found")))
    request.write(formatter.paragraph(0))
    request.write(formatter.bullet_list(1))
    for elem in sorted(elems):
        kwelem = {
            'querystr': wikiutil.makeQueryString({'action': 'MetaSearch', 'q': elem}),
            'allowed_attrs': ['title', 'href', 'class'],
            'class': 'meta_search'
        }
        request.write(formatter.listitem(1))
        request.write(formatter.pagelink(1, request.page.page_name,
                                         request.page, **kwelem))
        request.write(formatter.text(elem))
        request.write(formatter.pagelink(0))
        request.write(formatter.listitem(0))
    request.write(formatter.bullet_list(0))
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
Example #12
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)
Example #13
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)
Example #14
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
Example #15
0
def execute(pagename, request):
    _ = request.getText

    # Start content - IMPORTANT - without content div, there is no
    # direction support!
    if not hasattr(request, 'formatter'):
        formatter = HtmlFormatter(request)
    else:
        formatter = request.formatter
    request.page.formatter = formatter
    formatter.setPage(request.page)

    # This action generate data using the user language
    request.setContentLanguage(request.lang)

    request.theme.send_title(request.getText('Search by metadata'),
                             pagename=pagename)

    request.write(formatter.startContent("content"))

    q = ''
    mtabq = ''
    if request.values.has_key('q'):
        if request.values.has_key('mtab'):
            mtabq = ''.join(request.values.getlist('q'))
        else:
            q = ''.join(request.values.getlist('q'))

    request.write(u'<form method="GET" action="%s">\n' %
                  actionname(request, pagename))
    request.write(u'<input type=hidden name=action value="%s">' %
                  'MetaSearch')

    request.write(u'<input type="text" name="q" size=50 value="%s"> ' %
                  (form_escape(q)))
    request.write(u'<input type="submit" name="mtab" value="Search as MetaTable">')
    request.write(u'<input type="submit" value="' + _('Search') +
                  '">' + u'\n</form>\n')

    if q:
        if regexp_re.match(q):
            try:
                page_re = re.compile(q[1:-1])
                q = ''
            except re.error:
                request.write(render_error(_("Bad regexp!")))

        graphdata = request.graphdata
        graphdata.reverse_meta()
        keys_on_pages = graphdata.keys_on_pages
        vals_on_pages = graphdata.vals_on_pages

        keyhits = set([])
        keys = set([])
        for key in keys_on_pages:
            if q:
                if key == q:
                    keyhits.update(keys_on_pages[key])
                    keys.add(key)
            else:
                if page_re.match(key):
                    keyhits.update(keys_on_pages[key])
                    keys.add(key)

        valhits = set([])
        vals = set([])
        for val in vals_on_pages:
            if q:
                if val == q:
                    valhits.update(vals_on_pages[val])
                    vals.add(val)
            else:
                if page_re.match(val):
                    valhits.update(vals_on_pages[val])
                    vals.add(val)

        if not q:
            elemlist(request, formatter, keys, _('keys'))
            elemlist(request, formatter, vals, _('values'))

        request.write(formatter.paragraph(1))
        request.write(formatter.text(_("Found as key in following pages")))
        request.write(formatter.paragraph(0))

        request.write(formatter.bullet_list(1))
        for page in sorted(keyhits):
            # Do not include revisions etc so far, enabling this as per request
            if not graphdata[page].has_key(u'saved'):
                continue

            request.write(formatter.listitem(1))
            request.write(formatter.pagelink(1, page))
            request.write(formatter.text(page))
            request.write(formatter.pagelink(0))
            request.write(formatter.listitem(0))

        request.write(formatter.bullet_list(0))

        request.write(formatter.paragraph(1))
        request.write(formatter.text(_("Found as value in following pages")))
        request.write(formatter.paragraph(0))
        request.write(formatter.bullet_list(1))
        for page in sorted(valhits):
            # Do not include revisions etc so far, enabling this as per request
            if not graphdata[page].has_key(u'saved'):
                continue

            request.write(formatter.listitem(1))
            request.write(formatter.pagelink(1, page))
            request.write(formatter.text(page))
            request.write(formatter.pagelink(0))
            request.write(formatter.listitem(0))

        request.write(formatter.bullet_list(0))

    if mtabq:
        metatab = wikiutil.importPlugin(request.cfg, 'macro', 'MetaTable')
        request.write("<br>")
        # Poor but sufficient emulation of macro object
        mtabHTML = metatab(request.page, mtabq)
        request.write(mtabHTML)

    # End content
    request.write(formatter.endContent()) # end content div

    # Footer
    request.theme.send_footer(pagename)

    request.theme.send_closing_html()
Example #16
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 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