Exemplo n.º 1
0
    def get_project_events(self, project, days, minutes):
        """ List all events in project that happened in a given time span.
        """
        events = []
        project_href = Href(conf.url_projects_path + "/" + project.env_name)

        req = DummyReq('user', 'password', 'method', 'uri', 'args')
        req.permissions = (
        'TICKET_VIEW', 'CHANGESET_VIEW', 'WIKI_VIEW', 'ATTACHMENT_VIEW', 'DISCUSSION_VIEW', 'MILESTONE_VIEW')
        req.authname = 'authname'
        req.abs_href = project_href

        project_env = open_environment(conf.getEnvironmentSysPath(project.env_name), use_cache=True)
        event_provider = ProjectTimelineEvents(project_env)
        last_events = event_provider.get_timeline_events(req,
            time_in_days=days,
            time_in_minutes=minutes)

        for event in last_events:
            context = Context(resource=Resource(), href=project_href)
            context.req = req
            context.perm = req.perm
            events.append([project, event, context])

        events.sort(lambda x, y: cmp(y[1]['date'], x[1]['date']))
        return events
Exemplo n.º 2
0
    def convert_content(self, req, input_type, text, output_type):
        page_name = req.args.get('page', 'WikiStart')
        wikipage = WikiPage(self.env, page_name)

        wikiprint = WikiPrint(self.env)

        page = wikiprint.wikipage_to_html(text, page_name, req)

        #Get page title from first header in outline
        out = StringIO.StringIO()
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req

        outline = OutlineFormatter(self.env, context)
        outline.format(text, out, 1, 1)

        title = wikipage.name
        for depth, anchor, text in outline.outline:
            if depth == 1:
                title = text
                break

        out = wikiprint.html_to_pdf(req, [page],
                                    book=(output_type == 'pdfbook'),
                                    title=title,
                                    subject="%s - %s" %
                                    (self.env.project_name, page_name),
                                    version=str(wikipage.version),
                                    date=format_datetime(to_datetime(None)))
        return (out, 'application/pdf')
Exemplo n.º 3
0
 def _wiki_to_html(self, req, resource, wikitext):
     context = Context(resource, href=req.href, perm=req.perm)
     # HtmlFormatter relies on the .req even though that's not always present
     # in a Context. Seems like a known dark spot in Trac's API. Check
     # comments in trac.mimeview.api.Context.__call__()
     context.req = req
     return HtmlFormatter(self.env, context, wikitext).generate()
Exemplo n.º 4
0
    def wikipage_to_html(self, text, page_name, req):
        """
        Converts a wiki text to HTML, and makes some replacements in order to fix
        internal and external links and references
        """

        self.env.log.debug('WikiPrint => Start function wikipage_to_html')

        #Remove exclude expressions
        for r in EXCLUDE_RES:
            text = r.sub('', text)

        #Escape [[PageOutline]], to avoid wiki processing
        for r in [
                re.compile(r'\[\[TOC(\(.*\))?\]\]'),
                re.compile(r'\[\[PageOutline(\(.*\))?\]\]')
        ]:
            text = r.sub('![[pdf-toc]]', text)

        for macro in self.omit_macros:
            r = re.compile(r'\[\[' + macro + r'\(.*?\]\]')
            text = r.sub('', text)
            r = re.compile(
                r'^\{\{\{\r?\n#!' + macro + r'\r?\n(^.*\r?\n)*?^\}\}\}',
                re.MULTILINE)
            text = r.sub('', text)

        link_format = req.args.get('link_format', None)

        if self.omit_links:
            r1 = re.compile(r'\[wiki:(.*?) (.*?)\]')
            text = r1.sub('[\g<2>]', text)
            r2 = re.compile(r'\[wiki:(.*?)\]')
            text = r2.sub('[\g<1>]', text)
        elif link_format:
            #Keep links to the same export format
            r = re.compile(r'(?<=\[wiki:)(.*?)(?=(?: .*?)?\])')
            text = r.sub(
                '\g<1>?format=%s&link_format=%s' % (link_format, link_format),
                text)

        if self.rebase_links:
            r = re.compile(r'\[wiki:(.*?)\]')
            text = r.sub('[%s/wiki/\g<1>]' % self.rebase_links, text)

        self.env.log.debug('WikiPrint => Wiki input for WikiPrint: %r' % text)

        #First create a Context object from the wiki page
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req

        #Now convert in that context
        page = format_to_html(self.env, context, text)
        self.env.log.debug('WikiPrint => Wiki to HTML output: %r' % page)

        self.env.log.debug('WikiPrint => HTML output for WikiPrint is: %r' %
                           page)
        self.env.log.debug('WikiPrint => Finish function wikipage_to_html')

        return page
Exemplo n.º 5
0
    def convert_content(self, req, input_type, text, output_type):
        page_name = req.args.get('page', 'WikiStart')
        wikipage = WikiPage(self.env, page_name)
        
        wikiprint = WikiPrint(self.env)
        
        page = wikiprint.wikipage_to_html(text, page_name, req)
        
        #Get page title from first header in outline
        out = StringIO.StringIO()
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req

        outline = OutlineFormatter(self.env, context)
        outline.format(text, out, 1, 1)
        
        title = wikipage.name
        for depth, anchor, text in outline.outline:
            if depth == 1:
                title = text
                break
        
        out = wikiprint.html_to_pdf(req, [page], book = (output_type == 'pdfbook'),
            title=title,
            subject="%s - %s" % (self.env.project_name, page_name),
            version=str(wikipage.version),
            date=format_datetime(to_datetime(None)))
        return (out, 'application/pdf')
Exemplo n.º 6
0
    def get_project_events(self, project, days, minutes):
        """ List all events in project that happened in a given time span.
        """
        events = []
        project_href = Href(conf.url_projects_path + "/" + project.env_name)

        req = DummyReq('user', 'password', 'method', 'uri', 'args')
        req.permissions = ('TICKET_VIEW', 'CHANGESET_VIEW', 'WIKI_VIEW',
                           'ATTACHMENT_VIEW', 'DISCUSSION_VIEW',
                           'MILESTONE_VIEW')
        req.authname = 'authname'
        req.abs_href = project_href

        project_env = open_environment(conf.getEnvironmentSysPath(
            project.env_name),
                                       use_cache=True)
        event_provider = ProjectTimelineEvents(project_env)
        last_events = event_provider.get_timeline_events(
            req, time_in_days=days, time_in_minutes=minutes)

        for event in last_events:
            context = Context(resource=Resource(), href=project_href)
            context.req = req
            context.perm = req.perm
            events.append([project, event, context])

        events.sort(lambda x, y: cmp(y[1]['date'], x[1]['date']))
        return events
Exemplo n.º 7
0
def email_default_context():
    class NoEmailViewPerm(MockPerm):
        def has_permission(self, action, realm_or_resource=None, id=False, version=False):
            return action != "EMAIL_VIEW"

        __contains__ = has_permission

    context = Context(Resource("wiki", "WikiStart"), href=Href("/"), perm=NoEmailViewPerm())
    context.req = None  # 0.12 FIXME .req shouldn't be required by formatter
    return context
Exemplo n.º 8
0
    def wikipage_to_html(self, text, page_name, req):
        """
        Converts a wiki text to HTML, and makes some replacements in order to fix
        internal and external links and references
        """

        self.env.log.debug('WikiPrint => Start function wikipage_to_html')

        #Remove exclude expressions
        for r in EXCLUDE_RES:
            text = r.sub('', text)
        
        #Escape [[PageOutline]], to avoid wiki processing
        for r in [re.compile(r'\[\[TOC(\(.*\))?\]\]'), re.compile(r'\[\[PageOutline(\(.*\))?\]\]')]:
            text = r.sub('![[pdf-toc]]', text)
            
        for macro in self.omit_macros:
            r = re.compile(r'\[\[' + macro + r'\(.*?\]\]')
            text = r.sub('', text)
            r = re.compile(r'^\{\{\{\r?\n#!' + macro + r'\r?\n(^.*\r?\n)*?^\}\}\}', re.MULTILINE)
            text = r.sub('', text)

        link_format = req.args.get('link_format', None)
            
        if self.omit_links:
            r1 = re.compile(r'\[wiki:(.*?) (.*?)\]')
            text = r1.sub('[\g<2>]', text)            
            r2 = re.compile(r'\[wiki:(.*?)\]')
            text = r2.sub('[\g<1>]', text)            
        elif link_format:
            #Keep links to the same export format
            r = re.compile(r'(?<=\[wiki:)(.*?)(?=(?: .*?)?\])')
            text = r.sub('\g<1>?format=%s&link_format=%s' % (link_format, link_format), text)
            
        if self.rebase_links:
            r = re.compile(r'\[wiki:(.*?)\]')
            text = r.sub('[%s/wiki/\g<1>]' % self.rebase_links, text)

        self.env.log.debug('WikiPrint => Wiki input for WikiPrint: %r' % text)
        
        #First create a Context object from the wiki page
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req
        
        #Now convert in that context
        page = format_to_html(self.env, context, text)
        self.env.log.debug('WikiPrint => Wiki to HTML output: %r' % page)
        
        self.env.log.debug('WikiPrint => HTML output for WikiPrint is: %r' % page)
        self.env.log.debug('WikiPrint => Finish function wikipage_to_html')

        return page
Exemplo n.º 9
0
def email_default_context():
    class NoEmailViewPerm(MockPerm):
        def has_permission(self,
                           action,
                           realm_or_resource=None,
                           id=False,
                           version=False):
            return action != 'EMAIL_VIEW'

        __contains__ = has_permission

    context = Context(Resource('wiki', 'WikiStart'),
                      href=Href('/'),
                      perm=NoEmailViewPerm())
    context.req = None  # 0.12 FIXME .req shouldn't be required by formatter
    return context
Exemplo n.º 10
0
    def refresh_project(self, project_identifier, from_date, to_date=datetime.now(datefmt.localtz),
                        afilters=None, update=False):
        """
        Will refresh a project events in cache in given date range.

        .. NOTE::

            Dates needs to be given in datefmt.localtz form

        """
        # Initialize objects
        project = Project.get(env_name=project_identifier)
        if not project:
            conf.log.warning('Project {0} is already removed from system or it cannot be found'.format(project_identifier))
            return

        e = open_environment(conf.getEnvironmentSysPath(project.env_name), use_cache=True)
        pte = ProjectTimelineEvents(e)
        providers = pte.event_providers

        project_href = Href(conf.url_projects_path + '/' + project.env_name)

        context = Context(resource=Resource(), href=project_href)
        req = self._create_dummy_req(project_identifier)
        context.req = req
        context.perm = req.perm

        # Read events from timeline
        events = []
        for provider in providers:
            try:
                # Use filters in parameter or check filters from providers
                if afilters:
                    filters = afilters
                else:
                    available_filters = provider.get_timeline_filters(req) or []
                    filters = [f[0] for f in available_filters]

                for event in provider.get_timeline_events(req, from_date, to_date, filters):
                    event_data = self._event_data(provider, event)
                    if event_data['author'] != 'trac': # Skip system events
                        events.append(CachedEvent.from_event_data(project, event_data, context, filters[0]))
            except:
                conf.log.error("Could not read timeline events for %s from %s" % (project_identifier, str(provider)))

        # Write events into sql table
        self._write_events_into_cache(events, update)
Exemplo n.º 11
0
    def expand_macro(self, formatter, name, text, args=None):

        assert text.isdigit(), "Argument must be a number"

        out = "<dl class='lastevents'>"
        add_stylesheet(formatter.req, 'tracprojectmanager/css/lastevents.css')

        all_events = []
        if hasattr(self.env, 'cached_lastevents'):
            expiration = self.env.cached_lastevents[1] + timedelta(
                seconds=EVENT_CACHE_INTERVAL)
            if datetime.now() < expiration:
                all_events = self.env.cached_lastevents[0]

        if not all_events:
            stop = datetime.now(formatter.req.tz)
            start = stop - timedelta(days=EVENT_MAX_DAYS)

            projects = get_project_list(self.env, formatter.req)
            user = formatter.req.authname

            for project, project_path, project_url, env in projects:
                env_timeline = TimelineModule(env)
                for provider in env_timeline.event_providers:
                    filters = [
                        x[0]
                        for x in provider.get_timeline_filters(formatter.req)
                    ]
                    self.env.log.info("Project %s - Filters: %s", project,
                                      filters)
                    try:
                        events = provider.get_timeline_events(
                            formatter.req, start, stop, filters)
                        #self.env.log.info("Event count: %d", len([x for x in events]))

                        for event in events:
                            context = Context(formatter.resource,
                                              Href(project_url),
                                              formatter.req.perm)
                            context.req = formatter.req
                            #context = Context.from_request(formatter.req)

                            if len(event) == 6:  # 0.10 events
                                kind, url, title, date, author, desc = event
                            else:  # 0.11 events
                                if len(event) == 5:  # with special provider
                                    kind, date, author, data, provider = event
                                else:
                                    kind, date, author, data = event

                                title = to_unicode(
                                    provider.render_timeline_event(
                                        context, 'title', event))
                                url = provider.render_timeline_event(
                                    context, 'url', event)
                                desc = to_unicode(
                                    provider.render_timeline_event(
                                        context, 'description', event))

                            all_events.append((project, kind, date, title, url,
                                               author, desc))
                    except Exception, ex:
                        #import sys
                        self.env.log.warning("Exception: %s" %
                                             traceback.format_exc())
                        #out = out + "%s<br/>" % traceback.format_exc()

            all_events.sort(cmp=lambda x, y: x[2] < y[2] and 1 or -1)
            self.env.cached_lastevents = [all_events, datetime.now()]
Exemplo n.º 12
0
def trac_wiki(content):
	resource = Resource()
	context = Context(resource)
	context.req = None
	return format_to_html(TRAC_ENV, context, content)