def _link_tickets(self, req, tickets):
        items = []

        for i, word in enumerate(re.split(r'([;,\s]+)', tickets)):
            if i % 2:
                items.append(word)
            elif word:
                tid = word
                word = '#%s' % word

                try:
                    ticket = Ticket(self.env, tid)
                    if 'TICKET_VIEW' in req.perm(ticket.resource):
                        word = \
                            tag.a(
                                '#%s' % ticket.id,
                                href=req.href.ticket(ticket.id),
                                class_=classes(ticket['status'], 'ticket'),
                                title=get_resource_summary(self.env, ticket.resource)
                            )
                except ResourceNotFound:
                    pass

                items.append(word)

        if items:
            return tag(items)
        else:
            return None
示例#2
0
    def _link_tickets(self, req, tickets):
        items = []

        for i, word in enumerate(re.split(r'([;,\s]+)', tickets)):
            if i % 2:
                items.append(word)
            elif word:
                tid = word
                word = '#%s' % word

                try:
                    ticket = Ticket(self.env, tid)
                    if 'TICKET_VIEW' in req.perm(ticket.resource):
                        word = \
                            html.a(
                                '#%s' % ticket.id,
                                href=req.href.ticket(ticket.id),
                                class_=classes(ticket['status'], 'ticket'),
                                title=get_resource_summary(self.env,
                                                           ticket.resource)
                            )
                except ResourceNotFound:
                    pass

                items.append(word)

        if items:
            return html(items)
        else:
            return None
示例#3
0
    def test_global_neighborhood_report(self):
        target = resource.Neighborhood("global", None).child(self.resource)

        self.assertEquals("[global:] report:1", resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] report:1", resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] report:1", resource.get_resource_shortname(self.env, target))
        self.assertEquals("[global:] report:1 at version None", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/report/1", resource.get_resource_url(self.env, target, self.env.href)
        )
示例#4
0
    def test_global_neighborhood_wiki(self):
        target = resource.Neighborhood("global", None).child(self.resource)

        self.assertEquals("TestPage", resource.get_resource_description(self.env, target))
        self.assertEquals("TestPage", resource.get_resource_name(self.env, target))
        self.assertEquals("TestPage", resource.get_resource_shortname(self.env, target))
        self.assertEquals("TestPage", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/wiki/TestPage?version=2",
            resource.get_resource_url(self.env, target, self.env.href),
        )
示例#5
0
    def test_product_neighborhood_report(self):
        target = resource.Neighborhood("product", u"xü").child(self.resource)

        self.assertEquals(u"[product:xü] report:1", resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] report:1", resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] report:1", resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"[product:xü] report:1 at version None", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/products/x%C3%BC/report/1",
            resource.get_resource_url(self.env, target, self.env.href),
        )
示例#6
0
    def test_global_neighborhood_milestone(self):
        target = resource.Neighborhood("global", None).child(self.resource)

        self.assertEquals("[global:] Milestone milestone1", resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Milestone milestone1", resource.get_resource_name(self.env, target))
        self.assertEquals("milestone1", resource.get_resource_shortname(self.env, target))
        self.assertEquals("[global:] Milestone milestone1", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/milestone/milestone1",
            resource.get_resource_url(self.env, target, self.env.href),
        )
示例#7
0
    def test_product_neighborhood_wiki(self):
        target = resource.Neighborhood("product", u"xü").child(self.resource)

        self.assertEquals(u"TestPage", resource.get_resource_description(self.env, target))
        self.assertEquals(u"TestPage", resource.get_resource_name(self.env, target))
        self.assertEquals(u"TestPage", resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"TestPage", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/products/x%C3%BC/wiki/TestPage?version=2",
            resource.get_resource_url(self.env, target, self.env.href),
        )
示例#8
0
    def test_global_neighborhood_ticket(self):
        nbh = resource.Neighborhood("global", None)
        data = dict(summary="Ticket summary", description="Ticket description", type="enhancement", status="new")
        target = nbh.child("ticket", self._new_ticket(self.global_env, data))

        self.assertEquals("[global:] Ticket #1", resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Ticket #1", resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] #1", resource.get_resource_shortname(self.env, target))
        self.assertEquals("enhancement: Ticket summary (new)", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/ticket/1", resource.get_resource_url(self.env, target, self.env.href)
        )
示例#9
0
    def test_product_neighborhood_ticket(self):
        nbh = resource.Neighborhood("product", u"xü")
        data = dict(summary="Ticket summary", description="Ticket description", type="task", status="accepted")
        target = nbh.child("ticket", self._new_ticket(self.env1, data))

        self.assertEquals(u"[product:xü] Ticket #1", resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] Ticket #1", resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] #1", resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"task: Ticket summary (accepted)", resource.get_resource_summary(self.env, target))
        self.assertEquals(
            "http://example.org/trac.cgi/products/x%C3%BC/ticket/1",
            resource.get_resource_url(self.env, target, self.env.href),
        )
示例#10
0
    def test_product_neighborhood_milestone(self):
        target = resource.Neighborhood('product', u'xü').child(self.resource)

        self.assertEquals(u"[product:xü] Milestone milestone1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] Milestone milestone1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"milestone1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"[product:xü] Milestone milestone1",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals('http://example.org/trac.cgi/products/x%C3%BC/milestone/milestone1',
                          resource.get_resource_url(self.env,
                                                    target, self.env.href))
示例#11
0
    def test_global_neighborhood_wiki(self):
        target = resource.Neighborhood('global', None).child(self.resource)

        self.assertEquals("TestPage",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("TestPage",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("TestPage",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals("TestPage",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/wiki/TestPage?version=2',
            resource.get_resource_url(self.env, target, self.env.href))
示例#12
0
    def test_product_neighborhood_wiki(self):
        target = resource.Neighborhood('product', u'xü').child(self.resource)

        self.assertEquals(u"TestPage",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"TestPage",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"TestPage",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"TestPage",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/products/x%C3%BC/wiki/TestPage?version=2',
            resource.get_resource_url(self.env, target, self.env.href))
示例#13
0
    def test_product_neighborhood_attachments(self):
        target = resource.Neighborhood('product', u'xü').child(self.resource)

        self.assertEquals(u"[product:xü] Attachment 'foo.txt' in [product:xü] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] Attachment 'foo.txt' in [product:xü] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] foo.txt ([product:xü] Ticket #1)",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('Product Bar',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals('http://example.org/trac.cgi/products/x%C3%BC/attachment/ticket/1/foo.txt',
                          resource.get_resource_url(self.env,
                                                    target, self.env.href))
示例#14
0
    def test_global_neighborhood_attachments(self):
        target = resource.Neighborhood('global', None).child(self.resource)

        self.assertEquals("[global:] Attachment 'foo.txt' in [global:] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Attachment 'foo.txt' in [global:] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] foo.txt ([global:] Ticket #1)",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('Global Bar',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals('http://example.org/trac.cgi/attachment/ticket/1/foo.txt',
                          resource.get_resource_url(self.env,
                                                    target, self.env.href))
示例#15
0
    def test_product_neighborhood_report(self):
        target = resource.Neighborhood('product', u'xü').child(self.resource)

        self.assertEquals(u"[product:xü] report:1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] report:1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] report:1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"[product:xü] report:1 at version None",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/products/x%C3%BC/report/1',
            resource.get_resource_url(self.env, target, self.env.href))
示例#16
0
    def test_global_neighborhood_report(self):
        target = resource.Neighborhood('global', None).child(self.resource)

        self.assertEquals("[global:] report:1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] report:1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] report:1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('[global:] report:1 at version None',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/report/1',
            resource.get_resource_url(self.env, target, self.env.href))
示例#17
0
    def test_global_neighborhood_milestone(self):
        target = resource.Neighborhood('global', None).child(self.resource)

        self.assertEquals("[global:] Milestone milestone1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Milestone milestone1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("milestone1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals("[global:] Milestone milestone1",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/milestone/milestone1',
            resource.get_resource_url(self.env, target, self.env.href))
示例#18
0
    def test_product_neighborhood_attachments(self):
        target = resource.Neighborhood('product', u'xü').child(self.resource)

        self.assertEquals(
            u"[product:xü] Attachment 'foo.txt' in [product:xü] Ticket #1",
            resource.get_resource_description(self.env, target))
        self.assertEquals(
            u"[product:xü] Attachment 'foo.txt' in [product:xü] Ticket #1",
            resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] foo.txt ([product:xü] Ticket #1)",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('Product Bar',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/products/x%C3%BC/attachment/ticket/1/foo.txt',
            resource.get_resource_url(self.env, target, self.env.href))
示例#19
0
    def test_global_neighborhood_attachments(self):
        target = resource.Neighborhood('global', None).child(self.resource)

        self.assertEquals(
            "[global:] Attachment 'foo.txt' in [global:] Ticket #1",
            resource.get_resource_description(self.env, target))
        self.assertEquals(
            "[global:] Attachment 'foo.txt' in [global:] Ticket #1",
            resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] foo.txt ([global:] Ticket #1)",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('Global Bar',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/attachment/ticket/1/foo.txt',
            resource.get_resource_url(self.env, target, self.env.href))
    def filter_stream(self, req, method, filename, stream, data):
        crumbs = self._get_crumbs(req.session)
        if not crumbs:
            return stream

        add_stylesheet(req, 'breadcrumbs/css/breadcrumbs.css')
        ul = []

        path = req.path_info
        if path.count('/') >= 2:
            realm, resource_id = path.split('/', 2)[1:]
            if '&' in resource_id:
                resource_id = resource_id[0:resource_id.index('&')]
            current = '/'.join((realm, resource_id))
        else:
            current = None

        offset = 0
        if crumbs and crumbs[0] == current:
            offset = 1
        for crumb in crumbs[offset: self.max_crumbs + offset]:
            realm, resource_id = crumb.split('/', 1)
            resource = Resource(realm, resource_id)

            name = get_resource_shortname(self.env, resource)

            if not resource_exists(self.env, resource):
                continue

            title = get_resource_summary(self.env, resource)
            link = req.href(realm, resource_id)

            first = ul == []
            li = tag.li(tag.a(title=title, href=link)(name))
            if first:
                li(class_="first")
            ul.append(li)

        if ul:
            last = ul.pop()
            ul.append(last(class_="last"))
            label = self.label if self.label else "Breadcrumbs:"
            insert = tag.ul(class_="nav", id="breadcrumbs")(tag.li(label), ul)
        else:
            insert = ''

        return stream | Transformer('//div[@id="metanav"]/ul').after(insert)
示例#21
0
    def test_product_neighborhood_ticket(self):
        nbh = resource.Neighborhood('product', u'xü')
        data = dict(summary='Ticket summary', description='Ticket description',
                    type='task', status='accepted')
        target = nbh.child('ticket', self._new_ticket(self.env1, data))

        self.assertEquals(u"[product:xü] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] #1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"task: Ticket summary (accepted)",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals('http://example.org/trac.cgi/products/x%C3%BC/ticket/1',
                          resource.get_resource_url(self.env,
                                                    target, self.env.href))
示例#22
0
    def test_global_neighborhood_ticket(self):
        nbh = resource.Neighborhood('global', None)
        data = dict(summary='Ticket summary', description='Ticket description',
                    type='enhancement', status='new')
        target = nbh.child('ticket', self._new_ticket(self.global_env, data))

        self.assertEquals("[global:] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] #1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('enhancement: Ticket summary (new)',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals('http://example.org/trac.cgi/ticket/1',
                          resource.get_resource_url(self.env,
                                                    target, self.env.href))
示例#23
0
    def test_global_neighborhood_ticket(self):
        nbh = resource.Neighborhood('global', None)
        data = dict(summary='Ticket summary',
                    description='Ticket description',
                    type='enhancement',
                    status='new')
        target = nbh.child('ticket', self._new_ticket(self.global_env, data))

        self.assertEquals("[global:] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals("[global:] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals("[global:] #1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals('enhancement: Ticket summary (new)',
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/ticket/1',
            resource.get_resource_url(self.env, target, self.env.href))
示例#24
0
    def test_product_neighborhood_ticket(self):
        nbh = resource.Neighborhood('product', u'xü')
        data = dict(summary='Ticket summary',
                    description='Ticket description',
                    type='task',
                    status='accepted')
        target = nbh.child('ticket', self._new_ticket(self.env1, data))

        self.assertEquals(u"[product:xü] Ticket #1",
                          resource.get_resource_description(self.env, target))
        self.assertEquals(u"[product:xü] Ticket #1",
                          resource.get_resource_name(self.env, target))
        self.assertEquals(u"[product:xü] #1",
                          resource.get_resource_shortname(self.env, target))
        self.assertEquals(u"task: Ticket summary (accepted)",
                          resource.get_resource_summary(self.env, target))
        self.assertEquals(
            'http://example.org/trac.cgi/products/x%C3%BC/ticket/1',
            resource.get_resource_url(self.env, target, self.env.href))
示例#25
0
    def expand_macro(self, formatter, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = content.split(',')
        if len(args) == 0:
            raise Exception("No argument.")
        # strip unicode white-spaces and ZWSPs are copied from attachments
        # section (#10668)
        filespec = stripws(args.pop(0))

        # style information
        size_re = re.compile('[0-9]+(%|px)?$')
        attr_re = re.compile('(align|valign|border|width|height|alt'
                             '|margin(?:-(?:left|right|top|bottom))?'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        link = ''
        # helper for the special case `source:`
        #
        from trac.versioncontrol.web_ui import BrowserModule
        # FIXME: somehow use ResourceSystem.get_known_realms()
        #        ... or directly trac.wiki.extract_link
        try:
            browser_links = [
                res[0] for res in BrowserModule(self.env).get_link_resolvers()
            ]
        except Exception:
            browser_links = []
        while args:
            arg = stripws(args.pop(0))
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
            elif arg == 'nolink':
                link = None
            elif arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                elt = find_element(elt, 'href')
                link = None
                if elt is not None:
                    link = elt.attrib.get('href')
            elif arg in ('left', 'right'):
                style['float'] = arg
            elif arg == 'center':
                style['margin-left'] = style['margin-right'] = 'auto'
                style['display'] = 'block'
                style.pop('margin', '')
            elif arg in ('top', 'bottom', 'middle'):
                style['vertical-align'] = arg
            else:
                match = attr_re.match(arg)
                if match:
                    key, val = match.groups()
                    if (key == 'align' and
                            val in ('left', 'right', 'center')) or \
                        (key == 'valign' and \
                            val in ('top', 'middle', 'bottom')):
                        args.append(val)
                    elif key in ('margin-top', 'margin-bottom'):
                        style[key] = ' %dpx' % int(val)
                    elif key in ('margin', 'margin-left', 'margin-right') \
                             and 'display' not in style:
                        style[key] = ' %dpx' % int(val)
                    elif key == 'border':
                        style['border'] = ' %dpx solid' % int(val)
                    else:
                        m = quoted_re.search(val)  # unquote "..." and '...'
                        if m:
                            val = m.group(1)
                        attr[str(key)] = val  # will be used as a __call__ kwd

        # parse filespec argument to get realm and id if contained.
        parts = [
            i.strip('''['"]''')
            for i in self._split_filespec_re.split(filespec)
        ]
        url = raw_url = desc = None
        attachment = None
        if (parts and parts[0] in ('http', 'https', 'ftp')):  # absolute
            raw_url = url = filespec
            desc = url.rsplit('?')[0]
        elif filespec.startswith('//'):  # server-relative
            raw_url = url = filespec[1:]
            desc = url.rsplit('?')[0]
        elif filespec.startswith('/'):  # project-relative
            params = ''
            if '?' in filespec:
                filespec, params = filespec.rsplit('?', 1)
            url = formatter.href(filespec)
            if params:
                url += '?' + params
            raw_url, desc = url, filespec
        elif len(parts) == 3:  # realm:id:attachment-filename
            #                                 # or intertrac:realm:id
            realm, id, filename = parts
            intertrac_target = "%s:%s" % (id, filename)
            it = formatter.get_intertrac_url(realm, intertrac_target)
            if it:
                url, desc = it
                raw_url = url + unicode_quote('?format=raw')
            else:
                attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            realm, filename = parts
            if realm in browser_links:  # source:path
                # TODO: use context here as well
                rev = None
                if '@' in filename:
                    filename, rev = filename.rsplit('@', 1)
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename,
                                                 rev=rev,
                                                 format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                elif id == 'shared':
                    raw_url = url = formatter.href.chrome('shared', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm,
                                          id).child('attachment', filename)
        elif len(parts) == 1:  # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            raise TracError('No filespec given')
        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            raw_url = get_resource_url(self.env,
                                       attachment,
                                       formatter.href,
                                       format='raw')
            try:
                desc = get_resource_summary(self.env, attachment)
            except ResourceNotFound as e:
                raw_url = formatter.href.chrome('common/attachment.png')
                desc = _('No image "%(id)s" attached to %(parent)s',
                         id=attachment.id,
                         parent=get_resource_name(self.env, attachment.parent))
        for key in ('title', 'alt'):
            if desc and not key in attr:
                attr[key] = desc
        if style:
            attr['style'] = '; '.join('%s:%s' % (k, escape(v))
                                      for k, v in style.iteritems())
        result = tag.img(src=raw_url, **attr)
        if link is not None:
            result = tag.a(result,
                           href=link or url,
                           style='padding:0; border:none')
        return result
示例#26
0
    def expand_macro(self, formatter, name, content):
         # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = content.split(',')
        if len(args) == 0:
            raise Exception("No argument.")
        filespec = args[0]

        # style information
        size_re = re.compile('[0-9]+(%|px)?$')
        attr_re = re.compile('(align|border|width|height|alt'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        layers_re = re.compile("^[0-9]+(\.[0-9]+)*$")
        attr = {}
        style = {}
        link = ''
        width = None
        layers = None
        for arg in args[1:]:
            arg = arg.strip()
            if size_re.match(arg):
                if width:
                    raise Exception("Argument 'width' appears more than once.")
                width = arg
                attr['width'] = arg
                continue
            if arg == 'nolink':
                link = None
                continue
            if arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                link = None
                if isinstance(elt, Element):
                    link = elt.attrib.get('href')
                continue
            if arg in ('left', 'right', 'top', 'bottom'):
                style['float'] = arg
                continue
            if arg.startswith('layers='):
                if layers:
                    raise Exception("Argument 'layers' appears more than once.")
                layers = arg.split('=', 1)[1]
                if not layers_re.match(layers):
                    raise Exception("Wrong layer list format, use dot separated list of integer numbers.")
            match = attr_re.match(arg)
            if match:
                key, val = match.groups()
                m = quoted_re.search(val) # unquote "..." and '...'
                if m:
                    val = m.group(1)
                if key == 'align':
                    style['float'] = val
                elif key == 'border':
                    style['border'] = ' %dpx solid' % int(val);
                else:
                    attr[str(key)] = val # will be used as a __call__ keyword

        # Got the args now do some processing
        attachment = formatter.resource.child('attachment', filespec)
        realm = formatter.resource.realm
        resource_id     = formatter.resource.id         # The use of "id" could cause a conflict?

        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            description = get_resource_summary(self.env, attachment)

        # Includes vdx for use with Visio
        png_url = url.replace(".dia",".png").replace(".vdx",".png")
        dia_attachment = Attachment(self.env, realm, resource_id, filespec)
        dia_path = dia_attachment.path
        dia_filename = dia_attachment.filename
        png_path = dia_path.replace('.dia','.png').replace(".vdx",".png")
        png_filename = dia_filename.replace('.dia','.png').replace(".vdx",".png")

        # the layers are encoded into the path as dot-separated list, e.g. basename.1.2.png
        if layers:
            layers_extension = '.' + layers + '.png'
            png_path = png_path.replace('.png', layers_extension)
            png_filename = png_filename.replace('.png', layers_extension)
            png_url = png_url.replace(".png", layers_extension)

        png_attachment = Attachment(self.env, realm, resource_id, filespec)

        if len(description) <= 0:
            description = 'PNG render of ' + dia_filename

        self.env.log.info('Getting file modification times.')
        try:
            dia_mtime = os.path.getmtime(dia_path)
        except Exception:
            raise Exception('File does not exist: %s', dia_path)

        try:
            png_mtime = os.path.getmtime(png_path)
        except Exception:
            png_mtime = 0
        else:
            try:
                im = Image.open(png_path)
            except Exception, e:
                self.env.log.info('Error checking original png file width for Dia = %s',e)
                raise Exception('Error checking original png file width for Dia.')
            existing_width = im.size[0]
示例#27
0
    def expand_macro(self, formatter, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = content.split(',')
        if len(args) == 0:
            raise Exception("No argument.")
        filespec = args.pop(0)

        # style information
        size_re = re.compile('[0-9]+(%|px)?$')
        attr_re = re.compile('(align|valign|border|width|height|alt'
                             '|margin(?:-(?:left|right|top|bottom))?'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        link = ''
        while args:
            arg = args.pop(0).strip()
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
            elif arg == 'nolink':
                link = None
            elif arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                link = None
                if isinstance(elt, Element):
                    link = elt.attrib.get('href')
            elif arg in ('left', 'right'):
                style['float'] = arg
            elif arg == 'center':
                style['margin-left'] = style['margin-right'] = 'auto'
                style['display'] = 'block'
                style.pop('margin', '')
            elif arg in ('top', 'bottom', 'middle'):
                style['vertical-align'] = arg
            else:
                match = attr_re.match(arg)
                if match:
                    key, val = match.groups()
                    if (key == 'align' and 
                            val in ('left', 'right', 'center')) or \
                        (key == 'valign' and \
                            val in ('top', 'middle', 'bottom')):
                        args.append(val)
                    elif key in ('margin-top', 'margin-bottom'):
                        style[key] = ' %dpx' % int(val)
                    elif key in ('margin', 'margin-left', 'margin-right') \
                             and 'display' not in style:
                        style[key] = ' %dpx' % int(val)
                    elif key == 'border':
                        style['border'] = ' %dpx solid' % int(val)
                    else:
                        m = quoted_re.search(val) # unquote "..." and '...'
                        if m:
                            val = m.group(1)
                        attr[str(key)] = val # will be used as a __call__ kwd

        # parse filespec argument to get realm and id if contained.
        parts = filespec.split(':')
        url = raw_url = desc = None
        attachment = None
        if (parts and parts[0] in ('http', 'https', 'ftp')): # absolute
            raw_url = url = desc = filespec
        elif filespec.startswith('//'):       # server-relative
            raw_url = url = desc = filespec[1:]
        elif filespec.startswith('/'):        # project-relative
            # use href, but unquote to allow args (use default html escaping)
            raw_url = url = desc = unquote(formatter.href(filespec))
        elif len(parts) == 3:                 # realm:id:attachment-filename
            realm, id, filename = parts
            attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            # FIXME: somehow use ResourceSystem.get_known_realms()
            #        ... or directly trac.wiki.extract_link
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [res[0] for res in
                                 BrowserModule(self.env).get_link_resolvers()]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:   # source:path
                # TODO: use context here as well
                realm, filename = parts
                rev = None
                if '@' in filename:
                    filename, rev = filename.split('@')
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename, rev=rev,
                                                 format='raw')
                desc = filespec
            else: # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm, id).child('attachment',
                                                           filename)
        elif len(parts) == 1: # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            raise TracError('No filespec given')
        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            raw_url = get_resource_url(self.env, attachment, formatter.href,
                                       format='raw')
            try:
                desc = get_resource_summary(self.env, attachment)
            except ResourceNotFound, e:
                raw_url = formatter.href.chrome('common/attachment.png')
                desc = _('No image "%(id)s" attached to %(parent)s',
                         id=attachment.id,
                         parent=get_resource_name(self.env, attachment.parent))
示例#28
0
文件: macros.py 项目: exocad/exotrac
    def expand_macro(self, formatter, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = [stripws(arg) for arg
                             in self._split_args_re.split(content)[1::2]]
        # strip unicode white-spaces and ZWSPs are copied from attachments
        # section (#10668)
        filespec = args.pop(0)

        # style information
        attr = {}
        style = {}
        link = ''
        # helper for the special case `source:`
        #
        from trac.versioncontrol.web_ui import BrowserModule
        # FIXME: somehow use ResourceSystem.get_known_realms()
        #        ... or directly trac.wiki.extract_link
        try:
            browser_links = [res[0] for res in
                             BrowserModule(self.env).get_link_resolvers()]
        except Exception:
            browser_links = []
        while args:
            arg = args.pop(0)
            if self._size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
            elif arg == 'nolink':
                link = None
            elif arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                elt = find_element(elt, 'href')
                link = None
                if elt is not None:
                    link = elt.attrib.get('href')
            elif arg in ('left', 'right'):
                style['float'] = arg
            elif arg == 'center':
                style['margin-left'] = style['margin-right'] = 'auto'
                style['display'] = 'block'
                style.pop('margin', '')
            elif arg in ('top', 'bottom', 'middle'):
                style['vertical-align'] = arg
            else:
                match = self._attr_re.match(arg)
                if match:
                    key, val = match.groups()
                    if (key == 'align' and
                            val in ('left', 'right', 'center')) or \
                        (key == 'valign' and
                            val in ('top', 'middle', 'bottom')):
                        args.append(val)
                    elif key in ('margin-top', 'margin-bottom'):
                        style[key] = ' %dpx' % int(val)
                    elif key in ('margin', 'margin-left', 'margin-right') \
                             and 'display' not in style:
                        style[key] = ' %dpx' % int(val)
                    elif key == 'border':
                        style['border'] = ' %dpx solid' % int(val)
                    else:
                        m = self._quoted_re.search(val)  # unquote "..." and '...'
                        if m:
                            val = m.group(1)
                        attr[str(key)] = val  # will be used as a __call__ kwd

        if self._quoted_re.match(filespec):
            filespec = filespec.strip('\'"')
        # parse filespec argument to get realm and id if contained.
        parts = [i.strip('''['"]''')
                 for i in self._split_filespec_re.split(filespec)[1::2]]
        url = raw_url = desc = None
        attachment = None
        if parts and parts[0] in ('http', 'https', 'ftp', 'data'):  # absolute
            raw_url = url = filespec
            desc = url.rsplit('?')[0]
        elif filespec.startswith('//'):       # server-relative
            raw_url = url = filespec[1:]
            desc = url.rsplit('?')[0]
        elif filespec.startswith('/'):        # project-relative
            params = ''
            if '?' in filespec:
                filespec, params = filespec.rsplit('?', 1)
            url = formatter.href(filespec)
            if params:
                url += '?' + params
            raw_url, desc = url, filespec
        elif len(parts) == 3:                 # realm:id:attachment-filename
            #                                 # or intertrac:realm:id
            realm, id, filename = parts
            intertrac_target = "%s:%s" % (id, filename)
            it = formatter.get_intertrac_url(realm, intertrac_target)
            if it:
                url, desc = it
                raw_url = url + unicode_quote('?format=raw')
            else:
                attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            realm, filename = parts
            if realm in browser_links:  # source:path
                # TODO: use context here as well
                rev = None
                if '@' in filename:
                    filename, rev = filename.rsplit('@', 1)
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename, rev=rev,
                                                 format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                elif id == 'shared':
                    raw_url = url = formatter.href.chrome('shared', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm, id).child('attachment',
                                                           filename)
        elif len(parts) == 1:  # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            raise TracError(_("No filespec given"))
        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            raw_url = get_resource_url(self.env, attachment, formatter.href,
                                       format='raw')
            try:
                desc = get_resource_summary(self.env, attachment)
            except ResourceNotFound:
                raw_url = chrome_resource_path(formatter.context.req,
                                               'common/attachment.png')
                desc = _('No image "%(id)s" attached to %(parent)s',
                         id=attachment.id,
                         parent=get_resource_name(self.env, attachment.parent))
        for key in ('title', 'alt'):
            if desc and key not in attr:
                attr[key] = desc
        if style:
            attr['style'] = '; '.join('%s:%s' % (k, escape(v))
                                      for k, v in style.iteritems())
        result = tag.img(src=raw_url, **attr)
        if link is not None:
            result = tag.a(result, href=link or url,
                           style='padding:0; border:none')
        return result
示例#29
0
    def _format_name(self, req, url):
        linkname = url
        name = ""
        missing = False

        path_info = url
        query_string = ''
        idx = path_info.find('?')
        if idx >= 0:
            path_info, query_string = path_info[:idx], path_info[idx:]
        href = req.href(path_info) + query_string

        args = arg_list_to_args(parse_arg_list(query_string.lstrip('?')))
        version = args.get('version', False)

        path = path_info.strip('/').split('/')
        realm = path[0]
        class_ = realm
        if len(path) > 1:
            resource = Resource(realm, path[1])
            if resource:
                if realm == 'ticket':
                    linkname = get_resource_shortname(self.env, resource)
                    try:
                        name = get_resource_summary(self.env, resource)
                    except ResourceNotFound:
                        missing = True
                    else:
                        from trac.ticket.model import Ticket
                        class_ = Ticket(self.env, resource.id)['status'] + \
                            ' ' + class_
                elif realm == 'milestone':
                    linkname = get_resource_name(self.env, resource)
                elif realm == 'wiki':
                    resource = Resource(realm, '/'.join(path[1:]), version)
                    linkname = get_resource_shortname(self.env, resource)
                    if version:
                        linkname += '@' + version
                elif realm == 'report':
                    linkname = "{%s}" % path[1]
                    name = self._format_report_name(path[1])
                elif realm == 'changeset':
                    rev = path[1]
                    parent = Resource('source', '/'.join(path[2:]))
                    resource = Resource(realm, rev, False, parent)
                    linkname = "[%s]" % rev
                    name = get_resource_description(self.env, resource)
                elif realm == 'browser':
                    rm = RepositoryManager(self.env)
                    reponame, repos, path = rm.get_repository_by_path('/'.join(
                        path[1:]))
                    parent = Resource('source', reponame)
                    resource = Resource('source', path, False, parent)
                    linkname = get_resource_description(self.env, resource)
                    name = get_resource_summary(self.env, resource)
                elif realm == 'attachment':
                    # Assume a file and check existence
                    parent = Resource(path[1], '/'.join(path[2:-1]))
                    resource = Resource(realm, path[-1], parent=parent)
                    linkname = get_resource_name(self.env, resource)
                    if not resource_exists(self.env, resource):
                        # Assume an attachment list page and check existence
                        parent = Resource(path[1], '/'.join(path[2:]))
                        if resource_exists(self.env, parent):
                            resource = Resource(realm, parent=parent)
                            linkname = get_resource_name(self.env, resource)
                            if not query_string:
                                # Trailing slash needed for Trac < 1.0, t:#10280
                                href += '/'
                        else:
                            # Assume it's a missing attachment
                            missing = True
                else:
                    linkname = get_resource_shortname(self.env, resource)
                    name = get_resource_summary(self.env, resource)
        elif len(path) == 1 and path[0] and path[0] != 'wiki':
            linkname = path[0].capitalize()
        else:
            class_ = 'wiki'
            linkname = 'WikiStart'

        if missing:
            href = None
            class_ = 'missing ' + realm

        return {
            'class_': class_,
            'href': href,
            'linkname': linkname,
            'name': name,
            'delete': req.href.bookmark('delete_in_page', url),
        }
示例#30
0
    def expand_macro(self, formatter, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = content.split(',')
        if len(args) == 0:
            raise Exception("No argument.")
        filespec = args[0]

        # style information
        size_re = re.compile('[0-9]+(%|px)?$')
        attr_re = re.compile('(align|border|width|height|alt'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        link = ''
        for arg in args[1:]:
            arg = arg.strip()
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
                continue
            if arg == 'nolink':
                link = None
                continue
            if arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                link = None
                if isinstance(elt, Element):
                    link = elt.attrib.get('href')
                continue
            if arg in ('left', 'right', 'top', 'bottom'):
                style['float'] = arg
                continue
            match = attr_re.match(arg)
            if match:
                key, val = match.groups()
                m = quoted_re.search(val) # unquote "..." and '...'
                if m:
                    val = m.group(1)
                if key == 'align':
                    style['float'] = val
                elif key == 'border':
                    style['border'] = ' %dpx solid' % int(val);
                else:
                    attr[str(key)] = val # will be used as a __call__ keyword

        # parse filespec argument to get realm and id if contained.
        parts = filespec.split(':')
        url = raw_url = desc = None
        attachment = None
        if (parts and parts[0] in ('http', 'https', 'ftp')): # absolute
            raw_url = url = desc = filespec
        elif filespec.startswith('//'):       # server-relative
            raw_url = url = desc = filespec[1:]
        elif filespec.startswith('/'):        # project-relative
            # use href, but unquote to allow args (use default html escaping)
            raw_url = url = desc = unquote(formatter.href(filespec))
        elif len(parts) == 3:                 # realm:id:attachment-filename
            realm, id, filename = parts
            attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            # FIXME: somehow use ResourceSystem.get_known_realms()
            #        ... or directly trac.wiki.extract_link
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [res[0] for res in
                                 BrowserModule(self.env).get_link_resolvers()]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:   # source:path
                # TODO: use context here as well
                realm, filename = parts
                rev = None
                if '@' in filename:
                    filename, rev = filename.split('@')
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename, rev=rev,
                                                 format='raw')
                desc = filespec
            else: # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm, id).child('attachment',
                                                           filename)
        elif len(parts) == 1: # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            raise TracError('No filespec given')
        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            raw_url = get_resource_url(self.env, attachment, formatter.href,
                                       format='raw')
            desc = get_resource_summary(self.env, attachment)
        for key in ('title', 'alt'):
            if desc and not key in attr:
                attr[key] = desc
        if style:
            attr['style'] = '; '.join(['%s:%s' % (k, escape(v))
                                       for k, v in style.iteritems()])
        result = tag.img(src=raw_url, **attr)
        if link is not None:
            result = tag.a(result, href=link or url,
                           style='padding:0; border:none')
        return result
示例#31
0
文件: macros.py 项目: trac-ja/trac-ja
    def expand_macro(self, formatter, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        # parse arguments
        # we expect the 1st argument to be a filename (filespec)
        args = content.split(',')
        if len(args) == 0:
            raise Exception("No argument.")
        # strip unicode white-spaces and ZWSPs are copied from attachments
        # section (#10668)
        filespec = stripws(args.pop(0))

        # style information
        size_re = re.compile('[0-9]+(%|px)?$')
        attr_re = re.compile('(align|valign|border|width|height|alt'
                             '|margin(?:-(?:left|right|top|bottom))?'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        link = ''
        # helper for the special case `source:`
        #
        from trac.versioncontrol.web_ui import BrowserModule
        # FIXME: somehow use ResourceSystem.get_known_realms()
        #        ... or directly trac.wiki.extract_link
        try:
            browser_links = [res[0] for res in
                             BrowserModule(self.env).get_link_resolvers()]
        except Exception:
            browser_links = []
        while args:
            arg = args.pop(0).strip()
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
            elif arg == 'nolink':
                link = None
            elif arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                elt = find_element(elt, 'href')
                link = None
                if elt is not None:
                    link = elt.attrib.get('href')
            elif arg in ('left', 'right'):
                style['float'] = arg
            elif arg == 'center':
                style['margin-left'] = style['margin-right'] = 'auto'
                style['display'] = 'block'
                style.pop('margin', '')
            elif arg in ('top', 'bottom', 'middle'):
                style['vertical-align'] = arg
            else:
                match = attr_re.match(arg)
                if match:
                    key, val = match.groups()
                    if (key == 'align' and
                            val in ('left', 'right', 'center')) or \
                        (key == 'valign' and \
                            val in ('top', 'middle', 'bottom')):
                        args.append(val)
                    elif key in ('margin-top', 'margin-bottom'):
                        style[key] = ' %dpx' % int(val)
                    elif key in ('margin', 'margin-left', 'margin-right') \
                             and 'display' not in style:
                        style[key] = ' %dpx' % int(val)
                    elif key == 'border':
                        style['border'] = ' %dpx solid' % int(val)
                    else:
                        m = quoted_re.search(val) # unquote "..." and '...'
                        if m:
                            val = m.group(1)
                        attr[str(key)] = val # will be used as a __call__ kwd

        # parse filespec argument to get realm and id if contained.
        parts = filespec.split(':')
        url = raw_url = desc = None
        attachment = None
        if (parts and parts[0] in ('http', 'https', 'ftp')): # absolute
            raw_url = url = filespec
            desc = url.rsplit('?')[0]
        elif filespec.startswith('//'):       # server-relative
            raw_url = url = filespec[1:]
            desc = url.rsplit('?')[0]
        elif filespec.startswith('/'):        # project-relative
            params = ''
            if '?' in filespec:
                filespec, params = filespec.rsplit('?', 1)
            url = formatter.href(filespec)
            if params:
                url += '?' + params
            raw_url, desc = url, filespec
        elif len(parts) == 3:                 # realm:id:attachment-filename
            #                                 # or intertrac:realm:id
            realm, id, filename = parts
            intertrac_target = "%s:%s" % (id, filename)
            it = formatter.get_intertrac_url(realm, intertrac_target)
            if it:
                url, desc = it
                raw_url = url + unicode_quote('?format=raw')
            else:
                attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            realm, filename = parts
            if realm in browser_links:   # source:path
                # TODO: use context here as well
                rev = None
                if '@' in filename:
                    filename, rev = filename.rsplit('@', 1)
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename, rev=rev,
                                                 format='raw')
                desc = filespec
            else: # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm, id).child('attachment',
                                                           filename)
        elif len(parts) == 1: # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            raise TracError('No filespec given')
        if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, formatter.href)
            raw_url = get_resource_url(self.env, attachment, formatter.href,
                                       format='raw')
            try:
                desc = get_resource_summary(self.env, attachment)
            except ResourceNotFound, e:
                raw_url = formatter.href.chrome('common/attachment.png')
                desc = _('No image "%(id)s" attached to %(parent)s',
                         id=attachment.id,
                         parent=get_resource_name(self.env, attachment.parent))
示例#32
0
    def expand_macro(self, formatter, name, content):
        args = None
        if content:
            content = stripws(content)
            # parse arguments
            # we expect the 1st argument to be a filename (filespec)
            args = [stripws(arg) for arg
                                 in self._split_args_re.split(content)[1::2]]
        if not args:
            return ''
        # strip unicode white-spaces and ZWSPs are copied from attachments
        # section (#10668)
        filespec = args.pop(0)

        # style information
        attr = {}
        style = {}
        link = ''
        # helper for the special case `source:`
        #
        from trac.versioncontrol.web_ui import BrowserModule
        # FIXME: somehow use ResourceSystem.get_known_realms()
        #        ... or directly trac.wiki.extract_link
        try:
            browser_links = [res[0] for res in
                             BrowserModule(self.env).get_link_resolvers()]
        except Exception:
            browser_links = []
        while args:
            arg = args.pop(0)
            if self._size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
            elif arg == 'nolink':
                link = None
            elif arg.startswith('link='):
                val = arg.split('=', 1)[1]
                elt = extract_link(self.env, formatter.context, val.strip())
                elt = find_element(elt, 'href')
                link = None
                if elt is not None:
                    link = elt.attrib.get('href')
            elif arg in ('left', 'right'):
                style['float'] = arg
            elif arg == 'center':
                style['margin-left'] = style['margin-right'] = 'auto'
                style['display'] = 'block'
                style.pop('margin', '')
            elif arg in ('top', 'bottom', 'middle'):
                style['vertical-align'] = arg
            else:
                match = self._attr_re.match(arg)
                if match:
                    key, val = match.groups()
                    if (key == 'align' and
                            val in ('left', 'right', 'center')) or \
                        (key == 'valign' and
                            val in ('top', 'middle', 'bottom')):
                        args.append(val)
                    elif key in ('margin-top', 'margin-bottom'):
                        style[key] = ' %dpx' % _arg_as_int(val, key, min=1)
                    elif key in ('margin', 'margin-left', 'margin-right') \
                             and 'display' not in style:
                        style[key] = ' %dpx' % _arg_as_int(val, key, min=1)
                    elif key == 'border':
                        style['border'] = ' %dpx solid' % _arg_as_int(val, key)
                    else:
                        m = self._quoted_re.search(val)  # unquote "..." and '...'
                        if m:
                            val = m.group(1)
                        attr[str(key)] = val  # will be used as a __call__ kwd

        if self._quoted_re.match(filespec):
            filespec = filespec.strip('\'"')
        # parse filespec argument to get realm and id if contained.
        parts = [i.strip('\'"')
                 for i in self._split_filespec_re.split(filespec)[1::2]]
        realm = parts[0] if parts else None
        url = raw_url = desc = None
        attachment = None
        interwikimap = InterWikiMap(self.env)
        if realm in ('http', 'https', 'ftp', 'data'):  # absolute
            raw_url = url = filespec
            desc = url.rsplit('?')[0]
        elif realm in interwikimap:
            url, desc = interwikimap.url(realm, ':'.join(parts[1:]))
            raw_url = url
        elif filespec.startswith('//'):       # server-relative
            raw_url = url = filespec[1:]
            desc = url.rsplit('?')[0]
        elif filespec.startswith('/'):        # project-relative
            params = ''
            if '?' in filespec:
                filespec, params = filespec.rsplit('?', 1)
            url = formatter.href(filespec)
            if params:
                url += '?' + params
            raw_url, desc = url, filespec
        elif len(parts) == 3:                 # realm:id:attachment-filename
            #                                 # or intertrac:realm:id
            realm, id, filename = parts
            intertrac_target = "%s:%s" % (id, filename)
            it = formatter.get_intertrac_url(realm, intertrac_target)
            if it:
                url, desc = it
                raw_url = url + unicode_quote('?format=raw')
            else:
                attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            realm, filename = parts
            if realm in browser_links:  # source:path
                # TODO: use context here as well
                rev = None
                if '@' in filename:
                    filename, rev = filename.rsplit('@', 1)
                url = formatter.href.browser(filename, rev=rev)
                raw_url = formatter.href.browser(filename, rev=rev,
                                                 format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                realm = None
                id, filename = parts
                if id and id[0] == '#':
                    realm = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = formatter.href.chrome('site', filename)
                    desc = os.path.basename(filename)
                elif id == 'shared':
                    raw_url = url = formatter.href.chrome('shared', filename)
                    desc = os.path.basename(filename)
                else:
                    realm = 'wiki'
                if realm:
                    attachment = Resource(realm, id).child('attachment',
                                                           filename)
        elif len(parts) == 1:  # it's an attachment of the current resource
            attachment = formatter.resource.child('attachment', filespec)
        else:
            return system_message(_("No filespec given"))
        if attachment:
            try:
                desc = get_resource_summary(self.env, attachment)
            except ResourceNotFound:
                link = None
                raw_url = chrome_resource_path(formatter.context.req,
                                               'common/attachment.png')
                desc = _('No image "%(id)s" attached to %(parent)s',
                         id=attachment.id,
                         parent=get_resource_name(self.env, attachment.parent))
            else:
                if 'ATTACHMENT_VIEW' in formatter.perm(attachment):
                    url = get_resource_url(self.env, attachment,
                                           formatter.href)
                    raw_url = get_resource_url(self.env, attachment,
                                               formatter.href, format='raw')

        for key in ('title', 'alt'):
            if desc and key not in attr:
                attr[key] = desc
        if style:
            attr['style'] = '; '.join('%s:%s' % (k, escape(v))
                                      for k, v in style.iteritems())
        if not WikiSystem(self.env).is_safe_origin(raw_url,
                                                   formatter.context.req):
            attr['crossorigin'] = 'anonymous'  # avoid password prompt
        result = tag.img(src=raw_url, **attr)
        if link is not None:
            result = tag.a(result, href=link or url,
                           style='padding:0; border:none')
        return result
示例#33
0
    def _format_name(self, req, url):
        linkname = url
        name = ""
        missing = False

        path_info = url
        query_string = ''
        idx = path_info.find('?')
        if idx >= 0:
            path_info, query_string = path_info[:idx], path_info[idx:]
        href = req.href(path_info) + query_string

        args = arg_list_to_args(parse_arg_list(query_string.lstrip('?')))
        version = args.get('version', False)

        path = path_info.strip('/').split('/')
        realm = path[0]
        class_ = realm
        if len(path) > 1:
            resource = Resource(realm, path[1])
            if resource:
                if realm == 'ticket':
                    linkname = get_resource_shortname(self.env, resource)
                    try:
                        name = get_resource_summary(self.env, resource)
                    except ResourceNotFound:
                        missing = True
                    else:
                        from trac.ticket.model import Ticket
                        class_ = Ticket(self.env, resource.id)['status'] + \
                            ' ' + class_
                elif realm == 'milestone':
                    linkname = get_resource_name(self.env, resource)
                elif realm == 'wiki':
                    resource = Resource(realm, '/'.join(path[1:]), version)
                    linkname = get_resource_shortname(self.env, resource)
                    if version:
                        linkname += '@' + version
                elif realm == 'report':
                    linkname = "{%s}" % path[1]
                    name = self._format_report_name(path[1])
                elif realm == 'changeset':
                    rev = path[1]
                    parent = Resource('source', '/'.join(path[2:]))
                    resource = Resource(realm, rev, False, parent)
                    linkname = "[%s]" % rev
                    name = get_resource_description(self.env, resource)
                elif realm == 'browser':
                    parent = Resource('source', path[1])
                    resource = Resource('source', '/'.join(path[2:]), False, parent)
                    linkname = get_resource_description(self.env, resource)
                    name = get_resource_summary(self.env, resource)
                elif realm == 'attachment':
                    # Assume a file and check existence
                    parent = Resource(path[1], '/'.join(path[2:-1]))
                    resource = Resource(realm, path[-1], parent=parent)
                    linkname = get_resource_name(self.env, resource)
                    if not resource_exists(self.env, resource):
                        # Assume an attachment list page and check existence
                        parent = Resource(path[1], '/'.join(path[2:]))
                        if resource_exists(self.env, parent):
                            resource = Resource(realm, parent=parent)
                            linkname = get_resource_name(self.env, resource)
                            if not query_string:
                                # Trailing slash needed for Trac < 1.0, t:#10280
                                href += '/'
                        else:
                            # Assume it's a missing attachment
                            missing = True
                else:
                    linkname = get_resource_shortname(self.env, resource)
                    name = get_resource_summary(self.env, resource)
        elif len(path) == 1 and path[0] and path[0] != 'wiki':
            linkname = path[0].capitalize()
        else:
            class_ = 'wiki'
            linkname = 'WikiStart'

        if missing:
            href = None
            class_ = 'missing ' + realm

        return {
            'class_': class_,
            'href': href,
            'linkname': linkname,
            'name': name,
            'delete': req.href.bookmark('delete_in_page', url),
        }