Esempio n. 1
0
    def _dump_docs(self, req):
        self.log.debug("Rendering docs")

        # Dump RPC documentation
        req.perm.require('XML_RPC')  # Need at least XML_RPC
        namespaces = {}
        for method in XMLRPCSystem(self.env).all_methods(req):
            namespace = method.namespace.replace('.', '_')
            if namespace not in namespaces:
                namespaces[namespace] = {
                    'description':
                    wiki_to_oneliner(method.namespace_description,
                                     self.env,
                                     req=req),
                    'methods': [],
                    'namespace':
                    method.namespace,
                }
            try:
                namespaces[namespace]['methods'].append(
                    (method.signature,
                     wiki_to_oneliner(method.description, self.env,
                                      req=req), method.permission))
            except Exception, e:
                from tracrpc.util import StringIO
                import traceback
                out = StringIO()
                traceback.print_exc(file=out)
                raise Exception('%s: %s\n%s' %
                                (method.name, str(e), out.getvalue()))
Esempio n. 2
0
    def _dump_docs(self, req):
        self.log.debug("Rendering docs")

        # Dump RPC documentation
        req.perm.require('XML_RPC') # Need at least XML_RPC
        namespaces = {}
        for method in XMLRPCSystem(self.env).all_methods(req):
            namespace = method.namespace.replace('.', '_')
            if namespace not in namespaces:
                namespaces[namespace] = {
                    'description' : wiki_to_oneliner(
                                    method.namespace_description,
                                    self.env, req=req),
                    'methods' : [],
                    'namespace' : method.namespace,
                    }
            try:
                namespaces[namespace]['methods'].append(
                        (method.signature,
                        wiki_to_oneliner(
                            method.description, self.env, req=req),
                        method.permission))
            except Exception, e:
                from tracrpc.util import StringIO
                import traceback
                out = StringIO()
                traceback.print_exc(file=out)
                raise Exception('%s: %s\n%s' % (method.name,
                                                str(e), out.getvalue()))
Esempio n. 3
0
    def process_request(self, req):
        # Need at least XML_RPC
        req.perm.assert_permission('XML_RPC')

        # Dump RPC functions
        content_type = req.get_header('Content-Type')
        if content_type is None or 'text/xml' not in content_type:
            namespaces = {}
            for method in XMLRPCSystem(self.env).all_methods(req):
                namespace = method.namespace.replace('.', '_')
                if namespace not in namespaces:
                    namespaces[namespace] = {
                        'description':
                        wiki_to_oneliner(method.namespace_description,
                                         self.env),
                        'methods': [],
                        'namespace':
                        method.namespace,
                    }
                try:
                    namespaces[namespace]['methods'].append(
                        (method.signature,
                         wiki_to_oneliner(method.description,
                                          self.env), method.permission))
                except Exception, e:
                    from StringIO import StringIO
                    import traceback
                    out = StringIO()
                    traceback.print_exc(file=out)
                    raise Exception('%s: %s\n%s' %
                                    (method.name, str(e), out.getvalue()))
            add_stylesheet(req, 'common/css/wiki.css')
            req.hdf['xmlrpc.functions'] = namespaces
            return 'xmlrpclist.cs', None
Esempio n. 4
0
    def process_request(self, req):
        # Need at least XML_RPC
        req.perm.assert_permission('XML_RPC')

        # Dump RPC functions
        content_type = req.get_header('Content-Type')
        if content_type is None or 'text/xml' not in content_type:
            namespaces = {}
            for method in XMLRPCSystem(self.env).all_methods(req):
                namespace = method.namespace.replace('.', '_')
                if namespace not in namespaces:
                    namespaces[namespace] = {
                        'description' : wiki_to_oneliner(method.namespace_description, self.env),
                        'methods' : [],
                        'namespace' : method.namespace,
                        }
                try:
                    namespaces[namespace]['methods'].append((method.signature, wiki_to_oneliner(method.description, self.env), method.permission))
                except Exception, e:
                    from StringIO import StringIO
                    import traceback
                    out = StringIO()
                    traceback.print_exc(file=out)
                    raise Exception('%s: %s\n%s' % (method.name, str(e), out.getvalue()))
            add_stylesheet(req, 'common/css/wiki.css')
            req.hdf['xmlrpc.functions'] = namespaces
            return 'xmlrpclist.cs', None
Esempio n. 5
0
 def __fmt_changeset(self, rev, req):
     # use format_to_oneliner and drop num_args hack when we drop Trac 0.10
     # support
     import inspect
     num_args = len(inspect.getargspec(wiki_to_oneliner)[0])
     if num_args > 5:
         return wiki_to_oneliner('[%s]' % rev, self.env, req=req)
     else:
         return wiki_to_oneliner('[%s]' % rev, self.env)
Esempio n. 6
0
 def __fmt_changeset(self, rev, req):
     # use format_to_oneliner and drop num_args hack when we drop Trac 0.10
     # support
     import inspect
     num_args = len(inspect.getargspec(wiki_to_oneliner)[0])
     if num_args > 5:
         return wiki_to_oneliner('[%s]' % rev, self.env, req=req)
     else:
         return wiki_to_oneliner('[%s]' % rev, self.env)
Esempio n. 7
0
def execute(hdf, txt, env):
    if not txt:
        txt = ''
    items = []
    msgs = []
    title = ""
    args_re = re.compile("^(?:" + string.join(args_pat, "|") + ")$")
    for arg in [string.strip(s) for s in txt.split(',')]:
        match = args_re.match(arg)
        if not match:
            env.log.debug('Tk: unknown arg: %s' % arg)
            continue
        elif match.group('tktnum'):
            items.append(int(match.group('tktnum')))
            db = env.get_db_cnx()
            curs = db.cursor()
            try:
                curs.execute('SELECT summary FROM ticket WHERE id=%s' %
                             match.group('tktnum'))
                row = curs.fetchone()
                if row:
                    summary = row[0]
                    msgs.append("#%d : %s" %
                                (int(match.group('tktnum')), summary))

            finally:
                if not hasattr(env, 'get_cnx_pool'):
                    # without db connection pool, we should close db.
                    curs.close()
                    db.close()

    html = ''
    try:
        # for trac 0.9 or later
        from trac.wiki.formatter import wiki_to_oneliner
        for b in msgs:
            html += wiki_to_oneliner(string.join(["%s" % b]), env,
                                     env.get_db_cnx())
            html += '<br>'
    except:
        # for trac 0.8.x
        from trac.WikiFormatter import wiki_to_oneliner
        html = wiki_to_oneliner(string.join(["#%d" % c for c in items], ", "),
                                hdf, env, env.get_db_cnx())
    if html != '':
        try:
            title = title % len(items)  # process %d in title
        except:
            pass
        style = string.join(
            ["%s:%s" % (k, v) for k, v in styles.items() if v <> ""], "; ")
        return '%s' % (html)
    else:
        return ''
Esempio n. 8
0
def execute(hdf, txt, env):
    if not txt:
        txt = ''
    items = []
    msgs = []
    title = ""
    args_re = re.compile("^(?:" + string.join(args_pat, "|") + ")$")
    for arg in [string.strip(s) for s in txt.split(',')]:
        match = args_re.match(arg)
        if not match:
            env.log.debug('Tk: unknown arg: %s' % arg)
            continue
        elif match.group('tktnum'):
            items.append(int(match.group('tktnum')))
            db = env.get_db_cnx()
            curs = db.cursor()
            try:
                curs.execute('SELECT summary FROM ticket WHERE id=%s' % match.group('tktnum'))
                row = curs.fetchone()
                if row:
                    summary = row[0]
                    msgs.append("#%d : %s" % (int(match.group('tktnum')), summary))

            finally:
                if not hasattr(env, 'get_cnx_pool'):
                    # without db connection pool, we should close db.
                    curs.close()
                    db.close()
        
    html = ''
    try:
        # for trac 0.9 or later
        from trac.wiki.formatter import wiki_to_oneliner
        for b in msgs :
            html += wiki_to_oneliner(string.join(["%s" % b ]), env, env.get_db_cnx())
            html += '<br>'
    except:
        # for trac 0.8.x
        from trac.WikiFormatter import wiki_to_oneliner
        html = wiki_to_oneliner(string.join(["#%d" % c for c in items], ", "),
                                hdf, env, env.get_db_cnx())
    if html != '':
        try:
            title = title % len(items)  # process %d in title
        except:
            pass
        style = string.join(["%s:%s" % (k,v) for k,v in styles.items() if v <> ""], "; ")
        return '%s' %  (html)
    else:
        return ''
Esempio n. 9
0
 def test_xmlrpc_listMethods(self):
     for method in self.xml_rpc_system.all_methods(self.req):
             namespace = method.namespace.replace('.', '_')
             namespaces = {}
             if namespace not in namespaces:
                 namespaces[namespace] = {
                     'description' : wiki_to_oneliner(method.namespace_description, self.env),
                     'methods' : [],
                     'namespace' : method.namespace,
                     }
             try:
                 namespaces[namespace]['methods'].append((method.signature, wiki_to_oneliner(method.description, self.env), method.permission))
             except Exception, e:
                 self.fail('%s: %s\n' % (method.name, str(e)))
Esempio n. 10
0
    def render_poll(self, req, title, votes):
        from trac.ticket.model import Ticket, Priority
        from trac.ticket.query import Query
        add_stylesheet(req, 'poll/css/poll.css')
        if not req.perm.has_permission('POLL_VIEW') or \
                not req.perm.has_permission('TICKET_VIEW'):
            return ''

        all_votes = []
        ticket_count = 0
        for vote in votes:
            tickets = []
            if vote.startswith('#'):
                try:
                    tickets.append(int(vote.strip('#')))
                except ValueError:
                    raise TracError('Invalid ticket number %s' % vote)
            elif vote.startswith('query:'):
                query = vote[6:]
                tickets = [q['id'] for q in
                           Query.from_string(self.env, query).execute(req)]
            else:
                all_votes.append(('%08x' % abs(hash(vote)), None,
                                 wiki_to_oneliner(vote, self.env)))

            # Make tickets look pretty
            for idx, id in enumerate(tickets):
                try:
                    ticket = Ticket(self.env, id)
                except Exception:
                    continue
                summary = ticket['summary'] + ' (#%i)' % id
                priority = Priority(self.env, ticket['priority']).value
                summary = wiki_to_oneliner(summary, self.env)

                all_votes.append((str(id), "ticket prio%s%s%s" %
                                  (priority, ticket_count % 2 and ' even' or '',
                                  ticket['status'] == 'closed' and ' closed' or ''),
                                  summary))
                ticket_count += 1

        if not all_votes:
            raise TracError('No votes provided')

        poll = Poll(self.base_dir, title, all_votes)
        if req.perm.has_permission('POLL_VOTE'):
            poll.populate(req)
        return poll.render(self.env, req)
Esempio n. 11
0
    def _render_history(self, req, db, page):
        """Extract the complete history for a given page and stores it in the
        HDF.

        This information is used to present a changelog/history for a given
        page.
        """
        req.perm.assert_permission('WIKI_VIEW')

        if not page.exists:
            raise TracError, "Page %s does not exist" % page.name

        self._set_title(req, page, u'历史')

        history = []
        for version, t, author, comment, ipnr in page.get_history():
            history.append({
                'url': req.href.wiki(page.name, version=version),
                'diff_url': req.href.wiki(page.name, version=version,
                                          action='diff'),
                'version': version,
                'time': format_datetime(t),
                'time_delta': pretty_timedelta(t),
                'author': author,
                'comment': wiki_to_oneliner(comment or '', self.env, db),
                'ipaddr': ipnr
            })
        req.hdf['wiki.history'] = history
Esempio n. 12
0
 def name_details(self, name):
     ticket = model.Ticket(self.env, name)
     href = self.env.href.ticket(name)
     from trac.wiki.formatter import wiki_to_oneliner
     summary = ticket['summary'] or u''
     return (href, wiki_to_oneliner('#%s' % name, self.env),
             ticket.exists and summary)
Esempio n. 13
0
    def _render_history(self, req, db, page):
        """Extract the complete history for a given page and stores it in the
        HDF.

        This information is used to present a changelog/history for a given
        page.
        """
        req.perm.assert_permission("WIKI_VIEW")

        if not page.exists:
            raise TracError, "Page %s does not exist" % page.name

        req.hdf["title"] = page.name + " (history)"

        history = []
        for version, t, author, comment, ipnr in page.get_history():
            history.append(
                {
                    "url": self.env.href.wiki(page.name, version=version),
                    "diff_url": self.env.href.wiki(page.name, version=version, action="diff"),
                    "version": version,
                    "time": format_datetime(t),
                    "time_delta": pretty_timedelta(t),
                    "author": author,
                    "comment": wiki_to_oneliner(comment or "", self.env, db),
                    "ipaddr": ipnr,
                }
            )
        req.hdf["wiki.history"] = history
Esempio n. 14
0
    def render_macro(self, req, name, filter):
        from trac.config import Option
        from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner

        filter = filter or ""

        sections = set([section for section, option in Option.registry.keys() if section.startswith(filter)])

        return html.DIV(class_="tracini")(
            [
                (
                    html.H2("[%s]" % section, id="%s-section" % section),
                    html.TABLE(class_="wiki")(
                        html.TBODY(
                            [
                                html.TR(
                                    html.TD(html.TT(option.name)), html.TD(wiki_to_oneliner(option.__doc__, self.env))
                                )
                                for option in Option.registry.values()
                                if option.section == section
                            ]
                        )
                    ),
                )
                for section in sorted(sections)
            ]
        )
Esempio n. 15
0
 def name_details(self, name):
     ticket = model.Ticket(self.env, name)
     href = self.env.href.ticket(name)
     from trac.wiki.formatter import wiki_to_oneliner
     summary = ticket['summary'] or u''
     return (href, wiki_to_oneliner('#%s' % name, self.env), ticket.exists
             and summary)
Esempio n. 16
0
    def _render_history(self, req, db, page):
        """Extract the complete history for a given page and stores it in the
        HDF.

        This information is used to present a changelog/history for a given
        page.
        """
        req.perm.assert_permission('WIKI_VIEW')

        if not page.exists:
            raise TracError, "Page %s does not exist" % page.name

        self._set_title(req, page, u'历史')

        history = []
        for version, t, author, comment, ipnr in page.get_history():
            history.append({
                'url':
                req.href.wiki(page.name, version=version),
                'diff_url':
                req.href.wiki(page.name, version=version, action='diff'),
                'version':
                version,
                'time':
                format_datetime(t),
                'time_delta':
                pretty_timedelta(t),
                'author':
                author,
                'comment':
                wiki_to_oneliner(comment or '', self.env, db),
                'ipaddr':
                ipnr
            })
        req.hdf['wiki.history'] = history
Esempio n. 17
0
    def get_timeline_events(self, req, start, stop, filters):
        # timeline动作的输入
        if 'wiki' in filters:
            wiki = WikiSystem(self.env)
            format = req.args.get('format')
            href = format == 'rss' and req.abs_href or req.href
            db = self.env.get_db_cnx()
            cursor = db.cursor()
            cursor.execute("SELECT time,name,comment,author,version "
                           "FROM wiki WHERE time>=%s AND time<=%s",
                           (start, stop))
            for t,name,comment,author,version in cursor:
                title = Markup('<em>%s</em> '+ u"编辑者 %s",
                               wiki.format_page_name(name), author)
                diff_link = html.A(u'变化', href=href.wiki(name, action='diff',
                                                          version=version))
                if format == 'rss':
                    comment = wiki_to_html(comment or '--', self.env, req, db,
                                           absurls=True)
                else:
                    comment = wiki_to_oneliner(comment, self.env, db,
                                               shorten=True)
                if version > 1:
                    comment = Markup('%s (%s)', comment, diff_link)
                yield 'wiki', href.wiki(name), title, t, author, comment

            # Attachments
            att = AttachmentModule(self.env)
            for event in att.get_timeline_events(req, db, 'wiki', format,
                                                 start, stop,
                                                 lambda id: html.EM(id)):
                yield event
Esempio n. 18
0
    def name_details(self, name):
        from trac.wiki.formatter import wiki_to_oneliner

        return (
            getattr(self.env.href, self.tagspace),
            wiki_to_oneliner('[%s:"%s" %s]' % (self.tagspace, name, name), self.env),
            "",
        )
Esempio n. 19
0
 def _heading_formatter(self, match, fullmatch):
     Formatter._heading_formatter(self, match, fullmatch)
     depth = min(len(fullmatch.group('hdepth')), 5)
     heading = match[depth + 1:len(match) - depth - 1]
     anchor = self._anchors[-1]
     text = wiki_to_oneliner(heading, self.env, self.db, self._absurls)
     text = re.sub(r'</?a(?: .*?)?>', '', text)  # Strip out link tags
     self.outline.append((depth, '<a href="%s#%s">%s</a>' %
                          (self.env.href.wiki(self.__page), anchor, text)))
Esempio n. 20
0
 def _heading_formatter(self, match, fullmatch):
     Formatter._heading_formatter(self, match, fullmatch)
     depth = min(len(fullmatch.group('hdepth')), 5)
     heading = match[depth + 1:len(match) - depth - 1]
     anchor = self._anchors[-1]
     text = wiki_to_oneliner(heading, self.env, self.db, self._absurls)
     text = re.sub(r'</?a(?: .*?)?>', '', text) # Strip out link tags
     self.outline.append((depth, '<a href="%s#%s">%s</a>' %
                         (self.env.href.wiki(self.__page), anchor, text)))
Esempio n. 21
0
 def __project_display(self, req, milestone):
     row = self.__SmpModel.get_project_milestone(milestone)
     
     if row:
         return tag.span(
                         tag.h3(wiki_to_oneliner("Project: %s" % (row[0],), self.env, req=req))
                         )
     else:
         return []
Esempio n. 22
0
    def _render_view(self, req, db, page):
        page_name = self._set_title(req, page, '')
        if page.name == 'WikiStart':
            req.hdf['title'] = ''

        version = req.args.get('version')
        if version:
            # Ask web spiders to not index old versions
            req.hdf['html.norobots'] = 1

        # Add registered converters
        for conversion in Mimeview(
                self.env).get_supported_conversions('text/x-trac-wiki'):
            conversion_href = req.href.wiki(page.name,
                                            version=version,
                                            format=conversion[0])
            add_link(req, 'alternate', conversion_href, conversion[1],
                     conversion[3])

        latest_page = WikiPage(self.env, page.name)
        req.hdf['wiki'] = {
            'exists': page.exists,
            'version': page.version,
            'latest_version': latest_page.version,
            'readonly': page.readonly
        }
        if page.exists:
            req.hdf['wiki'] = {
                'page_html':
                wiki_to_html(page.text, self.env, req),
                'history_href':
                req.href.wiki(page.name, action='history'),
                'last_change_href':
                req.href.wiki(page.name, action='diff', version=page.version)
            }
            if version:
                req.hdf['wiki'] = {
                    'comment_html':
                    wiki_to_oneliner(page.comment or '--', self.env, db),
                    'author':
                    page.author,
                    'age':
                    pretty_timedelta(page.time)
                }
        else:
            if not req.perm.has_permission('WIKI_CREATE'):
                raise HTTPNotFound('Page %s not found', page.name)
            req.hdf['wiki.page_html'] = html.P('Describe "%s" here' %
                                               page_name)

        # Show attachments
        req.hdf['wiki.attachments'] = attachments_to_hdf(
            self.env, req, db, 'wiki', page.name)
        if req.perm.has_permission('WIKI_MODIFY'):
            attach_href = req.href.attachment('wiki', page.name)
            req.hdf['wiki.attach_href'] = attach_href
Esempio n. 23
0
 def expand_wiki_links(self, match):
     wiki_url = match.groups()[0]                     # TracLink ([1], source:file/, ...)
     html_url = wiki_to_oneliner(wiki_url, self.env)  # <a href="http://someurl">...</a>
     href     = re.search('href="(.*?)"', html_url)   # http://someurl
     url      = href and href.groups()[0] or html_url
     if self.out_format == 'svg':
         format = 'URL="javascript:window.parent.location.href=\'%s\'"'
     else:
         format = 'URL="%s"'
     return format % url
Esempio n. 24
0
 def get_task_markup(self, req, ticket, task):
     if not task:
         return ''
     
     ticket_text = 'ticket #' + str(task['ticket'])
     if task['ticket'] == ticket:
         ticket_text = 'this ticket'
     timedelta = pretty_timedelta(datetime.fromtimestamp(task['starttime']), None);
     
     return '<li>%s</li>' % wiki_to_oneliner('You have been working on %s for %s' % (ticket_text, timedelta), self.env, req=req)
Esempio n. 25
0
 def test_xmlrpc_listMethods(self):
     for method in self.xml_rpc_system.all_methods(self.req):
         namespace = method.namespace.replace('.', '_')
         namespaces = {}
         if namespace not in namespaces:
             namespaces[namespace] = {
                 'description':
                 wiki_to_oneliner(method.namespace_description, self.env),
                 'methods': [],
                 'namespace':
                 method.namespace,
             }
         try:
             namespaces[namespace]['methods'].append(
                 (method.signature,
                  wiki_to_oneliner(method.description,
                                   self.env), method.permission))
         except Exception, e:
             self.fail('%s: %s\n' % (method.name, str(e)))
Esempio n. 26
0
 def expand_wiki_links(self, match):
     wiki_url = match.groups()[0]  # TracLink ([1], source:file/, ...)
     html_url = wiki_to_oneliner(
         wiki_url, self.env)  # <a href="http://someurl">...</a>
     href = re.search('href="(.*?)"', html_url)  # http://someurl
     url = href and href.groups()[0] or html_url
     if self.out_format == 'svg':
         format = 'URL="javascript:window.parent.location.href=\'%s\'"'
     else:
         format = 'URL="%s"'
     return format % url
Esempio n. 27
0
	def output_line(self, line):
		print >> self.out, "\t<tr gid=\"%s\" vis=\"%s\">" % \
			(",".join(self.gids), ",".join(self.visibility))

		cells = re.split(' *\|\| *', line)[1:-1]

		print >> self.out, "\t\t<td>%s</td>" % self.marker
			
		for cell in cells:
			print >> self.out, "\t\t<td>%s</td>" % wiki_to_oneliner(cell, self.env, None)

		print >> self.out, "\t</tr>"
Esempio n. 28
0
    def render_poll(self, req, title, votes):
        add_stylesheet(req, 'poll/css/poll.css')
        if not req.perm.has_permission('POLL_VIEW'):
            return ''

        all_votes = []
        ticket_count = 0
        for vote in votes:
            tickets = []
            if vote.startswith('#'):
                try:
                    tickets.append(int(vote.strip('#')))
                except ValueError:
                    raise TracError('Invalid ticket number %s' % vote)
            elif vote.startswith('query:'):
                query = vote[6:]
                tickets = [q['id'] for q in
                           Query.from_string(self.env, query).execute(req)]
            else:
                all_votes.append(('%08x' % abs(hash(vote)), None,
                                 wiki_to_oneliner(vote, self.env, req=req)))

            # Make tickets look pretty
            for idx, id in enumerate(tickets):
                try:
                    ticket = Ticket(self.env, id)
                except Exception:
                    continue
                summary = ticket['summary'] + ' (#%i)' % id
                try:
                    priority = Priority(self.env, ticket['priority']).value
                except ResourceNotFound, e: #this priority name has been removed from model
                    priority = 0
                summary = wiki_to_oneliner(summary, self.env, req=req)

                all_votes.append((str(id), "ticket prio%s%s%s" %
                                  (priority, ticket_count % 2 and ' even' or '',
                                  ticket['status'] == 'closed' and ' closed' or ''),
                                  summary))
                ticket_count += 1
Esempio n. 29
0
    def output_line(self, line):
        print >> self.out, "\t<tr gid=\"%s\" vis=\"%s\">" % \
         (",".join(self.gids), ",".join(self.visibility))

        cells = re.split(' *\|\| *', line)[1:-1]

        print >> self.out, "\t\t<td>%s</td>" % self.marker

        for cell in cells:
            print >> self.out, "\t\t<td>%s</td>" % wiki_to_oneliner(
                cell, self.env, None)

        print >> self.out, "\t</tr>"
Esempio n. 30
0
    def _version_display(self, req, milestone):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT version FROM milestone_version WHERE milestone=%s", (milestone,))
        row = cursor.fetchone()

        if row:
            return tag.span(
                "; ",
                wiki_to_oneliner("For version:'%s'" % (row[0],), self.env, req=req),
                class_="date")
        else:
            return []
Esempio n. 31
0
    def get_timeline_events(self, req, start, stop, filters):
        format = req.args.get('format')

        href = format == 'rss' and req.abs_href or req.href

        # Ticket changes
        if 'worklog' in filters:
            add_stylesheet(req, "worklog/worklogplugin.css")
            db = self.env.get_db_cnx()
            cursor = db.cursor()

            cursor.execute(
                """SELECT wl.user,wl.ticket,wl.time,wl.starttime,wl.comment,wl.kind,wl.humankind,t.summary,t.status
                             FROM (
                             
                             SELECT user, ticket, starttime AS time, starttime, comment, 'workstart' AS kind, 'started' AS humankind
                             FROM work_log

                             UNION

                             SELECT user, ticket, endtime AS time, starttime, comment, 'workstop' AS kind, 'stopped' AS humankind
                             FROM work_log

                             ) AS wl
                             INNER JOIN ticket t ON t.id = wl.ticket 
                                 AND wl.time>=%s AND wl.time<=%s 
                           ORDER BY wl.time""" % (start, stop))
            previous_update = None
            for user, ticket, time, starttime, comment, kind, humankind, summary, status in cursor:
                summary = Markup.escape(summary)
                time = float(time)
                starttime = float(starttime)
                if format == 'rss':
                    title = Markup('%s %s working on Ticket #%s (%s): %s' % \
                                   (user, humankind, ticket, summary, comment))
                else:
                    title = Markup('%s %s working on Ticket <em title="%s">#%s</em>' % \
                                   (user, humankind, summary, ticket))
                message = ''
                if kind == 'workstop':
                    started = datetime.fromtimestamp(starttime)
                    finished = datetime.fromtimestamp(time)
                    if comment:
                        message = wiki_to_oneliner(
                            comment, self.env, db, shorten=True) + Markup(
                                '<br />(Time spent: %s)' %
                                pretty_timedelta(started, finished))
                    else:
                        message = 'Time spent: %s' % pretty_timedelta(
                            started, finished)
                yield kind, href.ticket(ticket), title, time, user, message
Esempio n. 32
0
def attachment_to_hdf(env, req, db, attachment):
    if not db:
        db = env.get_db_cnx()
    hdf = {
        'filename': attachment.filename,
        'description': wiki_to_oneliner(attachment.description, env, db),
        'author': attachment.author,
        'ipnr': attachment.ipnr,
        'size': pretty_size(attachment.size),
        'time': format_datetime(attachment.time),
        'age': pretty_timedelta(attachment.time),
        'href': attachment.href(req)
    }
    return hdf
Esempio n. 33
0
    def get_task_markup(self, req, ticket, task):
        if not task:
            return ''

        ticket_text = 'ticket #' + str(task['ticket'])
        if task['ticket'] == ticket:
            ticket_text = 'this ticket'
        timedelta = pretty_timedelta(datetime.fromtimestamp(task['starttime']),
                                     None)

        return '<li>%s</li>' % wiki_to_oneliner(
            'You have been working on %s for %s' % (ticket_text, timedelta),
            self.env,
            req=req)
Esempio n. 34
0
def attachment_to_hdf(env, req, db, attachment):
    if not db:
        db = env.get_db_cnx()
    hdf = {
        'filename': attachment.filename,
        'description': wiki_to_oneliner(attachment.description, env, db),
        'author': attachment.author,
        'ipnr': attachment.ipnr,
        'size': pretty_size(attachment.size),
        'time': format_datetime(attachment.time),
        'age': pretty_timedelta(attachment.time),
        'href': attachment.href(req)
    }
    return hdf
Esempio n. 35
0
 def get_timeline_events(self, req, start, stop, filters):
     if "wiki" in filters:
         format = req.args.get("format")
         db = self.env.get_db_cnx()
         cursor = db.cursor()
         cursor.execute("SELECT time,name,comment,author " "FROM wiki WHERE time>=%s AND time<=%s", (start, stop))
         for t, name, comment, author in cursor:
             title = Markup("<em>%s</em> edited by %s", name, author)
             if format == "rss":
                 href = self.env.abs_href.wiki(name)
                 comment = wiki_to_html(comment or "--", self.env, req, db, absurls=True)
             else:
                 href = self.env.href.wiki(name)
                 comment = wiki_to_oneliner(comment, self.env, db, shorten=True)
             yield "wiki", href, title, t, author, comment
Esempio n. 36
0
    def _render_view(self, req, db, page):
        page_name = self._set_title(req, page, '')
        if page.name == 'WikiStart':
            req.hdf['title'] = ''

        version = req.args.get('version')
        if version:
            # Ask web spiders to not index old versions
            req.hdf['html.norobots'] = 1

        # Add registered converters
        for conversion in Mimeview(self.env).get_supported_conversions(
                                             'text/x-trac-wiki'):
            conversion_href = req.href.wiki(page.name, version=version,
                                            format=conversion[0])
            add_link(req, 'alternate', conversion_href, conversion[1],
                     conversion[3])

        latest_page = WikiPage(self.env, page.name)
        req.hdf['wiki'] = {'exists': page.exists,
                           'version': page.version,
                           'latest_version': latest_page.version,
                           'readonly': page.readonly}
        if page.exists:
            req.hdf['wiki'] = {
                'page_html': wiki_to_html(page.text, self.env, req),
                'history_href': req.href.wiki(page.name, action='history'),
                'last_change_href': req.href.wiki(page.name, action='diff',
                                                  version=page.version)
                }
            if version:
                req.hdf['wiki'] = {
                    'comment_html': wiki_to_oneliner(page.comment or '--',
                                                     self.env, db),
                    'author': page.author,
                    'age': pretty_timedelta(page.time)
                    }
        else:
            if not req.perm.has_permission('WIKI_CREATE'):
                raise HTTPNotFound('Page %s not found', page.name)
            req.hdf['wiki.page_html'] = html.P(u'创建 "%s" ' % page_name)

        # Show attachments
        req.hdf['wiki.attachments'] = attachments_to_hdf(self.env, req, db,
                                                         'wiki', page.name)
        if req.perm.has_permission('WIKI_MODIFY'):
            attach_href = req.href.attachment('wiki', page.name)
            req.hdf['wiki.attach_href'] = attach_href
Esempio n. 37
0
    def _version_display(self, req, milestone):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            "SELECT version FROM milestone_version WHERE milestone=%s",
            (milestone, ))
        row = cursor.fetchone()

        if row:
            return tag.span("; ",
                            wiki_to_oneliner("For version:'%s'" % (row[0], ),
                                             self.env,
                                             req=req),
                            class_="date")
        else:
            return []
Esempio n. 38
0
    def get_timeline_events(self, req, start, stop, filters):
        format = req.args.get('format')

        href = format == 'rss' and req.abs_href or req.href

        # Ticket changes
        if 'worklog' in filters:
            add_stylesheet(req, "worklog/worklogplugin.css")
            db = self.env.get_db_cnx()
            cursor = db.cursor()

            cursor.execute("""SELECT wl.user,wl.ticket,wl.time,wl.starttime,wl.comment,wl.kind,wl.humankind,t.summary,t.status
                             FROM (
                             
                             SELECT user, ticket, starttime AS time, starttime, comment, 'workstart' AS kind, 'started' AS humankind
                             FROM work_log

                             UNION

                             SELECT user, ticket, endtime AS time, starttime, comment, 'workstop' AS kind, 'stopped' AS humankind
                             FROM work_log

                             ) AS wl
                             INNER JOIN ticket t ON t.id = wl.ticket 
                                 AND wl.time>=%s AND wl.time<=%s 
                           ORDER BY wl.time"""
                           % (start, stop))
            previous_update = None
            for user,ticket,time,starttime,comment,kind,humankind,summary,status in cursor:
                summary = Markup.escape(summary)
                time = float(time)
                starttime = float(starttime)
                if format == 'rss':
                    title = Markup('%s %s working on Ticket #%s (%s): %s' % \
                                   (user, humankind, ticket, summary, comment))
                else:
                    title = Markup('%s %s working on Ticket <em title="%s">#%s</em>' % \
                                   (user, humankind, summary, ticket))
                message = ''
                if kind == 'workstop':
                    started = datetime.fromtimestamp(starttime)
                    finished = datetime.fromtimestamp(time)
                    if comment:
                        message = wiki_to_oneliner(comment, self.env, db, shorten=True) + Markup('<br />(Time spent: %s)' % pretty_timedelta(started, finished))
                    else:
                        message = 'Time spent: %s' % pretty_timedelta(started, finished)
                yield kind, href.ticket(ticket), title, time, user, message
Esempio n. 39
0
    def render_macro(self, req, name, filter):
        from trac.config import Option
        from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner
        filter = filter or ''

        sections = set([section for section, option in Option.registry.keys()
                        if section.startswith(filter)])

        return html.DIV(class_='tracini')(
            [(html.H2('[%s]' % section, id='%s-section' % section),
              html.TABLE(class_='wiki')(
                  html.TBODY([html.TR(html.TD(html.TT(option.name)),
                                      html.TD(wiki_to_oneliner(option.__doc__,
                                                               self.env)))
                              for option in Option.registry.values()
                              if option.section == section])))
             for section in sorted(sections)])
Esempio n. 40
0
 def get_timeline_events(self, req, start, stop, filters):
     if 'wiki' in filters:
         format = req.args.get('format')
         db = self.env.get_db_cnx()
         cursor = db.cursor()
         cursor.execute("SELECT time,name,comment,author "
                        "FROM wiki WHERE time>=%s AND time<=%s",
                        (start, stop))
         for t,name,comment,author in cursor:
             title = Markup('<em>%s</em> edited by %s', name, author)
             if format == 'rss':
                 href = self.env.abs_href.wiki(name)
                 comment = wiki_to_html(comment or '--', self.env, req, db,
                                        absurls=True)
             else:
                 href = self.env.href.wiki(name)
                 comment = wiki_to_oneliner(comment, self.env, db,
                                            shorten=True)
             yield 'wiki', href, title, t, author, comment
Esempio n. 41
0
    def get_timeline_events(self, req, db, type, format, start, stop, display):
        """Return an iterable of events suitable for ITimelineEventProvider.

        `display` is a callback for formatting the attachment's parent
        """
        for change, type, id, filename, time, descr, author in \
                self.get_history(start, stop, type):
            title = html.EM(os.path.basename(filename)) + \
                    ' attached to ' + display(id)
            if format == 'rss':
                title = Markup(title).striptags()
                descr = wiki_to_html(descr or '--', self.env, req, db,
                                     absurls=True)
                href = req.abs_href
            else:
                descr = wiki_to_oneliner(descr, self.env, db, shorten=True)
                title += Markup(' by %s', author)
                href = req.href
            yield('attachment', href.attachment(type, id, filename), title,
                  time, author, descr)
Esempio n. 42
0
    def get_timeline_events(self, req, db, type, format, start, stop, display):
        """Return an iterable of events suitable for ITimelineEventProvider.

        `display` is a callback for formatting the attachment's parent
        """
        for change, type, id, filename, time, descr, author in \
                self.get_history(start, stop, type):
            title = html.EM(os.path.basename(filename)) + \
                    ' attached to ' + display(id)
            if format == 'rss':
                title = Markup(title).striptags()
                descr = wiki_to_html(descr or '--', self.env, req, db,
                                     absurls=True)
                href = req.abs_href
            else:
                descr = wiki_to_oneliner(descr, self.env, db, shorten=True)
                title += Markup(u' par %s', author)
                href = req.href
            yield('attachment', href.attachment(type, id, filename), title,
                  time, author, descr)
Esempio n. 43
0
    def get_timeline_events(self, req, start, stop, filters):
        # timeline动作的输入
        if 'wiki' in filters:
            wiki = WikiSystem(self.env)
            format = req.args.get('format')
            href = format == 'rss' and req.abs_href or req.href
            db = self.env.get_db_cnx()
            cursor = db.cursor()
            cursor.execute(
                "SELECT time,name,comment,author,version "
                "FROM wiki WHERE time>=%s AND time<=%s", (start, stop))
            for t, name, comment, author, version in cursor:
                title = Markup('<em>%s</em> ' + u"编辑者 %s",
                               wiki.format_page_name(name), author)
                diff_link = html.A(u'变化',
                                   href=href.wiki(name,
                                                  action='diff',
                                                  version=version))
                if format == 'rss':
                    comment = wiki_to_html(comment or '--',
                                           self.env,
                                           req,
                                           db,
                                           absurls=True)
                else:
                    comment = wiki_to_oneliner(comment,
                                               self.env,
                                               db,
                                               shorten=True)
                if version > 1:
                    comment = Markup('%s (%s)', comment, diff_link)
                yield 'wiki', href.wiki(name), title, t, author, comment

            # Attachments
            att = AttachmentModule(self.env)
            for event in att.get_timeline_events(req, db, 'wiki', format,
                                                 start, stop,
                                                 lambda id: html.EM(id)):
                yield event
Esempio n. 44
0
    def _render_editor(self, req, db, page, preview=False):
        req.perm.assert_permission('WIKI_MODIFY')

        if req.args.has_key('text'):
            page.text = req.args.get('text')
        if preview:
            page.readonly = req.args.has_key('readonly')

        author = get_reporter_id(req, 'author')
        comment = req.args.get('comment', '')
        editrows = req.args.get('editrows')
        if editrows:
            pref = req.session.get('wiki_editrows', '20')
            if editrows != pref:
                req.session['wiki_editrows'] = editrows
        else:
            editrows = req.session.get('wiki_editrows', '20')

        self._set_title(req, page, u'编辑')
        info = {
            'page_source': page.text,
            'version': page.version,
            'author': author,
            'comment': comment,
            'readonly': page.readonly,
            'edit_rows': editrows,
            'scroll_bar_pos': req.args.get('scroll_bar_pos', '')
        }
        if page.exists:
            info['history_href'] = req.href.wiki(page.name,
                                                 action='history')
            info['last_change_href'] = req.href.wiki(page.name,
                                                     action='diff',
                                                     version=page.version)
        if preview:
            info['page_html'] = wiki_to_html(page.text, self.env, req, db)
            info['comment_html'] = wiki_to_oneliner(comment, self.env, db)
            info['readonly'] = int(req.args.has_key('readonly'))
        req.hdf['wiki'] = info
Esempio n. 45
0
    def _render_history(self, req, db, page):
        """Extract the complete history for a given page and stores it in the
        HDF.

        This information is used to present a changelog/history for a given
        page.
        """
        req.perm.assert_permission('WIKI_VIEW')

        if not page.exists:
            raise TracError, "Page %s does not exist" % page.name

        req.hdf['title'] = escape(page.name) + ' (history)'

        history = []
        for version, t, author, comment, ipnr in page.get_history():
            history.append({
                'url':
                escape(self.env.href.wiki(page.name, version=version)),
                'diff_url':
                escape(
                    self.env.href.wiki(page.name,
                                       version=version,
                                       action='diff')),
                'version':
                version,
                'time':
                time.strftime('%x %X', time.localtime(int(t))),
                'time_delta':
                pretty_timedelta(t),
                'author':
                escape(author),
                'comment':
                wiki_to_oneliner(comment or '', self.env, db),
                'ipaddr':
                ipnr
            })
        req.hdf['wiki.history'] = history
Esempio n. 46
0
    def _render_editor(self, req, db, page, preview=False):
        req.perm.assert_permission('WIKI_MODIFY')

        if req.args.has_key('text'):
            page.text = req.args.get('text')
        if preview:
            page.readonly = req.args.has_key('readonly')

        author = get_reporter_id(req, 'author')
        comment = req.args.get('comment', '')
        editrows = req.args.get('editrows')
        if editrows:
            pref = req.session.get('wiki_editrows', '20')
            if editrows != pref:
                req.session['wiki_editrows'] = editrows
        else:
            editrows = req.session.get('wiki_editrows', '20')

        self._set_title(req, page, u'编辑')
        info = {
            'page_source': page.text,
            'version': page.version,
            'author': author,
            'comment': comment,
            'readonly': page.readonly,
            'edit_rows': editrows,
            'scroll_bar_pos': req.args.get('scroll_bar_pos', '')
        }
        if page.exists:
            info['history_href'] = req.href.wiki(page.name, action='history')
            info['last_change_href'] = req.href.wiki(page.name,
                                                     action='diff',
                                                     version=page.version)
        if preview:
            info['page_html'] = wiki_to_html(page.text, self.env, req, db)
            info['comment_html'] = wiki_to_oneliner(comment, self.env, db)
            info['readonly'] = int(req.args.has_key('readonly'))
        req.hdf['wiki'] = info
Esempio n. 47
0
    def expand_macro(self, formatter, name, content):
        req = formatter.req

        if 'CHANGESET_VIEW' not in req.perm:
            return Markup('<i>Changelog not available</i>')

        context = web_context(req)
        context.href is req.href
        args, kwargs = parse_args(content)
        args += [None, None]
        path, limit, rev = args[:3]
        limit = kwargs.pop('limit', limit)
        rev = kwargs.pop('rev', rev)
        if ':' in path:
            reponame, path = path.split(':', 2)
        else:
            reponame = ''
        if '@' in path:
            path, rev = path.split('@', 2)
        repo = self.env.get_repository(reponame)
        path = repo.normalize_path(path)
        revstart = 0
        if rev is not None:
            for d in [':', '-']:
                if d in rev:
                    revstart, revstop = rev.split(d, 2)
                    if not revstop or revstop.lower() in ['head', '0']:
                        revstart = int(revstart)
                        rev = repo.get_youngest_rev()
                        limit = rev - revstart + 1
                    else:
                        revstart, revstop = int(revstart), int(revstop)
                        if revstart > revstop:
                            revstart, revstop = revstop, revstart
                        limit = revstop - revstart + 1
                        rev = revstop or None
                    break

        if rev is None:
            rev = repo.get_youngest_rev()
        rev = repo.normalize_rev(rev)
        if limit is None:
            limit = 5
        else:
            limit = int(limit)
        node = repo.get_node(path, rev)
        out = StringIO()
        out.write('</p>')  # close surrounding paragraph
        out.write('\n<div class="changelog">\n<dl class="wiki">')
        for npath, nrev, nlog in node.get_history(limit):
            if nrev < revstart:
                break
            change = repo.get_changeset(nrev)
            datetime = format_datetime(change.date, '%Y-%m-%d %H:%M:%S',
                                       req.tz)
            if not reponame:
                cset = str(nrev)
            else:
                cset = '%s/%s' % (nrev, reponame)
            header = wiki_to_oneliner("[%s] by %s on %s" %
                                      (cset, change.author, datetime),
                                      self.env,
                                      req=req)
            out.write('\n<dt id="changelog-changeset-%s">\n%s\n</dt>' %
                      (cset, header))
            message = _remove_p(
                format_to_html(self.env,
                               context,
                               change.message,
                               escape_newlines=True))
            out.write('\n<dd>\n%s\n</dd>' % message)
        out.write('\n</dl>\n</div>')
        out.write('\n<p>')  # re-open surrounding paragraph
        return out.getvalue()
Esempio n. 48
0
    def _generate_blog(self, req, args, kwargs):
        """Extract the blog pages and fill the HDF.

        *args is a list of tags to use to limit the blog scope
        **kwargs are any aditional keyword arguments that are needed
        """
        tallies = {}
        parms = self._get_display_params(req, kwargs)
        tagged_pages, tlist = self._initialize_tags(args, kwargs)
        poststart, postend, default_times = self._get_time_range(parms, req, 
                                                                 kwargs)

        # The blog can be displayed in various formats depending on the values
        # of the parameters.  The two main methods/displays are:
        #  * Fixed number of posts, ie. always show the last 5 posts.
        #  * All posts in a given date range, ie. all posts for a given month.
        # Issues with the first method is that all posts have to be read, and
        # then sorted by date before the selection can be made, as we are not
        # guaranteed any specific order from the tag retrieval.
        #
        # Issues with the second are likewise.  However, with the second, while
        # we still need to read in all of the posts, we can drop those that are
        # out of range in the process, so no extra sorting need be done. 
        #
        # An option for parsing would be:
        # for each tagged post:
        #   load post
        #   save post_time and page name in list
        # sort the list
        # Formatting
        # 
        # Create a dictionary of page names keyed by the post date.  Create a
        # sorted (decending) list of post date timestamps.
        for p in tagged_pages:
            page = WikiPage(self.env, version=1, name=p)
            version, post_time, author, comment, ipnr = page.get_history(
                                                        ).next()
            posts[post_time] = p
            # We also take time to update our tallies
            self._tally(tallies, post_time, p)
            continue
        post_times = posts.keys()
        post_times.sort()
        post_times.reverse()
        # Slice the list of post times down to those posts that fall in the
        # selected time frame and/or number of posts.
        if default_times and parms['num_posts']:
            post_times = post_times[:parms['num_posts']]
        else:
            i = 0 
            maxindex = len(post_times)
            while (i < maxindex) and (post_times[i] < poststart):
                i += 1
            start_index = i
            while (i < maxindex) and (post_times[i] <= postend):
                i += 1
            stop_index = i 
            post_times = post_times[start_index:stop_index]
            if parms['num_posts'] and (parms['num_posts'] <= len(post_times)):
                post_times = post_times[:parms['num_posts']]
        # Now that we have the list of pages that we are going to use, what now?

        # We need the following information:
        #- * formatted post time
        #- * truncated(?) version of page to display
        #  * list of tags to display in "tagged under"
        #    * link name (tag)
        #    * tag name (tag)
        #    * last tag indicator
        #- * page name
        #- * link to wiki page (read_post)
        #- * author
        #- * comment (?)
        #  * whether or not tags are present
        #  * whether or not more tags are available
        #- * whether or not the post has been updated
        #-   * update time 
        entries = {}
        for post in post_times:
            page = WikiPage(self.env, name=posts[post])
            version, modified, author, comment, ipnr = page.get_history().next()
            # Truncate the post text if necessary and format for display
            post_text = wiki_to_nofloat_html(self._trin_page(page.text), 
                                    self.env, req,
                                    macro_blacklist=parms['macro_blacklist'])
            # Format the page time for display
            post_time = format_datetime(post_time, format=parms['date_format']) 
            # Create the link to the full post text
            read_post_link = wiki_to_oneliner(parms['read_post'] % posts[post],
                                              self.env),
            # Set whether or not the page has been modified
            post_modified = ((modified != post) and parms['mark_updated'])
            # Create post modified string.  If {{{post_modified}}} is false,
            # this string is simply ignored.
            modified_notice = format_datetime(modified, 
                                              format=parms['date_format'])
            data = {
                    'name'      : posts[post],
                    'wiki_text' : post_text,
                    'time'      : post_time,
                    'author'    : author, # need to make sure this is the orig.
                    'comment'   : comment,
                    'modified'  : post_modified,
                    'mod_time'  : modified_notice,
                    'wiki_link' : read_post_link,
                    'tags'      : {
                                    'present' : tags_present,
                                    'tags'    : page_tags,
                                    'more'    : more_tags,
                                  },
                   }
            entries[post_time] = data
            
            
        for blog_entry in blog:
                pagetags = [x for x in self.tags.get_name_tags(blog_entry) 
                            if x not in tlist]
                tagtags = []
                for i, t in enumerate(pagetags[:3]):
                    d = { 'link' : t,
                          'name' : t,
                          'last' : i == 2,
                        }
                    tagtags.append(d)
                    continue
                data = {
                        'tags'      : {
                                        'present' : len(pagetags),
                                        'tags'    : tagtags,
                                        'more'    : len(pagetags) > 3 or 0,
                                      },
                       }
            continue
        # mark the last post so that we don't display a line after the last post
        if post_times:
            entries[post_times[-1]]['last'] = 1
        # fill the HDF with the blog entries
        req.hdf['blog.entries'] = [entries[x] for x in post_times]
        # set link name for blog posts
        bloglink = self.env.config.get('blog', 'new_blog_link', 'New Blog Post')
        req.hdf['blog.newblog'] = bloglink
        # generate calendar
        hidecal = self._choose_value('hidecal', req, kwargs)
        if not hidecal:
            self._generate_calendar(req, tallies)
        req.hdf['blog.hidecal'] = hidecal
        pass
Esempio n. 49
0
 def name_details(self, name):
     from trac.wiki.formatter import wiki_to_oneliner
     return (getattr(self.env.href, self.tagspace),
             wiki_to_oneliner('[%s:"%s" %s]' % (self.tagspace, name, name), self.env), '')
Esempio n. 50
0
    def expand_macro(self, formatter, name, args):
        req = formatter.req
        tag_system = TagSystem(self.env)

        all_releases = natural_sort([r.id for r, _ in
                                     tag_system.query(req, 'realm:wiki release')])
        all_categories = sorted([r.id for r, _ in
                                 tag_system.query(req, 'realm:wiki type')])

        hide_release_picker = False
        hide_fieldset_legend = False
        hide_fieldset_description = False
        other = []
        if args:
            categories = []
            releases = []
            for arg in args.split():
                if arg in all_releases:
                    hide_release_picker = True
                    releases.append(arg)
                elif arg in all_categories:
                    categories.append(arg)
                else:
                    other.append(arg)

            if len(categories) or len(releases):
                hide_fieldset_description = True

            if not len(categories):
                categories = all_categories
            elif len(categories) == 1:
                hide_fieldset_legend = True

            if not len(releases):
                releases = all_releases
        else:
            categories = all_categories
            releases = all_releases

        if 'update_th_filter' in req.args:
            show_releases = req.args.get('release', ['0.11'])
            if isinstance(show_releases, basestring):
                show_releases = [show_releases]
            req.session['th_release_filter'] = ','.join(show_releases)
        else:
            show_releases = req.session.get('th_release_filter', '0.11').split(',')

        output = ""
        if not hide_release_picker:
            style = "text-align:right; padding-top:1em; margin-right:5em;"
            form = builder.form('\n', style=style, method="get")

            style = "font-size:xx-small;"
            span = builder.span("Show hacks for releases:", style=style)

            for version in releases:
                inp = builder.input(version, type_="checkbox", name="release",
                                    value=version)
                if version in show_releases:
                    inp(checked="checked")
                span(inp, '\n')

            style = "font-size:xx-small; padding:0; border:solid 1px black;"
            span(builder.input(name="update_th_filter", type_="submit",
                               style=style, value="Update"), '\n')
            form('\n', span, '\n')
            output = "%s%s\n" % (output, form)


        def link(resource):
            return render_resource_link(self.env, formatter.context,
                                        resource, 'compact')

        for category in categories:
            page = WikiPage(self.env, category)
            match = self.title_extract.search(page.text)
            if match:
                cat_title = '%s' % match.group(1).strip()
                cat_body = self.title_extract.sub('', page.text, 1)
            else:
                cat_title = '%s' % category
                cat_body = page.text
            cat_body = self.self_extract.sub('', cat_body).strip()

            style = "padding:1em; margin:0em 5em 2em 5em; border:1px solid #999;"
            fieldset = builder.fieldset('\n', style=style)
            if not hide_fieldset_legend:
                legend = builder.legend(style="color: #999;")
                legend(builder.a(cat_title, href=self.env.href.wiki(category)))
                fieldset(legend, '\n')
            if not hide_fieldset_description:
                fieldset(builder.p(wiki_to_html(cat_body, self.env, req)))

            ul = builder.ul('\n', class_="listtagged")
            query = 'realm:wiki (%s) %s %s' % \
                (' or '.join(show_releases), category, ' '.join(other))

            lines = 0
            for resource, tags in tag_system.query(req, query):
                # filter out the page used to make important tags
                # persistent
                if resource.id == "tags/persistent":
                    continue

                lines += 1
                li = builder.li(link(resource), ': ')

                page = WikiPage(self.env, resource)
                match = self.title_extract.search(page.text)
                description = "''no description available''"
                if match:
                    if match.group(1):
                        description = match.group(1).strip()

                li(wiki_to_oneliner(description, self.env, req=req))
                if tags:
                    if hide_fieldset_legend == False and category in tags:
                        tags.remove(category)
                        self.log.debug("hide %s: no legend" % category)
                    for o in other:
                        if o in tags: tags.remove(o)
                    rendered_tags = [ link(resource('tag', tag))
                                      for tag in natural_sort(tags) ]

                    span = builder.span(style="font-size:xx-small;")
                    span(' (tags: ', rendered_tags[0],
                       [(', ', tag) for tag in rendered_tags[1:]], ')')
                    li(span)
                ul(li, '\n')

            if lines:
                fieldset(ul, '\n')
            else:
                message = "No results for %s." % \
                    (hide_release_picker and "this version" or "your selection")
                fieldset(builder.p(builder.em(message)), '\n')
            output = "%s%s\n" % (output, fieldset)

        return output
Esempio n. 51
0
    def _generate_blog(self, req, *args, **kwargs):
        """Extract the blog pages and fill the HDF.

        *args is a list of tags to use to limit the blog scope
        **kwargs are any aditional keyword arguments that are needed
        """
        tallies = {}
        tags = TagEngine(self.env).tagspace.wiki
        try:
            union = kwargs['union']
        except KeyError:
            union = False
        # Formatting
        read_post = "[wiki:%s Read Post]"
        entries = {}
        if not len(args):
            tlist = [self.env.config.get('blog', 'default_tag', 'blog')]
        else:
            tlist = args
        if union:
            blog = tags.get_tagged_names(tlist, operation='union')
        else:
            blog = tags.get_tagged_names(tlist, operation='intersection')
        macropage = req.args.get('page', None)

        poststart, postend, default_times = self._get_time_range(req, **kwargs)
        mark_updated = self._choose_value('mark_updated',
                                          req,
                                          kwargs,
                                          convert=bool_val)
        if not mark_updated and (not isinstance(mark_updated, bool)):
            mark_updated = bool_val(
                self.env.config.get('blog', 'mark_updated', True))
        macro_bl = self.env.config.get('blog', 'macro_blacklist',
                                       '').split(',')
        macro_bl = [name.strip() for name in macro_bl if name.strip()]
        macro_bl.append('BlogShow')

        # Get the email addresses of all known users and validate the "poster"
        # BlogShow optional argument at the same time (avoids looping the user
        # list twice).
        is_poster = None
        limit_poster = self._choose_value('poster', req, kwargs, convert=None)
        email_map = {}
        for username, name, email in self.env.get_known_users():
            if email:
                email_map[username] = email
            if limit_poster != None:
                if username == limit_poster:
                    is_poster = username

        num_posts = self._choose_value('num_posts', req, kwargs, convert=int)
        if num_posts and default_times:
            poststart = sys.maxint
            postend = 0
        for blog_entry in blog:
            if blog_entry == macropage:
                continue
            try:
                page = WikiPage(self.env, version=1, name=blog_entry)
                version, post_time, author, comment, ipnr = page.get_history(
                ).next()
                # if we're limiting by poster, do so now so that the calendar
                # only shows the number of entries the specific poster made.
                if is_poster != None:
                    if is_poster != author:
                        continue

                self._add_to_tallies(tallies, post_time, blog_entry)
                page = WikiPage(self.env, name=blog_entry)
                version, modified, author, comment, ipnr = page.get_history(
                ).next()
            except:
                self.log.debug("Error loading wiki page %s" % blog_entry,
                               exc_info=True)
                continue
            if poststart >= post_time >= postend:
                time_format = self.env.config.get('blog', 'date_format') \
                              or '%x %X'
                timeStr = format_datetime(post_time, format=time_format)
                fulltext = page.text
                # remove comments in blog view:
                del_comments = re.compile('==== Comment.*\Z', re.DOTALL)
                fulltext = del_comments.sub('', fulltext)
                # remove the [[AddComment...]] tag, otherwise it would appeare
                # more than one and crew up the blog view:
                del_addcomment = re.compile('\[\[AddComment.*\Z', re.DOTALL)
                fulltext = del_addcomment.sub('', fulltext)
                # limit length of preview:
                post_size = self._choose_value('post_size', req, kwargs, int)
                if not post_size and (not isinstance(post_size, int)):
                    post_size = int(
                        self.env.config.get('blog', 'post_size', 1024))
                text = self._trim_page(fulltext, blog_entry, post_size)
                pagetags = [
                    x for x in tags.get_name_tags(blog_entry) if x not in tlist
                ]
                tagtags = []
                for i, t in enumerate(pagetags[:3]):
                    d = {
                        'link': t,
                        'name': t,
                        'last': i == (len(pagetags[:3]) - 1),
                    }
                    tagtags.append(d)
                    continue
                # extract title from text:
                match = _title_split_match(fulltext)
                if match:
                    title = match.group(1)
                    fulltext = match.group(2)
                else:
                    title = blog_entry
                html_text = wiki_to_html(fulltext, self.env, req)
                rss_text = Markup.escape(to_unicode(html_text))
                data = {
                    'name':
                    blog_entry,
                    'title':
                    title,
                    'href':
                    self.env.href.wiki(blog_entry),
                    'wiki_link':
                    wiki_to_oneliner(read_post % blog_entry, self.env),
                    'time':
                    timeStr,
                    'date':
                    http_date(post_time),
                    #                        'date'      : http_date(page.time),
                    'author':
                    author,
                    'wiki_text':
                    wiki_to_nofloat_html(text,
                                         self.env,
                                         req,
                                         macro_blacklist=macro_bl),
                    'rss_text':
                    rss_text,
                    'comment':
                    wiki_to_oneliner(comment, self.env),
                    'tags': {
                        'present': len(pagetags),
                        'tags': tagtags,
                        'more': len(pagetags) > 3 or 0,
                    },
                }
                if author:
                    # For RSS, author must be an email address
                    if author.find('@') != -1:
                        data['author.email'] = author
                    elif email_map.has_key(author):
                        data['author.email'] = email_map[author]

                if (modified != post_time) and mark_updated:
                    data['modified'] = 1
                    mod_str = format_datetime(modified, format=time_format)
                    data['mod_time'] = mod_str
                entries[post_time] = data
            continue
        tlist = entries.keys()
        tlist.sort()
        tlist.reverse()
        if num_posts and (num_posts <= len(tlist)):
            tlist = tlist[:num_posts]
        if tlist:
            entries[tlist[-1]]['last'] = 1
        req.hdf['blog.entries'] = [entries[x] for x in tlist]
        bloglink = self.env.config.get('blog', 'new_blog_link',
                                       'New Blog Post')
        req.hdf['blog.newblog'] = bloglink
        hidecal = self._choose_value('hidecal', req, kwargs)
        if not hidecal:
            self._generate_calendar(req, tallies)
        req.hdf['blog.hidecal'] = hidecal
        # Insert /wiki/BlogHeader into /blog.  If the page does not exist,
        # this'll be a no-op
        blog_header = WikiPage(self.env, name='BlogHeader').text
        req.hdf['blog.header'] = Mimeview(self.env).render(
            req, 'text/x-trac-wiki', blog_header)
Esempio n. 52
0
    def expand_macro(self, formatter, name, content):
        req = formatter.req

        if "CHANGESET_VIEW" not in req.perm:
            return Markup("<i>Changelog not available</i>")

        context = web_context(req)
        context.href is req.href
        args, kwargs = parse_args(content)
        args += [None, None]
        path, limit, rev = args[:3]
        limit = kwargs.pop("limit", limit)
        rev = kwargs.pop("rev", rev)
        if ":" in path:
            reponame, path = path.split(":", 2)
        else:
            reponame = ""
        if "@" in path:
            path, rev = path.split("@", 2)
        repo = self.env.get_repository(reponame)
        path = repo.normalize_path(path)
        revstart = 0
        if rev is not None:
            for d in [":", "-"]:
                if d in rev:
                    revstart, revstop = rev.split(d, 2)
                    if not revstop or revstop.lower() in ["head", "0"]:
                        revstart = int(revstart)
                        rev = repo.get_youngest_rev()
                        limit = rev - revstart + 1
                    else:
                        revstart, revstop = int(revstart), int(revstop)
                        if revstart > revstop:
                            revstart, revstop = revstop, revstart
                        limit = revstop - revstart + 1
                        rev = revstop or None
                    break

        if rev is None:
            rev = repo.get_youngest_rev()
        rev = repo.normalize_rev(rev)
        if limit is None:
            limit = 5
        else:
            limit = int(limit)
        node = repo.get_node(path, rev)
        out = StringIO()
        out.write("</p>")  # close surrounding paragraph
        out.write('\n<div class="changelog">\n<dl class="wiki">')
        for npath, nrev, nlog in node.get_history(limit):
            if nrev < revstart:
                break
            change = repo.get_changeset(nrev)
            datetime = format_datetime(change.date, "%Y-%m-%d %H:%M:%S", req.tz)
            if not reponame:
                cset = str(nrev)
            else:
                cset = "%s/%s" % (nrev, reponame)
            header = wiki_to_oneliner("[%s] by %s on %s" % (cset, change.author, datetime), self.env, req=req)
            out.write('\n<dt id="changelog-changeset-%s">\n%s\n</dt>' % (cset, header))
            message = _remove_p(format_to_html(self.env, context, change.message, escape_newlines=True))
            out.write("\n<dd>\n%s\n</dd>" % message)
        out.write("\n</dl>\n</div>")
        out.write("\n<p>")  # re-open surrounding paragraph
        return out.getvalue()
Esempio n. 53
0
 def expand_macro(self, formatter, name, args):
     req = formatter.req
     
     pollValidTypes = ["single", "multiple"]
     changeVoteValidOptions = ["true", "false"]
     validChartTypes = ["bar", "pie"]
     
     pollType = "single"
     pollOptions = []
     pollName = None
     optionsLabelDict = {}
     optionsLabelDictForGraph = {}
     userCanChangeVote = "false"
     pollIdentifier = None
     chartType = "pie"
     
     args = args.strip()
     splitData = args.split(",")
     if len(splitData) > 0:
         for arg in splitData:
             argSplitData = arg.split("=")
             key = argSplitData[0].strip()
             value = argSplitData[1].strip()
             if key == "response_type":
                 if value in pollValidTypes:
                     pollType = value.strip()
             elif key == "title":
                 pollName = value.strip()
             elif key == "options":
                 tp = value.split(":")
                 updatePollOptions = []
                 optionsLabelDict = {}
                 for op in tp:
                     if len(op.strip()) > 0:
                         tempOp = op.strip()
                         if tempOp.startswith("#"):
                             tempTicketId = tempOp[1:]
                             if tempTicketId.isdigit():
                                 try:
                                     ticketObj = Ticket(self.env, tempTicketId)
                                     if ticketObj is not None and ticketObj.exists:
                                         ticketStr = ticketObj["summary"].strip()
                                         hashOp = self.getStringHash(ticketStr)
                                         updatePollOptions.append(hashOp)
                                         ticketLbl = ticketStr + ' Link: #%i' % int(tempTicketId)
                                         optionsLabelDict[hashOp] = escape(wiki_to_oneliner(ticketLbl, self.env, req=req))
                                         optionsLabelDictForGraph[hashOp] = escape(ticketLbl)
                                 except:
                                     pass
                         else:
                             hashOp = self.getStringHash(tempOp)
                             updatePollOptions.append(hashOp)
                             optionsLabelDict[hashOp] = escape(wiki_to_oneliner((tempOp), self.env, req=req))
                             optionsLabelDictForGraph[hashOp] = escape(tempOp)
                 pollOptions = updatePollOptions
             elif key == "user_can_change_vote":
                 if value in changeVoteValidOptions:
                     userCanChangeVote = value
             elif key == "chart_type":
                 if value in validChartTypes:
                     chartType = value
             elif key == "name":
                 pollIdentifier = value
                 
     if pollIdentifier is not None and pollName is not None and len(pollOptions) > 0:
         html = self.getPollHTML(req, pollIdentifier, pollName, pollType, pollOptions, userCanChangeVote, chartType, optionsLabelDict, optionsLabelDictForGraph)
         return html
     else:
         return self.getMsgTemplate('Information given for poll is insufficient/improper')
Esempio n. 54
0
    def name_details(self, name):
        ticket = model.Ticket(self.env, name)
        href = self.env.href.ticket(name)
        from trac.wiki.formatter import wiki_to_oneliner

        return (href, wiki_to_oneliner("#%s" % name, self.env), ticket.exists and ticket["summary"] or "")
Esempio n. 55
0
    def render_macro(self, req, name, args):
        db = self.env.get_db_cnx()
        formatter = MyOutlineFormatter(self.env)
        
        # Bail out if we are in a no-float zone
        if 'macro_no_float' in req.hdf:
            return ''
        
        # If this is a page preview, try to figure out where its from
        current_page = req.hdf.getValue('wiki.page_name','WikiStart')
        in_preview = False
        if not req.hdf.has_key('wiki.page_name'):
            if req.path_info.startswith('/wiki/'):
                current_page = req.path_info[6:]
                in_preview = True
            else:
                return ''
         
        def get_page_text(pagename):
            """Return a tuple of (text, exists) for a page, taking into account previews."""
            if in_preview and pagename == current_page:
                return (req.args.get('text',''), True)
            else:
                page = WikiPage(self.env,pagename)
                return (page.text, page.exists)            
                
        # Split the args
        if not args: args = ''
        args = [x.strip() for x in args.split(',')]
        # Options
        inline = False
        heading = 'Table of Contents'
        pagenames = []
        root = ''
        params = { 'title_index': False, 'min_depth': 1, 'max_depth': 6 }
        # Global options
        for arg in args:
            if arg == 'inline':
                inline = True
            elif arg == 'noheading':
                heading = ''
            elif arg == 'notitle':
                params['min_depth'] = 2     # Skip page title
            elif arg == 'titleindex':
                params['title_index'] = True
                heading = ''
            elif arg == 'nofloat':
                return ''
            elif arg.startswith('heading='):
                heading = arg[8:]
            elif arg.startswith('depth='):
                params['max_depth'] = int(arg[6:])
            elif arg.startswith('root='):
                root = arg[5:]
            elif arg != '':
                pagenames.append(arg)
        
        # Has the user supplied a list of pages?
        if not pagenames:
            pagenames.append(current_page)
            root = ''
            params['min_depth'] = 2     # Skip page title

        out = StringIO()
        if not inline:
            out.write("<div class='wiki-toc'>\n")
        if heading:
            out.write("<h4>%s</h4>\n" % heading)
        for pagename in pagenames:
            if params['title_index']:
                li_class = pagename.startswith(current_page) and ' class="active"' or ''
                prefix = (pagename.split('/'))[0]
                prefix = prefix.replace('\'', '\'\'')
                all_pages = list(WikiSystem(self.env).get_pages(prefix))
                if all_pages:
                    all_pages.sort()
                    out.write('<ol>')
                    for page in all_pages:
                        page_text, _ = get_page_text(page)
    
                        formatter.format(current_page, page, page_text, NullOut(), 1, 1)
                        header = ''
                        if formatter.outline:
                            title = formatter.outline[0][1]
                            title = re.sub('<[^>]*>','', title) # Strip all tags
                            header = ': ' + wiki_to_oneliner(title, self.env)
                        out.write('<li%s> <a href="%s">%s</a> %s</li>\n' % (li_class, self.env.href.wiki(page), page, header))
                    out.write('</ol>')        
                else :
                    out.write('<div class="system-message"><strong>Error: No page matching %s found</strong></div>' % prefix)
            else:
                page = root + pagename
                page_text, page_exists = get_page_text(page)
                if page_exists:
                    formatter.format(current_page, page, page_text, out, params['min_depth'], params['max_depth'])
                else:
                    out.write('<div class="system-message"><strong>Error: Page %s does not exist</strong></div>' % pagename)
        if not inline:
            out.write("</div>\n")
        return out.getvalue()
Esempio n. 56
0
    def render_macro(self, req, name, args):
        # Note for 0.11: `req` will be replaced by `formatter`
        #  req = formatter.req
        #  db = formatter.db
        db = self.env.get_db_cnx()
        formatter = MyOutlineFormatter(self.env)  # FIXME 0.11: give 'req'

        # Bail out if we are in a no-float zone
        # Note for 0.11: if 'macro_no_float' in formatter.properties
        if 'macro_no_float' in req.hdf:
            return ''

        # If this is a page preview, try to figure out where its from
        # Note for 0.11: formatter.context could be the main `object`
        # to which the text being formatted belongs to...
        current_page = req.hdf.get('wiki.page_name', 'WikiStart')
        in_preview = req.args.has_key('preview')

        def get_page_text(pagename):
            """Return a tuple of (text, exists) for a page,
            taking into account previews.

            Note for 0.11: `formatter` should have the original text,
            so there would be no need for the `in_preview` stuff.
            """
            if in_preview and pagename == current_page:
                return (req.args.get('text', ''), True)
            else:
                page = WikiPage(self.env, pagename)
                return (page.text, page.exists)

        # Split the args
        if not args: args = ''
        args = [x.strip() for x in args.split(',')]
        # Options
        inline = False
        heading = 'Table of Contents'
        pagenames = []
        root = ''
        params = {'title_index': False, 'min_depth': 1, 'max_depth': 6}
        # Global options
        for arg in args:
            if arg == 'inline':
                inline = True
            elif arg == 'noheading':
                heading = ''
            elif arg == 'notitle':
                params['min_depth'] = 2  # Skip page title
            elif arg == 'titleindex':
                params['title_index'] = True
                heading = ''
            elif arg == 'nofloat':
                return ''
            elif arg.startswith('heading='):
                heading = arg[8:]
            elif arg.startswith('depth='):
                params['max_depth'] = int(arg[6:])
            elif arg.startswith('root='):
                root = arg[5:]
            elif arg != '':
                pagenames.append(arg)

        # Has the user supplied a list of pages?
        if not pagenames:
            pagenames.append(current_page)
            root = ''
            params['min_depth'] = 2  # Skip page title

        out = StringIO()
        if not inline:
            out.write("<div class='wiki-toc'>\n")
        if heading:
            out.write("<h4>%s</h4>\n" % heading)
        for pagename in pagenames:
            if params['title_index']:
                li_class = pagename.startswith(
                    current_page) and ' class="active"' or ''
                prefix = (pagename.split('/'))[0]
                prefix = prefix.replace('\'', '\'\'')
                all_pages = list(WikiSystem(self.env).get_pages(prefix))
                if all_pages:
                    all_pages.sort()
                    out.write('<ol>')
                    for page in all_pages:
                        page_text, _ = get_page_text(page)

                        formatter.format(current_page, page, page_text,
                                         NullOut(), 1, 1)
                        header = ''
                        if formatter.outline:
                            title = formatter.outline[0][1]
                            title = re.sub('<[^>]*>', '',
                                           title)  # Strip all tags
                            header = ': ' + wiki_to_oneliner(title, self.env)
                        out.write(
                            '<li%s> <a href="%s">%s</a> %s</li>\n' %
                            (li_class, req.href.wiki(page), page, header))
                    out.write('</ol>')
                else:
                    out.write(
                        system_message('Error: No page matching %s found' %
                                       prefix))
            else:
                page = root + pagename
                page_text, page_exists = get_page_text(page)
                if page_exists:
                    formatter.format(current_page, page, page_text, out,
                                     params['min_depth'], params['max_depth'])
                else:
                    out.write(
                        system_message('Error: Page %s does not exist' %
                                       pagename))
        if not inline:
            out.write("</div>\n")
        return out.getvalue()