Пример #1
0
def _send_user_error(req, env, e):
    # See trac/web/api.py for the definition of HTTPException subclasses.
    if env:
        env.log.warning('[%s] %s, %r, referrer %r', req.remote_addr,
                        exception_to_unicode(e), req,
                        req.environ.get('HTTP_REFERER'))
    data = {
        'title': e.title,
        'type': 'TracError',
        'message': e.message,
        'frames': [],
        'traceback': None
    }
    if e.code == 403 and not req.is_authenticated:
        # TRANSLATOR: ... not logged in, you may want to 'do so' now (link)
        do_so = tag.a(_("do so"), href=req.href.login())
        add_notice(
            req,
            tag_(
                "You are currently not logged in. You may want "
                "to %(do_so)s now.",
                do_so=do_so))
    try:
        req.send_error(sys.exc_info(), status=e.code, env=env, data=data)
    except RequestDone:
        pass
Пример #2
0
 def render_group(group):
     return tag.ul(
         tag.li(tag(tag.strong(elt[0].strip('/')), render_group(elt[1]))
                if isinstance(elt, tuple) else
                tag.a(wiki.format_page_name(omitprefix(elt)),
                      href=formatter.href.wiki(elt)))
         for elt in group)
Пример #3
0
 def _format_export_link(self, formatter, ns, export, label):
     export, query, fragment = formatter.split_link(export)
     if ':' in export:
         rev, path = export.split(':', 1)
     elif '@' in export:
         path, rev = export.split('@', 1)
     else:
         rev, path = None, export
     node, raw_href, title = self._get_link_info(path, rev, formatter.href,
                                                 formatter.perm)
     if raw_href:
         return tag.a(label,
                      class_='export',
                      href=raw_href + fragment,
                      title=title)
     return tag.a(label, class_='missing export')
Пример #4
0
 def get_navigation_items(self, req):
     """Should return an iterable object over the list of navigation items to
     add, each being a tuple in the form (category, name, text).
     """
     if 'BLOG_VIEW' in req.perm('blog'):
         yield ('mainnav', 'blog',
                tag.a(_('Blog'), href=req.href.blog()) )
Пример #5
0
    def _render_full_format(self, formatter, post_list, post_instances,
                            heading, max_size, show_meta):
        """ Renters full blog posts. """
        out = ''
        if 'BLOG_VIEW' in formatter.req.perm('blog'):
            out = tag.div(class_="blog")
            out.append(
                tag.div(tag.a(heading, href=formatter.req.href.blog()),
                        class_="blog-list-title"))
            for post in post_instances:
                data = {
                    'post':
                    post,
                    'blog_personal_blog':
                    self.config.getbool('fullblog', 'personal_blog'),
                    'list_mode':
                    True,
                    'show_meta':
                    show_meta,
                    'execute_blog_macro':
                    True
                }
                if max_size:
                    data['blog_max_size'] = max_size

                txt = Chrome(self.env).render_template(
                    formatter.req, 'fullblog_macro_post.html', data,
                    {'fragment': True})
                out.append(Markup(to_unicode(txt)))
        return out
Пример #6
0
 def generate_prefix(prefix):
     intertrac = intertracs[prefix]
     if isinstance(intertrac, basestring):
         yield tag.tr(
             tag.td(tag.strong(prefix)),
             tag.td(
                 tag_("Alias for %(name)s",
                      name=tag.strong(intertrac))))
     else:
         url = intertrac.get('url', '')
         if url:
             title = intertrac.get('title', url)
             yield tag.tr(
                 tag.td(
                     tag.a(tag.strong(prefix), href=url + '/timeline')),
                 tag.td(tag.a(title, href=url)))
Пример #7
0
 def get_resource_description(self, resource, format=None, context=None,
                              **kwargs):
     bp = BlogPost(self.env, resource.id, resource.version)
     if context:
         return tag.a('Blog: '+ bp.title, href=context.href.blog(resource.id))
     else:
         return 'Blog: '+ bp.title
Пример #8
0
    def test_attributes_preserved_in_navigation_item(self):
        req = MockRequest(self.env)
        self.env.config.set('mainnav', 'test2.label', 'Test Two')
        self.env.config.set('mainnav', 'test3.label', 'Test Three')
        self.env.config.set('mainnav', 'test3.href', 'testthree')

        mainnav = req.chrome['nav']['mainnav']

        item = self._get_navigation_item(mainnav, 'test2')
        self.assertEqual(
            unicode(tag.a('Test Two', href='test2', target='blank')),
            unicode(item['label']))
        item = self._get_navigation_item(mainnav, 'test3')
        self.assertEqual(
            unicode(tag.a('Test Three', href='testthree', target='blank')),
            unicode(item['label']))
Пример #9
0
 def test_resource_has_no_manager_default_format(self):
     res = resource.Resource('unmanaged', 'exists', version=1)
     link = resource.render_resource_link(self.env, self.context, res)
     html = tag.a('unmanaged:exists',
                  class_='unmanaged',
                  href='/trac.cgi/unmanaged/exists?version=1')
     self.assertEqual(unicode(html), unicode(link))
Пример #10
0
    def expand_macro(self, formatter, name, content):
        from trac.mimeview.api import Mimeview
        mime_map = Mimeview(self.env).mime_map
        mime_type_filter = ''
        args, kw = parse_args(content)
        if args:
            mime_type_filter = args.pop(0).strip().rstrip('*')

        mime_types = {}
        for key, mime_type in mime_map.iteritems():
            if (not mime_type_filter or mime_type.startswith(mime_type_filter)
                ) and key != mime_type:
                mime_types.setdefault(mime_type, []).append(key)

        return tag.div(class_='mimetypes')(
            tag.table(class_='wiki')(
                tag.thead(
                    tag.tr(
                        tag.th(_("MIME Types")),  # always use plural
                        tag.th(
                            tag.a("WikiProcessors",
                                  href=formatter.context.href.wiki(
                                      'WikiProcessors'))))),
                tag.tbody(
                    tag.tr(
                        tag.th(tag.code(mime_type), style="text-align: left"),
                        tag.td(
                            tag.code(' '.join(sorted(mime_types[mime_type])))))
                    for mime_type in sorted(mime_types))))
Пример #11
0
 def test_tgettext(self):
     rv = to_fragment(
         tgettext('Back to %(parent)s',
                  parent=tag.a('WikiStart', href='http://localhost/')))
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('Back to <a href="http://localhost/">WikiStart</a>',
                      unicode(rv))
Пример #12
0
 def test_tag(self):
     self.assertEqual(Markup('0<a>0</a> and <b>0</b> and <c></c>'
                             ' and <d class="a b" more_="[\'a\']"></d>'),
                      Markup(tag(0, tag.a(0, href=''), b' and ', tag.b(0.0),
                                 ' and ', tag.c(None), ' and ',
                                 tag.d('', class_=['a', '', 'b'],
                                       more__=[b'a']))))
Пример #13
0
 def test_tracerror_with_tracerror_with_element(self):
     message = tag.p('Powered by ',
                     tag.a('Trac', href='https://trac.edgewall.org/'))
     rv = to_fragment(TracError(TracError(message)))
     self.assertEqual(Element, type(rv))
     self.assertEqual('<p>Powered by <a href="https://trac.edgewall.org/">'
                      'Trac</a></p>', unicode(rv))
Пример #14
0
    def _do_save(self, req, page):
        if not page.exists:
            req.perm(page.resource).require('WIKI_CREATE')
        else:
            req.perm(page.resource).require('WIKI_MODIFY')

        if 'WIKI_CHANGE_READONLY' in req.perm(page.resource):
            # Modify the read-only flag if it has been changed and the user is
            # WIKI_ADMIN
            page.readonly = int('readonly' in req.args)

        try:
            page.save(get_reporter_id(req, 'author'), req.args.get('comment'))
        except TracError:
            add_warning(req, _("Page not modified, showing latest version."))
            return self._render_view(req, page)

        href = req.href.wiki(page.name, action='diff', version=page.version)
        add_notice(
            req,
            tag_(
                "Your changes have been saved in version "
                "%(version)s (%(diff)s).",
                version=page.version,
                diff=tag.a(_("diff"), href=href)))
        req.redirect(
            get_resource_url(self.env, page.resource, req.href, version=None))
Пример #15
0
 def test_resource_exists_default_format(self):
     res = resource.Resource('fake', 'exists', version=1)
     link = resource.render_resource_link(self.env, self.context, res)
     html = tag.a('fake:exists',
                  class_='fake',
                  href='/trac.cgi/fake/exists?version=1')
     self.assertEqual(unicode(html), unicode(link))
Пример #16
0
        def sha_link(sha, label=None):
            # sha is assumed to be a non-abbreviated 40-chars sha id
            try:
                reponame = context.resource.parent.id
                repos = RepositoryManager(self.env).get_repository(reponame)
                cset = repos.get_changeset(sha)
                if label is None:
                    label = repos.display_rev(sha)

                return tag.a(label, class_='changeset',
                             title=shorten_line(cset.message),
                             href=context.href.changeset(sha, repos.reponame))

            except Exception as e:
                return tag.a(sha, class_='missing changeset',
                             title=to_unicode(e), rel='nofollow')
Пример #17
0
Файл: html.py Проект: zxfly/trac
 def test_tracerror_with_tracerror_with_fragment(self):
     message = tag('Powered by ',
                   tag.a('Trac', href='http://trac.edgewall.org/'))
     rv = to_fragment(TracError(TracError(message)))
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('Powered by <a href="http://trac.edgewall.org/">Trac'
                      '</a>', unicode(rv))
Пример #18
0
 def get_navigation_items(self, req):
     rm = RepositoryManager(self.env)
     if any(
             repos.is_viewable(req.perm)
             for repos in rm.get_real_repositories()):
         yield ('mainnav', 'browser',
                tag.a(_('Browse Source'), href=req.href.browser()))
Пример #19
0
    def _do_login(self, req):
        """Log the remote user in.

        This function expects to be called when the remote user name
        is available. The user name is inserted into the `auth_cookie`
        table and a cookie identifying the user on subsequent requests
        is sent back to the client.

        If the Authenticator was created with `ignore_case` set to
        true, then the authentication name passed from the web server
        in req.remote_user will be converted to lower case before
        being used. This is to avoid problems on installations
        authenticating against Windows which is not case sensitive
        regarding user names and domain names
        """
        if not req.remote_user:
            # TRANSLATOR: ... refer to the 'installation documentation'. (link)
            inst_doc = tag.a(_("installation documentation"),
                             title=_("Configuring Authentication"),
                             href=req.href.wiki('TracInstall') +
                                                "#ConfiguringAuthentication")
            raise TracError(tag_("Authentication information not available. "
                                 "Please refer to the %(inst_doc)s.",
                                 inst_doc=inst_doc))
        remote_user = req.remote_user
        if self.ignore_case:
            remote_user = remote_user.lower()

        if req.authname not in ('anonymous', remote_user):
            raise TracError(_("Already logged in as %(user)s.",
                              user=req.authname))

        with self.env.db_transaction as db:
            # Delete cookies older than 10 days
            db("DELETE FROM auth_cookie WHERE time < %s",
               (int(time_now()) - 86400 * 10,))
            # Insert a new cookie if we haven't already got one
            cookie = None
            trac_auth = req.incookie.get('trac_auth')
            if trac_auth is not None:
                name = self._cookie_to_name(req, trac_auth)
                cookie = trac_auth.value if name == remote_user else None
            if cookie is None:
                cookie = hex_entropy()
                db("""
                    INSERT INTO auth_cookie (cookie, name, ipnr, time)
                         VALUES (%s, %s, %s, %s)
                   """, (cookie, remote_user, req.remote_addr,
                         int(time_now())))
        req.authname = remote_user
        req.outcookie['trac_auth'] = cookie
        if self.auth_cookie_domain:
            req.outcookie['trac_auth']['domain'] = self.auth_cookie_domain
        req.outcookie['trac_auth']['path'] = self.auth_cookie_path \
                                             or req.base_path or '/'
        if self.env.secure_cookies:
            req.outcookie['trac_auth']['secure'] = True
        req.outcookie['trac_auth']['httponly'] = True
        if self.auth_cookie_lifetime > 0:
            req.outcookie['trac_auth']['expires'] = self.auth_cookie_lifetime
Пример #20
0
    def expand_macro(self, formatter, name, content):
        interwikis = []
        for k in sorted(self.keys()):
            prefix, url, title = self[k]
            interwikis.append({
                'prefix': prefix, 'url': url, 'title': title,
                'rc_url': self._expand_or_append(url, ['RecentChanges']),
                'description': url if title == prefix else title})

        return tag.table(tag.tr(tag.th(tag.em(_("Prefix"))),
                                tag.th(tag.em(_("Site")))),
                         [tag.tr(tag.td(tag.a(w['prefix'], href=w['rc_url'])),
                                 tag.td(tag.a(w['description'],
                                              href=w['url'])))
                          for w in interwikis ],
                         class_="wiki interwiki")
Пример #21
0
 def test_resource_exists_summary_format(self):
     res = resource.Resource('fake', 'exists', version=1)
     link = resource.render_resource_link(self.env, self.context, res,
                                          'summary')
     html = tag.a('fake:exists at version 1',
                  class_='fake',
                  href='/trac.cgi/fake/exists?version=1')
     self.assertEqual(str(html), str(link))
Пример #22
0
 def test_resource_has_no_manager_summary_format(self):
     res = resource.Resource('unmanaged', 'exists', version=1)
     link = resource.render_resource_link(self.env, self.context, res,
                                          'summary')
     html = tag.a('unmanaged:exists at version 1',
                  class_='unmanaged',
                  href='/trac.cgi/unmanaged/exists?version=1')
     self.assertEqual(str(html), str(link))
Пример #23
0
 def test_tracerror_with_tgettext(self):
     e = TracError(
         tgettext('Back to %(parent)s',
                  parent=tag.a('WikiStart', href='http://localhost/')))
     rv = to_fragment(e)
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('Back to <a href="http://localhost/">WikiStart</a>',
                      str(rv))
Пример #24
0
 def _format_link(self,
                  formatter,
                  ns,
                  pagename,
                  label,
                  ignore_missing,
                  original_label=None):
     pagename, query, fragment = formatter.split_link(pagename)
     version = None
     if '@' in pagename:
         pagename, version = pagename.split('@', 1)
     if version and query:
         query = '&' + query[1:]
     pagename = pagename.rstrip('/') or self.START_PAGE
     referrer = ''
     if formatter.resource and formatter.resource.realm == self.realm:
         referrer = formatter.resource.id
     if pagename.startswith('/'):
         pagename = pagename.lstrip('/')
     elif pagename.startswith(('./', '../')) or pagename in ('.', '..'):
         pagename = self._resolve_relative_name(pagename, referrer)
     else:
         pagename = self._resolve_scoped_name(pagename, referrer)
     label = unquote_label(label)
     if 'WIKI_VIEW' in formatter.perm(self.realm, pagename, version):
         href = formatter.href.wiki(pagename, version=version) + query \
                + fragment
         if self.has_page(pagename):
             return tag.a(label, href=href, class_='wiki')
         else:
             if ignore_missing:
                 return original_label or label
             if 'WIKI_CREATE' in \
                     formatter.perm(self.realm, pagename, version):
                 return tag.a(label,
                              class_='missing wiki',
                              href=href,
                              rel='nofollow')
             else:
                 return tag.a(label, class_='missing wiki')
     elif ignore_missing and not self.has_page(pagename):
         return original_label or label
     else:
         return tag.a(label,
                      class_='forbidden wiki',
                      title=_("no permission to view this wiki page"))
Пример #25
0
 def get_timeline_link(self, req, date, label=None, precision='hours',
                       query=None, fragment=None, title=None):
     iso_date = format_datetime(date, 'iso8601', req.tz)
     href = req.href.timeline(from_=iso_date, precision=precision)
     return tag.a(label or iso_date, class_='timeline',
                  title=title or _("See timeline at %(absolutetime)s",
                                   absolutetime=iso_date),
                  href=concat_path_query_fragment(href, query, fragment))
Пример #26
0
 def _format_link(self, formatter, ns, target, label):
     link, params, fragment = formatter.split_link(target)
     ids = link.split(':', 2)
     attachment = None
     if len(ids) == 3:
         known_realms = ResourceSystem(self.env).get_known_realms()
         # new-style attachment: TracLinks (filename:realm:id)
         if ids[1] in known_realms:
             attachment = Resource(ids[1], ids[2]).child(self.realm,
                                                         ids[0])
         else:  # try old-style attachment: TracLinks (realm:id:filename)
             if ids[0] in known_realms:
                 attachment = Resource(ids[0], ids[1]).child(self.realm,
                                                             ids[2])
     else:  # local attachment: TracLinks (filename)
         attachment = formatter.resource.child(self.realm, link)
     if attachment and 'ATTACHMENT_VIEW' in formatter.perm(attachment):
         try:
             Attachment(self.env, attachment)
         except ResourceNotFound:
             pass
         else:
             raw_href = get_resource_url(self.env, attachment,
                                         formatter.href, format='raw')
             if ns.startswith('raw'):
                 return tag.a(label, class_='attachment',
                              href=raw_href + params,
                              title=get_resource_name(self.env, attachment))
             href = get_resource_url(self.env, attachment, formatter.href)
             title = get_resource_name(self.env, attachment)
             return tag(tag.a(label, class_='attachment', title=title,
                              href=href + params),
                        tag.a(u'\u200b', class_='trac-rawlink',
                              href=raw_href + params, title=_("Download")))
         # FIXME: should be either:
         #
         # model = Attachment(self.env, attachment)
         # if model.exists:
         #     ...
         #
         # or directly:
         #
         # if attachment.exists:
         #
         # (related to #4130)
     return tag.a(label, class_='missing attachment')
Пример #27
0
 def test_resource_missing_default_format(self):
     res = resource.Resource('fake', 'missing', version=1)
     link = resource.render_resource_link(self.env, self.context, res)
     html = tag.a('fake:missing',
                  class_='fake missing',
                  rel='nofollow',
                  href='/trac.cgi/fake/missing?version=1')
     self.assertEqual(unicode(html), unicode(link))
Пример #28
0
def _get_source_link(spath, context):
    """Return a link to a merge source."""
    reponame = context.resource.parent.id
    return tag.a('/' + spath,
                 title=_('View merge source'),
                 href=context.href.browser(reponame or None,
                                           spath,
                                           rev=context.resource.version))
Пример #29
0
    def test_navigation_item_customization(self):
        req = MockRequest(self.env)
        self.env.config.set('mainnav', 'test2.href', 'testtwo')
        self.env.config.set('mainnav', 'test3.label', 'Test Three')
        self.env.config.set('mainnav', 'test3.href', 'testthree')

        mainnav = req.chrome['nav']['mainnav']

        item = self._get_navigation_item(mainnav, 'test1')
        self.assertEqual('Test 1', item['label'])
        item = self._get_navigation_item(mainnav, 'test2')
        self.assertEqual(str(tag.a('Test 2', href='testtwo', target='blank')),
                         str(item['label']))
        item = self._get_navigation_item(mainnav, 'test3')
        self.assertEqual(
            str(tag.a('Test Three', href='testthree', target='blank')),
            str(item['label']))
Пример #30
0
    def _format_comment_link(self, formatter, ns, target, label):
        resource = None
        if ':' in target:
            elts = target.split(':')
            if len(elts) == 3:
                cnum, realm, id = elts
                if cnum != 'description' and cnum and not cnum[0].isdigit():
                    realm, id, cnum = elts  # support old comment: style
                id = as_int(id, None)
                if realm in ('bug', 'issue'):
                    realm = 'ticket'
                resource = formatter.resource(realm, id)
        else:
            resource = formatter.resource
            cnum = target

        if resource and resource.id and resource.realm == self.realm and \
                cnum and (cnum.isdigit() or cnum == 'description'):
            href = title = class_ = None
            if self.resource_exists(resource):
                from trac.ticket.model import Ticket
                ticket = Ticket(self.env, resource.id)
                if cnum != 'description' and not ticket.get_change(cnum):
                    title = _("ticket comment does not exist")
                    class_ = 'missing ticket'
                elif 'TICKET_VIEW' in formatter.perm(resource):
                    href = formatter.href.ticket(resource.id) + \
                           "#comment:%s" % cnum
                    if resource.id != formatter.resource.id:
                        summary = self.format_summary(ticket['summary'],
                                                      ticket['status'],
                                                      ticket['resolution'],
                                                      ticket['type'])
                        if cnum == 'description':
                            title = _("Description for #%(id)s: %(summary)s",
                                      id=resource.id,
                                      summary=summary)
                        else:
                            title = _(
                                "Comment %(cnum)s for #%(id)s: "
                                "%(summary)s",
                                cnum=cnum,
                                id=resource.id,
                                summary=summary)
                        class_ = ticket['status'] + ' ticket'
                    else:
                        title = _("Description") if cnum == 'description' \
                                                 else _("Comment %(cnum)s",
                                                        cnum=cnum)
                        class_ = 'ticket'
                else:
                    title = _("no permission to view ticket")
                    class_ = 'forbidden ticket'
            else:
                title = _("ticket does not exist")
                class_ = 'missing ticket'
            return tag.a(label, class_=class_, href=href, title=title)
        return label
Пример #31
0
    def post_process_request(self, req, template, data, content_type):
        if 'SPAM_REPORT' in req.perm:
            i = req.path_info.find("/", 1)
            if (req.path_info[1:i] if i > 0 else req.path_info[1:]) in self.checkreq:
                isauth = 1 if req.authname and req.authname != 'anonymous' else 0
                if self.env.db_query("""
                    SELECT id FROM spamfilter_report
                       WHERE entry = %s
                          AND author = %s
                          AND authenticated = %s""",
                                     (req.path_info, req.authname, isauth)):
                    add_ctxtnav(req, _('Reported spam'))
                else:
                    add_script_data(req, {'spamreport_comment': _("Comment")})
                    add_script(req, 'spamfilter/reportspam.js')
                    add_ctxtnav(req, tag.a(_('Report spam'), id='reportspam', href=req.href('reportspam', (('page', req.path_info),))))
        if 'SPAM_CHECKREPORTS' in req.perm:
            for total, in self.env.db_query("SELECT COUNT(*) FROM spamfilter_report"):
                if total:
                    add_notice(req, tag.a(ngettext('%(num)d spam report', '%(num)d spam reports', total),
                    href=req.href.admin("spamfilter/report")))

        return template, data, content_type