Esempio n. 1
0
def search_pages_macro(macro, environ, **kwargs):
    """
    A creole macro that lists wiki pages according to various criteria (tags only for now).
    Usage: <<PageList tags=tag1,tag2,tag3>>
    """
    from genshi import Markup
    from ductus.resource.ductmodels import tag_value_attribute_validator
    from ductus.index import search_pages

    tags = kwargs.get("tags", '')

    try:
        parsed_tags = tags.split(',')
        for tag in parsed_tags:
            tag_value_attribute_validator(tag)
    except Exception:
        return Markup('<p>Invalid tag search</p>')

    try:
        pages = search_pages(tags=parsed_tags)
    except Exception:
        return Markup('<p>Search failed</p>')

    html = ['<ul>']
    for page in pages:
        html.append('<li><a href="{0}">{1}</a></li>'.format(
            page['path'], page['absolute_pagename']))

    html.append('</ul>')
    return Markup('<p class="search_results">' + '\n'.join(html) + '</p>')
Esempio n. 2
0
def add_script(req,
               filename,
               mimetype='text/javascript',
               charset='utf-8',
               ie_if=None):
    """Add a reference to an external javascript file to the template.

    If `filename` is a network-path reference (i.e. starts with a protocol
    or `//`), the return value will not be modified. If `filename` is absolute
    (i.e. starts with `/`), the generated link will be based off the
    application root path. If it is relative, the link will be based off the
    `/chrome/` path.
    """
    scriptset = req.chrome.setdefault('scriptset', set())
    if filename in scriptset:
        return False  # Already added that script

    href = _chrome_resource_path(req, filename)
    script = {
        'href': href,
        'type': mimetype,
        'charset': charset,
        'prefix': Markup('<!--[if %s]>' % ie_if) if ie_if else None,
        'suffix': Markup('<![endif]-->') if ie_if else None
    }

    req.chrome.setdefault('scripts', []).append(script)
    scriptset.add(filename)
Esempio n. 3
0
    def GET(self):
        uri = URIRef(web.input()['uri'])
        r = MediaResource(graph, uri)
        size = r.getSize(sizes["screen"])

        try:
            created = photoCreated(graph, uri)
            prettyDate = created.date().isoformat()
        except ValueError:
            prettyDate = "(unknown date)"
            
        tmpl = loader.load("sharesingle.html")
        stream = tmpl.generate(
            title="photo",
            prettyDate=prettyDate,
            bestJqueryLink=networking.jqueryLink(
                web.ctx.environ.get('HTTP_X_FORWARDED_FOR', '')),
            featuredImg=Markup('<img src="%s" width="%s" height="%s"/>' %
                               (localSite(uri)+"?size=screen",
                                size[0], size[1])),
            loginWidget=Markup(networking.getLoginBarSync(
                web.ctx.environ.get('HTTP_COOKIE', ''))),
            actionsAllowed=[],
            otherSizeLinks=[],
            link="l",
            allowedToWriteMeta=False,
            pageJson="",
            )
        return (''.join(serializer(stream))).encode('utf8')
Esempio n. 4
0
    def _on_httperror(self, event, req, res, code, **kwargs):
        event.stop()

        self.environ.request = req
        self.environ.response = res
        data = event.data.copy()
        data["title"] = "Error"
        data["traceback"] = Markup(data["traceback"])
        data["description"] = Markup(data["description"] or u"")
        response.body = self.render("error.html", **data)

        return self.fire(response(res))
Esempio n. 5
0
def render_stream(stream, method='auto', template_name=None):
    """Render the given stream to a unicode Markup string.

    We substitute the standard XHTMLSerializer with our own
    :class:`XHTMLPlusSerializer` which is (more) HTML5-aware.

    :type stream: :class:`genshi.Stream`
    :param stream: An iterable markup stream.
    :param method: The serialization method for Genshi to use.
        If given 'auto', the default value, we assume xhtml unless
        a template name is given with an xml extension.
    :param template_name: Optional template name which we use only to
        guess what method to use, if one hasn't been explicitly provided.
    :rtype: :class:`genshi.Markup`
    :returns: A subclassed `unicode` object.

    """
    if method == 'auto':
        if template_name and template_name.endswith('.xml'):
            method = 'xml'
        else:
            method = 'xhtml'

    if method == 'xhtml':
        method = XHTMLPlusSerializer

    return Markup(stream.render(method=method, encoding=None))
Esempio n. 6
0
    def query(self, req, query='', attribute_handlers=None):
        """Return a sequence of (resource, tags) tuples matching a query.

        Query syntax is described in tractags.query.

        :param attribute_handlers: Register additional query attribute
                                   handlers. See Query documentation for more
                                   information.
        """
        def realm_handler(_, node, context):
            return query.match(node, [context.realm])

        all_attribute_handlers = {
            'realm': realm_handler,
        }
        all_attribute_handlers.update(attribute_handlers or {})
        if re.search(
                r'(expression|tagspace|tagspaces|operation|showheadings'
                '|expression)=', query):
            message = Markup(
                'You seem to be using an old Tag query. '
                'Try using the <a href="%s">new syntax</a> in your '
                '<strong>ListTagged</strong> macro.', req.href('tags'))
            add_warning(req, message)
        query = Query(query, attribute_handlers=all_attribute_handlers)

        query_tags = set(query.terms())
        for provider in self.tag_providers:
            for resource, tags in provider.get_tagged_resources(
                    req, query_tags):
                if query(tags, context=resource):
                    yield resource, tags
Esempio n. 7
0
def render_template(template_name, template_vals={}):
    loader = TemplateLoader('theme/frontend')
    template = loader.load(template_name)
    template_vals['render'] = render_template
    template_vals['Registry'] = Registry
    stream = template.generate(**template_vals)
    rendered = stream.render()
    return Markup(rendered.decode('utf-8'))
Esempio n. 8
0
def code(macro, environ, lang='text', linenos=False):
    """Macro for syntax highlighting using pygments."""
    try:
        lexer = get_lexer_by_name(lang)
    except ClassNotFound:
        return tag.div(_('No such language: {lang}').format(lang=lang),
                       class_='error')
    formatter = HtmlFormatter(linenos=linenos == 'yes')
    return Markup(highlight(macro.body, lexer, formatter))
Esempio n. 9
0
def prevnext_nav(req, prev_label, next_label, up_label=None):
    """Add Previous/Up/Next navigation links.

       :param        req: a `Request` object
       :param prev_label: the label to use for left (previous) link
       :param   up_label: the label to use for the middle (up) link
       :param next_label: the label to use for right (next) link
    """
    links = req.chrome['links']
    prev_link = next_link = None

    if not any(lnk in links
               for lnk in ('prev', 'up', 'next')):  # Short circuit
        return

    if 'prev' in links:
        prev = links['prev'][0]
        prev_link = tag.a(prev_label,
                          href=prev['href'],
                          title=prev['title'],
                          class_='prev')

    add_ctxtnav(
        req,
        tag.span(Markup('&larr; '),
                 prev_link or prev_label,
                 class_='missing' if not prev_link else None))

    if up_label and 'up' in links:
        up = links['up'][0]
        add_ctxtnav(req, tag.a(up_label, href=up['href'], title=up['title']))

    if 'next' in links:
        next_ = links['next'][0]
        next_link = tag.a(next_label,
                          href=next_['href'],
                          title=next_['title'],
                          class_='next')

    add_ctxtnav(
        req,
        tag.span(next_link or next_label,
                 Markup(' &rarr;'),
                 class_='missing' if not next_link else None))
Esempio n. 10
0
    def set_mixed_value(self, override, attrs, stream, node):
        """
        For output nodes that may either take a 'value=""' or encode
        their value in nested content.  Node value will be passed
        along as unescaped markup if child nodes are generated!

        """
        if attrs.get(H_VALUE, None) is None:
            stream = self.set_stream_value(stream, Markup(node))
        else:
            attrs = self.set_simple_value(override, attrs, node)
        return stream, attrs
Esempio n. 11
0
def global_resources():
    """ Returns a rendered Moksha Global Resource Widget.

    This widget contains all of the resources and widgets on the
    `moksha.global` entry-point.  To use it, simply do this at the bottom of
    your master template::

        ${tmpl_context.moksha_global_resources()}

    """
    import tg
    from moksha.api.widgets.global_resources import global_resources as globs
    if tg.config.default_renderer == 'genshi':
        # There's Got To Be A Better Way!
        from genshi import unescape, Markup
        return Markup(unescape(Markup(globs)))
    elif tg.config.default_renderer == 'mako':
        return globs()
    else:
        # If this gets called, and explodes, then you need to add support
        # for your templating engine here.
        return globs()
Esempio n. 12
0
def global_resources():
    """ Returns a rendered Moksha Global Resource Widget.

    This widget contains all of the resources and widgets on the
    `moksha.global` entry-point.  To use it, simply do this at the bottom of
    your master template::

        ${tmpl_context.moksha_global_resources()}

    :Warning: It must be called at the *bottom* of your template.  It must be
              the last thing that executes.  It won't inject resources for
              widgets that get displayed *after* this function is called.

    Often, you want moksha's global resources to appear on every page.
    You can override the BaseController of your app in ``yourapp.lib.base`` and
    set the following inside the __call__ method::

        from moksha.wsgi.ext.turbogears import global_resources
        tmpl_context.moksha_global_resources = global_resources

    """
    import tg
    from moksha.wsgi.widgets.api.global_resources import global_resources as globs
    globs = globs(config=tg.config, request=tg.request, base_url=tg.url('/'))

    if tg.config.default_renderer == 'genshi':
        # There's Got To Be A Better Way!
        # TODO -- consider webhelpers.literal
        from genshi import unescape, Markup
        return Markup(unescape(Markup(globs.display())))
    elif tg.config.default_renderer == 'mako':
        return globs.display()
    else:
        # If this gets called, and explodes, then you need to add support
        # for your templating engine here.
        return globs.display()
Esempio n. 13
0
def dados_adicionais_libreoffice(NFe):
    da = ''

    if hasattr(NFe.infNFe, 'infAdic'):
        if hasattr(NFe.infNFe.infAdic, 'infAdFisco'):
            da = NFe.infNFe.infAdic.infAdFisco.text.replace(
                '| ', '<text:line-break/>')

        if hasattr(NFe.infNFe.infAdic, 'infCpl'):
            if len(da) > 0:
                da += '<text:line-break/>'

            da += NFe.infNFe.infAdic.infCpl.text.replace(
                '| ', '<text:line-break/>')

    return Markup(da)
Esempio n. 14
0
def highlight(text, mime=None, lang=None, linenos=False, title=""):
    formatter = HTMLFormatter(cssclass="code",
                              linenos=linenos,
                              full=True,
                              title=title)

    try:
        if mime:
            lexer = pygments.lexers.get_lexer_for_mimetype(mime)
        elif lang:
            lexer = pygments.lexers.get_lexer_by_name(lang)
        else:
            lexer = pygments.lexers.guess_lexer(text)
    except pygments.util.ClassNotFound:
        return tag.pre(text)

    return Markup(pygments.highlight(text, lexer, formatter))
Esempio n. 15
0
    def expand_macro(self, formatter, name, content):
        citelist = getattr(formatter, CITELIST, [])
        bibdb = getattr(formatter, BIBDB, {})

        page = WikiPage(self.env, 'BibTex')
        if page.exists:
            if '{{{' in page.text and '}}}' in page.text:
                tmp = re.compile('{{{|}}}', 2).split(page.text)
                bibdb.update(extract_entries(tmp[1]))
                setattr(formatter, BIBDB, bibdb)

        str = ''
        for k in citelist:
            if bibdb.has_key(k) == False:
                str += 'No entry ' + k + ' found.\n'
        if str != '':
            raise TracError('[[' + str + ']]')

        l = []
        for k in citelist:
            content = []
            for bibkey in BIBTEX_KEYS:
                if bibdb[k].has_key(bibkey):
                    content.append(tag.span(Markup(bibdb[k][bibkey] + ', ')))
            if bibdb[k].has_key('url') == False:
                l.append(
                    tag.li(tag.a(name=k),
                           tag.a(href='#cite_%s' % k)('^'), content))
            else:
                url = bibdb[k]['url']
                l.append(
                    tag.li(tag.a(name=k),
                           tag.a(href='#cite_%s' % k)('^'), content, tag.br(),
                           tag.a(href=url)(url)))

        ol = tag.ol(*l)
        tags = []
        tags.append(tag.h1(id='References')('References'))
        tags.append(ol)

        return tag.div(id='References')(*tags)
Esempio n. 16
0
 def get_navigation_items(self, req):
     yield 'mainnav', 'tracker', Markup('<a href="%s">Tracker</a>' %
                                        (self.env.href.tracker()))
Esempio n. 17
0
    def render_template(self,
                        req,
                        filename,
                        data,
                        content_type=None,
                        fragment=False,
                        method=None):
        """Render the `filename` using the `data` for the context.

        The `content_type` argument is used to choose the kind of template
        used (`NewTextTemplate` if `'text/plain'`, `MarkupTemplate`
        otherwise), and tweak the rendering process. Doctype for `'text/html'`
        can be specified by setting the `html_doctype` attribute (default
        is `XHTML_STRICT`)

        The rendering `method` (xml, xhtml or text) may be specified and is
        inferred from the `content_type` if not specified.

        When `fragment` is specified, the (filtered) Genshi stream is
        returned.
        """
        if content_type is None:
            content_type = 'text/html'

        if method is None:
            method = {
                'text/html': 'xhtml',
                'text/plain': 'text'
            }.get(content_type, 'xml')

        if method == "xhtml":
            # Retrieve post-redirect messages saved in session
            for type_ in ['warnings', 'notices']:
                try:
                    for i in itertools.count():
                        message = Markup(
                            req.session.pop('chrome.%s.%d' % (type_, i)))
                        if message not in req.chrome[type_]:
                            req.chrome[type_].append(message)
                except KeyError:
                    pass

        template = self.load_template(filename, method=method)
        data = self.populate_data(req, data)
        data['chrome']['content_type'] = content_type

        stream = template.generate(**data)

        # Filter through ITemplateStreamFilter plugins
        if self.stream_filters:
            stream |= self._filter_stream(req, method, filename, stream, data)

        if fragment:
            return stream

        if method == 'text':
            buffer = StringIO()
            stream.render('text', out=buffer, encoding='utf-8')
            return buffer.getvalue()

        doctype = None
        if content_type == 'text/html':
            doctype = self.html_doctype
            if req.form_token:
                stream |= self._add_form_token(req.form_token)
            if not int(req.session.get('accesskeys', 0)):
                stream |= self._strip_accesskeys

        links = req.chrome.get('links')
        scripts = req.chrome.get('scripts')
        script_data = req.chrome.get('script_data')
        req.chrome['links'] = {}
        req.chrome['scripts'] = []
        req.chrome['script_data'] = {}
        data.setdefault('chrome', {}).update({
            'late_links':
            req.chrome['links'],
            'late_scripts':
            req.chrome['scripts'],
            'late_script_data':
            req.chrome['script_data'],
        })

        try:
            buffer = StringIO()
            stream.render(method,
                          doctype=doctype,
                          out=buffer,
                          encoding='utf-8')
            return buffer.getvalue().translate(_translate_nop,
                                               _invalid_control_chars)
        except Exception as e:
            # restore what may be needed by the error template
            req.chrome['links'] = links
            req.chrome['scripts'] = scripts
            req.chrome['script_data'] = script_data
            # give some hints when hitting a Genshi unicode error
            if isinstance(e, UnicodeError):
                pos = self._stream_location(stream)
                if pos:
                    location = "'%s', line %s, char %s" % pos
                else:
                    location = _("(unknown template location)")
                raise TracError(
                    _(
                        "Genshi %(error)s error while rendering "
                        "template %(location)s",
                        error=e.__class__.__name__,
                        location=location))
            raise
Esempio n. 18
0
 def escape(text, quotes=True):
     if text:
         return _escape(text, quotes=quotes)
     else:
         return Markup(u'')
Esempio n. 19
0
def informacoes_adicionais_formatadas(det):
    formatado = str(det.infAdProd).replace('|', '<text:line-break/>')
    return Markup(formatado)
Esempio n. 20
0
    def render(self,
               context,
               mimetype,
               content,
               filename=None,
               url=None,
               annotations=None,
               force_source=False):
        """Render an XHTML preview of the given `content`.

        `content` is the same as an `IHTMLPreviewRenderer.render`'s
        `content` argument.

        The specified `mimetype` will be used to select the most appropriate
        `IHTMLPreviewRenderer` implementation available for this MIME type.
        If not given, the MIME type will be infered from the filename or the
        content.

        Return a string containing the XHTML text.

        When rendering with an `IHTMLPreviewRenderer` fails, a warning is added
        to the request associated with the context (if any), unless the
        `disable_warnings` hint is set to `True`.
        """
        if not content:
            return ''
        if not isinstance(context, RenderingContext):
            raise TypeError("RenderingContext expected (since 0.11)")

        # Ensure we have a MIME type for this content
        full_mimetype = mimetype
        if not full_mimetype:
            if hasattr(content, 'read'):
                content = content.read(self.max_preview_size)
            full_mimetype = self.get_mimetype(filename, content)
        if full_mimetype:
            mimetype = ct_mimetype(full_mimetype)  # split off charset
        else:
            mimetype = full_mimetype = 'text/plain'  # fallback if not binary

        # Determine candidate `IHTMLPreviewRenderer`s
        candidates = []
        for renderer in self.renderers:
            qr = renderer.get_quality_ratio(mimetype)
            if qr > 0:
                candidates.append((qr, renderer))
        candidates.sort(lambda x, y: cmp(y[0], x[0]))

        # Wrap file-like object so that it can be read multiple times
        if hasattr(content, 'read'):
            content = Content(content, self.max_preview_size)

        # First candidate which renders successfully wins.
        # Also, we don't want to expand tabs more than once.
        expanded_content = None
        for qr, renderer in candidates:
            if force_source and not getattr(renderer, 'returns_source', False):
                continue  # skip non-source renderers in force_source mode
            if isinstance(content, Content):
                content.reset()
            try:
                ann_names = ', '.join(annotations) if annotations else \
                           'no annotations'
                self.log.debug('Trying to render HTML preview using %s [%s]',
                               renderer.__class__.__name__, ann_names)

                # check if we need to perform a tab expansion
                rendered_content = content
                if getattr(renderer, 'expand_tabs', False):
                    if expanded_content is None:
                        content = content_to_unicode(self.env, content,
                                                     full_mimetype)
                        expanded_content = content.expandtabs(self.tab_width)
                    rendered_content = expanded_content

                result = renderer.render(context, full_mimetype,
                                         rendered_content, filename, url)
                if not result:
                    continue

                if not (force_source
                        or getattr(renderer, 'returns_source', False)):
                    # Direct rendering of content
                    if isinstance(result, basestring):
                        if not isinstance(result, unicode):
                            result = to_unicode(result)
                        return Markup(to_unicode(result))
                    elif isinstance(result, Fragment):
                        return result.generate()
                    else:
                        return result

                # Render content as source code
                if annotations:
                    marks = context.req.args.get('marks') if context.req \
                            else None
                    if marks:
                        context.set_hints(marks=marks)
                    return self._render_source(context, result, annotations)
                else:
                    if isinstance(result, list):
                        result = Markup('\n').join(result)
                    return tag.div(class_='code')(tag.pre(result)).generate()

            except Exception as e:
                self.log.warning('HTML preview using %s failed: %s',
                                 renderer.__class__.__name__,
                                 exception_to_unicode(e, traceback=True))
                if context.req and not context.get_hint('disable_warnings'):
                    from trac.web.chrome import add_warning
                    add_warning(
                        context.req,
                        _("HTML preview using %(renderer)s failed (%(err)s)",
                          renderer=renderer.__class__.__name__,
                          err=exception_to_unicode(e)))
Esempio n. 21
0
def comment(match, environ):
    return Markup()
Esempio n. 22
0
 def expand_macro(self, formatter, name, content):
     add_stylesheet(formatter.req, 'dirclass/css/dirclass.css')
     return Markup('<div class="rtl">')
Esempio n. 23
0
    def _process_revtree(self, req):
        """Handle revtree generation requests"""
        tracrepos = self.env.get_repository()
        youngest = int(tracrepos.get_youngest_rev())
        oldest = max(self.oldest, int(tracrepos.get_oldest_rev()))
        if self.abstime:
            timebase = int(time.time())
        else:
            timebase = to_timestamp(tracrepos.get_changeset(youngest).date)
        revstore = RevtreeStore(self.env, req.authname, \
                                (oldest, youngest),
                                timebase, self.style)
        if req.args.has_key('reset') and req.args['reset']:
            revstore.clear(req.session)
        else:
            revstore.load(req.session)
        if req.args:
            revstore.populate(req.args)
        revstore.compute_range(timebase)
        data = revstore.get_values()

        try:
            if not revstore.can_be_rendered():
                raise EmptyRangeError
            repos = Repository(self.env, req.authname)
            repos.build(self.bcre, revstore.revrange, revstore.timerange)
            (branches, authors) = \
                self._select_parameters(repos, req, revstore)
            svgrevtree = self.rt.get_revtree(repos, req)
            if revstore['branch']:
                sbranches = [revstore['branch']]
                sbranches.extend(
                    filter(lambda t: t not in sbranches, self.trunks))
            else:
                sbranches = None
            sauthors = revstore['author'] and [revstore['author']] or None
            if revstore['showdel']:
                hidetermbranch = False
            else:
                hidetermbranch = True
            svgrevtree.create(req,
                              revisions=revstore.revrange,
                              branches=sbranches,
                              authors=sauthors,
                              hidetermbranch=hidetermbranch,
                              style=revstore['style'])
            svgrevtree.build()
            svgrevtree.render(self.scale * 0.6)
            style = req.href.chrome('revtree/css/revtree.css')
            svgstyle = '<?xml-stylesheet href="%s" type="text/css"?>' % style
            data.update({
                'svg': Markup(unicode(str(svgrevtree), 'utf-8')),
                'svgstyle': Markup(svgstyle)
            })
            # create and order the drop-down list content, starting with the
            # global values
            branches = repos.branches().keys()
            authors = repos.authors()
            # save the user parameters only if the tree can be rendered
            revstore.save(req.session)
        except EmptyRangeError:
            data.update({'errormsg': \
                         "Selected filters cannot render a revision tree"})
            # restore default parameters
            repos = Repository(self.env, req.authname)
            repos.build(self.bcre, revrange=(oldest, youngest))
            branches = repos.branches().keys()
            authors = repos.authors()

        revrange = repos.revision_range()
        revisions = self._get_ui_revisions((oldest, youngest), revrange)
        branches.sort()
        # prepend the trunks to the selected branches
        for b in filter(lambda t: t not in branches, self.trunks):
            branches.insert(0, b)
        branches = filter(None, branches)
        branches.insert(0, '')
        authors.sort()
        authors = filter(None, authors)
        authors.insert(0, '')

        dauthors = [dict(name=a, label=a or 'All') for a in authors]
        dbranches = [dict(name=b, label=b or 'All') for b in branches]

        data.update({
            'title': 'Revision Tree',
            'periods': self._get_periods(),
            'revmin': str(revrange[0]),
            'revmax': str(revrange[1]),
            'revisions': revisions,
            'branches': dbranches,
            'authors': dauthors
        })

        # add javascript for AJAX tooltips
        add_script(req, 'revtree/js/svgtip.js')
        # add custom stylesheet
        add_stylesheet(req, 'revtree/css/revtree.css')
        return 'revtree.html', {'rt': data}, 'application/xhtml+xml'
Esempio n. 24
0
def striptags(x):
    if isinstance(x, (Stream, Markup)):
        return Markup(x).striptags()
    else:
        return x
Esempio n. 25
0
    def populate_data(self, req, data):
        d = self._default_context_data.copy()
        d['trac'] = {
            'version': VERSION,
            'homepage': 'http://trac.edgewall.org/',  # FIXME: use setup data
        }

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

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

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

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

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

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

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

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

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

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

        # Finally merge in the page-specific data
        d.update(data)
        return d
Esempio n. 26
0
File: story.py Progetto: drewp/photo
def renderPage(graph, topic, foafUser, cookie):
    isVideo = {}
    photos = photosWithTopic(graph, {'topic': topic}, isVideo=isVideo)
    filtered = starFilter(graph, 'only', foafUser, photos)
    if filtered:
        photos = filtered

    tmpl = loader.load("story.html")

    rows = []
    knownFacts = set()
    commentJs = '1'
    for photo in photos:
        if not access.viewable(graph, photo, foafUser):
            log.debug("story %s NeedsMoreAccess because %s can't view %s",
                      topic, foafUser, photo)
            raise access.NeedsMoreAccess()
        try:
            date = photoCreated(graph, photo).date()
        except ValueError:
            date = None
        else:
            if not rows or rows[-1]['date'] != date:
                rows.append(dict(type='date', date=date))

        facts = json.loads(syncServiceCall('facts', photo, foafUser))
        factLines = [
            l['line'] for l in facts['factLines']
            if not l['line'].startswith("Picture taken ")
        ]
        factLines = [l for l in factLines if l not in knownFacts]
        knownFacts.update(factLines)

        commentHtml = syncServiceCall('comments',
                                      photo,
                                      foafUser,
                                      js=commentJs)
        if commentJs == '1':
            commentJs = '0'

        rows.append(
            dict(
                type='pic',
                date=date,
                uri=photo,
                # more stable than the row num as pics get added and removed:
                anchor=hashlib.md5(photo).hexdigest()[:8],
                factLines=factLines,
                isVideo=isVideo.get(photo, False),
                commentHtml=Markup(commentHtml),
                desc=graph.value(photo, RDFS.comment),
            ))

    accessControl = pystache.render(
        open("template/aclwidget.mustache").read(),
        access.accessControlWidget(graph, foafUser, topic))

    stream = tmpl.generate(
        rows=rows,
        title=graph.value(topic, RDFS.label, any=True),
        localSite=localSite,
        loginBar=Markup(networking.getLoginBarSync(cookie)),
        accessControl=Markup(accessControl),
        dateRange=findDateRange(graph, photos),
        sizeAttrs=lambda uri, sizeName: sizeAttrs(graph, foafUser, uri,
                                                  sizeName),
    )
    return (''.join(serializer(stream))).encode('utf8')
Esempio n. 27
0
 def expand_macro(self, formatter, name, content):
     add_stylesheet(formatter.req, 'newsflash/css/newsflash.css')
     return Markup('<div class="newsflash">')
Esempio n. 28
0
 def expand_macro(self, formatter, name, content):
     return Markup('</div>')
Esempio n. 29
0
def diff_blocks(fromlines,
                tolines,
                context=None,
                tabwidth=8,
                ignore_blank_lines=0,
                ignore_case=0,
                ignore_space_changes=0):
    """Return an array that is adequate for adding to the data dictionary

    See `get_filtered_hunks` for the parameter descriptions.

    See also the diff_div.html template.
    """

    type_map = {
        'replace': 'mod',
        'delete': 'rem',
        'insert': 'add',
        'equal': 'unmod'
    }

    space_re = re.compile(' ( +)|^ ')

    def htmlify(match):
        div, mod = divmod(len(match.group(0)), 2)
        return div * '&nbsp; ' + mod * '&nbsp;'

    def markup_intraline_changes(opcodes):
        for tag, i1, i2, j1, j2 in opcodes:
            if tag == 'replace' and i2 - i1 == j2 - j1:
                for i in range(i2 - i1):
                    fromline, toline = fromlines[i1 + i], tolines[j1 + i]
                    (start, end) = get_change_extent(fromline, toline)
                    if start != 0 or end != 0:
                        last = end + len(fromline)
                        fromlines[i1 + i] = (fromline[:start] + '\0' +
                                             fromline[start:last] + '\1' +
                                             fromline[last:])
                        last = end + len(toline)
                        tolines[j1 + i] = (toline[:start] + '\0' +
                                           toline[start:last] + '\1' +
                                           toline[last:])
            yield tag, i1, i2, j1, j2

    changes = []
    for group in get_filtered_hunks(fromlines, tolines, context,
                                    ignore_blank_lines, ignore_case,
                                    ignore_space_changes):
        blocks = []
        last_tag = None
        for tag, i1, i2, j1, j2 in markup_intraline_changes(group):
            if tag != last_tag:
                blocks.append({
                    'type': type_map[tag],
                    'base': {
                        'offset': i1,
                        'lines': []
                    },
                    'changed': {
                        'offset': j1,
                        'lines': []
                    }
                })
            if tag == 'equal':
                for line in fromlines[i1:i2]:
                    line = line.expandtabs(tabwidth)
                    line = space_re.sub(htmlify, escape(line, quotes=False))
                    blocks[-1]['base']['lines'].append(Markup(unicode(line)))
                for line in tolines[j1:j2]:
                    line = line.expandtabs(tabwidth)
                    line = space_re.sub(htmlify, escape(line, quotes=False))
                    blocks[-1]['changed']['lines'].append(Markup(
                        unicode(line)))
            else:
                if tag in ('replace', 'delete'):
                    for line in fromlines[i1:i2]:
                        line = expandtabs(line, tabwidth, '\0\1')
                        line = escape(line, quotes=False)
                        line = '<del>'.join([
                            space_re.sub(htmlify, seg)
                            for seg in line.split('\0')
                        ])
                        line = line.replace('\1', '</del>')
                        blocks[-1]['base']['lines'].append(
                            Markup(unicode(line)))
                if tag in ('replace', 'insert'):
                    for line in tolines[j1:j2]:
                        line = expandtabs(line, tabwidth, '\0\1')
                        line = escape(line, quotes=False)
                        line = '<ins>'.join([
                            space_re.sub(htmlify, seg)
                            for seg in line.split('\0')
                        ])
                        line = line.replace('\1', '</ins>')
                        blocks[-1]['changed']['lines'].append(
                            Markup(unicode(line)))
        changes.append(blocks)
    return changes
Esempio n. 30
0
    def expand_macro(self, formatter, name, content):
        env = formatter.env
        req = formatter.req
        if not 'VOTE_VIEW' in req.perm:
            return
        # Simplify function calls.
        format_author = partial(Chrome(self.env).format_author, req)
        if not content:
            args = []
            compact = None
            kw = {}
            top = 5
        else:
            args, kw = parse_args(content)
            compact = 'compact' in args and True
            top = as_int(kw.get('top'), 5, min=0)

        if name == 'LastVoted':
            lst = tag.ul()
            for i in self.get_votes(req, top=top):
                resource = Resource(i[0], i[1])
                # Anotate who and when.
                voted = (
                    'by %s at %s' %
                    (format_author(i[3]), format_datetime(to_datetime(i[4]))))
                lst(
                    tag.li(
                        tag.a(get_resource_description(
                            env, resource, compact and 'compact' or 'default'),
                              href=get_resource_url(env, resource,
                                                    formatter.href),
                              title=(compact and '%+i %s' % (i[2], voted)
                                     or None)),
                        (not compact and Markup(' %s %s' %
                                                (tag.b('%+i' % i[2]), voted))
                         or '')))
            return lst

        elif name == 'TopVoted':
            realm = kw.get('realm')
            lst = tag.ul()
            for i in self.get_top_voted(req, realm=realm, top=top):
                if 'up-only' in args and i[2] < 1:
                    break
                resource = Resource(i[0], i[1])
                lst(
                    tag.li(
                        tag.a(get_resource_description(
                            env, resource, compact and 'compact' or 'default'),
                              href=get_resource_url(env, resource,
                                                    formatter.href),
                              title=(compact and '%+i' % i[2] or None)),
                        (not compact and ' (%+i)' % i[2] or '')))
            return lst

        elif name == 'VoteList':
            lst = tag.ul()
            resource = resource_from_path(env, req.path_info)
            for i in self.get_votes(req, resource, top=top):
                vote = ('at %s' % format_datetime(to_datetime(i[4])))
                lst(
                    tag.li(compact and format_author(i[3]) or Markup(
                        u'%s by %s %s' %
                        (tag.b('%+i' % i[2]), tag(format_author(i[3])), vote)),
                           title=(compact and '%+i %s' % (i[2], vote)
                                  or None)))
            return lst