Example #1
0
 def get_admin_panels(self, req):
     if 'TICKET_ADMIN' in req.perm('admin', 'ticket/' + self._type):
         # in global scope show only products
         # in local scope everything but products
         parent = getattr(self.env, 'parent', None)
         if (parent is None and self._type == 'products') or \
            (parent and self._type != 'products'):
             yield ('ticket', _('Ticket System'), self._type,
                    gettext(self._label[1]))
Example #2
0
 def get_admin_panels(self, req):
     if 'TICKET_ADMIN' in req.perm:
         # in global scope show only products
         # in local scope everything but products
         parent = getattr(self.env, 'parent', None)
         if (parent is None and self._type == 'products') or \
            (parent and self._type != 'products'):
             yield ('ticket', _('Ticket System'), self._type,
                     gettext(self._label[1]))
Example #3
0
 def __init__(self, message, title=None, show_traceback=False):
     """If message is a genshi.builder.tag object, everything up to the
     first <p> will be displayed in the red box, and everything after will
     be displayed below the red box.
     If title is given, it will be displayed as the large header above the
     error message.
     """
     from trac.util.translation import gettext
     Exception.__init__(self, message)
     self._message = message
     self.title = title or gettext(self.title)
     self.show_traceback = show_traceback
Example #4
0
    def get_ticket_fields(self):
        """Returns list of fields available for tickets.

        Each field is a dict with at least the 'name', 'label' (localized)
        and 'type' keys.
        It may in addition contain the 'custom' key, the 'optional' and the
        'options' keys. When present 'custom' and 'optional' are always `True`.
        """
        fields = copy.deepcopy(self.fields)
        label = 'label'  # workaround gettext extraction bug
        for f in fields:
            f[label] = gettext(f[label])
        return fields
Example #5
0
    def get_ticket_fields(self):
        """Returns list of fields available for tickets.

        Each field is a dict with at least the 'name', 'label' (localized)
        and 'type' keys.
        It may in addition contain the 'custom' key, the 'optional' and the
        'options' keys. When present 'custom' and 'optional' are always `True`.
        """
        fields = copy.deepcopy(self.fields)
        label = 'label' # workaround gettext extraction bug
        for f in fields:
            f[label] = gettext(f[label])
        return fields
Example #6
0
File: core.py Project: hanotch/trac
    def __init__(self, message, title=None, show_traceback=False):
        """If the `message` contains a `p` or `div` element it will be
        rendered directly. Use the `message` class on the `p` or `div`
        element to style as a red box. Otherwise, the message should be
        plain text or contain only inline elements and will be wrapped
        in a `p` element and rendered in a red box.

        If title is given, it will be displayed as the large header
        above the error message.
        """
        from trac.util.translation import gettext
        super(TracError, self).__init__(message)
        self._message = message
        self.title = title or gettext(self.title)
        self.show_traceback = show_traceback
Example #7
0
 def test_tracerror_with_gettext(self):
     e = TracError(gettext('%(size)s bytes', size=0))
     rv = to_fragment(e)
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('0 bytes', unicode(rv))
Example #8
0
 def test_gettext(self):
     rv = to_fragment(gettext('%(size)s bytes', size=0))
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('0 bytes', unicode(rv))
Example #9
0
 def test_tracerror_with_gettext(self):
     e = TracError(gettext('%(size)s bytes', size=0))
     rv = to_fragment(e)
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('0 bytes', unicode(rv))
Example #10
0
 def get_admin_panels(self, req):
     if all(perm in req.perm('admin', 'ticket/' + self._type)
            for perm in self._view_perms):
         yield ('ticket', _('Ticket System'), self._type,
                gettext(self._label[1]))
Example #11
0
 def get_admin_panels(self, req):
     if 'TICKET_ADMIN' in req.perm('admin', 'ticket/' + self._type):
         yield ('ticket', _('Ticket System'), self._type,
                gettext(self._label[1]))
Example #12
0
    def _render_admin_panel(self, req, cat, page, path_info):
        label = [gettext(each) for each in self._label]
        data = {
            'label_singular': label[0],
            'label_plural': label[1],
            'type': self._type
        }

        # Detail view?
        if path_info:
            enum = self._enum_cls(self.env, path_info)
            if req.method == 'POST':
                if req.args.get('save'):
                    enum.name = req.args.get('name')
                    enum.update()
                    add_notice(req, _('Your changes have been saved.'))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
            data.update({'view': 'detail', 'enum': enum})

        else:
            default = self.config.get('ticket', 'default_%s' % self._type)
            if req.method == 'POST':
                # Add enum
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        enum = self._enum_cls(self.env, name=name)
                    except:
                        enum = self._enum_cls(self.env)
                        enum.name = name
                        enum.insert()
                        add_notice(
                            req,
                            _(
                                'The %(field)s value "%(name)s" has '
                                'been added.',
                                field=label[0],
                                name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if enum.name is None:
                            raise TracError(
                                _('Invalid %(type)s value.', type=label[0]))
                        raise TracError(
                            _('%(type)s value "%(name)s" already '
                              'exists',
                              type=label[0],
                              name=name))

                # Remove enums
                elif req.args.get('remove'):
                    sel = req.args.get('sel')
                    if not sel:
                        raise TracError(_('No %s selected') % self._type)
                    if not isinstance(sel, list):
                        sel = [sel]

                    @self.env.with_transaction()
                    def do_remove(db):
                        for name in sel:
                            enum = self._enum_cls(self.env, name, db=db)
                            enum.delete()

                    add_notice(
                        req,
                        _(
                            'The selected %(field)s values have '
                            'been removed.',
                            field=label[0]))
                    req.redirect(req.href.admin(cat, page))

                # Apply changes
                elif req.args.get('apply'):
                    changed = [False]

                    # Set default value
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info('Setting default %s to %s', self._type,
                                      name)
                        self.config.set('ticket', 'default_%s' % self._type,
                                        name)
                        try:
                            self.config.save()
                            changed[0] = True
                        except Exception, e:
                            self.log.error('Error writing to trac.ini: %s',
                                           exception_to_unicode(e))
                            add_warning(
                                req,
                                _('Error writing to trac.ini, make '
                                  'sure it is writable by the web '
                                  'server. The default value has not '
                                  'been saved.'))

                    # Change enum values
                    order = dict([(str(int(key[6:])),
                                   str(int(req.args.get(key))))
                                  for key in req.args.keys()
                                  if key.startswith('value_')])
                    values = dict([(val, True) for val in order.values()])
                    if len(order) != len(values):
                        raise TracError(_('Order numbers must be unique'))

                    @self.env.with_transaction()
                    def do_change(db):
                        for enum in self._enum_cls.select(self.env, db=db):
                            new_value = order[enum.value]
                            if new_value != enum.value:
                                enum.value = new_value
                                enum.update()
                                changed[0] = True

                    if changed[0]:
                        add_notice(req, _('Your changes have been saved.'))
                    req.redirect(req.href.admin(cat, page))

            data.update(
                dict(enums=list(self._enum_cls.select(self.env)),
                     default=default,
                     view='list'))
Example #13
0
 def get_admin_panels(self, req):
     if all(perm in req.perm('admin', 'ticket/' + self._type)
            for perm in self._view_perms):
         yield ('ticket', _('Ticket System'), self._type,
                gettext(self._label[1]))
Example #14
0
 def get_preference_panels(self, req):
     yield ("sshkeys", gettext("SSH keys"))
Example #15
0
 def render_property(self, name, mode, context, props):
     return RenderedProperty(name=gettext(name+':'), 
             name_attributes=[("class", "property")],
             content=self._render_property(name, mode, context, props))
Example #16
0
 def get_admin_panels(self, req):
     perm = req.perm('admin', 'ticket/' + self._type)
     if 'MILESTONE_ADMIN' in perm or \
             'MILESTONE_VIEW' in perm and 'TICKET_ADMIN' in perm:
         yield ('ticket', _('Ticket System'), self._type,
                gettext(self._label[1]))
Example #17
0
    def populate_data(self, req, data):
        d = self._default_context_data.copy()
        d['trac'] = {
            'version': VERSION,
            'homepage': 'http://trac.edgewall.org/',  # FIXME: use setup data
        }

        href = req and req.href
        abs_href = req.abs_href if req else self.env.abs_href
        admin_href = None
        if self.env.project_admin_trac_url == '.':
            admin_href = href
        elif self.env.project_admin_trac_url:
            admin_href = Href(self.env.project_admin_trac_url)

        d['project'] = {
            'name': self.env.project_name,
            'descr': self.env.project_description,
            'url': self.env.project_url,
            'admin': self.env.project_admin,
            'admin_href': admin_href,
            'admin_trac_url': self.env.project_admin_trac_url,
        }
        footer = self.env.project_footer
        d['chrome'] = {
            'footer': Markup(footer and translation.gettext(footer))
        }
        if req:
            d['chrome'].update(req.chrome)
        else:
            d['chrome'].update({
                'htdocs_location': self.htdocs_location,
                'logo': self.get_logo_data(self.env.abs_href),
            })

        try:
            show_email_addresses = (self.show_email_addresses or not req
                                    or 'EMAIL_VIEW' in req.perm)
        except Exception as e:
            # simply log the exception here, as we might already be rendering
            # the error page
            self.log.error("Error during check of EMAIL_VIEW: %s",
                           exception_to_unicode(e))
            show_email_addresses = False

        def pretty_dateinfo(date, format=None, dateonly=False):
            if not date:
                return ''
            if format == 'date':
                absolute = user_time(req, format_date, date)
            else:
                absolute = user_time(req, format_datetime, date)
            now = datetime.datetime.now(localtz)
            relative = pretty_timedelta(date, now)
            if not format:
                format = req.session.get('dateinfo',
                                         self.default_dateinfo_format)
            in_or_ago = _("in %(relative)s", relative=relative) \
                        if date > now else \
                        _("%(relative)s ago", relative=relative)
            if format == 'relative':
                label = in_or_ago if not dateonly else relative
                title = absolute
            else:
                if dateonly:
                    label = absolute
                elif req.lc_time == 'iso8601':
                    label = _("at %(iso8601)s", iso8601=absolute)
                else:
                    label = _("on %(date)s at %(time)s",
                              date=user_time(req, format_date, date),
                              time=user_time(req, format_time, date))
                title = in_or_ago
            return tag.span(label, title=title)

        def dateinfo(date):
            return pretty_dateinfo(date, format='relative', dateonly=True)

        def get_rel_url(resource, **kwargs):
            return get_resource_url(self.env, resource, href, **kwargs)

        def get_abs_url(resource, **kwargs):
            return get_resource_url(self.env, resource, abs_href, **kwargs)

        d.update({
            'context':
            web_context(req) if req else None,
            'Resource':
            Resource,
            'url_of':
            get_rel_url,
            'abs_url_of':
            get_abs_url,
            'name_of':
            partial(get_resource_name, self.env),
            'shortname_of':
            partial(get_resource_shortname, self.env),
            'summary_of':
            partial(get_resource_summary, self.env),
            'req':
            req,
            'abs_href':
            abs_href,
            'href':
            href,
            'perm':
            req and req.perm,
            'authname':
            req.authname if req else '<trac>',
            'locale':
            req and req.locale,
            'show_email_addresses':
            show_email_addresses,
            'show_ip_addresses':
            self.show_ip_addresses,
            'authorinfo':
            partial(self.authorinfo, req),
            'authorinfo_short':
            self.authorinfo_short,
            'format_author':
            partial(self.format_author, req),
            'format_emails':
            self.format_emails,
            'get_systeminfo':
            self.env.get_systeminfo,
            'captioned_button':
            partial(presentation.captioned_button, req),

            # Date/time formatting
            'dateinfo':
            dateinfo,
            'pretty_dateinfo':
            pretty_dateinfo,
            'format_datetime':
            partial(user_time, req, format_datetime),
            'format_date':
            partial(user_time, req, format_date),
            'format_time':
            partial(user_time, req, format_time),
            'fromtimestamp':
            partial(datetime.datetime.fromtimestamp, tz=req and req.tz),
            'from_utimestamp':
            from_utimestamp,

            # Wiki-formatting functions
            'wiki_to':
            partial(format_to, self.env),
            'wiki_to_html':
            partial(format_to_html, self.env),
            'wiki_to_oneliner':
            partial(format_to_oneliner, self.env),
        })

        # Finally merge in the page-specific data
        d.update(data)
        return d
Example #18
0
 def get_admin_panels(self, req):
     if 'TICKET_ADMIN' in req.perm:
         yield ('ticket', _('Ticket System'), self._type,
                gettext(self._label[1]))
Example #19
0
    def _render_admin_panel(self, req, cat, page, path_info):
        label = [gettext(each) for each in self._label]
        data = {'label_singular': label[0], 'label_plural': label[1],
                'type': self._type}

        # Detail view?
        if path_info:
            enum = self._enum_cls(self.env, path_info)
            if req.method == 'POST':
                if req.args.get('save'):
                    enum.name = name = req.args.get('name')
                    try:
                        enum.update()
                    except self.env.db_exc.IntegrityError:
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))
                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
            data.update({'view': 'detail', 'enum': enum})

        else:
            default = self.config.get('ticket', 'default_%s' % self._type)
            if req.method == 'POST':
                # Add enum
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        enum = self._enum_cls(self.env, name=name)
                    except ResourceNotFound:
                        enum = self._enum_cls(self.env)
                        enum.name = name
                        enum.insert()
                        add_notice(req, _('The %(field)s value "%(name)s" '
                                          'has been added.',
                                          field=label[0], name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if enum.name is None:
                            raise TracError(_("Invalid %(type)s value.",
                                              type=label[0]))
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))

                # Remove enums
                elif req.args.get('remove'):
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No %s selected") % self._type)
                    with self.env.db_transaction:
                        for name in sel:
                            self._enum_cls(self.env, name).delete()
                            if name == default:
                                self.config.set('ticket',
                                                'default_%s' % self._type, '')
                                self.config.save()
                    add_notice(req, _("The selected %(field)s values have "
                                      "been removed.", field=label[0]))
                    req.redirect(req.href.admin(cat, page))

                # Apply changes
                elif req.args.get('apply'):
                    changed = False

                    # Set default value
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default %s to %s",
                                      self._type, name)
                        self.config.set('ticket', 'default_%s' % self._type,
                                        name)
                        try:
                            self.config.save()
                            changed = True
                        except Exception as e:
                            self.log.error("Error writing to trac.ini: %s",
                                           exception_to_unicode(e))
                            add_warning(req,
                                        _("Error writing to trac.ini, make "
                                          "sure it is writable by the web "
                                          "server. The default value has not "
                                          "been saved."))

                    # Change enum values
                    order = dict([(str(int(key[6:])),
                                   str(int(req.args.get(key)))) for key
                                  in req.args.keys()
                                  if key.startswith('value_')])
                    values = dict([(val, True) for val in order.values()])
                    if len(order) != len(values):
                        raise TracError(_("Order numbers must be unique"))
                    with self.env.db_transaction:
                        for enum in self._enum_cls.select(self.env):
                            new_value = order[enum.value]
                            if new_value != enum.value:
                                enum.value = new_value
                                enum.update()
                                changed = True

                    if changed:
                        add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))

                # Clear default
                elif req.args.get('clear'):
                    self.log.info("Clearing default %s", self._type)
                    self.config.set('ticket', 'default_%s' % self._type, '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            data.update(dict(enums=list(self._enum_cls.select(self.env)),
                             default=default, view='list'))

        Chrome(self.env).add_jquery_ui(req)
        add_script(req, 'common/js/admin_enums.js')
        return 'admin_enums.html', data
Example #20
0
    def _render_admin_panel(self, req, cat, page, path_info):
        label = [gettext(each) for each in self._label]
        data = {'label_singular': label[0], 'label_plural': label[1],
                'type': self._type}

        # Detail view?
        if path_info:
            enum = self._enum_cls(self.env, path_info)
            if req.method == 'POST':
                if req.args.get('save'):
                    enum.name = req.args.get('name')
                    enum.description = req.args.get('description')
                    enum.update()
                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
            chrome = Chrome(self.env)
            chrome.add_wiki_toolbars(req)
            chrome.add_auto_preview(req)
            data.update({'view': 'detail', 'enum': enum})

        else:
            default = self.config.get('ticket', 'default_%s' % self._type)
            if req.method == 'POST':
                # Add enum
                if req.args.get('add') and req.args.get('name'):
                    enum = self._enum_cls(self.env)
                    enum.name = req.args.get('name')
                    enum.insert()
                    add_notice(req, _('The %(field)s value "%(name)s" '
                                      'has been added.',
                                      field=label[0], name=enum.name))
                    req.redirect(req.href.admin(cat, page))

                # Remove enums
                elif req.args.get('remove'):
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No %s selected") % self._type)
                    with self.env.db_transaction:
                        for name in sel:
                            self._enum_cls(self.env, name).delete()
                            if name == default:
                                self.config.set('ticket',
                                                'default_%s' % self._type, '')
                                self.config.save()
                    add_notice(req, _("The selected %(field)s values have "
                                      "been removed.", field=label[0]))
                    req.redirect(req.href.admin(cat, page))

                # Apply changes
                elif req.args.get('apply'):
                    # Set default value
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default %s to %s",
                                      self._type, name)
                        self.config.set('ticket', 'default_%s' % self._type,
                                        name)
                        self._save_config(req)

                    # Change enum values
                    order = {str(int(key[6:])): str(req.args.getint(key))
                             for key in req.args
                             if key.startswith('value_')}
                    values = {val: True for val in order.values()}
                    if len(order) != len(values):
                        raise TracError(_("Order numbers must be unique"))
                    changed = False
                    with self.env.db_transaction:
                        for enum in self._enum_cls.select(self.env):
                            new_value = order[enum.value]
                            if new_value != enum.value:
                                enum.value = new_value
                                enum.update()
                                changed = True

                    if changed:
                        add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))

                # Clear default
                elif req.args.get('clear'):
                    self.log.info("Clearing default %s", self._type)
                    self.config.set('ticket', 'default_%s' % self._type, '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            Chrome(self.env).add_jquery_ui(req)
            add_script(req, 'common/js/admin_enums.js')
            data.update(dict(enums=list(self._enum_cls.select(self.env)),
                             default=default, view='list'))

        return 'admin_enums.html', data
Example #21
0
 def get_preference_panels(self, req):
     yield ('sshkeys', gettext('SSH keys'))
Example #22
0
    def _render_admin_panel(self, req, cat, page, path_info):
        label = [gettext(each) for each in self._label]
        data = {'label_singular': label[0], 'label_plural': label[1],
                'type': self._type}

        # Detail view?
        if path_info:
            enum = self._enum_cls(self.env, path_info)
            if req.method == 'POST':
                if req.args.get('save'):
                    enum.name = name = req.args.get('name')
                    try:
                        enum.update()
                    except self.env.db_exc.IntegrityError:
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))
                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
            data.update({'view': 'detail', 'enum': enum})

        else:
            default = self.config.get('ticket', 'default_%s' % self._type)
            if req.method == 'POST':
                # Add enum
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        enum = self._enum_cls(self.env, name=name)
                    except ResourceNotFound:
                        enum = self._enum_cls(self.env)
                        enum.name = name
                        enum.insert()
                        add_notice(req, _('The %(field)s value "%(name)s" has '
                                          'been added.',
                                          field=label[0], name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if enum.name is None:
                            raise TracError(_("Invalid %(type)s value.",
                                              type=label[0]))
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))

                # Remove enums
                elif req.args.get('remove'):
                    sel = req.args.get('sel')
                    if not sel:
                        raise TracError(_("No %s selected") % self._type)
                    if not isinstance(sel, list):
                        sel = [sel]
                    with self.env.db_transaction:
                        for name in sel:
                            self._enum_cls(self.env, name).delete()
                    add_notice(req, _("The selected %(field)s values have "
                                      "been removed.", field=label[0]))
                    req.redirect(req.href.admin(cat, page))

                # Apply changes
                elif req.args.get('apply'):
                    changed = False

                    # Set default value
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default %s to %s",
                                      self._type, name)
                        self.config.set('ticket', 'default_%s' % self._type,
                                        name)
                        try:
                            self.config.save()
                            changed = True
                        except Exception, e:
                            self.log.error("Error writing to trac.ini: %s",
                                           exception_to_unicode(e))
                            add_warning(req,
                                        _("Error writing to trac.ini, make "
                                          "sure it is writable by the web "
                                          "server. The default value has not "
                                          "been saved."))

                    # Change enum values
                    order = dict([(str(int(key[6:])),
                                   str(int(req.args.get(key)))) for key
                                  in req.args.keys()
                                  if key.startswith('value_')])
                    values = dict([(val, True) for val in order.values()])
                    if len(order) != len(values):
                        raise TracError(_("Order numbers must be unique"))
                    with self.env.db_transaction:
                        for enum in self._enum_cls.select(self.env):
                            new_value = order[enum.value]
                            if new_value != enum.value:
                                enum.value = new_value
                                enum.update()
                                changed = True

                    if changed:
                        add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))

            data.update(dict(enums=list(self._enum_cls.select(self.env)),
                             default=default, view='list'))
Example #23
0
 def test_gettext(self):
     rv = to_fragment(gettext('%(size)s bytes', size=0))
     self.assertEqual(Fragment, type(rv))
     self.assertEqual('0 bytes', unicode(rv))