def render_registration_fields(self, req, data):
        """Add a hidden text input field to the registration form, and
        a visible one with mandatory input as well, if token is configured.
        """
        if self.reg_basic_token:
            # Preserve last input for editing on failure instead of typing
            # everything again.
            old_value = req.args.get('basic_token', '')

            if self.reg_basic_question:
                # TRANSLATOR: Question-style hint for visible bot trap
                # registration input field.
                hint = tag.p(_("Please answer above: %(question)s",
                               question=self.reg_basic_question),
                             class_='hint')
            else:
                # TRANSLATOR: Verbatim token hint for visible bot trap
                # registration input field.
                hint = tag.p(tag_(
                    "Please type [%(token)s] as verification token, "
                    "exactly replicating everything within the braces.",
                    token=tag.b(self.reg_basic_token)), class_='hint')
            insert = tag(
                tag.label(_("Parole:"),
                          tag.input(type='text', name='basic_token', size=20,
                                    class_='textwidget', value=old_value)),
                hint)
        else:
            insert = None
        # TRANSLATOR: Registration form hint for hidden bot trap input field.
        insert = tag(insert,
                     tag.input(type='hidden', name='sentinel',
                               title=_("Better do not fill this field.")))
        return insert, data
Beispiel #2
0
 def _toggleBox(self, req, label, name, default):
     if self._session(req, name, default) == '1':
         checkbox = tag.input(type='checkbox',
                              id=name,
                              name=name,
                              value='true',
                              checked='checked')
     else:
         checkbox = tag.input(type='checkbox',
                              id=name,
                              name=name,
                              value='true')
     return checkbox + ' ' + tag.label(label, for_=name)
 def render_registration_fields(self, req, data):
     """Add an email address text input field to the registration form."""
     # Preserve last input for editing on failure instead of typing
     # everything again.
     old_value = req.args.get('email', '').strip()
     insert = tag.label(_("Email:"),
                        tag.input(type='text', name='email', size=20,
                                  class_='textwidget', value=old_value))
     # Deferred import required to aviod circular import dependencies.
     from acct_mgr.web_ui import AccountModule
     reset_password = AccountModule(self.env).reset_password_enabled
     verify_account = self.env.is_enabled(EmailVerificationModule) and \
                      EmailVerificationModule(self.env).verify_email
     if verify_account:
         # TRANSLATOR: Registration form hints for a mandatory input field.
         hint = tag.p(_("""
             The email address is required for Trac to send you a
             verification token.
             """), class_='hint')
         if reset_password:
             hint = tag(hint, tag.p(_("""
                 Entering your email address will also enable you to reset
                 your password if you ever forget it.
                 """), class_='hint'))
         return tag(insert, hint), data
     elif reset_password:
         # TRANSLATOR: Registration form hint, if email input is optional.
         hint = tag.p(_("""Entering your email address will enable you to
                        reset your password if you ever forget it."""),
                      class_='hint')
         return dict(optional=tag(insert, hint)), data
     else:
         # Always return the email text input itself as optional field.
         return dict(optional=insert), data
Beispiel #4
0
 def _filterBox(self, req, label, name):
     return tag.label(label,
                      tag.input(type="text",
                                name=name,
                                value=self._session(req, name, ''),
                                style_="width:60%",
                                title=_('available prefixes: contains: ~, starts with: ^, ends with: $')))
Beispiel #5
0
    def post_process_request(self, req, template, data, content_type):
        if data and req.path_info == '/timeline' and \
                'TAGS_VIEW' in req.perm(Resource('tags')):

            def realm_handler(_, node, context):
                return query.match(node, [context.realm])

            query_str = req.args.getfirst(self.key)
            if query_str is None and req.args.get('format') != 'rss':
                query_str = req.session.get('timeline.%s' % self.key)
            else:
                query_str = (query_str or '').strip()
                # Record tag query expression between visits.
                req.session['timeline.%s' % self.key] = query_str

            if data.get('events') and query_str:
                tag_system = TagSystem(self.env)
                try:
                    query = Query(query_str,
                                  attribute_handlers={'realm': realm_handler})
                except InvalidQuery as e:
                    add_warning(req, _("Tag query syntax error: %s" % e))
                else:
                    all_realms = tag_system.get_taggable_realms(req.perm)
                    query_realms = set()
                    for m in REALM_RE.finditer(query.as_string()):
                        query_realms.add(m.group(1))
                    # Don't care about resources from non-taggable realms.
                    realms = not query_realms and all_realms or \
                             query_realms.intersection(all_realms)
                    events = []
                    self.log.info("Filtering timeline events by tags '%s'",
                                   query_str)
                    for event in data['events']:
                        resource = resource_from_event(event)
                        if resource and resource.realm in realms:
                            # Shortcut view permission checks here.
                            tags = tag_system.get_tags(None, resource)
                            if query(tags, context=resource):
                                events.append(event)
                    # Overwrite with filtered list.
                    data['events'] = events
            if query_str:
                # Add current value for next form rendering.
                data[self.key] = query_str
            elif self.key in req.session:
                del req.session[self.key]

            filter_lst = []
            # xpath = '//form[@id="prefs"]/div[1]'
            xform = JTransformer('form#prefs > div:nth-of-type(1)')
            insert = builder(Markup('<br />'), tag_("matching tags "),
                             builder.input(type='text', name=self.key,
                                           value=data.get(self.key)))
            filter_lst.append(xform.append(Markup(insert)))
            add_script_data(req, {'tags_filter': filter_lst})
            add_script(req, 'tags/js/tags_jtransform.js')

        return template, data, content_type
Beispiel #6
0
 def filter_stream(self, req, method, filename, stream, data):
     if filename == 'wiki_edit.html' and 'section' in req.args and 'merge' not in req.args:
         if 'section_text' in req.args:
             section_pre, section_text, section_post = req.args.get('section_pre'), req.args.get('section_text'), req.args.get('section_post')
         else:
             section_pre, section_text, section_post = self._split_page_text(data['page'].text, req.args['section'])
             section_text = ''.join(section_text)
         
         section_element = html.input(type='hidden', name='section', id='section', value=req.args.get('section'))
         pre_element = html.input(type='hidden', name='section_pre', id='section_pre', value=''.join(section_pre))
         post_element = html.input(type='hidden', name='section_post', id='section_post', value=''.join(section_post))
         
         section_html = html(section_element, pre_element, post_element)
         stream = stream | Transformer('//textarea[@name="text"]').empty().append(section_text).before(section_html)
         stream = stream | Transformer('//div[@id="content"]//h1').append("/%s (section %s)"%(section_text[:section_text.find('\n')].strip(" = \r\n"), req.args['section']))
         if not self.preview_whole_page:
            stream = stream | Transformer('//div[@class="wikipage"]').empty().append(HTML(wiki_to_html(section_text, self.env, req)))
     return stream
Beispiel #7
0
 def filter_stream(self, req, method, filename, stream, data):
     if req.path_info == '/timeline':
         insert = builder(
             Markup('<br />'), tag_("matching tags "),
             builder.input(type='text',
                           name=self.key,
                           value=data.get(self.key)))
         xpath = '//form[@id="prefs"]/div[1]'
         stream = stream | Transformer(xpath).append(insert)
     return stream
 def render_ticket_action_control(self, req, ticket, action):
     """Returns the action control"""
     id = 'action_%s_xref' % action
     ticketnum = req.args.get(id, '')
     actions = self.get_configurable_workflow().actions
     label = actions[action]['label']
     hint = actions[action].get('xref_hint') or \
            _("The specified ticket will be cross-referenced with this "
              "ticket.")
     control = html.input(type='text', id=id, name=id, value=ticketnum)
     return label, control, hint
 def render_ticket_action_control(self, req, ticket, action):
     """Returns the action control"""
     id = 'action_%s_xref' % action
     ticketnum = req.args.get(id, '')
     actions = self.get_configurable_workflow().actions
     label = actions[action]['name']
     hint = actions[action].get('xref_hint') or \
            _("The specified ticket will be cross-referenced with this "
              "ticket.")
     control = html.input(type='text', id=id, name=id, value=ticketnum)
     return label, control, hint
Beispiel #10
0
    def filter_stream(self, req, method, filename, stream, data):
        if filename == 'wiki_edit.html' and 'section' in req.args and 'merge' not in req.args:
            if 'section_text' in req.args:
                section_pre, section_text, section_post = req.args.get(
                    'section_pre'), req.args.get('section_text'), req.args.get(
                        'section_post')
            else:
                section_pre, section_text, section_post = self._split_page_text(
                    data['page'].text, req.args['section'])
                section_text = ''.join(section_text)

            section_element = html.input(type='hidden',
                                         name='section',
                                         id='section',
                                         value=req.args.get('section'))
            pre_element = html.input(type='hidden',
                                     name='section_pre',
                                     id='section_pre',
                                     value=''.join(section_pre))
            post_element = html.input(type='hidden',
                                      name='section_post',
                                      id='section_post',
                                      value=''.join(section_post))

            section_html = html(section_element, pre_element, post_element)
            stream = stream | Transformer('//textarea[@name="text"]').empty(
            ).append(section_text).before(section_html)
            stream = stream | Transformer('//div[@id="content"]//h1').append(
                "/%s (section %s)" %
                (section_text[:section_text.find('\n')].strip(" = \r\n"),
                 req.args['section']))
            if not self.preview_whole_page:
                stream = stream | Transformer(
                    '//div[@class="wikipage"]').empty().append(
                        HTML(wiki_to_html(section_text, self.env, req)))
        return stream
    def filter_stream(self, req, method, filename, stream, data):
        if req.path_info.startswith('/register') and (
            req.method == 'GET' or
            'registration_error' in data or
                'captcha_error' in req.session):
            if not (self.private_key or self.private_key):
                return stream
            captcha_opts = tag.script("""\
var RecaptchaOptions = {
  theme: "%s",
  lang: "%s"
}""" % (self.theme, self.lang), type='text/javascript')
            captcha_js = captcha.displayhtml(
                self.public_key, use_ssl=req.scheme == 'https',
                error='reCAPTCHA incorrect. Please try again.',
                version=2
            ) + captcha.load_script(version=2)
            # First Fieldset of the registration form XPath match
            xpath_match = '//form[@id="acctmgr_registerform"]/fieldset[1]'
            return stream | Transformer(xpath_match). \
                append(captcha_opts + tag(Markup(captcha_js)))
        # Admin Configuration
        elif req.path_info.startswith('/admin/accounts/config'):
            api_html = tag.div(
                tag.label("Public Key:", for_="recaptcha_public_key") +
                tag.input(class_="textwidget", name="recaptcha_public_key",
                          value=self.public_key, size=40)
            ) + tag.div(
                tag.label("Private Key:", for_="recaptcha_private_key") +
                tag.input(class_="textwidget", name="recaptcha_private_key",
                          value=self.private_key, size=40)
            )
            if not (self.private_key or self.public_key):
                api_html = tag.div(
                    tag.a("Generate a reCAPTCHA API key for this Trac "
                          "instance domain.", target="_blank",
                          href="http://recaptcha.net/api/getkey?domain=%s&"
                          "app=TracRecaptchaRegister" %
                          req.environ.get('SERVER_NAME')
                          )
                ) + tag.br() + api_html

            theme_html = tag.div(
                tag.label("reCPATCHA theme:", for_='recaptcha_theme') +
                tag.select(
                    tag.option("Black Glass",
                               value="blackglass",
                               selected=self.theme == 'blackglass' or None) +
                    tag.option("Clean",
                               value="clean",
                               selected=self.theme == 'clean' or None) +
                    tag.option("Red",
                               value="red",
                               selected=self.theme == 'red' or None) +
                    tag.option("White",
                               value="white",
                               selected=self.theme == 'white' or None),
                    name='recaptcha_theme'
                )
            )

            language_html = tag.div(
                tag.label("reCAPTCHA language:", for_='recaptcha_lang') +
                tag.select(
                    tag.option("Dutch",
                               value="nl",
                               selected=self.lang == 'nl' or None) +
                    tag.option("English",
                               value="en",
                               selected=self.lang == 'en' or None) +
                    tag.option("French",
                               selected=self.lang == 'fr' or None) +
                    tag.option("German",
                               value="de",
                               selected=self.lang == 'de' or None) +
                    tag.option("Portuguese",
                               value="pt",
                               selected=self.lang == 'pt' or None) +
                    tag.option("Russian",
                               value="ru",
                               selected=self.lang == 'ru' or None) +
                    tag.option("Spanish",
                               value="es",
                               selected=self.lang == 'es' or None) +
                    tag.option("Turkish",
                               value="tr",
                               selected=self.lang == 'tr' or None),
                    name='recaptcha_lang'))

            # First fieldset of the Account Manager config form
            xpath_match = '//form[@id="cfg_wiz"]/fieldset[1]'

            return stream | Transformer(xpath_match). \
                before(tag.fieldset(tag.legend("reCAPTCHA") + api_html +
                                    tag.br() + theme_html + language_html))
        return stream
    def filter_stream(self, req, method, filename, stream, data):
        if not req.path_info.startswith('/ticket/'):
            return stream

        div = None
        link = None
        button = None

        if 'ticket' in data:
            # get parents data
            ticket = data['ticket']
            # title
            div = tag.div(class_='description')
            if 'TICKET_CREATE' in req.perm(ticket.resource) \
                    and ticket['status'] != 'closed':
                opt_inherit = self.env.config.getlist(
                    'subtickets', 'type.%(type)s.child_inherits' % ticket)
                if self.opt_add_style == 'link':
                    inh = {f: ticket[f] for f in opt_inherit}
                    link = tag.a(_('add'),
                                 href=req.href.newticket(parents=ticket.id,
                                                         **inh))
                    link = tag.span('(', link, ')', class_='addsubticket')
                else:
                    inh = [
                        tag.input(type='hidden', name=f, value=ticket[f])
                        for f in opt_inherit
                    ]

                    button = tag.form(tag.div(tag.input(
                        type="submit",
                        value=_("Create"),
                        title=_("Create a child ticket")),
                                              inh,
                                              tag.input(type="hidden",
                                                        name="parents",
                                                        value=str(ticket.id)),
                                              class_="inlinebuttons"),
                                      method="get",
                                      action=req.href.newticket())
            div.append(button)
            div.append(tag.h3(_('Subtickets '), link))

        if 'subtickets' in data:
            # table
            tbody = tag.tbody()
            div.append(tag.table(tbody, class_='subtickets'))
            # tickets
            self._create_subtickets_table(req, data['subtickets'], tbody)

        if div:
            add_stylesheet(req, 'subtickets/css/subtickets.css')
            '''
            If rendered in preview mode, DIV we're interested in isn't a child
            but the root and transformation won't succeed.
            According to HTML specification, id's must be unique within a
            document, so it's safe to omit the leading '.' in XPath expression
            to select all matching regardless of hierarchy their in.
            '''
            stream |= Transformer('//div[@id="ticket"]').append(div)

        return stream
Beispiel #13
0
                 if data.has_key('messages'):
                     um_data['messages'].extend(data.pop('messages'))
     
     # adding user list
     um_data.update(users = UserManager(self.env).get_active_users())
     
     # additional cells
     um_data.update(cells=list(self._get_cells(um_data['users'])))
     
     # adding usernamager's data to the data dict
     data.update(user_manager = um_data)
     
     # checking for external users
     trac_managed_users_out = self._do_import_current_users(req, dry_run=True)
     if len(trac_managed_users_out)>0:
         um_data['errors'].append(html.form(html.b(_("WARNING: ")),_(" [%s] users are not added to the team.")%(', '.join(trac_managed_users_out)),html.input(type="submit", name="um_import_current_users", value=_("Add Users")), action=req.href.admin('accounts/users'), method="post") )
     
     try:
         from acct_mgr.api import AccountManager
         data.update(account_manager = AccountManager(self.env))
     except Exception, e:
         data.update(account_manager = {'has_user':lambda x: False})
         self.log.error('Account manager not loaded')
     
     # adding stylesheets
     add_stylesheet(req, 'tracusermanager/css/admin_um.css')
     add_script(req, 'tracusermanager/js/admin_um.js')
     
     return 'admin_um.html', data    
 
 # Internal methods
Beispiel #14
0
        # adding usernamager's data to the data dict
        data.update(user_manager=um_data)

        data['sort'] = req.args.get('sort') or 'name'
        data['asc'] = req.args.get('asc') or '1'

        # checking for external users
        trac_managed_users_out = self._do_import_current_users(req,
                                                               dry_run=True)
        if len(trac_managed_users_out) > 0:
            um_data['errors'].append(
                html.form(html.b(_("WARNING: ")),
                          _(" [%s] users are not added to the team.") %
                          (', '.join(trac_managed_users_out)),
                          html.input(type="submit",
                                     name="um_import_current_users",
                                     value=_("Add Users")),
                          action=req.href.admin('accounts/users'),
                          method="post"))

        try:
            from acct_mgr.api import AccountManager
            data.update(account_manager=AccountManager(self.env))
        except Exception, e:
            data.update(account_manager={'has_user': lambda x: False})
            self.log.error('Account manager not loaded')

        # adding stylesheets
        add_stylesheet(req, 'tracusermanager/css/admin_um.css')
        add_script(req, 'tracusermanager/js/admin_um.js')
Beispiel #15
0
 def _hackedHiddenField(self):
     # Hack: shove a hidden field in so we can tell if the update
     # button has been hit.
     return tag.input(type='hidden',
                      name='user_modification',
                      value='true')