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
    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
示例#3
0
def linebreaks(value):
    """Converts newlines in strings into <p> and <br />s."""
    if not value:
        return ''
    value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
    paras = re.split('\n{2,}', value)
    return tag(tag.p((line, tag.br) for line in para.splitlines())
               for para in paras)
示例#4
0
def create_graph_data(self, req, name=''):
    txt = req.args.get('text')
    if txt:
        actions, error_txt = get_workflow_actions_from_text(txt)
        if error_txt:
            t = error_txt
        else:
            t = "New custom workflow (not saved)"
        if not actions:
            # We should never end here...
            actions = get_workflow_config_by_type(self.config, 'default')
            t = "Custom workflow is broken. Showing default workflow"
    else:
        t = u""
        print(name)
        if name == 'default':
            actions = get_workflow_config_by_type(self.config, 'default')
        else:
            actions = get_workflow_config_by_type(self.config, name)

    states = list(set(
        [state for action in actions.itervalues()
         for state in action['oldstates']] + [action['newstate'] for action in
                                              actions.itervalues()]))

    action_labels = [action_info['label'] for action_name, action_info in
                     actions.items()]
    action_names = actions.keys()

    edges = []
    for name, action in actions.items():
        new_index = states.index(action['newstate'])
        name_index = action_names.index(name)
        for old_state in action['oldstates']:
            old_index = states.index(old_state)
            edges.append((old_index, new_index, name_index))

    args = {}
    width = args.get('width', 800)
    height = args.get('height', 600)
    graph = {'nodes': states, 'actions': action_labels, 'edges': edges,
             'width': width, 'height': height}
    graph_id = '%012x' % id(self)  # id(graph)

    scr_data = {'graph_%s' % graph_id: graph}

    res = tag(
        tag.p(t),
        tag.div('', class_='multiple-workflow-graph trac-noscript',
                id='trac-workflow-graph-%s' % graph_id,
                style="display:inline-block;width:%spx;height:%spx" %
                      (width, height)),
        tag.noscript(
            tag.div(_("Enable JavaScript to display the workflow graph."),
                    class_='system-message')))
    return res, scr_data, graph
    def expand_macro(self, formatter, name, content):
        arguments = content.split(',')
        error_hash = arguments[0]
        
        peer = SymfonyErrorPeer(self.env)
        msg = peer.retrieve_by_hash(error_hash)
        if msg:
            html_msg_h3 = html.h3('Komunikat')            
            html_msg = html.p(html.b(msg[0]))
            html_uri_h3 = html.h3('Adres strony')
            html_uri = html.p(msg[1])
            html_symfony_action = html.h3(html.span('Modul: ') + html.b(msg[2]) + html.span(' Akcja: ') + html.b(msg[3]))
            html_delete_link = html.a('Usun podobne bledy', href='/trac/bugs?delete_bug_id=' + arguments[0])
            html_error = html.div(html_msg_h3 + html_msg + html_uri_h3 + html_uri + html_symfony_action + html_delete_link, class_='ticket_symfony_box')
            return html_error
        else:
            return 'Brak bledu o podanym identyfikatorze: ' + arguments[0]

        return html_url
示例#6
0
    def expand_macro(self, formatter, name, content, args={}):
        reponame = args.get('repository') or ''
        rev_str = args.get('revision')
        repos = RepositoryManager(self.env).get_repository(reponame)
        rev = None
        try:
            changeset = repos.get_changeset(repos.normalize_rev(rev_str))
            message = changeset.message
            rev = repos.db_rev(changeset.rev)
            resource = repos.resource

            # add review status to commit message (
            review = CodeReview(self.env, reponame, rev)
            status = review.encode(review.status)
            message += '\n\n{{{#!html \n'
            message += '<div class="codereviewstatus">'
            message += '  <div class="system-message %s">' % status.lower()
            message += '    <p>Code review status: '
            message += '      <span>%s</span>' % review.status
            message += '    </p>'
            message += '  </div>'
            message += '</div>'
            message += '\n}}}'

        except Exception:
            message = content
            resource = Resource('repository', reponame)
        if formatter.context.resource.realm == 'ticket':
            ticket_re = CommitTicketUpdater.ticket_re
            if not any(
                    int(tkt_id) == int(formatter.context.resource.id)
                    for tkt_id in ticket_re.findall(message)):
                return tag.p(
                    "(The changeset message doesn't reference this "
                    "ticket)",
                    class_='hint')
        if ChangesetModule(self.env).wiki_format_messages:
            ctxt = formatter.context
            return tag.div(format_to_html(self.env,
                                          ctxt('changeset',
                                               rev,
                                               parent=resource),
                                          message,
                                          escape_newlines=True),
                           class_='message')
        else:
            return tag.pre(message, class_='message')
示例#7
0
 def __iter__(self):
     if self.this_milestone is not None:  # for /milestone/xxx
         milestone = self.this_milestone
     else:
         if len(self.buffer.events) >= 4 and len(
                 self.buffer.events[3]) >= 1:
             milestone = self.buffer.events[3][1]
         else:
             self.log.debug(
                 'see https://trac-hacks.org/ticket/13565 & 13161')
             milestone = ''
     if milestone not in self.hours.keys():
         return iter([])
     hours = self.hours[milestone]
     estimated_hours = hours['estimatedhours']
     total_hours = hours['totalhours']
     if not (estimated_hours or total_hours):
         return iter([])
     items = []
     if estimated_hours:
         if parse_version(TRAC_VERSION) < parse_version('1.0'):
             items.append(tag.dt(_("Estimated Hours:")))
             items.append(tag.dd(str(estimated_hours)))
         else:
             items.append(
                 tag.span(_("Estimated Hours: "),
                          str(estimated_hours),
                          class_="first interval"))
     date = hours['date']
     link = self.href("hours",
                      milestone=milestone,
                      from_year=date.year,
                      from_month=date.month,
                      from_day=date.day)
     if parse_version(TRAC_VERSION) < parse_version('1.0'):
         items.append(tag.dt(tag.a("Total Hours:", href=link)))
         items.append(
             tag.dd(tag.a(hours_format % total_hours, href=link)))
         return iter(tag.dl(*items))
     else:
         items.append(
             tag.span(tag.a(_("Total Hours: "),
                            hours_format % total_hours,
                            href=link),
                      class_='interval'))
         return iter(tag.p(*items, class_='legend'))
 def expand_macro(self, formatter, name, content):
     env = formatter.env
     req = formatter.req
     if not content:
         args = []
         kw = {}
     else:
         args, kw = parse_args(content)
     if name == 'ProjectStats':
         if 'wiki' in kw.keys():
             prefix = 'prefix' in kw.keys() and kw['prefix'] or None
             wiki = WikiSystem(env)
             if kw['wiki'] == 'count' or 'count' in args:
                 return tag(len(list(wiki.get_pages(prefix))))
     elif name == 'UserQuery':
         msg_no_perm = tag.p(tag_("(required %(perm)s missing)",
                                  perm=tag.strong('USER_VIEW')),
                             class_='hint')
         if 'perm' in kw.keys():
             perm_sys = PermissionSystem(self.env)
             users = perm_sys.get_users_with_permission(kw['perm'].upper())
         else:
             acct_mgr = AccountManager(env)
             users = list(set(acct_mgr.get_users()))
         if 'locked' in kw.keys() or 'locked' in args:
             guard = AccountGuard(env)
             locked = []
             for user in users:
                 if guard.user_locked(user):
                     locked.append(user)
             if kw.get('locked', 'True').lower() in ('true', 'yes', '1'):
                 users = locked
             else:
                 users = list(set(users) - set(locked))
         elif 'visit' in kw.keys() or 'visit' in args:
             if 'USER_VIEW' not in req.perm:
                 return msg_no_perm
             cols = []
             data = {'accounts': fetch_user_data(env, req), 'cls': 'wiki'}
             for col in ('email', 'name'):
                 if col in args:
                     cols.append(col)
             data['cols'] = cols
             return Chrome(env).render_template(req, 'user_table.html',
                                                data, 'text/html', True)
         if kw.get('format') == 'count' or 'count' in args:
             return tag(len(users))
         if 'USER_VIEW' not in req.perm:
             return msg_no_perm
         if 'email' in args or 'name' in args:
             # Replace username with full name, add email if available.
             for username, name, email in self.env.get_known_users():
                 if username in users:
                     if 'name' not in args or name is None:
                         name = username
                     if 'email' in args and email is not None:
                         email = ''.join(['<', email, '>'])
                         name = ' '.join([name, email])
                     if not username == name:
                         users.pop(users.index(username))
                         users.append(name)
         if not users and 'nomatch' in kw.keys():
             return format_to_oneliner(env, formatter.context,
                                       kw['nomatch'])
         users = sorted(users)
         if kw.get('format') == 'list':
             return tag.ul([
                 tag.li(Chrome(env).format_author(req, user))
                 for user in users
             ])
         else:
             # Default output format: comma-separated list.
             return tag(', '.join(
                 [Chrome(env).format_author(req, user) for user in users]))
 def expand_macro(self, formatter, name, content):
     env = formatter.env
     req = formatter.req
     if not content:
         args = []
         kw = {}
     else:
         args, kw = parse_args(content)
     if name == 'ProjectStats':
         if 'wiki' in kw.keys():
             prefix = 'prefix' in kw.keys() and kw['prefix'] or None
             wiki = WikiSystem(env)
             if kw['wiki'] == 'count' or 'count' in args:
                 return tag(len(list(wiki.get_pages(prefix))))
     elif name == 'UserQuery':
         msg_no_perm = tag.p(tag_("(required %(perm)s missing)",
                                  perm=tag.strong('USER_VIEW')),
                             class_='hint')
         if 'perm' in kw.keys():
             perm_sys = PermissionSystem(self.env)
             users = perm_sys.get_users_with_permission(kw['perm'].upper())
         else:
             acct_mgr = AccountManager(env)
             users = list(set(acct_mgr.get_users()))
         if 'locked' in kw.keys() or 'locked' in args:
             guard = AccountGuard(env)
             locked = []
             for user in users:
                 if guard.user_locked(user):
                     locked.append(user)
             if kw.get('locked', 'True').lower() in ('true', 'yes', '1'):
                 users = locked
             else:
                 users = list(set(users) - set(locked))
         elif 'visit' in kw.keys() or 'visit' in args:
             if 'USER_VIEW' not in req.perm:
                 return msg_no_perm
             cols = []
             data = {'accounts': fetch_user_data(env, req), 'cls': 'wiki'}
             for col in ('email', 'name'):
                 if col in args:
                     cols.append(col)
             data['cols'] = cols
             return Chrome(env).render_template(
                 req, 'user_table.html', data, 'text/html', True)
         if kw.get('format') == 'count' or 'count' in args:
             return tag(len(users))
         if 'USER_VIEW' not in req.perm:
             return msg_no_perm
         if 'email' in args or 'name' in args:
             # Replace username with full name, add email if available.
             for username, name, email in self.env.get_known_users():
                 if username in users:
                     if 'name' not in args or name is None:
                         name = username
                     if 'email' in args and email is not None:
                         email = ''.join(['<', email, '>'])
                         name = ' '.join([name, email])
                     if not username == name:
                         users.pop(users.index(username))
                         users.append(name)
         if not users and 'nomatch' in kw.keys():
             return format_to_oneliner(env, formatter.context,
                                       kw['nomatch'])
         users = sorted(users)
         if kw.get('format') == 'list':
             return tag.ul([tag.li(Chrome(env).format_author(req, user))
                            for user in users])
         else:
             # Default output format: comma-separated list.
             return tag(', '.join([Chrome(env).format_author(req, user)
                                   for user in users]))