Esempio n. 1
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
Esempio n. 2
0
    def _version_edit(self, data):
        if data.get('milestone'):
            milestone = data.get('milestone').name
        else:
            milestone = ''
        for version, in self.env.db_query(
                """
                SELECT version FROM milestone_version WHERE milestone=%s
                """, (milestone, )):
            break
        else:
            version = None

        return tag.div(tag.label(
            'Version:', tag.br(),
            tag.select(tag.option(), [
                tag.option(name, selected=(version == name or None))
                for name, in self.env.db_query(
                    """
                        SELECT name FROM version
                        WHERE time IS NULL OR time = 0 OR time>%s OR name = %s
                        ORDER BY name""", (to_timestamp(None), version))
            ],
                       name="version")),
                       class_="field")
Esempio n. 3
0
    def expand_macro(self, formatter, name, content):
        
        data=dict(user_profiles=[], user_profile_fields={})
        rendered_result=""
        content_args={}
        layout_args={}
        user_profile_templates=[]     
        
        # collecting arguments
        if content:    
            for i, macro_args in enumerate( content.split('|') ):
                if i == 0:
                    content_args = MacroArguments( macro_args )
                    continue
                if i == 1: 
                    layout_args = MacroArguments( macro_args )
                    break
            
            # extracting userProfile attrs 
            if len(content_args)>0:
                user_profile_templates.append(User(**content_args))
                
            if len(content_args.get_list_args())>0:
                for list_item in content_args.get_list_args():
                    user_profile_templates.append(User( **MacroArguments(list_item[1:len(list_item)-1])))
        
        # adding profiles fields description 
        data['user_profile_fields'].update(UserProfileManager(self.env).get_user_profile_fields(ignore_internal=True))

        # removing picture_href
        data['user_profile_fields'].pop('picture_href')
        
        
        def inline_wiki_to_html(text):
            return wiki_to_html(text, self.env, formatter.req)
        data['wiki_to_html'] = inline_wiki_to_html
        
        # grabbing users
        if len(user_profile_templates)>0:
            data['user_profiles'] = UserManager(self.env).search_users(user_profile_templates)
        else:
            data['user_profiles'] = UserManager(self.env).get_active_users()
        
        data['cells']=list(self._get_cells(data['user_profiles']))
        
        # add stylesheet&script
        add_stylesheet(formatter.req,'tracusermanager/css/macros_um_profile.css')
        add_script(formatter.req,'tracusermanager/js/macros_um_profile.js')
        
        # render template
        template = Chrome(self.env).load_template('macro_um_profile.html',method='xhtml')
        data = Chrome(self.env).populate_data(formatter.req, {'users':data})

        rendered_result = template.generate(**data)

        # wrap everything 
        if len(layout_args)>0:
            rendered_result= html.div(rendered_result, **layout_args)

        return rendered_result
Esempio n. 4
0
    def _parent_component_select(self, req, data):
        match = re.match(r'/admin/ticket/components/(.+)$', req.path_info)
        if match:
            component = match.group(1)
            all_components = \
                [comp.name for comp in model.Component.select(self.env)]

            if component:
                cur_parent = self._ChModel.get_parent_component(component)
            else:
                cur_parent = None

            div = html.div(class_='field')
            label = html.label('%s:' % _("Parent Component"))
            label.append(html.br())

            select = html.select(id='parent_component',
                                 name='parent_component')
            select.append(html.option('', value=''))
            for comp in sorted(all_components):
                if comp != component and \
                        not self._ChModel.is_child(component, comp):
                    # Show components that aren't children of the current one
                    if cur_parent and comp == cur_parent:
                        select.append(
                            html.option(comp, value=comp, selected='selected'))
                    else:
                        select.append(html.option(comp, value=comp))

            label.append(select)
            div.append(label)
            return div
Esempio n. 5
0
 def check_syntax(self, kind, content):
     try:
         diag.get_builder(kind)().parse_string(content)
         return True
     except:
         msg = kind + 'diag: an error occurred while parsing source text.'
         msg = html.strong(msg)
         pre = html.pre(content)
         return html.div(msg, pre)
    def __call__(self, field, context):
        orig = self.base_render(field, context)
        if field != 'description':
            return orig
        if not self.event.get('author'):
            return orig
        author = self.event['author']

        return tag.div(self.generate_avatar(author), orig)
Esempio n. 7
0
 def _user_field_input(self, req):
     add_fields = tag.div(self._hackedHiddenField()
                          + self._toggleBox(req,
                                            _('Show milestone descriptions'),
                                            'show_descriptions',
                                            'true')
                          )
     add_fields += tag.br()
     add_fields += self._filterBox(req, _('Filter:  '), "inc_milestones")
     return add_fields
Esempio n. 8
0
 def filter_stream(self, req, method, filename, stream, data):
     if filename != 'wiki_view.html':
         return stream
     items = WikiNegotiator(self.env).make_menu_bar(req)
     if not items or len(items) <= 1:
         return stream
     li = []
     for content, cls in items:
         li.append(tag.li(content, class_=cls))
     insert = tag.div(tag.ul(li), id='langmenu')
     return stream | Transformer(self._menu_location).before(insert)
Esempio n. 9
0
 def filter_stream(self, req, method, filename, stream, data):
     if filename != 'wiki_view.html':
         return stream
     items = WikiNegotiator(self.env).make_menu_bar(req)
     if not items or len(items) <= 1:
         return stream
     li = []
     for content, cls in items:
         li.append(tag.li(content, class_=cls))
     insert = tag.div(tag.ul(li), id='langmenu')
     return stream | Transformer(self._menu_location).before(insert)
Esempio n. 10
0
    def expand_macro(self, formatter, name, content):
        if name == 'ViewTopic':
            self.log.debug("Rendering ViewTopic macro...")

            # Determine topic subject
            page_name = formatter.req.path_info[6:] or 'WikiStart'
            subject = content or page_name

            # Create request context.
            context = Context.from_request(formatter.req)
            context.realm = 'discussion-wiki'

            # Get database access.
            db = self.env.get_db_cnx()
            context.cursor = db.cursor()

            # Get API object.
            api = self.env[DiscussionApi]

            # Get topic by subject
            topic = api.get_topic_by_subject(context, subject)
            self.log.debug('subject: %s' % (subject,))
            self.log.debug('topic: %s' % (topic,))

            # Prepare request and resource object.
            if topic:
                context.req.args['topic'] = topic['id']
                context.resource = Resource('discussion', 'topic/%s' % (
                  topic['id'],))

            # Process discussion request.
            template, data = api.process_discussion(context)

            # Return rendered template.
            data['discussion']['mode'] = 'message-list'
            data['discussion']['page_name'] = page_name
            if context.redirect_url:
                # Generate HTML elements for redirection.
                href = context.req.href(context.redirect_url[0]) + \
                  context.redirect_url[1]
                self.log.debug("Redirecting to %s" % (href))
                return html.div(html.strong('Redirect: '),
                  ' This page redirects to ', html.a(href, href = href),
                  html.script("window.location = '" + context.req.href(
                  'discussion', 'redirect', redirect_url = href) + "'",
                  language = "JavaScript"), class_ = "system-message")
            else:
                # Render template.
                return to_unicode(Chrome(self.env).render_template(
                  formatter.req, template, data, 'text/html', True))
        else:
            raise TracError('Not implemented macro %s' % (name))
Esempio n. 11
0
    def expand_macro(self, formatter, name, content):
        
        teamRosterData=dict(userProfiles=[])
        rendered_result=""
        contentArgs={}
        layoutArgs={}
        userProfileTemplates=[]     
       
        # collecting arguments
        if content:    
            for i, macroArgs in enumerate( content.split('|') ):
                if i == 0:
                    contentArgs = MacroArguments( macroArgs )
                    self.log.error(contentArgs)
                    continue
                if i == 1: 
                    layoutArgs = MacroArguments( macroArgs )
                    break
            
            # extracting userProfile attrs 
            if len(contentArgs)>0:
                userProfileTemplates.append(UserProfile(**contentArgs))
                
            if len(contentArgs.getListArgs())>0:
                for listItem in contentArgs.getListArgs():
                    userProfileTemplates.append(UserProfile( **MacroArguments(listItem[1:len(listItem)-1])))
            
        # _fixes
        def _fixes(userProfile):
            userProfile.bio_html = wiki_to_html(userProfile.bio, self.env, formatter.req) or "[blank]"
            return userProfile
        
        # grabbing userProfiles
        if len(userProfileTemplates)>0:              
            teamRosterData['userProfiles'] = map(_fixes,UserProfilesSystem(self.env).search_userProfile(userProfileTemplates))
        else:
            teamRosterData['userProfiles'] = map(_fixes,UserProfilesSystem(self.env).get_active_userProfiles())
        
        # add stylesheet&script
        add_stylesheet(formatter.req,'tracteamroster/css/teamroster.css')
        add_script(formatter.req,'tracteamroster/js/teamroster.js')
        
        # render template
        rendered_result = Chrome(self.env).render_template(formatter.req, 'macro_teamroster_team.html', {'teamRoster':teamRosterData}, fragment=True)
            
        # wrap everything 
        if len(layoutArgs)>0:
            rendered_result= html.div(rendered_result, **layoutArgs)

        return rendered_result
Esempio n. 12
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')
    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
Esempio n. 14
0
 def get_navigation_items(self, req):
     if req.authname and req.authname != 'anonymous':
         # Use the same names as LoginModule to avoid duplicates.
         yield ('metanav', 'login', _('logged in as %(user)s',
                                      user=req.authname))
         logout_href = req.href('%s/logout' % self.auth_path_prefix)
         from pkg_resources import parse_version
         if parse_version(trac.__version__) < parse_version('1.0.2'):
             yield ('metanav', 'logout', tag.a(_('Logout'), logout_href))
         else:
             yield ('metanav', 'logout',
                    tag.form(tag.div(tag.button(_('Logout'),
                                                name='logout',
                                                type='submit')),
                             action=logout_href, method='post', id='logout',
                             class_='trac-logout'))
     else:
         yield ('metanav', 'github_login',
                tag.a(_('GitHub Login'),
                      href=req.href('%s/login' % self.auth_path_prefix)))
Esempio n. 15
0
def _get_wiki_html(env, data, is_new_ticket):
    wiki_page = is_new_ticket and NEW_TICKET_PAGE_NAME or \
                MODIFY_TICKET_PAGE_NAME
    page = WikiPage(env, wiki_page)
    if len(page.text) != 0:
        text = page.text
    else:
        if is_new_ticket:
            text = "No ticket guidelines for creating a new ticket have " \
                   "been specified. Please create [wiki:%s this wiki page] " \
                   "to specify these guidelines." \
                   % NEW_TICKET_PAGE_NAME
        else:
            text = "No ticket guidelines for modifying a ticket have been " \
                   "specified. Please create [wiki:%s this wiki page] to " \
                   "specify these guidelines." \
                   % MODIFY_TICKET_PAGE_NAME

    return html.div(format_to_html(env, data['context'], text),
                    class_='ticket-guidelines')
Esempio n. 16
0
def _get_wiki_html(env, data, is_new_ticket):
    wiki_page = is_new_ticket and NEW_TICKET_PAGE_NAME or \
                MODIFY_TICKET_PAGE_NAME
    page = WikiPage(env, wiki_page)
    if len(page.text) != 0:
        text = page.text
    else:
        if is_new_ticket:
            text = "No ticket guidelines for creating a new ticket have " \
                   "been specified. Please create [wiki:%s this wiki page] " \
                   "to specify these guidelines." \
                   % NEW_TICKET_PAGE_NAME
        else:
            text = "No ticket guidelines for modifying a ticket have been " \
                   "specified. Please create [wiki:%s this wiki page] to " \
                   "specify these guidelines." \
                   % MODIFY_TICKET_PAGE_NAME

    return html.div(format_to_html(env, data['context'], text),
                    class_='ticket-guidelines')
Esempio n. 17
0
    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
Esempio n. 18
0
    def expand_macro(self, formatter, name, content):

        teamRosterData = dict(userProfiles=[])
        rendered_result = ""
        contentArgs = {}
        layoutArgs = {}
        userProfileTemplates = []

        # collecting arguments
        if content:
            for i, macroArgs in enumerate(content.split('|')):
                if i == 0:
                    contentArgs = MacroArguments(macroArgs)
                    self.log.error(contentArgs)
                    continue
                if i == 1:
                    layoutArgs = MacroArguments(macroArgs)
                    break

            # extracting userProfile attrs
            if len(contentArgs) > 0:
                userProfileTemplates.append(UserProfile(**contentArgs))

            if len(contentArgs.getListArgs()) > 0:
                for listItem in contentArgs.getListArgs():
                    userProfileTemplates.append(
                        UserProfile(**MacroArguments(listItem[1:len(listItem) -
                                                              1])))

        # _fixes
        def _fixes(userProfile):
            userProfile.bio_html = wiki_to_html(userProfile.bio, self.env,
                                                formatter.req) or "[blank]"
            return userProfile

        # grabbing userProfiles
        if len(userProfileTemplates) > 0:
            teamRosterData['userProfiles'] = map(
                _fixes,
                UserProfilesSystem(
                    self.env).search_userProfile(userProfileTemplates))
        else:
            teamRosterData['userProfiles'] = map(
                _fixes,
                UserProfilesSystem(self.env).get_active_userProfiles())

        # add stylesheet&script
        add_stylesheet(formatter.req, 'tracteamroster/css/teamroster.css')
        add_script(formatter.req, 'tracteamroster/js/teamroster.js')

        # render template
        rendered_result = Chrome(self.env).render_template(
            formatter.req,
            'macro_teamroster_team.html', {'teamRoster': teamRosterData},
            fragment=True)

        # wrap everything
        if len(layoutArgs) > 0:
            rendered_result = html.div(rendered_result, **layoutArgs)

        return rendered_result
Esempio n. 19
0
    def render_macro(self, req, name, content):

        # Get database access.
        db = self.env.get_db_cnx()
        cursor = db.cursor()

        # Get API component.
        api = self.env[ScreenshotsApi]

        if name == 'Screenshot':
            # Check permission.
            if not req.perm.has_permission('SCREENSHOTS_VIEW'):
               return html.div('No permissions to see screenshots.',
               class_ = 'system-message')

            # Get macro arguments.
            arguments = content.split(',')

            # Get screenshot ID.
            try:
               screenshot_id = int(arguments[0])
            except:
                 raise TracError("Missing screenshot ID in macro arguments.")

            # Try to get screenshots of that ID.
            screenshot = api.get_screenshot(cursor, screenshot_id)

            # Build and return macro content.
            if screenshot:
                # Set default values of image attributes.
                attributes = {'align' : 'none',
                              'border' : '1',
                              'format' : 'raw',
                              'width' : screenshot['width'],
                              'height' : screenshot['height'],
                              'alt' : screenshot['description'],
                              'description' : self.default_description}

                # Fill attributes from macro arguments.
                for argument in arguments[1:]:
                    argument = argument.strip()
                    match = self.attributes_re.match(argument)
                    if match:
                        attributes[str(match.group(1))] = match.group(2)
                self.log.debug('attributes: %s' % (attributes,))

                # Format screenshot description from template.
                attributes['description'] = self._format_description(
                  attributes['description'], screenshot)

                # Make copy of attributes for image tag.
                img_attributes = {'align' : 'center',
                                  'style' : 'border-width: %spx;' % (
                                    attributes['border'],)}
                for attribute in attributes.keys():
                    if attribute not in ('align', 'border', 'description',
                      'format'):
                        img_attributes[attribute] = attributes[attribute]

                # Add CSS for image.
                add_stylesheet(req, 'screenshots/css/screenshots.css')

                # Build screenshot image and/or screenshot link.
                image = html.img(src = req.href.screenshots(screenshot['id'],
                  width = attributes['width'], height = attributes['height'],
                  format = 'raw'), **img_attributes)
                link = html.a(image, href = req.href.screenshots(screenshot['id'],
                  format = attributes['format']), title =
                  screenshot['description'])
                description = html.span(attributes['description'], class_ =
                  'description')
                thumbnail_class = 'thumbnail' + ((attributes['align'] == 'left')
                  and '-left' or (attributes['align'] == 'right') and '-right'
                  or '')
                thumbnail = html.span(link, ' ', description, class_ =
                  thumbnail_class, style = "width: %spx;" % (
                  int(attributes['width']) + 2 * int(attributes['border'],)))
                return thumbnail
            else:
                return html.a(screenshot_id, href = req.href.screenshots(),
                  title = content, class_ = 'missing')

        elif name == 'ScreenshotsList':
            # Check permission.
            if not req.perm.has_permission('SCREENSHOTS_VIEW'):
               return html.div('No permissions to see screenshots.',
               class_ = 'system-message')

            # Get desired list item description
            list_item_description = content or self.default_list_item

            # Get all screenshots.
            screenshots = api.get_screenshots_complete(cursor)

            # Create and return HTML list of screenshots.
            list_items = []
            for screenshot in screenshots:
                list_item = self._format_description(list_item_description,
                  screenshot)
                list_items.append(html.li(html.a(list_item, href =
                  req.href.screenshots(screenshot['id']))))
            return html.ul(list_items)
Esempio n. 20
0
    def expand_macro(self, formatter, name, content):

        env = self.env
        req = formatter.req

        content_args = {}
        data = dict(user_profiles=[], user_profile_fields={})
        layout_args = {}
        rendered_result = ""
        user_profile_templates = []

        # collecting arguments
        if content:
            for i, macro_args in enumerate(content.split('|')):
                if i == 0:
                    content_args = MacroArguments(macro_args)
                    continue
                if i == 1:
                    layout_args = MacroArguments(macro_args)
                    break

            # extracting userProfile attrs
            if len(content_args) > 0:
                user_profile_templates.append(User(**content_args))

            if len(content_args.get_list_args()) > 0:
                for list_item in content_args.get_list_args():
                    user_profile_templates.append(
                        User(**MacroArguments(list_item[1:len(list_item) -
                                                        1])))

        # adding profiles fields description
        data['user_profile_fields'].update(
            UserProfileManager(env).get_user_profile_fields(
                ignore_internal=True))

        # removing picture_href
        data['user_profile_fields'].pop('picture_href')

        def inline_wiki_to_html(text):
            return wiki_to_html(text, env, req)

        data['wiki_to_html'] = inline_wiki_to_html

        # grabbing users
        if len(user_profile_templates) > 0:
            data['user_profiles'] = UserManager(env).search_users(
                user_profile_templates)
        else:
            data['user_profiles'] = UserManager(env).get_active_users()

        data['cells'] = list(self._get_cells(req, data['user_profiles']))

        # add stylesheet&script
        add_script(req, 'tracusermanager/js/macros_um_profile.js')
        add_stylesheet(req, 'tracusermanager/css/macros_um_profile.css')

        # render template
        template = Chrome(env).load_template('macro_um_profile.html',
                                             method='xhtml')
        data = Chrome(env).populate_data(req, {'users': data})

        rendered_result = template.generate(**data)

        # wrap everything
        if len(layout_args) > 0:
            rendered_result = html.div(rendered_result, **layout_args)

        return rendered_result
Esempio n. 21
0
    def render_macro(self, req, name, content):

        # Get database access.
        db = self.env.get_db_cnx()
        cursor = db.cursor()

        # Get API component.
        api = self.env[ScreenshotsApi]

        if name == 'Screenshot':
            # Check permission.
            if not req.perm.has_permission('SCREENSHOTS_VIEW'):
                return html.div('No permissions to see screenshots.',
                                class_='system-message')

            # Get macro arguments.
            arguments = content.split(',')

            # Get screenshot ID.
            try:
                screenshot_id = int(arguments[0])
            except:
                raise TracError("Missing screenshot ID in macro arguments.")

            # Try to get screenshots of that ID.
            screenshot = api.get_screenshot(cursor, screenshot_id)

            # Build and return macro content.
            if screenshot:
                # Set default values of image attributes.
                attributes = {
                    'align': 'none',
                    'border': '1',
                    'format': 'raw',
                    'width': screenshot['width'],
                    'height': screenshot['height'],
                    'alt': screenshot['description'],
                    'description': self.default_description
                }

                # Fill attributes from macro arguments.
                for argument in arguments[1:]:
                    argument = argument.strip()
                    match = self.attributes_re.match(argument)
                    if match:
                        attributes[str(match.group(1))] = match.group(2)
                self.log.debug('attributes: %s' % (attributes, ))

                # Format screenshot description from template.
                attributes['description'] = self._format_description(
                    attributes['description'], screenshot)

                # Make copy of attributes for image tag.
                img_attributes = {
                    'align': 'center',
                    'style': 'border-width: %spx;' % (attributes['border'], )
                }
                for attribute in attributes.keys():
                    if attribute not in ('align', 'border', 'description',
                                         'format'):
                        img_attributes[attribute] = attributes[attribute]

                # Add CSS for image.
                add_stylesheet(req, 'screenshots/css/screenshots.css')

                # Build screenshot image and/or screenshot link.
                image = html.img(src=req.href.screenshots(
                    screenshot['id'],
                    width=attributes['width'],
                    height=attributes['height'],
                    format='raw'),
                                 **img_attributes)
                link = html.a(image,
                              href=req.href.screenshots(
                                  screenshot['id'],
                                  format=attributes['format']),
                              title=screenshot['description'])
                description = html.span(attributes['description'],
                                        class_='description')
                thumbnail_class = 'thumbnail' + (
                    (attributes['align'] == 'left') and '-left' or
                    (attributes['align'] == 'right') and '-right' or '')
                thumbnail = html.span(link,
                                      ' ',
                                      description,
                                      class_=thumbnail_class,
                                      style="width: %spx;" %
                                      (int(attributes['width']) +
                                       2 * int(attributes['border'], )))
                return thumbnail
            else:
                return html.a(screenshot_id,
                              href=req.href.screenshots(),
                              title=content,
                              class_='missing')

        elif name == 'ScreenshotsList':
            # Check permission.
            if not req.perm.has_permission('SCREENSHOTS_VIEW'):
                return html.div('No permissions to see screenshots.',
                                class_='system-message')

            # Get desired list item description
            list_item_description = content or self.default_list_item

            # Get all screenshots.
            screenshots = api.get_screenshots_complete(cursor)

            # Create and return HTML list of screenshots.
            list_items = []
            for screenshot in screenshots:
                list_item = self._format_description(list_item_description,
                                                     screenshot)
                list_items.append(
                    html.li(
                        html.a(list_item,
                               href=req.href.screenshots(screenshot['id']))))
            return html.ul(list_items)
Esempio n. 22
0
 def expand_macro(self, formatter, name, content):
     return html.div('Hello World, args = ', content, class_="code")
Esempio n. 23
0
    def _render_readme(self, req, stream, data):
        add_stylesheet(req, 'common/css/code.css')

        repos = data.get('repos') or self.env.get_repository()
        rev = req.args.get('rev', None)

        # Rendering all READMEs in a directory preview
        for entry in data['dir']['entries']:
            try:
                if not entry.isdir and entry.name.lower().startswith('readme'):
                    node = repos.get_node(entry.path, rev)
                    req.perm(data['context'].resource).require('FILE_VIEW')
                    mimeview = Mimeview(self.env)
                    content = node.get_content()
                    mimetype = node.content_type
                    divclass = 'searchable'
                    if entry.name.lower().endswith('.wiki'):
                        mimetype = 'text/x-trac-wiki'
                        divclass = 'searchable wiki'
                    elif entry.name.lower().endswith('.md'):
                        mimetype = 'text/x-markdown'
                        divclass = 'searchable markdown'
                    if not mimetype or mimetype == 'application/octet-stream':
                        mimetype = mimeview.get_mimetype(
                            node.name, content.read(4096)) or \
                            mimetype or 'text/plain'
                    del content
                    self.log.debug(
                        "ReadmeRenderer: rendering node %s@%s as %s",
                        node.name, rev, mimetype)
                    output = mimeview.preview_data(
                        data['context'],
                        node.get_content(),
                        node.get_content_length(),
                        mimetype,
                        node.created_path,
                        '',
                        annotations=[],
                        force_source=False)

                    if output:
                        if isinstance(output['rendered'], Stream):
                            content = output['rendered'].select('.')
                        else:
                            content = output['rendered']
                        insert = tag.div(
                            tag.h1(entry.name,
                                   tag.a(Markup(' &para;'),
                                         class_="anchor",
                                         href='#' + entry.name,
                                         title='Link to file'),
                                   id_=entry.name),
                            tag.div(content,
                                    class_=divclass,
                                    title=entry.name),
                            class_="readme",
                            style="padding-top: 1em;"
                        )
                        xpath = "//div[@id='content']/div[@id='help']"
                        stream |= Transformer(xpath).before(insert)
            except Exception, e:
                self.log.debug(to_unicode(e))
Esempio n. 24
0
    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
Esempio n. 25
0
    def expand_macro(self, formatter, name, content):

        # Create request context.
        context = Context.from_request(formatter.req)('screenshots-wiki')

        # Get database access.
        db = self.env.get_db_cnx()
        context.cursor = db.cursor()

        # Get API component.
        api = self.env[ScreenshotsApi]

        if name == 'Screenshot':
            # Check permission.
            if not formatter.req.perm.has_permission('SCREENSHOTS_VIEW'):
                return html.div(_("No permissions to see screenshots."),
                                class_='system-message')

            # Get macro arguments.
            arguments = content.split(',')

            # Get screenshot ID.
            try:
                screenshot_id = int(arguments[0])
            except:
                raise TracError(_("Missing screenshot ID in macro arguments."))

            # Try to get screenshots of that ID.
            screenshot = api.get_screenshot(context, screenshot_id)

            # Build and return macro content.
            if screenshot:
                # Set default values of image attributes.
                attributes = {
                    'align': 'none',
                    'border': '1',
                    'format': 'raw',
                    'alt': screenshot['description'],
                    'description': self.default_description
                }

                # Fill attributes from macro arguments.
                for argument in arguments[1:]:
                    argument = argument.strip()
                    match = self.attributes_re.match(argument)
                    if match:
                        attributes[str(match.group(1))] = match.group(2)

                # Zero width or height means keep original.
                if attributes.has_key('width'):
                    if attributes['width'] == 0:
                        attributes['width'] = screenshot['width']
                if attributes.has_key('height'):
                    if attributes['height'] == 0:
                        attributes['height'] = screenshot['height']

                # If one dimension is missing compute second to keep aspect.
                if not attributes.has_key('width') and \
                  attributes.has_key('height'):
                    attributes['width'] = int(
                        int(attributes['height']) *
                        (float(screenshot['width']) /
                         float(screenshot['height'])) + 0.5)
                if not attributes.has_key('height') and \
                  attributes.has_key('width'):
                    attributes['height'] = int(
                        int(attributes['width']) *
                        (float(screenshot['height']) /
                         float(screenshot['width'])) + 0.5)

                # If both dimensions are missing keep original.
                if not attributes.has_key('width') and not \
                  attributes.has_key('height'):
                    attributes['width'] = screenshot['width']
                    attributes['height'] = screenshot['height']

                self.log.debug('attributes: %s' % (attributes, ))

                # Format screenshot description from template.
                attributes['description'] = self._format_description(
                    context, attributes['description'], screenshot)

                # Make copy of attributes for image tag.
                img_attributes = {}
                for attribute in attributes.keys():
                    if attribute not in ('align', 'border', 'description',
                                         'format', 'width', 'height'):
                        img_attributes[attribute] = attributes[attribute]

                # Add CSS for image.
                add_stylesheet(formatter.req,
                               'screenshots/css/screenshots.css')

                # Build screenshot image and/or screenshot link.
                image = html.img(src=formatter.req.href.screenshots(
                    screenshot['id'],
                    format='raw',
                    width=attributes['width'],
                    height=attributes['height']),
                                 **img_attributes)
                link = html.a(image,
                              href=formatter.req.href.screenshots(
                                  screenshot['id'],
                                  format=attributes['format']),
                              title=screenshot['description'],
                              style='border-width: %spx;' %
                              (attributes['border'], ))
                width_and_border = int(attributes['width']) + 2 * \
                  int(attributes['border'])
                description = html.span(attributes['description'],
                                        class_='description',
                                        style="width: %spx;" %
                                        (width_and_border, ))
                auxilary = html.span(link,
                                     description,
                                     class_='aux',
                                     style="width: %spx;" %
                                     (width_and_border, ))
                thumbnail_class = 'thumbnail' + (
                    (attributes['align'] == 'left') and '-left' or
                    (attributes['align'] == 'right') and '-right' or '')
                thumbnail = html.span(auxilary, class_=thumbnail_class)
                return thumbnail
            else:
                return html.a(screenshot_id,
                              href=formatter.req.href.screenshots(),
                              title=content,
                              class_='missing')

        elif name == 'ScreenshotsList':
            # Check permission.
            if not formatter.req.perm.has_permission('SCREENSHOTS_VIEW'):
                return html.div(_("No permissions to see screenshots."),
                                class_='system-message')

            # Get desired list item description
            list_item_description = content or self.default_list_item

            # Get all screenshots.
            screenshots = api.get_screenshots_complete(context)

            # Create and return HTML list of screenshots.
            list_items = []
            for screenshot in screenshots:
                list_item = self._format_description(context,
                                                     list_item_description,
                                                     screenshot)
                list_items.append(
                    html.li(
                        html.a(list_item,
                               href=formatter.req.href.screenshots(
                                   screenshot['id']))))
            return html.ul(list_items)
Esempio n. 26
0
    def expand_macro(self, formatter, name, content):

        # Create request context.
        context = Context.from_request(formatter.req)('screenshots-wiki')

        # Get database access.
        db = self.env.get_db_cnx()
        context.cursor = db.cursor()

        # Get API component.
        api = self.env[ScreenshotsApi]

        if name == 'Screenshot':
            # Check permission.
            if not formatter.req.perm.has_permission('SCREENSHOTS_VIEW'):
               return html.div('No permissions to see screenshots.',
               class_ = 'system-message')

            # Get macro arguments.
            arguments = content.split(',')

            # Get screenshot ID.
            try:
               screenshot_id = int(arguments[0])
            except:
                 raise TracError("Missing screenshot ID in macro arguments.")

            # Try to get screenshots of that ID.
            screenshot = api.get_screenshot(context, screenshot_id)

            # Build and return macro content.
            if screenshot:
                # Set default values of image attributes.
                attributes = {'align' : 'none',
                              'border' : '1',
                              'format' : 'raw',
                              'alt' : screenshot['description'],
                              'description' : self.default_description}

                # Fill attributes from macro arguments.
                for argument in arguments[1:]:
                    argument = argument.strip()
                    match = self.attributes_re.match(argument)
                    if match:
                        attributes[str(match.group(1))] = match.group(2)

                # Zero width or height means keep original.
                if attributes.has_key('width'):
                    if attributes['width'] == 0:
                        attributes['width'] = screenshot['width']
                if attributes.has_key('height'):
                    if attributes['height'] == 0:
                        attributes['height'] = screenshot['height']

                # If one dimension is missing compute second to keep aspect.
                if not attributes.has_key('width') and \
                  attributes.has_key('height'):
                    attributes['width'] = int(int(attributes['height']) * (
                      float(screenshot['width']) / float(screenshot['height']))
                      + 0.5)
                if not attributes.has_key('height') and \
                  attributes.has_key('width'):
                    attributes['height'] = int(int(attributes['width']) * (
                      float(screenshot['height']) / float(screenshot['width']))
                      + 0.5)

                # If both dimensions are missing keep original.
                if not attributes.has_key('width') and not \
                  attributes.has_key('height'):
                    attributes['width'] = screenshot['width']
                    attributes['height'] = screenshot['height']

                self.log.debug('attributes: %s' % (attributes,))

                # Format screenshot description from template.
                attributes['description'] = self._format_description(context,
                  attributes['description'], screenshot)

                # Make copy of attributes for image tag.
                img_attributes = {}
                for attribute in attributes.keys():
                    if attribute not in ('align', 'border', 'description',
                      'format', 'width', 'height'):
                        img_attributes[attribute] = attributes[attribute]

                # Add CSS for image.
                add_stylesheet(formatter.req, 'screenshots/css/screenshots.css')

                # Build screenshot image and/or screenshot link.
                image = html.img(src = formatter.req.href.screenshots(
                  screenshot['id'], format = 'raw', width = attributes['width'],
                  height = attributes['height']), **img_attributes)
                link = html.a(image, href = formatter.req.href.screenshots(
                  screenshot['id'], format = attributes['format']), title =
                  screenshot['description'], style = 'border-width: %spx;' % (
                  attributes['border'],))
                width_and_border = int(attributes['width']) + 2 * \
                  int(attributes['border'])
                description = html.span(attributes['description'], class_ =
                  'description', style = "width: %spx;" % (width_and_border,))
                auxilary = html.span(link, description, class_ = 'aux',
                  style = "width: %spx;" % (width_and_border,))
                thumbnail_class = 'thumbnail' + ((attributes['align'] == 'left')
                  and '-left' or (attributes['align'] == 'right') and '-right'
                  or '')
                thumbnail = html.span(auxilary, class_ = thumbnail_class)
                return thumbnail
            else:
                return html.a(screenshot_id, href =
                  formatter.req.href.screenshots(), title = content,
                  class_ = 'missing')

        elif name == 'ScreenshotsList':
            # Check permission.
            if not formatter.req.perm.has_permission('SCREENSHOTS_VIEW'):
               return html.div('No permissions to see screenshots.',
               class_ = 'system-message')

            # Get desired list item description
            list_item_description = content or self.default_list_item

            # Get all screenshots.
            screenshots = api.get_screenshots_complete(context)

            # Create and return HTML list of screenshots.
            list_items = []
            for screenshot in screenshots:
                list_item = self._format_description(context,
                  list_item_description, screenshot)
                list_items.append(html.li(html.a(list_item, href =
                  formatter.req.href.screenshots(screenshot['id']))))
            return html.ul(list_items)
Esempio n. 27
0
    def expand_macro(self, formatter, name, content, args=None):
        class_list = ['wikiextras', 'box']
        style_list = []
        if args is None:
            content, args = parse_args(content)

        #noinspection PyArgumentList
        if not Icons(self.env).shadowless:
            class_list.append('shadow')

        class_arg = args.get('class', '')
        if class_arg:
            class_list.append(class_arg)

        align = ('right' if name in ('newsbox', 'rbox') else 'center'
                 if name == 'imagebox' else 'left' if name == 'lbox' else '')
        align = args.get('align', align)
        if align:
            class_list.append(align)

        if name == 'newsbox':
            type = 'news'
        elif name == 'imagebox':
            type = 'image'
        else:
            type = args.get('type')
            if not type:
                for flag, value in args.iteritems():
                    if value is True:
                        type = flag
                        break
            type = self._get_type(type)
        if type in self.types:
            td = self.types[type]  # type data
            if td[1]:  #icon
                class_list += ['icon', td[1]]
            else:
                class_list.append(type)
            bg = self.urgency_bg.get(td[0])
            if bg:
                class_list.append(bg)
            del td
        elif type:
            class_list.append(type)

        style = args.get('style', '')
        if style:
            style_list.append(style)

        width = args.get('width', '')
        if width:
            if width.isdigit():
                width = '%spx' % width
            if width.endswith('px'):
                # compensate for padding
                if self._has_icon(type):
                    width = '%dpx' % (int(width[:-2]) - 57)
                else:
                    width = '%dpx' % (int(width[:-2]) - 22)
            style_list.append('width:%s' % width)

        html = format_to_html(self.env, formatter.context, content)
        class_ = ' '.join(class_list)
        style = ';'.join(style_list)
        div = sanitize_attrib(self.env, tag.div(class_=class_, style=style))
        div(html)
        return div