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): 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
def _version_display(self, req, milestone): resource = Resource('milestone', milestone) context = web_context(req, resource) for ver, in self.env.db_query( """ SELECT version FROM milestone_version WHERE milestone=%s """, (milestone, )): link = VisibleVersion(self.env)._render_link(context, ver, ver) return tag.span("; For ", link, class_='date') else: return []
def _append_parent_links(self, req, data, ids): links = [] for id in sorted(ids, key=lambda x: int(x)): try: ticket = Ticket(self.env, id) elem = tag.a('#%s' % id, href=req.href.ticket(id), class_='%s ticket' % ticket['status'], title=ticket['summary']) if len(links) > 0: links.append(', ') links.append(elem) except ResourceNotFound: pass for field in data.get('fields', ''): if field.get('name') == 'parents': field['rendered'] = tag.span(*links)
def expand_macro(self, formatter, name, content): attachment_type = "" if content: argv = [arg.strip() for arg in content.split(',')] if len(argv) > 0: attachment_type = argv[0] with self.env.db_transaction as db: if attachment_type is None or attachment_type == "": attachments = db(""" SELECT type,id,filename,size,time, description,author,ipnr FROM attachment """) else: attachments = db( """ SELECT type,id,filename,size,time, description,author,ipnr FROM attachment WHERE type=%s """, (attachment_type, )) formatters = { 'wiki': formatter.href.wiki, 'ticket': formatter.href.ticket, 'milestone': formatter.href.milestone, } types = { 'wiki': '', 'ticket': 'ticket ', 'milestone': 'milestone ', } return html.ul([ html.li( html.a(filename, href=formatter.href.attachment(type + '/' + id + '/' + filename)), " (", html.span(pretty_size(size), title=size), ") - added by ", html.em(author), " to ", html.a(types[type] + ' ' + id, href=formatters[type](id)), ' ') for type, id, filename, size, time, description, author, ipnr in attachments if self._has_perm(type, id, filename, formatter.context) ])
def expand_macro(self, formatter, name, content): attachment_type = "" if content: argv = [arg.strip() for arg in content.split(',')] if len(argv) > 0: attachment_type = argv[0] with self.env.db_transaction as db: if attachment_type is None or attachment_type == "": attachments = db(""" SELECT type,id,filename,size,time, description,author,ipnr FROM attachment """) else: attachments = db(""" SELECT type,id,filename,size,time, description,author,ipnr FROM attachment WHERE type=%s """, (attachment_type, )) formatters = { 'wiki': formatter.href.wiki, 'ticket': formatter.href.ticket, 'milestone': formatter.href.milestone, } types = { 'wiki': '', 'ticket': 'ticket ', 'milestone': 'milestone ', } return html.ul( [html.li( html.a(filename, href=formatter.href.attachment(type + '/' + id + '/' + filename)), " (", html.span(pretty_size(size), title=size), ") - added by ", html.em(author), " to ", html.a(types[type] + ' ' + id, href=formatters[type](id)), ' ') for type, id, filename, size, time, description, author, ipnr in attachments if self._has_perm(type, id, filename, formatter.context)])
def expand_macro(self, formatter, name, content, args=None): style_args = {'fg': 'color', 'bg': 'background-color', 'size': 'font-size'} style_values = {'color': '', 'background-color': '', 'font-size': ''} space_start = '' space_end = '' if args: text = content for k in args.keys(): style = style_args[k] if k in style_args else k style_values[style] = args.get(k) html = format_to_html(self.env, formatter.context, text) else: args = content.split(',') text = ','.join(args[:-1]) args = args[-1].split('/') + ['']*3 style_values['color'] = args.pop(0).strip() # background color is optional arg = args.pop(0).strip() if len(arg) > 0 and arg[0].isdigit(): style_values['font-size'] = arg else: style_values['background-color'] = arg style_values['font-size'] = args.pop(0).strip() html = format_to_oneliner(self.env, formatter.context, text) if text.startswith(u' '): space_start = Markup(' ') if text.endswith(u' '): space_end = Markup(' ') if style_values['font-size'].isdigit(): style_values['font-size'] = '%s%%' % style_values['font-size'] style = ';'.join('%s:%s' % (k, v) for (k, v) in style_values.iteritems() if v) span = sanitize_attrib(self.env, tag.span(style=style)) span(space_start, html, space_end) return span
def expand_macro(self, formatter, name, content): if name == 'DownloadsCount': api = self.env[DownloadsApi] # Check empty macro content. download_ids = [] if content and content.strip() != '': # Get download IDs or filenames from content. items = to_list(content) # Resolve filenames to IDs. for item in items: try: # Try if it's download ID first. download_id = int(item) if download_id: download_ids.append(download_id) else: # Any zero ID means all downloads. download_ids = [] break except ValueError: # If it wasn't ID resolve filename. download_id = api.get_download_id_from_file(item) if download_id: download_ids.append(download_id) else: self.log.debug("Could not resolve download " "filename to ID.") # Empty list mean all. if len(download_ids) == 0: download_ids = None # Ask for aggregated downloads count. self.log.debug(download_ids) count = api.get_number_of_downloads(download_ids) # Return simple <span> with result. return html.span(to_unicode(count), class_="downloads_count") elif name == 'ListDownloads': # Determine wiki page name. page_name = formatter.req.path_info[6:] or 'WikiStart' api = self.env[DownloadsApi] # Get form values. req = formatter.req order = req.args.get('order') or 'id' desc = req.args.get('desc') has_tags = self.env.is_component_enabled('tractags.api.TagEngine') visible_fields = self.config.getlist('downloads', 'visible_fields') # Prepare template data. data = { 'order': order, 'desc': desc, 'has_tags': has_tags, 'downloads': api.get_downloads(order, desc), 'visible_fields': visible_fields, 'page_name': page_name } # Return rendered template. return to_unicode( Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads': data}, 'text/html', True))
def render_macro(self, req, name, content): content = content.strip() #return tag.script('', src=self.SCRIPT_LOCATION%content, type='text/javascript') statuses = twitter.Api().GetUserTimeline(content) return tag.span("Said " + statuses[0].GetRelativeCreatedAt() + ": \"" + statuses[0].text + "\"", class_="tweet")
def expand_macro(self, formatter, name, content): if name == 'DownloadsCount': # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API component. api = self.env[DownloadsApi] # Check empty macro content. download_ids = [] if content.strip() != '': # Get download IDs or filenames from content. items = [item.strip() for item in content.split(',')] # Resolve filenames to IDs. for item in items: try: # Try if it's download ID first. download_id = int(item) if download_id: download_ids.append(download_id) else: # Any zero ID means all downloads. download_ids = [] break except ValueError: # If it wasn't ID resolve filename. download_id = api.get_download_id_from_file( context, item) if download_id: download_ids.append(download_id) else: self.log.debug( 'Could not resolve download filename' ' to ID.') # Empty list mean all. if len(download_ids) == 0: download_ids = None # Ask for aggregated downloads count. self.log.debug(download_ids) count = api.get_number_of_downloads(context, download_ids) # Return simple <span> with result. return html.span(to_unicode(count), class_="downloads_count") elif name == 'ListDownloads': self.log.debug("Rendering ListDownloads macro...") # Determine wiki page name. page_name = formatter.req.path_info[6:] or 'WikiStart' # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled( 'tractags.api.TagEngine') data['downloads'] = api.get_downloads(context, order, desc) data['visible_fields'] = [ visible_field for visible_field in self.visible_fields ] data['page_name'] = page_name # Return rendered template. return to_unicode( Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads': data}, 'text/html', True))
def expand_macro(self, formatter, name, content, args=None): # Parse optional arguments if args is None: args = parse_args(content) if len(args) > 1: args = args[1] files_core = FilesCoreComponent(self.env) node_factory, download_config = files_core.files_node_factory_and_config(formatter.req) if 'FILES_DOWNLOADS_VIEW' not in formatter.req.perm: return '' if name == 'FilesDownloadsCount': count = ProjectDownloadEntry.total_download_count(node_factory.project_id) return html.span(count, class_="files_downloads_count") elif name == 'FilesDownloads' or name == 'FilesDownloadsNarrow': is_narrow = True if name == 'FilesDownloads': is_narrow = False no_hide = False if args.has_key('no_hide') and args['no_hide'].lower() == 'true': no_hide = True only_featured = False if args.has_key('only_featured') and args['only_featured'].lower() == 'true': only_featured = True title = _('Featured downloads') if only_featured else _('Downloads') try: title = _(args['title']) except KeyError: title = _('Featured downloads') if only_featured else _('Downloads') except ValueError as e: title = _('Invalid title: %(reason)s', reason=str(e)) download_entries = ProjectDownloadEntry.get_all_download_entries(node_factory.project_id, only_featured=only_featured) downloads = [] user_store = None user_by_id = {} if not is_narrow: user_store = get_userstore() for download_entry in download_entries: if not is_narrow and not user_by_id.has_key(download_entry.uploader_id): user = user_store.getUserWhereId(download_entry.uploader_id) user_by_id[download_entry.uploader_id] = user # This doesn't check whether the node really exists node = MappedFileNode.from_download_entry(download_entry, node_factory) downloads.append(node) add_stylesheet(formatter.req, 'multiproject/css/files.css') add_script(formatter.req, 'multiproject/js/files.js') return Chrome(self.env).render_template(formatter.req, 'multiproject_files_wiki.html', {'downloads' : downloads, 'downloads_dir': download_config.downloads_dir, 'is_narrow': is_narrow, 'no_hide': no_hide, 'only_featured': only_featured, 'user_by_id': user_by_id, 'title': title, 'format_filename': format_filename}, 'text/html', True)
def expand_macro(self, formatter, name, content): if name == 'DownloadsCount': # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API component. api = self.env[DownloadsApi] # Check empty macro content. download_ids = [] if content and content.strip() != '': # Get download IDs or filenames from content. items = [item.strip() for item in content.split(',')] # Resolve filenames to IDs. for item in items: try: # Try if it's download ID first. download_id = int(item) if download_id: download_ids.append(download_id) else: # Any zero ID means all downloads. download_ids = [] break except ValueError: # If it wasn't ID resolve filename. download_id = api.get_download_id_from_file( context, item) if download_id: download_ids.append(download_id) else: self.log.debug( 'Could not resolve download filename to ID.') # Empty list mean all. if len(download_ids) == 0: download_ids = None # Ask for aggregated downloads count. self.log.debug(download_ids) count = api.get_number_of_downloads(context, download_ids) # Return simple <span> with result. return html.span(to_unicode(count), class_="downloads_count") elif name == 'ListDownloads' or name == 'FeaturedDownloads' or name == 'ListFeaturedDownloads': # Determine wiki page name. page_name = formatter.req.path_info[6:] # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') or '1' # Validate input if order not in self.all_fields: return system_message("%s: Invalid order by" % name) if desc not in ('0', '1'): return system_message("%s: Invalid desc" % name) # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled( 'tractags.api.TagEngine') if name == 'ListDownloads': data['downloads'] = api.get_downloads(context, order, desc) else: data['downloads'] = api.get_featured_downloads( context, order, desc) data['visible_fields'] = [(visible_field, None) for visible_field in self.visible_fields] data['page_name'] = page_name # Return rendered template. return to_unicode( Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads': data}, 'text/html', True)) elif name == 'CustomListDownloads' or name == 'CustomFeaturedDownloads' or name == 'CustomListFeaturedDownloads': if not content: return '' args = content.split(',') if len(args) == 0: return system_message("%s: Argument missing" % name) # Determine wiki page name. page_name = formatter.req.path_info[6:] # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') or '1' # Validate input if order not in self.all_fields: return system_message("%s: Invalid order by" % name) if desc not in ('0', '1'): return system_message("%s: Invalid desc" % name) attr_re = re.compile('(%s)=(.+)' % '|'.join(self.all_fields)) # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled( 'tractags.api.TagEngine') data['page_name'] = page_name if name == 'CustomListDownloads': data['downloads'] = api.get_downloads(context, order, desc) else: data['downloads'] = api.get_featured_downloads( context, order, desc) data['visible_fields'] = [] while args: arg = args.pop(0).strip() match = attr_re.match(arg) if match: key, val = match.groups() else: key = arg val = None if key in self.all_fields: data['visible_fields'].append((key, val)) # Return rendered template. return to_unicode( Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads': data}, 'text/html', True))
def make_menu_bar(self, req): langs = self._get_available_langs() if not langs: return [] # no need for lang menu dflt = None # default language if not self._default_in_menu: dflt = self._default_lang # add default lang for the mean of default lang page if self._default_lang not in langs: langs.append(self._default_lang) langs.sort() page = req.args.get('page', 'WikiStart') thisname, thislang = util.split_lang(page, 'default') selected = req.session.get('wiki_lang', 'default') # selected lang css = 'wikinegotiator/css/langmenu-%s.css' % self._menu_style add_stylesheet(req, css) lang_name_map = util.make_kvmap(self._lang_names) # add selected lang if need if selected not in langs: langs.append(selected) # Move 'default' to tail in menu bar if option is set or having # default_lang page other than default page. if 'default' in langs: langs.remove('default') if self._default_in_menu: langs.append('default') # always elif dflt and self._has_page(thisname, dflt) and self._has_page(thisname): # both default_lang and default page are exist. langs.append('default') # make list of menu item result = [(tag.span('Language:', title='Select a language of wiki content'), 'first')] for i, lang in enumerate(langs): cls = '' acls = '' title = '' if lang == selected: acls += 'selected' title = 'selected language' if lang == thislang or (lang == dflt and thislang == 'default' and 'default' not in langs): cls += ' active' title = 'displaying language (default)' if lang == selected == thislang: title = 'selected and displaying language' if (lang == dflt and 'default' not in langs) or lang == 'default': # map default lang to default page suffix = '' else: suffix = lang if not self._has_page(thisname, suffix): acls += ' notexist' title += ' (not available)' if i == len(langs)-1: cls += ' last' a = tag.a(lang_name_map.get(lang, lang), href=req.href.wiki('%s.%s' % (thisname, suffix)), class_=acls, title=title.strip()) result.append((a, cls)) return result
def expand_macro(self, formatter, name, content): if name == 'DownloadsCount': # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API component. api = self.env[DownloadsApi] # Check empty macro content. download_ids = [] if content.strip() != '': # Get download IDs or filenames from content. items = [item.strip() for item in content.split(',')] # Resolve filenames to IDs. for item in items: try: # Try if it's download ID first. download_id = int(item) if download_id: download_ids.append(download_id) else: # Any zero ID means all downloads. download_ids = [] break; except ValueError: # If it wasn't ID resolve filename. download_id = api.get_download_id_from_file(context, item) if download_id: download_ids.append(download_id) else: self.log.debug('Could not resolve download filename' ' to ID.') # Empty list mean all. if len(download_ids) == 0: download_ids = None # Ask for aggregated downloads count. self.log.debug(download_ids) count = api.get_number_of_downloads(context, download_ids) # Return simple <span> with result. return html.span(to_unicode(count), class_ = "downloads_count") elif name == 'ListDownloads': self.log.debug("Rendering ListDownloads macro...") # Determine wiki page name. page_name = formatter.req.path_info[6:] or 'WikiStart' # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled( 'tractags.api.TagEngine') data['downloads'] = api.get_downloads(context, order, desc) data['visible_fields'] = [visible_field for visible_field in self.visible_fields] data['page_name'] = page_name # Return rendered template. return to_unicode(Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads' : data}, 'text/html', True))
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)
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)
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)
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
def expand_macro(self, formatter, name, content): if name == 'DownloadsCount': # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API component. api = self.env[DownloadsApi] # Check empty macro content. download_ids = [] if content and content.strip() != '': # Get download IDs or filenames from content. items = [item.strip() for item in content.split(',')] # Resolve filenames to IDs. for item in items: try: # Try if it's download ID first. download_id = int(item) if download_id: download_ids.append(download_id) else: # Any zero ID means all downloads. download_ids = [] break; except ValueError: # If it wasn't ID resolve filename. download_id = api.get_download_id_from_file(context, item) if download_id: download_ids.append(download_id) else: self.log.debug('Could not resolve download filename to ID.') # Empty list mean all. if len(download_ids) == 0: download_ids = None # Ask for aggregated downloads count. self.log.debug(download_ids) count = api.get_number_of_downloads(context, download_ids) # Return simple <span> with result. return html.span(to_unicode(count), class_ = "downloads_count") elif name == 'ListDownloads' or name == 'FeaturedDownloads' or name == 'ListFeaturedDownloads': # Determine wiki page name. page_name = formatter.req.path_info[6:] # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') or '1' # Validate input if order not in self.all_fields: return system_message("%s: Invalid order by" % name) if desc not in ('0', '1'): return system_message("%s: Invalid desc" % name) # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled('tractags.api.TagEngine') if name == 'ListDownloads': data['downloads'] = api.get_downloads(context, order, desc) else: data['downloads'] = api.get_featured_downloads(context, order, desc) data['visible_fields'] = [(visible_field, None) for visible_field in self.visible_fields] data['page_name'] = page_name # Return rendered template. return to_unicode(Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads' : data}, 'text/html', True)) elif name == 'CustomListDownloads' or name == 'CustomFeaturedDownloads' or name == 'CustomListFeaturedDownloads': if not content: return '' args = content.split(',') if len(args) == 0: return system_message("%s: Argument missing" % name) # Determine wiki page name. page_name = formatter.req.path_info[6:] # Create request context. context = Context.from_request(formatter.req)('downloads-wiki') # Get database access. db = self.env.get_db_cnx() context.cursor = db.cursor() # Get API object. api = self.env[DownloadsApi] # Get form values. order = context.req.args.get('order') or 'id' desc = context.req.args.get('desc') or '1' # Validate input if order not in self.all_fields: return system_message("%s: Invalid order by" % name) if desc not in ('0', '1'): return system_message("%s: Invalid desc" % name) attr_re = re.compile('(%s)=(.+)' % '|'.join(self.all_fields)) # Prepare template data. data = {} data['order'] = order data['desc'] = desc data['has_tags'] = self.env.is_component_enabled('tractags.api.TagEngine') data['page_name'] = page_name if name == 'CustomListDownloads': data['downloads'] = api.get_downloads(context, order, desc) else: data['downloads'] = api.get_featured_downloads(context, order, desc) data['visible_fields'] = [] while args: arg = args.pop(0).strip() match = attr_re.match(arg) if match: key, val = match.groups() else: key = arg val = None if key in self.all_fields: data['visible_fields'].append((key, val)) # Return rendered template. return to_unicode(Chrome(self.env).render_template(formatter.req, 'wiki-downloads-list.html', {'downloads' : data}, 'text/html', True))
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)
def make_menu_bar(self, req): langs = self._get_available_langs() if not langs: return [] # no need for lang menu dflt = None # default language if not self._default_in_menu: dflt = self._default_lang # add default lang for the mean of default lang page if self._default_lang not in langs: langs.append(self._default_lang) langs.sort() page = req.args.get('page', 'WikiStart') thisname, thislang = util.split_lang(page, 'default') selected = req.session.get('wiki_lang', 'default') # selected lang css = 'wikinegotiator/css/langmenu-%s.css' % self._menu_style add_stylesheet(req, css) lang_name_map = util.make_kvmap(self._lang_names) # add selected lang if need if selected not in langs: langs.append(selected) # Move 'default' to tail in menu bar if option is set or having # default_lang page other than default page. if 'default' in langs: langs.remove('default') if self._default_in_menu: langs.append('default') # always elif dflt and self._has_page(thisname, dflt) and self._has_page(thisname): # both default_lang and default page are exist. langs.append('default') # make list of menu item result = [(tag.span('Language:', title='Select a language of wiki content'), 'first')] for i, lang in enumerate(langs): cls = '' acls = '' title = '' if lang == selected: acls += 'selected' title = 'selected language' if lang == thislang or (lang == dflt and thislang == 'default' and 'default' not in langs): cls += ' active' title = 'displaying language (default)' if lang == selected == thislang: title = 'selected and displaying language' if (lang == dflt and 'default' not in langs) or lang == 'default': # map default lang to default page suffix = '' else: suffix = lang if not self._has_page(thisname, suffix): acls += ' notexist' title += ' (not available)' if i == len(langs) - 1: cls += ' last' a = tag.a(lang_name_map.get(lang, lang), href=req.href.wiki('%s.%s' % (thisname, suffix)), class_=acls, title=title.strip()) result.append((a, cls)) return result