Ejemplo n.º 1
0
 def __unicode__(self):
     # unbound forms should return the HTML unmodified. If this was passed
     # through htmlfill instead, all form values would be nuked.
     try:
         response_charset = response.determine_charset()
     except TypeError: # no pylons request is active
         response_charset = 'utf-8'
         
     if not self.is_bound:
         defaults = self.initial.copy()
         # using WebHelpers, boolean values cannot be True; they must be '1'
         for key, value in defaults.items():
             if value is True:
                 defaults[key] = '1'
         return literal(formencode.htmlfill.render(
             form=self.html,
             defaults=defaults,
             errors=self.errors,
             encoding=response_charset # use the proper charset
         ))
     else:
         defaults = self.data.copy()
         # using WebHelpers, boolean values cannot be True; they must be '1'
         for key, value in defaults.items():
             if value is True:
                 defaults[key] = '1'
         return literal(formencode.htmlfill.render(
             form=self.html,
             defaults=defaults,
             errors=self.errors,
             encoding=response_charset # use the proper charset
         ))
Ejemplo n.º 2
0
def get_master_style():
    if config.get('ngds.is_development', "false") == "true":
        less_file = '<link rel="stylesheet/less" type="text/css" href="/css/main.less"/>'
        less_js = ' <script type="text/javascript" src="/vendor/less/less.min.js"></script>'
        return literal('%s %s' % (less_file, less_js))

    return literal('<link rel="stylesheet" type="text/css" href="/css/main.css"/>')
Ejemplo n.º 3
0
def aloha_editable_attribute(request, obj, attr):
    val = getattr(obj, attr, '')
    pk_id = getattr(obj, obj.__pk__, '')
    if is_crm_logged_in(request):
        editable_id = '%s%s' % (obj.__pk__, attr)
        val = unicodedata.normalize('NFKD', val).encode('ascii','ignore') if val else ''
        return literal("""
                <div id="editable_{editable_id}">
                    {val}
                </div>
                <input type="hidden" id="editable_{editable_id}_type" value="attribute"/>
                <input type="hidden" id="editable_{editable_id}_objtype" value="{objtype}"/>
                <input type="hidden" id="editable_{editable_id}_module" value="{module}"/>
                <input type="hidden" id="editable_{editable_id}_attr" value="{attr}"/>
                <input type="hidden" id="editable_{editable_id}_pk_id" value="{pk_id}"/>
                <script type="text/javascript">
                    Aloha.ready( function() {{
                        Aloha.jQuery('#editable_{editable_id}').aloha();
                        Aloha.bind('aloha-editable-deactivated', pvs_aloha_onsave);
                    }} );
                </script>""".format(editable_id=editable_id,
                                    pk_id=pk_id,
                                    module=obj.__module__,
                                    attr=attr,
                                    objtype=obj.__class__.__name__,
                                    val=literal(str(val))))
    else:
        return literal(val)
Ejemplo n.º 4
0
def render_body(context,**pageargs):
    context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs)
        capture = context.get('capture', UNDEFINED)
        c = context.get('c', UNDEFINED)
        self = context.get('self', UNDEFINED)
        __M_writer = context.writer()
        # SOURCE LINE 1
        __M_writer(u'\n\n')
        # SOURCE LINE 3
        __M_writer(u'\n')
        # SOURCE LINE 4
        __M_writer(u'\n\n')
        # SOURCE LINE 6
        __M_writer(escape(literal(c.page.content)))
        __M_writer(u'\n\n')
        # SOURCE LINE 17
        __M_writer(u'\n\n')
        # SOURCE LINE 22
        __M_writer(u'\n\n')
        # SOURCE LINE 24
        if c.available_tags:
            # SOURCE LINE 25
            __M_writer(escape(literal(htmlfill.render(capture(self.tags, c.available_tags), c.selected_tags))))
            __M_writer(u'\n')
        # SOURCE LINE 27
        __M_writer(u'\n')
        # SOURCE LINE 52
        __M_writer(u'\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
Ejemplo n.º 5
0
        def _make_menu_item_handling_many_package_types(menu_item, title, **kw):
            # See ckan/lib/helpers.py:545

            _menu_items = config['routes.named_routes']
            if menu_item not in _menu_items:
                raise Exception('menu item `%s` cannot be found' % menu_item)
            item = copy.copy(_menu_items[menu_item])
            item.update(kw)
            active = h._link_active(item)

            if c.controller == 'package' and len(menu_item) > 7:
                # Guess type of package
                if request.path == '/':
                    type = 'dataset'

                else:
                    parts = [x for x in request.path.split('/') if x]
                    if len(parts[0]) == 2: # is it locale? simple check
                        type = parts[1]
                    else:
                        type = parts[0]

                active = type == menu_item[:-7] # assuming menu_item == '<type>_search'

            needed = item.pop('needed')
            for need in needed:
                if need not in kw:
                    raise Exception('menu item `%s` need parameter `%s`'
                                    % (menu_item, need))
            link = h._link_to(title, menu_item, suppress_active_class=True, **item)
            if active:
                return literal('<li class="active">') + link + literal('</li>')
            return literal('<li>') + link + literal('</li>')
Ejemplo n.º 6
0
def _make_menu_item(menu_item, title, **kw):
    ''' build a navigation item used for example breadcrumbs

    outputs <li><a href="..."></i> title</a></li>

    :param menu_item: the name of the defined menu item defined in
    config/routing as the named route of the same name
    :type menu_item: string
    :param title: text used for the link
    :type title: string
    :param **kw: additional keywords needed for creating url eg id=...

    :rtype: HTML literal

    This function is called by wrapper functions.
    '''
    _menu_items = config['routes.named_routes']
    if menu_item not in _menu_items:
        raise Exception('menu item `%s` cannot be found' % menu_item)
    item = copy.copy(_menu_items[menu_item])
    item.update(kw)
    active =  _link_active(item)
    controller = item.pop('controller')
    needed = item.pop('needed')
    for need in needed:
        if need not in kw:
            raise Exception('menu item `%s` need parameter `%s`'
                            % (menu_item, need))
    link = nav_link(title, controller, suppress_active_class=True, **item)
    if active:
        return literal('<li class="active">') + link + literal('</li>')
    return literal('<li>') + link + literal('</li>')
Ejemplo n.º 7
0
    def _generate_fields(self, request, fields_list, override_data):
        html = []
        for name in fields_list['fields']:
            field = self._fields[name]

            values = {'with_tip':self._params.get('with_tip', True)}
            values.update(field)
            data = override_data.get(name, {})
            values.update(data)

            values.pop('validator', None)
            input = InputField(name=name, **values)
            html.append(input(request))

        # Don't show empty fieldsets
        if not html:
            return ''

        title = fields_list.get('name', '')
        template_path = request.registry.settings.get(
            'pyramid_webforms.fieldset_tpl',
            'pyramid_webforms:templates/fieldset.p_wf_mako'
        )
        return literal(
            render(
                template_path,
                {
                    'fieldset_title': title,
                    'fieldset_fields': literal(''.join(html))
                },
                request
            )
        )
Ejemplo n.º 8
0
    def build_paginator(self, current_page, total_pages, base_url, query):
        next = current_page + 1
        prev = current_page - 1
        rand = random.randint(1, total_pages)

        at_start = (current_page <= 1 or total_pages <= 1)
        at_end = current_page >= total_pages

        first_html  = "First" if at_start else self.gen_page_link(base_url, query, 1, "First")
        prev_html   = "Prev"  if at_start else self.gen_page_link(base_url, query, prev, "Prev")
        random_html =                          self.gen_page_link(base_url, query, rand, "Random")
        next_html   = "Next"  if at_end   else self.gen_page_link(base_url, query, next, "Next")
        last_html   = "Last"  if at_end   else self.gen_page_link(base_url, query, total_pages, "Last")

        start = max(current_page - 5, 1)
        end = min(start+10, total_pages)

        pages = []
        for n in range(start, end):
            pages.append(self.gen_page_link_block(base_url, query, n, current_page, str(n)))

        return (
            literal(" | ").join([first_html, prev_html, random_html, next_html, last_html]) +
            literal("<br>") +
            literal(" | ").join(pages)
        )
Ejemplo n.º 9
0
Archivo: page.py Proyecto: shish/shimpy
    def add_auto_html_headers(self):
        # 404/static handler will map these to themes/foo/bar.ico or lib/static/bar.ico
        self.add_html_header(literal("<link rel='icon' type='image/x-icon' href='/favicon.ico'>"))
        self.add_html_header(literal("<link rel='apple-touch-icon' href='/apple-touch-icon.png'>"))

        theme = context.config.get("theme", "default")

        # TODO: concatenate files
        for css in (
            glob("shimpy/static/*.css") +
            glob("shimpy/ext/*/style.css") +
            glob("shimpy/theme/%s/*.css" % theme)
        ):
            mtime = os.stat(css).st_mtime
            css = css.replace("shimpy/static/", "")
            css = css.replace("shimpy/theme/%s/" % theme, "")
            self.add_html_header(literal("<link rel='stylesheet' href='/static/%s?ts=%d' type='text/css'>") % (css, mtime))

        for js in (
            glob("shimpy/static/*.js") +
            glob("shimpy/ext/*/script.css") +
            glob("shimpy/theme/%s/script.js" % theme)
        ):
            mtime = os.stat(js).st_mtime
            js = js.replace("shimpy/static/", "")
            js = js.replace("shimpy/theme/%s/" % theme, "")
            self.add_html_header(literal("<script src='/static/%s?ts=%d'></script>") % (js, mtime))
Ejemplo n.º 10
0
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        try:
            template_path, template_type = render_.template_info(template_name)
        except render_.TemplateNotFound:
            template_type = 'genshi'
            template_path = ''

        # snippets should not pass the context
        # but allow for legacy genshi templates
        if renderer == 'snippet' and template_type != 'genshi':
            del globs['c']
            del globs['tmpl_context']

        log.debug('rendering %s [%s]' % (template_path, template_type))
        if config.get('debug'):
            context_vars = globs.get('c')
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {'template_name': template_name,
                          'template_path': template_path,
                          'template_type': template_type,
                          'vars': globs,
                          'c_vars': context_vars,
                          'renderer': renderer}
            if 'CKAN_DEBUG_INFO' not in request.environ:
                request.environ['CKAN_DEBUG_INFO'] = []
            request.environ['CKAN_DEBUG_INFO'].append(debug_info)

        # Jinja2 templates
        if template_type == 'jinja2':
            # We don't want to have the config in templates it should be
            # accessed via g (app_globals) as this gives us flexability such
            # as changing via database settings.
            del globs['config']
            # TODO should we raise error if genshi filters??
            return render_jinja2(template_name, globs)

        # Genshi templates
        template = globs['app_globals'].genshi_loader.load(
            template_name.encode('utf-8'), cls=loader_class
        )
        stream = template.generate(**globs)

        for item in p.PluginImplementations(p.IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(stream.render(method=method, encoding=None,
                                     strip_whitespace=True))
Ejemplo n.º 11
0
def _SI_number_span_close(number):
    ''' outputs a span with the number in SI unit eg 14700 -> 14.7k '''
    number = int(number)
    if number < 1000:
        output = literal('<span>')
    else:
        output = literal('<span title="' + formatters.localised_number(number) + '">')
    return output + formatters.localised_SI_number(number) + literal('</span>')
Ejemplo n.º 12
0
def SI_number_span(number):
    """ outputs a span with the number in SI unit eg 14700 -> 14.7k """
    number = int(number)
    if number < 1000:
        output = literal("<span>")
    else:
        output = literal('<span title="' + formatters.localised_number(number) + '">')
    return output + formatters.localised_SI_number(number) + literal("</span>")
Ejemplo n.º 13
0
 def display_page(self, page, image, parts):
     page.heading = " ".join([t.name for t in image.tags])
     page.title = "Image %d: %s" % (image.id, page.heading)
     page.add_html_header(literal("<meta name=\"keywords\" content=\"%s\">") % image.tags_plain_text.replace(" ", ", "))
     page.add_html_header(literal("<meta property=\"og:title\" content=\"%s\">") % image.title)
     page.add_html_header(literal("<meta property=\"og:type\" content=\"article\">"))
     page.add_html_header(literal("<meta property=\"og:image\" content=\"%s\">") % image.thumb_url)
     page.add_html_header(literal("<meta property=\"og:url\" content=\"%s\">") % image.page_url)
Ejemplo n.º 14
0
def gravatar(email, _class=None, size=48, default_type='identicon'):
    if _class:
        return literal('<img src="' + \
                get_gravatar_url(email, size, default_type) + \
                '" class="' + _class + '" />')
    else:
        return literal('<img src="' + \
                get_gravatar_url(email, size, default_type) + '" />')
Ejemplo n.º 15
0
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs["actions"] = model.Action

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs["url"]

        try:
            template_path, template_type = lib.render.template_info(template_name)
        except lib.render.TemplateNotFound:
            template_type = "genshi"
            template_path = ""

        # snippets should not pass the context
        # but allow for legacy genshi templates
        if renderer == "snippet" and template_type != "genshi":
            del globs["c"]
            del globs["tmpl_context"]

        log.debug("rendering %s [%s]" % (template_path, template_type))
        if config.get("debug"):
            context_vars = globs.get("c")
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {
                "template_name": template_name,
                "template_path": template_path,
                "template_type": template_type,
                "vars": globs,
                "c_vars": context_vars,
                "renderer": renderer,
            }
            if "CKAN_DEBUG_INFO" not in request.environ:
                request.environ["CKAN_DEBUG_INFO"] = []
            request.environ["CKAN_DEBUG_INFO"].append(debug_info)

        # Jinja2 templates
        if template_type == "jinja2":
            # We don't want to have the config in templates it should be
            # accessed via g (app_globals) as this gives us flexability such
            # as changing via database settings.
            del globs["config"]
            # TODO should we raise error if genshi filters??
            return render_jinja2(template_name, globs)

        # Genshi templates
        template = globs["app_globals"].genshi_loader.load(template_name, cls=loader_class)
        stream = template.generate(**globs)

        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(stream.render(method=method, encoding=None, strip_whitespace=True))
Ejemplo n.º 16
0
    def __call__(self, request, name=None, value=None, selected=None,
                 title=None, tip=None, data=None, **kwargs):
        # self.kw is global so we need thread-local kw dictionary here
        kw = {}
        if data is None:
            data = {}
        if title is None:
            title = self.title
        if tip is None:
            tip = self.tip

        if self.type == 'html':
            input = value or self.value
        else:
            kw.update(self.kw)
            kw.update(**data)

            if name is None:
                name = self.name

            kwargs = self.__getattribute__('_prepare_{}'.format(self.type))()
            with_tip = self.kw.get('with_tip', kwargs.get('with_tip', True))
            kwargs['class_'] = '{var}{const}'.format(
                var=kwargs.get('class_', self.type),
                const=(with_tip and ' with-tip' or '')
            )
            kwargs.update(self.kw.get('html5_attrs', {}))
            input = tags.__dict__[self.tag_type](**kwargs)

        extra_html = literal(kw.pop('extra_html', ''))
        tip_escape = kw.pop('tip_escape', False)
        input_only = kw.pop('input_only', False)

        if input_only:
            # input is already a literal type
            return input

        error = request.tmpl_context.form_errors.get(name, '')
        if error:
            error = field_error(request, error)
        template_path = request.registry.settings.get(
            'pyramid_webforms.field_tpl',
            'pyramid_webforms:templates/field.p_wf_mako'
        )
        return literal(
            render(template_path,
                {
                    'field_name': name,
                    'field_title': title,
                    'field_error_message': error,
                    'field_input': input,
                    'field_tip': self.tooltip(request, tip, tip_escape),
                    'field_extras': extra_html
                },
                request
            )
        )
Ejemplo n.º 17
0
def test_lit_re():
    lit = literal('This is a <string>')
    unlit = 'This is also a <string>'

    result = lit_sub(r'<str', literal('<b'), lit)
    eq_(u'This is a <bing>', escape(result))

    result = lit_sub(r'a <str', 'a <b> <b', unlit)
    eq_(u'This is also a &lt;b&gt; &lt;bing&gt;', escape(result))
Ejemplo n.º 18
0
def test_lit_re():
    lit = literal("This is a <string>")
    unlit = "This is also a <string>"

    result = lit_sub(r"<str", literal("<b"), lit)
    assert u"This is a <bing>" == escape(result)

    result = lit_sub(r"a <str", "a <b> <b", unlit)
    assert u"This is also a &lt;b&gt; &lt;bing&gt;" == escape(result)
Ejemplo n.º 19
0
def test_literal_dict():
    lit = literal(u"This string <>")
    unq = "This has <crap>"
    sub = literal("%s and %s")
    assert u"This string <> and This has &lt;crap&gt;" == sub % (lit, unq)

    sub = literal("%(lit)s and %(lit)r")
    assert u"This string <> and literal(u'This string &lt;&gt;')" == sub % dict(lit=lit)
    sub = literal("%(unq)r and %(unq)s")
    assert u"'This has &lt;crap&gt;' and This has &lt;crap&gt;" == sub % dict(unq=unq)
Ejemplo n.º 20
0
 def render(self, *args, **kw):
     direction = kw.get('direction', 'vertical')
     if direction == 'horizontal':
         class_ = kw.get('class_header', 'navbar-text')
         return literal(u'<li><p class="%s">' % (class_) + unicode(self) + u'</p></li>')
     elif direction == 'vertical' or direction == 'dropdown':
         class_ = kw.get('class_header', 'nav-header')
         return literal(u'<li class="%s">' % (class_) + unicode(self) + u'</li>')
     else:
         return literal(unicode(self))
Ejemplo n.º 21
0
 def assignment(self, obj):
     try:
         a = obj.assignment
         l = h.link(obj.assignment.name, obj.assignment.url)
         if not a.is_active:
             l = literal('<i title="Assignment not active">') + l + literal('</i>')
         return l
     except AttributeError:
         log.warn('Submission %r has no assignment', obj)
         return u'<span class="label label-inverse">None</a>'
Ejemplo n.º 22
0
def advise_warn_if(val, warn_func, error_func):
    """
    Like warn_if_not, but adds an orange advisory condition.
    """
    if error_func(val):
        return literal("<span style='color: red; font-weight: bold;'>"+val+"</span>")
    elif warn_func(val):
        return literal("<span style='color: orange; font-weight: bold;'>"+val+"</span>")
    else:
        return val
Ejemplo n.º 23
0
def markdown_wrap(text, extract_length=190):
    ''' return the plain text representation of markdown encoded text.  That
    is the texted without any html tags.  If extract_length is 0 then it
    will not be truncated.'''
    if (text is None) or (text.strip() == ''):
        return ''
    plain = RE_MD_HTML_TAGS.sub('', markdown(text))
    if not extract_length or len(plain) < extract_length:
        return literal(plain)
    return literal(unicode(wrap_paragraphs(plain, width=extract_length)))
Ejemplo n.º 24
0
 def handle_match(matchobj):
     all = matchobj.group()
     before, prefix, link, after = matchobj.group(1, 2, 3, 4)
     if re.match(r'<a\s', before, re.I):
         return all
     text = literal(prefix + link)
     if prefix == "www.":
         prefix = "http://www."
     a_options = dict(href_options)
     a_options['href'] = literal(prefix + link)
     return literal(before) + HTML.a(text, **a_options) + literal(after)
Ejemplo n.º 25
0
def label(value, **kwargs):
    """
    Return a label tag

        >>> print label('My label', for_='fieldname')
        <label for="fieldname">My label</label>

    """
    if 'for_' in kwargs:
        kwargs['for'] = kwargs.pop('for_')
    return tag('label', open=True, **kwargs) + literal(value) + literal('</label>')
Ejemplo n.º 26
0
def createSoundPreview(file):
    open_tags = """\
                        <div id="media">
"""
    content = """\
                            <embed src="/media/%s" controller="true" autoplay="false"
                            autostart="false" height="40" width="250" loop="false" />
""" % file.path
    close_tags = """\
                        </div>
"""
    return (literal(open_tags), literal(content), literal(close_tags))
Ejemplo n.º 27
0
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        try:
            template_path, template_type = render_.template_info(template_name)
        except render_.TemplateNotFound:
            raise

        log.debug('rendering %s [%s]' % (template_path, template_type))
        if config.get('debug'):
            context_vars = globs.get('c')
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {
                'template_name': template_name,
                'template_path': template_path,
                'template_type': template_type,
                'vars': globs,
                'c_vars': context_vars,
                'renderer': renderer
            }
            if 'CKAN_DEBUG_INFO' not in request.environ:
                request.environ['CKAN_DEBUG_INFO'] = []
            request.environ['CKAN_DEBUG_INFO'].append(debug_info)

        # Jinja2 templates
        if template_type == 'jinja2':
            # We don't want to have the config in templates it should be
            # accessed via g (app_globals) as this gives us flexability such
            # as changing via database settings.
            del globs['config']
            # TODO should we raise error if genshi filters??
            return render_jinja2(template_name, globs)

        # Genshi templates
        template = globs['app_globals'].genshi_loader.load(
            template_name.encode('utf-8'), cls=loader_class)
        stream = template.generate(**globs)

        for item in p.PluginImplementations(p.IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(
            stream.render(method=method, encoding=None, strip_whitespace=True))
Ejemplo n.º 28
0
 def render(self, *args, **kw):
     direction = kw.get('direction', 'vertical')
     if direction == 'horizontal':
         class_ = kw.get('class_header', 'navbar-text')
         return literal(u'<li><p class="%s">' % (class_) + unicode(self) +
                        u'</p></li>')
     elif direction == 'vertical' or direction == 'dropdown':
         class_ = kw.get('class_header', 'nav-header')
         return literal(u'<li class="%s">' % (class_) + unicode(self) +
                        u'</li>')
     else:
         return literal(unicode(self))
Ejemplo n.º 29
0
def createSoundPreview(file):
    open_tags = """\
                        <div id="media">
"""
    content = """\
                            <embed src="/media/%s" controller="true" autoplay="false"
                            autostart="false" height="40" width="250" loop="false" />
""" % file.path
    close_tags = """\
                        </div>
"""
    return (literal(open_tags), literal(content), literal(close_tags))
Ejemplo n.º 30
0
def test_literal_dict():
    lit = literal(u'This string <>')
    unq = 'This has <crap>'
    sub = literal('%s and %s')
    eq_(u'This string <> and This has &lt;crap&gt;', sub % (lit, unq))

    sub = literal('%(lit)s and %(lit)r')
    eq_(u"This string <> and literal(u&#39;This string &lt;&gt;&#39;)",
        sub % dict(lit=lit))
    sub = literal('%(unq)r and %(unq)s')
    eq_(u"&#39;This has &lt;crap&gt;&#39; and This has &lt;crap&gt;",
        sub % dict(unq=unq))
Ejemplo n.º 31
0
def make_menu_item(menu_item, active=False, is_submenu=False):
    icon = ''
    if is_submenu:
        icon = literal('<span class="fa fa-long-arrow-right"></span>')

    link = literal('<a href="') + menu_item.get('url') + literal(
        '">') + icon + menu_item.get('title') + literal('</a>')
    item_classes = ''

    if active:
        item_classes += 'active'
    return literal('<li class="' + item_classes + '">') + link
Ejemplo n.º 32
0
def test_markdown_embedded_html():
    _markdown = _get_markdown_module()
    markdown_text = 'This text includes <script>Javascript</script> & stuff.'
    if _markdown.version_info >= (2, 0):
        expected = literal(
            u'<p>This text includes &lt;script&gt;Javascript&lt;/script&gt; &amp; stuff.</p>'
        )
    else:
        expected = literal(
            u'<p>This text includes &lt;script&gt;Javascript&lt;/script&gt; &amp; stuff.\n</p>'
        )
    eq_(markdown(markdown_text, safe_mode="escape", markdown=_markdown),
        expected)
Ejemplo n.º 33
0
def get_snippet_actor(activity, detail):
    user = authz.auth_is_loggedin_user()
    if not user:
        if i18n.get_lang() == 'fr':
            return literal(
                '''<span class="actor">%s</span>''' %
                "L'équipe de données ouvertes de l'Ontario".decode('utf8'))
        else:
            return literal('''<span class="actor">Ontario's Open Data Team \
                </span>''')
    else:
        return literal('''<span class="actor">%s</span>''' %
                       (helpers.linked_user(activity['user_id'], 0, 30)))
Ejemplo n.º 34
0
def test_literal():
    lit = literal(u"This string <>")
    other = literal(u"<other>")
    assert u"This string <><other>" == lit + other
    assert type(lit + other) is literal

    assert u"&quot;<other>" == '"' + other
    assert u"<other>&quot;" == other + '"'

    mod = literal("<%s>ello")
    assert u"<&lt;H&gt;>ello" == mod % "<H>"
    assert type(mod % "<H>") is literal
    assert HTML("<a>") == "&lt;a&gt;"
    assert type(HTML("<a>")) is literal
Ejemplo n.º 35
0
def test_literal():
    lit = literal(u'This string <>')
    other = literal(u'<other>')
    eq_(u'This string <><other>', lit + other)
    assert type(lit + other) is literal

    eq_(u'&#34;<other>', '"' + other)
    eq_(u'<other>&#34;', other + '"')

    mod = literal('<%s>ello')
    eq_(u'<&lt;H&gt;>ello', mod % '<H>')
    assert type(mod % '<H>') is literal
    eq_(HTML('<a>'), '&lt;a&gt;')
    assert type(HTML('<a>')) is literal
Ejemplo n.º 36
0
def link(controller=None, action=None, id=None, text="Ссылка", title="", class_="", id_=""):
    answer = literal("<a ")
    if class_:
        answer += literal('class="' + class_ + '" ')
    if id_:
        answer += literal('id="' + id_ + '" ')
    if title:
        answer += literal('title="') + title + literal('" ')
    if url_for(id=id) != url_for(controller=controller, action=action, id=id):
        answer += literal('href="') + url_for(controller=controller, action=action, id=id) + literal('"')
        answer += literal(">") + text + literal("</a>")
    else:
        answer += literal('class="nolink">') + text + literal("</a>")
    return answer
Ejemplo n.º 37
0
def test_literal():
    lit = literal(u'This string <>')
    other = literal(u'<other>')
    eq_(u'This string <><other>', lit + other)
    assert type(lit + other) is literal

    eq_(u'&#34;<other>', '"' + other)
    eq_(u'<other>&#34;', other + '"')

    mod = literal('<%s>ello')
    eq_(u'<&lt;H&gt;>ello', mod % '<H>')
    assert type(mod % '<H>') is literal
    eq_(HTML('<a>'), '&lt;a&gt;')
    assert type(HTML('<a>')) is literal
Ejemplo n.º 38
0
def render_stars(stars, reason, last_updated):
    if stars==0:
        stars_html = 5 * icon('star-grey')
    else:
        stars_html = stars * icon('star')

    tooltip = literal('<div class="star-rating-reason"><b>Reason: </b>%s</div>' % reason) if reason else ''
    for i in range(5,0,-1):
        classname = 'fail' if (i > stars) else ''
        tooltip += literal('<div class="star-rating-entry %s">%s</div>' % (classname, mini_stars_and_caption(i)))

    datestamp = last_updated.strftime('%d/%m/%Y')
    tooltip += literal('<div class="star-rating-last-updated"><b>Score updated: </b>%s</div>' % datestamp)

    return literal('<span class="star-rating"><span class="tooltip">%s</span><a href="http://lab.linkeddata.deri.ie/2010/star-scheme-by-example/" target="_blank">%s</a></span>' % (tooltip, stars_html))
Ejemplo n.º 39
0
def sa_learned(value):
    "indicate learning status"
    if not value:
        HTML.span(_('N'), class_='negative')

    match = LEARN_RE.search(value)
    if match:
        if match.groups()[0] == 'disabled':
            return (HTML.span(_('N'), class_='negative') +
                literal('&nbsp;') + '(%s)' % escape(match.group(1)))
        else:
            return (HTML.span(_('Y'), class_='positive') +
                literal('&nbsp;') + '(%s)' % escape(match.group(1)))
    else:
        return HTML.span(_('N'), class_='negative')
Ejemplo n.º 40
0
def sa_learned(value):
    "indicate learning status"
    if not value:
        HTML.span(_('N'), class_='negative')

    match = LEARN_RE.search(value)
    if match:
        if match.groups()[0] == 'disabled':
            return (HTML.span(_('N'), class_='negative') + literal('&nbsp;') +
                    '(%s)' % escape(match.group(1)))
        else:
            return (HTML.span(_('Y'), class_='positive') + literal('&nbsp;') +
                    '(%s)' % escape(match.group(1)))
    else:
        return HTML.span(_('N'), class_='negative')
Ejemplo n.º 41
0
def paginate(page, **attrs):
    p = page.pager('$link_previous ~2~ $link_next',
                   symbol_first=u'First',
                   symbol_previous=u'Previous',
                   symbol_next=u'Next',
                   symbol_last=u'Last',
                   show_if_single_page=False,
                   link_attr={'class': None},
                   curpage_attr={'class': 'active'},
                   dotdot_attr={'class': 'disabled'},
                   **attrs)

    p = lit_sub(u'<a', literal('<li><a'), p)
    p = lit_sub(patterns[0], patterns[1], p)
    return literal(u'<ul>') + p + literal(u'</ul>')
Ejemplo n.º 42
0
    def pager(
            self,
            format='<ul class="pagination">$link_previous ~2~ $link_next</ul>',
            page_param='page',
            partial_param='partial',
            show_if_single_page=False,
            separator=' ',
            onclick=None,
            symbol_first='<<',
            symbol_last='>>',
            symbol_previous='<',
            symbol_next='>',
            link_attr=None,
            curpage_attr=None,
            dotdot_attr=None,
            **kwargs):
        self.curpage_attr = curpage_attr or {'class': 'active'}
        self.separator = separator
        self.pager_kwargs = kwargs
        self.page_param = page_param
        self.partial_param = partial_param
        self.onclick = onclick
        self.link_attr = link_attr or {
            'class': 'pager_link',
            'rel': 'prerender'
        }
        self.dotdot_attr = dotdot_attr or {'class': 'pager_dotdot'}

        # Don't show navigator if there is no more than one page
        if self.page_count == 0 or (self.page_count == 1
                                    and not show_if_single_page):
            return ''

        from string import Template
        # Replace ~...~ in token format by range of pages
        result = re.sub(r'~(\d+)~', self._range, format)

        # Interpolate '%' variables
        result = Template(result).safe_substitute({
            'first_page': self.first_page,
            'last_page': self.last_page,
            'page': self.page,
            'page_count': self.page_count,
            'items_per_page': self.items_per_page,
            'first_item': self.first_item,
            'last_item': self.last_item,
            'item_count': self.item_count,
            'link_first': self.page > self.first_page and \
                    self._pagerlink(self.first_page, symbol_first) or '',
            'link_last': self.page < self.last_page and \
                    self._pagerlink(self.last_page, symbol_last) or '',
            'link_previous': HTML.li(self.previous_page and \
                    self._pagerlink(self.previous_page, symbol_previous) \
                    or HTML.a(symbol_previous)),
            'link_next': HTML.li(self.next_page and \
                    self._pagerlink(self.next_page, symbol_next) \
                    or HTML.a(symbol_next))
        })

        return literal(result)
Ejemplo n.º 43
0
Archivo: base.py Proyecto: mattcen/ckan
def render_snippet(*template_names, **kw):
    ''' Helper function for rendering snippets. Rendered html has
    comment tags added to show the template used. NOTE: unlike other
    render functions this takes a list of keywords instead of a dict for
    the extra template variables.

    :param template_names: the template to render, optionally with fallback
        values, for when the template can't be found. For each, specify the
        relative path to the template inside the registered tpl_dir.
    :type template_names: str
    :param kw: extra template variables to supply to the template
    :type kw: named arguments of any type that are supported by the template
    '''

    exc = None
    for template_name in template_names:
        try:
            output = render(template_name, extra_vars=kw)
            if config.get('debug'):
                output = (
                    '\n<!-- Snippet %s start -->\n%s\n<!-- Snippet %s end -->'
                    '\n' % (template_name, output, template_name))
            return literal(output)
        except TemplateNotFound as exc:
            if exc.name == template_name:
                # the specified template doesn't exist - try the next fallback
                continue
            # a nested template doesn't exist - don't fallback
            raise exc
    else:
        raise exc or TemplateNotFound
Ejemplo n.º 44
0
def markdown(text, markdown=None, **kwargs):
    """Format the text to HTML with Markdown formatting.

    Markdown is a wiki-like text markup language, originally written by
    John Gruber for Perl.  The helper converts Markdown text to HTML.

    There are at least two Python implementations of Markdown.
    Markdown <http://www.freewisdom.org/projects/python-markdown/>`_is the
    original port, and version 2.x contains extensions for footnotes, RSS, etc. 
    `Markdown2 <http://code.google.com/p/python-markdown2/>`_ is another port
    which claims to be faster and to handle edge cases better. 

    You can pass the desired Markdown module as the ``markdown``
    argument, or the helper will try to import ``markdown``. If neither is
    available, it will fall back to ``webhelpers.markdown``, which is
    Freewisdom's Markdown 1.7 without extensions.
    
    IMPORTANT:
    If your source text is untrusted and may contain malicious HTML markup,
    pass ``safe_mode="escape"`` to escape it, ``safe_mode="replace"`` to
    replace it with a scolding message, or ``safe_mode="remove"`` to strip it.
    """
    if not markdown:
        markdown = _get_markdown_module()
    return literal(markdown.markdown(text, **kwargs))
Ejemplo n.º 45
0
def get_snippet_dataset(activity, detail):
    data = activity['data']
    pkg_dict = data.get('package') or data.get('dataset')
    link = h.dataset_link(pkg_dict) if pkg_dict else ''
    return literal('''<span>%s</span>'''
        % (link)
        )
Ejemplo n.º 46
0
def ip_details(ipaddr):
    "Return IP type and country for an IP address"
    try:
        country_code = ''
        country_name = ''
        hostname = ''
        iptype = IP(ipaddr).iptype()
        if (iptype != "LOOPBACK" and ipaddr != '127.0.0.1'
                and iptype != "LINKLOCAL"):
            socket.setdefaulttimeout(60)
            #hostname = socket.gethostbyaddr(ipaddr)[0]
            hostname = get_hostname(ipaddr)
            if iptype != "PRIVATE":
                country_name, country_code = geoip_lookup(ipaddr)
        elif iptype == "LINKLOCAL":
            hostname = _('IPv6 Link local address')
    except (socket.gaierror, socket.timeout, socket.error, ValueError):
        if 'iptype' in locals() and iptype == "PRIVATE":
            hostname = _("RFC1918 Private address")
        else:
            hostname = _("Reverse lookup failed")
    finally:
        details = dict(ip_address=ipaddr,
                       hostname=hostname or literal('unknown'),
                       country_code=country_code or 'unknown',
                       country_name=country_name or '',
                       media_url=media_url())
    return details
Ejemplo n.º 47
0
def end_with_layout():
    """\
    End a form started with ``start_with_layout()``
    >>> end_with_layout()
    literal(u'</table></form>')
    """
    return literal("</table>")+end_form()
Ejemplo n.º 48
0
def js(value):
    """Convert Python value to the corresponding JavaScript representation.

    This is necessary to safely insert arbitrary values into HTML <script>
    sections e.g. using Mako template expression substitution.

    Note: Rather than using this function, it's preferable to avoid the
    insertion of values into HTML <script> sections altogether. Instead,
    data should (to the extent possible) be passed to JavaScript using
    data attributes or AJAX calls, eliminating the need for JS specific
    escaping.

    Note: This is not safe for use in attributes (e.g. onclick), because
    quotes are not escaped.

    Because the rules for parsing <script> varies between XHTML (where
    normal rules apply for any special characters) and HTML (where
    entities are not interpreted, but the literal string "</script>"
    is forbidden), the function ensures that the result never contains
    '&', '<' and '>', thus making it safe in both those contexts (but
    not in attributes).
    """
    return literal(
        ('(' + json.dumps(value) + ')')
        # In JSON, the following can only appear in string literals.
        .replace('&', r'\x26')
        .replace('<', r'\x3c')
        .replace('>', r'\x3e')
    )
Ejemplo n.º 49
0
def javascript_link(*urls, **attrs):
    """Return script include tags for the specified javascript URLs.
    
    ``urls`` should be the exact URLs desired.  A previous version of this
    helper added magic prefixes; this is no longer the case.

    Specify the keyword argument ``defer=True`` to enable the script 
    defer attribute.

    Examples::
    
        >>> print javascript_link('/javascripts/prototype.js', '/other-javascripts/util.js')
        <script src="/javascripts/prototype.js" type="text/javascript"></script>
        <script src="/other-javascripts/util.js" type="text/javascript"></script>

        >>> print javascript_link('/app.js', '/test/test.1.js')
        <script src="/app.js" type="text/javascript"></script>
        <script src="/test/test.1.js" type="text/javascript"></script>
        
    """
    convert_boolean_attrs(attrs, ["defer"])
    tags = []
    for url in urls:
        tag = HTML.script("", type="text/javascript", src=url, **attrs)
        tags.append(tag)
    return literal("\n").join(tags)
Ejemplo n.º 50
0
def gravatar(email_address, cls='', size=30):
    """return html element of the gravatar

    This method will return an <img> with the resolution double the size (for
    retina screens) of the image. If the url returned from gravatar_url is
    empty then we fallback to using an icon.

    """
    from tg import tmpl_context as c
    if not c.visual.use_gravatar:
        return ''

    src = gravatar_url(email_address, size * 2)

    if src:
        # here it makes sense to use style="width: ..." (instead of, say, a
        # stylesheet) because we using this to generate a high-res (retina) size
        html = (
            '<img alt="" class="{cls}" style="width: {size}px; height: {size}px" src="{src}"/>'
            .format(cls=cls, size=size, src=src))

    else:
        # if src is empty then there was no gravatar, so we use a font icon
        html = (
            """<i class="icon-user {cls}" style="font-size: {size}px;"></i>""".
            format(cls=cls, size=size, src=src))

    return literal(html)
Ejemplo n.º 51
0
def action_parser_icon(user_log):
    action = user_log.action
    action_params = None
    x = action.split(':')

    if len(x) > 1:
        action, action_params = x

    tmpl = """<img src="%s%s" alt="%s"/>"""
    map = {
        'user_deleted_repo': 'database_delete.png',
        'user_created_repo': 'database_add.png',
        'user_created_fork': 'arrow_divide.png',
        'user_forked_repo': 'arrow_divide.png',
        'user_updated_repo': 'database_edit.png',
        'admin_deleted_repo': 'database_delete.png',
        'admin_created_repo': 'database_add.png',
        'admin_forked_repo': 'arrow_divide.png',
        'admin_updated_repo': 'database_edit.png',
        'push': 'script_add.png',
        'push_local': 'script_edit.png',
        'push_remote': 'connect.png',
        'pull': 'down_16.png',
        'started_following_repo': 'heart_add.png',
        'stopped_following_repo': 'heart_delete.png',
    }
    return literal(tmpl %
                   ((url('/images/icons/')), map.get(action, action), action))
Ejemplo n.º 52
0
def highlight(text,
              phrase,
              highlighter='<strong class="highlight">\\1</strong>'):
    """Highlight the ``phrase`` where it is found in the ``text``.
    
    The highlighted phrase will be surrounded by the highlighter, 
    by default::
    
        <strong class="highlight">I'm a highlight phrase</strong>
    
    ``highlighter``
        Defines the highlighting phrase. This argument should be a 
        single-quoted string with ``\\1`` where the phrase is supposed 
        to be inserted.
        
    Note: The ``phrase`` is sanitized to include only letters, digits, 
    and spaces before use.

    Example::

        >>> highlight('You searched for: Pylons', 'Pylons')
        'You searched for: <strong class="highlight">Pylons</strong>'
        
    """
    if not phrase or not text:
        return text
    highlight_re = re.compile('(%s)' % re.escape(phrase), re.I)
    if hasattr(text, '__html__'):
        return literal(highlight_re.sub(highlighter, text))
    else:
        return highlight_re.sub(highlighter, text)
Ejemplo n.º 53
0
def image_fixups(content, msgid, archive, richformat, allowimgs):
    "Replace the CID links stored messages"
    html = local_fromstring(content)
    for element, attribute, link, _ in iterlinks(html):
        if not link.startswith('cid:'):
            if not allowimgs and attribute == 'src':
                element.attrib['src'] = '%simgs/blocked.gif' % media_url()
                element.attrib['title'] = link
                if richformat:
                    if archive:
                        displayurl = url('message-preview-archived-with-imgs',
                                         msgid=msgid)
                    else:
                        displayurl = url('message-preview-with-imgs',
                                         msgid=msgid)
                    flash(
                        ugettext('This message contains external'
                                 ' images, which have been blocked. ') +
                        literal(link_to(ugettext('Display images'),
                                        displayurl)))
        else:
            imgname = link.replace('cid:', '')
            if archive:
                imgurl = url('messages-preview-archived-img',
                             img=imgname.replace('/', '__xoxo__'),
                             msgid=msgid)
            else:
                imgurl = url('messages-preview-img',
                             img=imgname.replace('/', '__xoxo__'),
                             msgid=msgid)
            element.attrib['src'] = imgurl
    return tostring(html)
Ejemplo n.º 54
0
def stylesheet_link(*urls, **attrs):
    """Return CSS link tags for the specified stylesheet URLs.

    ``urls`` should be the exact URLs desired.  A previous version of this
    helper added magic prefixes; this is no longer the case.

    Examples::

        >>> stylesheet_link('/stylesheets/style.css')
        literal(u'<link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />')

        >>> stylesheet_link('/stylesheets/dir/file.css', media='all')
        literal(u'<link href="/stylesheets/dir/file.css" media="all" rel="stylesheet" type="text/css" />')

    """
    if "href" in attrs:
        raise TypeError("keyword arg 'href' not allowed")
    attrs.setdefault("rel", "stylesheet")
    attrs.setdefault("type", "text/css")
    attrs.setdefault("media", "screen")
    tags = []
    for url in urls:
        tag = HTML.link(href=url, **attrs)
        tags.append(tag)
    return literal('\n').join(tags)
Ejemplo n.º 55
0
def end_layout():
    """\
    End a layout without adding the end form tag
    >>> end_layout()
    literal(u'</table>')
    """
    return literal('</table>')
Ejemplo n.º 56
0
def auto_link(text, link="all", **href_attrs):
    """
    Turn all urls and email addresses into clickable links.
    
    ``link``
        Used to determine what to link. Options are "all", 
        "email_addresses", or "urls"

    ``href_attrs``
        Additional attributes for generated <a> tags.
    
    Example::
    
        >>> auto_link("Go to http://www.planetpython.com and say hello to [email protected]")
        literal(u'Go to <a href="http://www.planetpython.com">http://www.planetpython.com</a> and say hello to <a href="mailto:[email protected]">[email protected]</a>')
        
    """
    if not text:
        return literal(u"")
    text = escape(text)
    if link == "all":
        return _auto_link_urls(_auto_link_email_addresses(text), **href_attrs)
    elif link == "email_addresses":
        return _auto_link_email_addresses(text)
    else:
        return _auto_link_urls(text, **href_attrs)
Ejemplo n.º 57
0
 def render(self, **kwargs):
     for r in self._fanstatic_resources:
         r.need()
     if 'autocomplete' in kwargs:
         kwargs.pop('autocomplete')
     request = self.request
     html = renderer.render(self, autocomplete='off', **kwargs)
     kwargs.update(self.jq_options)
     options = dict(
         tag=tag,
         html=html,
         plugin=plugin,
         name=self.name,
         show_input=show_input,
         resources=[
             url(r, prefix=self.resources_prefix, request=request)
             for r in self._resources
         ],
     )
     try:
         self.update_options(options, kwargs)
     except AttributeError:
         pass
     try:
         options.update(options=dumps(kwargs))
     except TypeError:
         options.update(options={})
     try:
         return literal(self.template.render_unicode(**options))
     except:
         raise ValueError('Invalid options: %s' % options)
Ejemplo n.º 58
0
    def threads(self):
        import sys
        import traceback
        items = sys._current_frames().items()
        dumps = []
        for thread, frame in items:
            dumps.append({
                "id": str(thread),
                "info": _get_info(frame),
                "trace": "\n".join(traceback.format_stack(frame)),
            })

        from webhelpers.html import HTML, literal
        out = literal()
        out += str(len(items)) + " threads:\n"
        for data in dumps:
            out += HTML.br()
            out += HTML.a(data["info"], href="#" + data["id"])
        for data in dumps:
            out += HTML.hr()
            out += HTML.a(data["id"] + ": " + HTML.b(data["info"]),
                          name=data["id"])
            out += HTML.p()
            out += HTML.pre(data["trace"])
        return out
Ejemplo n.º 59
0
def _legacy_highlight(text, phrase, highlighter, flags):
    """WebHelpers 0.6 style highlight with deprecated ``highlighter arg."""
    warnings.warn("the ``highlighter`` argument is deprecated",
        DeprecationWarning)
    pat = "(%s)" % re.escape(phrase)
    rx = re.compile(pat, flags)
    highlighter = literal(highlighter)
    return lit_sub(rx, highlighter, text)
Ejemplo n.º 60
0
 def render(self, name, **kwargs):
     name = name.strip('/')
     if 'template' in kwargs:
         name = kwargs.pop('template')
     if not name.endswith('.mako'):
         name = '%s.mako' % name
     template = self.templates.get_template('/forms/%s' % name)
     return literal(template.render_unicode(**kwargs))