コード例 #1
0
    def get_file(self, filespec, req):
        # parse filespec argument to get module and id if contained.
        parts = filespec.split(':')
        url = None
        if len(parts) == 3:  # module:id:attachment
            if parts[0] in ['wiki', 'ticket']:
                module, id, file = parts
            else:
                return None
        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [
                    link for link, _ in BrowserModule(
                        self.env).get_link_resolvers()
                ]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:  # source:path
                module, file = parts
                rev = None
                if '@' in file:
                    file, rev = file.split('@')
                url = req.href.browser(file, rev=rev)
                raw_url = req.href.browser(file, rev=rev, format='raw')
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                id, file = parts
                if id and id[0] == '#':
                    module = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = req.href.chrome('site', file)
                elif id in ('http', 'https', 'ftp'):  # external URLs
                    raw_url = url = id + ':' + file
                else:
                    module = 'wiki'
        elif len(parts) == 1:  # attachment
            # determine current object
            # FIXME: should be retrieved from the formatter...
            # ...and the formatter should be provided to the macro
            file = filespec
            module, id = 'wiki', 'WikiStart'
            path_info = req.path_info.split('/', 2)
            if len(path_info) > 1:
                module = path_info[1]
            if len(path_info) > 2:
                id = path_info[2]
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
        else:
            raise Exception('No filespec given')

        if not url:  # this is an attachment
            from trac.attachment import Attachment
            attachment = Attachment(self.env, module, id, file)
            url = attachment.href(req)
            raw_url = attachment.href(req, format='raw')

        return url
コード例 #2
0
ファイル: p4trac.py プロジェクト: pombredanne/trachacks
 def process_request(self, req):
     # before:
     #branch = req.args.get('branch')
     #tag = req.args.get('tag')
     #if branch:
     #    req.args['rev'] = branch
     #elif tag:
     #    req.args['rev'] = tag
     return BrowserModule.process_request(self, req)
コード例 #3
0
ファイル: p4trac.py プロジェクト: nyuhuhuu/trachacks
 def process_request(self, req):
     # before:
     # branch = req.args.get('branch')
     # tag = req.args.get('tag')
     # if branch:
     #    req.args['rev'] = branch
     # elif tag:
     #    req.args['rev'] = tag
     return BrowserModule.process_request(self, req)
コード例 #4
0
def find_file(env, filespec, req):
    # parse filespec argument to get module and id if contained.
    parts = filespec.split(':')
    url = None
    if len(parts) == 3:                 # module:id:attachment
        if parts[0] in ['wiki', 'ticket']:
            module, id, file = parts
        else:
            return None
    elif len(parts) == 2:
        from trac.versioncontrol.web_ui import BrowserModule
        try:
            browser_links = [link for link,_ in
                             BrowserModule(env).get_link_resolvers()]
        except Exception:
            browser_links = []
        if parts[0] in browser_links:   # source:path
            module, file = parts
            rev = None
            if '@' in file:
                file, rev = file.split('@')
            url = req.href.browser(file, rev=rev)
            raw_url = req.href.browser(file, rev=rev, format='raw')
        else: # #ticket:attachment or WikiPage:attachment
            id, file = parts
            if id and id[0] == '#':
                module = 'ticket'
                id = id[1:]
            elif id == 'htdocs':
                raw_url = url = req.href.chrome('site', file)
            elif id in ('http', 'https', 'ftp'): # external URLs
                raw_url = url = id+':'+file
            else:
                module = 'wiki'
    elif len(parts) == 1:               # attachment
        file = filespec
        module, id = 'wiki', 'WikiStart'
        path_info = req.path_info.split('/',2)
        if len(path_info) > 1:
            module = path_info[1]
        if len(path_info) > 2:
            id = path_info[2]
        if module not in ['wiki', 'ticket']:
            raise Exception('Cannot reference local attachment from here')
    else:
        raise Exception('No filespec given')

##     if not url: # this is an attachment
##         from trac.attachment import Attachment
##         attachment = Attachment(env, module, id, file)
##         url = attachment.path
##         raw_url = attachment.path #(req, format='raw')

    return url
コード例 #5
0
def _parse_filespec(filespec, hdf, env):
    # parse filespec argument to get module and id if contained.
    if filespec[:5] == 'http:' or filespec[:6] == 'https:':
        parts = [ 'url', '', filespec ]
    else:
        parts = filespec.split(':', 2)

    if len(parts) == 3:                 # module:id:attachment
        if parts[0] in ['wiki', 'ticket', 'browser', 'file', 'url']:
            module, id, file = parts
        else:
            raise Exception("unknown module %s" % parts[0])

    elif len(parts) == 2:
        from trac.versioncontrol.web_ui import BrowserModule
        try:
            browser_links = [link for link,_ in
                             BrowserModule(env).get_link_resolvers()]
        except Exception:
            browser_links = []

        id, file = parts
        if id in browser_links:         # source:path
            module = 'browser'
        elif id and id[0] == '#':       # #ticket:attachment
            module = 'ticket'
            id = id[1:]
        elif id == 'htdocs':            # htdocs:path
            module = 'file'
        else:                           # WikiPage:attachment
            module = 'wiki'

    elif len(parts) == 1:               # attachment
        # determine current object
        # FIXME: should be retrieved from the formatter...
        # ...and the formatter should be provided to the macro
        file = filespec
        module, id = 'wiki', 'WikiStart'
        path_info = hdf.getValue('HTTP.PathInfo', "").split('/',2)
        if len(path_info) > 1:
            module = path_info[1]
        if len(path_info) > 2:
            id = path_info[2]
        if module not in ['wiki', 'ticket']:
            raise Exception('Cannot reference local attachment from here')

    else:
        raise Exception('No filespec given')

    return module, id, file
コード例 #6
0
ファイル: macro.py プロジェクト: pombredanne/trachacks
    def _parse_filespec(self, filespec, context, env):
        # parse filespec argument to get module and id if contained.
        if filespec[:5] == 'http:' or filespec[:6] == 'https:':
            parts = [ 'url', '', filespec ]
        else:
            parts = filespec.split(':', 2)

        if len(parts) == 3:                 # module:id:attachment
            if parts[0] in ['wiki', 'ticket', 'browser', 'file', 'url']:
                module, id, file = parts
            else:
                raise Exception("unknown module %s" % parts[0])

        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [link for link,_ in
                                 BrowserModule(env).get_link_resolvers()]
            except Exception:
                browser_links = []

            id, file = parts
            if id in browser_links:         # source:path
                module = 'browser'
            elif id and id[0] == '#':       # #ticket:attachment
                module = 'ticket'
                id = id[1:]
            elif id == 'htdocs':            # htdocs:path
                module = 'file'
            else:                           # WikiPage:attachment
                module = 'wiki'

        elif len(parts) == 1:               # attachment
            # determine current object
            module = context.resource.realm or 'wiki'
            id     = context.resource.id
            file   = filespec
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
            if not id:
                raise Exception('unknown context id')

        else:
            raise Exception('No filespec given')

        return module, id, file
コード例 #7
0
    def render_macro(self, req, 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]
        size_re = re.compile('[0-9]+%?$')
        attr_re = re.compile('(align|border|width|height|alt'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        nolink = False
        for arg in args[1:]:
            arg = arg.strip()
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
                continue
            if arg == 'nolink':
                nolink = True
                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 module and id if contained.
        parts = filespec.split(':')
        url = None
        if len(parts) == 3:  # module:id:attachment
            if parts[0] in ['wiki', 'ticket']:
                module, id, file = parts
            else:
                raise Exception("%s module can't have attachments" % parts[0])
        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [
                    link for link, _ in BrowserModule(
                        self.env).get_link_resolvers()
                ]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:  # source:path
                module, file = parts
                rev = None
                if '@' in file:
                    file, rev = file.split('@')
                url = req.href.browser(file, rev=rev)
                raw_url = req.href.browser(file, rev=rev, format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                id, file = parts
                if id and id[0] == '#':
                    module = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = req.href.chrome('site', file)
                    desc = os.path.basename(file)
                elif id in ('http', 'https', 'ftp'):  # external URLs
                    raw_url = url = desc = id + ':' + file
                else:
                    module = 'wiki'
        elif len(parts) == 1:  # attachment
            # determine current object
            # FIXME: should be retrieved from the formatter...
            # ...and the formatter should be provided to the macro
            file = filespec
            module, id = 'wiki', 'WikiStart'
            path_info = req.path_info.split('/', 2)
            if len(path_info) > 1:
                module = path_info[1]
            if len(path_info) > 2:
                id = path_info[2]
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
        else:
            raise Exception('No filespec given')
        if not url:  # this is an attachment
            from trac.attachment import Attachment
            attachment = Attachment(self.env, module, id, file)
            url = attachment.href(req)
            raw_url = attachment.href(req, format='raw')
            desc = attachment.description
        for key in ['title', 'alt']:
            if desc and not attr.has_key(key):
                attr[key] = desc
        if style:
            attr['style'] = '; '.join(
                ['%s:%s' % (k, escape(v)) for k, v in style.iteritems()])
        result = Markup(html.IMG(src=raw_url, **attr)).sanitize()
        if not nolink:
            result = html.A(result, href=url, style='padding:0; border:none')
        return result
コード例 #8
0
ファイル: macros.py プロジェクト: omunroe-com/tracdebdev
    def render_macro(self, req, 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]
        size_re = re.compile('^[0-9]+%?$')
        align_re = re.compile('^(?:left|right|top|bottom)$')
        keyval_re = re.compile('^([-a-z0-9]+)([=:])(.*)')
        quoted_re = re.compile("^(?:"|')(.*)(?:"|')$")
        attr = {}
        style = {}
        nolink = False
        for arg in args[1:]:
            arg = arg.strip()
            if size_re.search(arg):
                # 'width' keyword
                attr['width'] = arg
                continue
            if align_re.search(arg):
                # 'align' keyword
                attr['align'] = arg
                continue
            if arg == 'nolink':
                nolink = True
                continue
            match = keyval_re.search(arg)
            if match:
                key = match.group(1)
                sep = match.group(2)
                val = match.group(3)
                m = quoted_re.search(val)  # unquote " character "
                if m:
                    val = m.group(1)
                if sep == '=':
                    attr[key] = val
                elif sep == ':':
                    style[key] = val

        # parse filespec argument to get module and id if contained.
        parts = filespec.split(':')
        url = None
        if len(parts) == 3:  # module:id:attachment
            if parts[0] in ['wiki', 'ticket']:
                module, id, file = parts
            else:
                raise Exception("%s module can't have attachments" % parts[0])
        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [
                    link for link, _ in BrowserModule(
                        self.env).get_link_resolvers()
                ]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:  # source:path
                module, file = parts
                url = self.env.href.browser(file)
                raw_url = self.env.href.browser(file, format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                id, file = parts
                if id and id[0] == '#':
                    module = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = self.env.href.chrome('site', file)
                    desc = os.path.basename(file)
                else:
                    module = 'wiki'
        elif len(parts) == 1:  # attachment
            # determine current object
            # FIXME: should be retrieved from the formatter...
            # ...and the formatter should be provided to the macro
            file = filespec
            module, id = 'wiki', 'WikiStart'
            path_info = req.path_info.split('/', 2)
            if len(path_info) > 1:
                module = path_info[1]
            if len(path_info) > 2:
                id = path_info[2]
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
        else:
            raise Exception('No filespec given')
        if not url:  # this is an attachment
            from trac.attachment import Attachment
            attachment = Attachment(self.env, module, id, file)
            url = attachment.href()
            raw_url = attachment.href(format='raw')
            desc = attachment.description
        for key in ['title', 'alt']:
            if desc and not attr.has_key(key):
                attr[key] = desc
        a_style = 'padding:0; border:none'  # style of anchor
        img_attr = ' '.join(['%s="%s"' % x for x in attr.iteritems()])
        img_style = '; '.join(['%s:%s' % x for x in style.iteritems()])
        result = '<img src="%s" %s style="%s" />' \
                 % (raw_url, img_attr, img_style)
        if not nolink:
            result = '<a href="%s" style="%s">%s</a>' % (url, a_style, result)
        return result
コード例 #9
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
コード例 #10
0
ファイル: p4trac.py プロジェクト: nyuhuhuu/trachacks
 def _render_directory(self, req, repos, node, rev=None):
     BrowserModule._render_directory(self, req, repos, node, rev)
コード例 #11
0
ファイル: p4trac.py プロジェクト: nyuhuhuu/trachacks
 def _render_file(self, req, repos, node, rev=None):
     BrowserModule._render_file(self, req, repos, node, rev)
コード例 #12
0
 def _render_directory(self, req, repos, node, rev=None):
     BrowserModule._render_directory(self, req, repos, node, rev)
コード例 #13
0
ファイル: p4trac.py プロジェクト: nyuhuhuu/trachacks
 def process_request(self, req):
     return BrowserModule.process_request(self, req)
コード例 #14
0
    def render_macro(self, req, 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]
        size_re = re.compile('[0-9]+%?$')
        attr_re = re.compile('(align|border|width|height|alt'
                             '|title|longdesc|class|id|usemap)=(.+)')
        quoted_re = re.compile("(?:[\"'])(.*)(?:[\"'])$")
        attr = {}
        style = {}
        nolink = False
        for arg in args[1:]:
            arg = arg.strip()
            if size_re.match(arg):
                # 'width' keyword
                attr['width'] = arg
                continue
            if arg == 'nolink':
                nolink = True
                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 module and id if contained.
        parts = filespec.split(':')
        url = None
        if len(parts) == 3:                 # module:id:attachment
            if parts[0] in ['wiki', 'ticket']:
                module, id, file = parts
            else:
                raise Exception("%s module can't have attachments" % parts[0])
        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [link for link,_ in 
                                 BrowserModule(self.env).get_link_resolvers()]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:   # source:path
                module, file = parts
                rev = None
                if '@' in file:
                    file, rev = file.split('@')
                url = req.href.browser(file, rev=rev)
                raw_url = req.href.browser(file, rev=rev, format='raw')
                desc = filespec
            else: # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                id, file = parts
                if id and id[0] == '#':
                    module = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = req.href.chrome('site', file)
                    desc = os.path.basename(file)
                elif id in ('http', 'https', 'ftp'): # external URLs
                    raw_url = url = desc = id+':'+file
                else:
                    module = 'wiki'
        elif len(parts) == 1:               # attachment
            # determine current object
            # FIXME: should be retrieved from the formatter...
            # ...and the formatter should be provided to the macro
            file = filespec
            module, id = 'wiki', 'WikiStart'
            path_info = req.path_info.split('/',2)
            if len(path_info) > 1:
                module = path_info[1]
            if len(path_info) > 2:
                id = path_info[2]
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
        else:
            raise Exception('No filespec given')
        if not url: # this is an attachment
            from trac.attachment import Attachment
            attachment = Attachment(self.env, module, id, file)
            url = attachment.href(req)

            dia_url = attachment.href(req, format='raw')
	    dia_path = attachment.path
	    dia_filename = attachment.filename
            img_url = dia_url.replace(".dia",".png")
	    img_path = dia_path.replace('.dia','.png')
	    img_filename = dia_filename.replace('.dia','.png')

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

            try:
              img_mtime = os.path.getmtime(img_path)
            except Exception:
              img_mtime = 0
                
            self.env.log.info('Comparing dia and png file modification times : %s, %s',dia_mtime,img_mtime)

            # if diagram is newer than image, then regenerate image
            if (dia_mtime > img_mtime):
              try:
		# TODO: read this comment and adjust the command line to taste
		# You should probably use the correct path
		# The options are correct for the 0.96.1, but you may bee to adjust them
                diacmd = 'dia -l --filter=png --export='+img_path+' '+dia_path
                self.env.log.info('Running Dia : %s',diacmd)
	        f = popen2.Popen4(diacmd)
                lines = []
                while (f.poll() == -1):
                  lines += f.fromchild.readlines()
                  f.wait()	
	        #ecode = os.spawnl(os.P_WAIT,'/usr/bin/dia','/usr/bin/dia','-l','--export-to-format=png', '--export='+img_path, dia_path)
                self.env.log.info('Exiting Dia')
              except Exception, e:
                self.env.log.info('Dia failed with exception= %s',e)
                raise Exception('Dia execution failed.')
            try:
	      attachment._fetch(img_filename)
	    except Exception:
              db = self.env.get_db_cnx()
              handle_ta = True
              attachment.size = 0
              attachment.time = 0
              cursor = db.cursor()
              cursor.execute("INSERT INTO attachment "
                             "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                             (attachment.parent_type, attachment.parent_id, img_filename,
                              attachment.size, attachment.time, 'PNG render of a DIA file', attachment.author,
                              attachment.ipnr))
              attachment.filename = img_filename

              self.env.log.info('New attachment: %s', img_filename)

              if handle_ta:
                  db.commit()

            desc = 'JPG render of a DIA file.'
コード例 #15
0
ファイル: macros.py プロジェクト: wiraqutra/photrackjp
    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))
コード例 #16
0
 def process_request(self, req):
     return BrowserModule.process_request(self, req)
コード例 #17
0
 def _render_file(self, req, repos, node, rev=None):
     BrowserModule._render_file(self, req, repos, node, rev)
コード例 #18
0
ファイル: flashview.py プロジェクト: pombredanne/trachacks
    def render_macro(self, req, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            return ''
        args = content.split(',')
        filespec = args[0]

        # parse filespec argument to get module and id if contained.
        parts = filespec.split(':')
        url = None
        if len(parts) == 3:  # module:id:attachment
            if parts[0] in ['wiki', 'ticket']:
                module, id, file = parts
            else:
                raise Exception("%s module can't have attachments" % parts[0])
        elif len(parts) == 2:
            from trac.versioncontrol.web_ui import BrowserModule
            try:
                browser_links = [
                    link for link, _ in BrowserModule(
                        self.env).get_link_resolvers()
                ]
            except Exception:
                browser_links = []
            if parts[0] in browser_links:  # source:path
                module, file = parts
                rev = None
                if '@' in file:
                    file, rev = file.split('@')
                url = req.href.browser(file, rev=rev)
                raw_url = req.href.browser(file, rev=rev, format='raw')
                desc = filespec
            else:  # #ticket:attachment or WikiPage:attachment
                # FIXME: do something generic about shorthand forms...
                id, file = parts
                if id and id[0] == '#':
                    module = 'ticket'
                    id = id[1:]
                elif id == 'htdocs':
                    raw_url = url = req.href.chrome('site', file)
                    desc = os.path.basename(file)
                elif id in ('http', 'https', 'ftp'):  # external URLs
                    raw_url = url = desc = id + ':' + file
                else:
                    module = 'wiki'
        elif len(parts) == 1:  # attachment
            # determine current object
            # FIXME: should be retrieved from the formatter...
            # ...and the formatter should be provided to the macro
            file = filespec
            module, id = 'wiki', 'WikiStart'
            path_info = req.path_info.split('/', 2)
            if len(path_info) > 1:
                module = path_info[1]
            if len(path_info) > 2:
                id = path_info[2]
            if module not in ['wiki', 'ticket']:
                raise Exception('Cannot reference local attachment from here')
        else:
            raise Exception('No filespec given')
        if not url:  # this is an attachment
            from trac.attachment import Attachment
            attachment = Attachment(self.env, module, id, file)
            url = attachment.href(req)
            raw_url = attachment.href(req, format='raw')
            desc = attachment.description
            width, height = swfsize(attachment.open())
            if len(args) == 3:
                if args[1][0] == '*':
                    width = int(width * float(args[1][1:]))
                else:
                    width = args[1]
                if args[2][0] == '*':
                    height = int(height * float(args[2][1:]))
                else:
                    height = args[2]
            elif len(args) != 1:
                raise Exception('Too few arguments. (filespec, width, height)')
        else:
            if len(args) < 3:
                raise Exception('Too few arguments. (filespec, width, height)')
            else:
                width = args[1]
                height = args[2]

        vars = {'width': width, 'height': height, 'raw_url': raw_url}

        return """
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
        width="%(width)s" height="%(height)s">
  <param name="movie" value="%(raw_url)s">
  <param name="quality" value="low">
  <param name="play" value="true">
  <embed src="%(raw_url)s" quality="low" width="%(width)s" height="%(height)s"
         type="application/x-shockwave-flash"
         pluginspage="http://www.macromedia.com/go/getflashplayer">
  </embed>
</object>
        """ % dict(map(lambda i: (i[0], escapeHTML(str(i[1]))), vars.items()))
コード例 #19
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
コード例 #20
0
ファイル: pdfimg.py プロジェクト: pombredanne/trachacks
    def parse_trac(self,filespec):
        """
         Parse arguments like in the ImageMacro (trac/wiki/macros.py)
        """
        parts = filespec.split(':')
      
        url = raw_url =  None
        attachment = None  
        if len(parts) == 3:  # realm:id:attachment-filename
            realm, id, filename = parts
            attachment = Resource(realm, id).child('attachment', filename)
        elif len(parts) == 2:
            # TODO howto Access the Subversion / Browser ...
            # 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 = []
                # TODO what to do with browserlinks...
            if parts[0] in browser_links:   # source:path
                ##  ['repos', 'export', 'source', 'browser']
                # TODO: use context here as well
                realm, filename = parts
                rev = None
                if '@' in filename:
                    filename, rev = filename.split('@')
                url = self.formatter.href.browser(filename, rev=rev)
                raw_url = self.formatter.href.browser(filename, rev=rev, format='raw')
                
                from trac.versioncontrol.web_ui import get_existing_node
                from trac.versioncontrol import RepositoryManager
                
                if hasattr(RepositoryManager, 'get_repository_by_path'): # Trac 0.12
                    repo = RepositoryManager(self.env).get_repository_by_path(file)[1:3]
                else:
                    repo = RepositoryManager(self.env).get_repository(self.formatter.req.authname)
                obj = get_existing_node(self.formatter.req, repo, filename, rev)
                svn_core_stream=obj.get_content()
                
                # write file to filesystem (needed for convert
                imgname="%s/%s" %(self.images_folder,self.filenamehash)
                f = open( imgname , 'w+')
                f.write( svn_core_stream.read() )
                f.close()
                
                # set standard properties
                # SVN is always cache because it may change...
                self.cache = False
                self.pdfinput = imgname
                self.url=url
                self.rawurl=raw_url
                self.wikilink=filespec 
                return
                    #            else: # #ticket:attachment or WikiPage:attachment
            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:]
                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 = self.formatter.resource.child('attachment', filespec)
        else:
            raise TracError('No filespec given')
        if attachment and 'ATTACHMENT_VIEW' in self.formatter.perm(attachment):
            url = get_resource_url(self.env, attachment, self.formatter.href)
            raw_url = get_resource_url(self.env, attachment, self.formatter.href,
                                       format='raw')
        
        self.wikilink=filespec
        self.url=url
        self.rawurl=raw_url

        self.pdfinput=( Attachment(self.env,attachment) ).path
        self.env.log.debug("PdfImg..trac-Attachment  %r ***", self.pdfinput )