Esempio n. 1
0
def abort(send):
    """
        An enhanced version of Werkzeug's abort.  `send` is handled differently
        based on what it is:

        int: assumed to be a HTTP status code; not all codes supported by
            default, see the Werkzeug documentation for an explanation.
        string/unicode: will put the string as the body of a response and send
            it.
        callable: assume its a Response object or other WSGI application; wrap
            in proxy HTTPException and raise it;
        anything else: pformat, escape, wrap in <pre> tags, and treat like
            string/unicode above.
    """
    # this is a circular import if done at the module level
    from blazeweb.wrappers import Response

    response_body = reindent(
        """
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>abort() Response</title>
    <h1 style="margin-bottom: 25px">abort() Response</h1>

    %s""".strip(), 0)

    if isinstance(send, int) or hasattr(send, '__call__'):
        response = send
    elif isinstance(send, six.string_types):
        response = Response(response_body % escape(send))
    else:
        response = Response(response_body %
                            ('<pre>%s</pre>' % escape(pformat(send))))
    werkzeug.abort(response)
Esempio n. 2
0
def abort(send):
    """
        An enhanced version of Werkzeug's abort.  `send` is handled differently
        based on what it is:

        int: assumed to be a HTTP status code; not all codes supported by
            default, see the Werkzeug documentation for an explanation.
        string/unicode: will put the string as the body of a response and send
            it.
        callable: assume its a Response object or other WSGI application; wrap
            in proxy HTTPException and raise it;
        anything else: pformat, escape, wrap in <pre> tags, and treat like
            string/unicode above.
    """
    # this is a circular import if done at the module level
    from blazeweb.wrappers import Response

    response_body = reindent("""
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>abort() Response</title>
    <h1 style="margin-bottom: 25px">abort() Response</h1>

    %s""".strip(), 0)

    if isinstance(send, int) or hasattr(send, '__call__'):
        response = send
    elif isinstance(send, six.string_types):
        response = Response(response_body % escape(send))
    else:
        response = Response(response_body % ('<pre>%s</pre>' % escape(pformat(send))))
    werkzeug.abort(response)
Esempio n. 3
0
    def __str__(self):
        if self.static:
            value = ''
            for (v,l) in self.options:
                if v == self.value:
                    value = l
            return self.as_static(value)

        options = []
        for val, label in self.options:
            selected = ''
            if self.value and self.value == val:
                selected = 'selected="selected"'
            options.append( '<option value="%s" %s>%s</option>' %
                        (escape(val), selected, escape(label) ))
        html = literal( input_select_template.format(
                    name = escape(self.name), label = escape(self.label),
                    value = escape(self.value),
                    options = '\n'.join(options),
                    multiple = 'multiple="multiple"' if self.multiple else '',
                    class_label = 'col-md-%d control-label' % self.offset,
                    class_value = 'col-md-%d' % self.size,
                    class_input = 'form-control',
                    extra_control = literal(self.extra_control) if self.extra_control else '',
                ))
        return self.div_wrap(html)
Esempio n. 4
0
 def as_static(self, value=None):
     return literal( input_static_template.format( name=escape(self.name),
                     label=escape(self.label), value=escape(value or self.value),
                     class_div = 'form-group' + (' has-error' if self.error else ''),
                     class_label = 'col-md-%d control-label' % self.offset,
                     class_value = 'col-md-%d' % self.size,
                     class_input = 'form-control',
                 ) )
Esempio n. 5
0
 def test_lit_sub(self):
     lit = literal("This is a <string>")
     unlit = "This is also a <string>"
     
     result = lit_sub(r"<str", literal("<b"), lit)
     assert "This is a <bing>" == escape(result)
     
     result = lit_sub(r"a <str", "a <b> <b", unlit)
     assert "This is also a &lt;b&gt; &lt;bing&gt;" == escape(result)
Esempio n. 6
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))
Esempio n. 7
0
 def test_lit_sub(self):
     lit = literal("This is a <string>")
     unlit = "This is also a <string>"
     
     result = lit_sub(r"<str", literal("<b"), lit)
     assert "This is a <bing>" == escape(result)
     
     result = lit_sub(r"a <str", "a <b> <b", unlit)
     assert "This is also a &lt;b&gt; &lt;bing&gt;" == escape(result)
Esempio n. 8
0
 def attributes(self):
     attrs = []
     if self.name or self.id:
         attrs.append('name="%s" id="%s"' % (escape(self.name or self.id),
                     escape(self.id or self.name)))
     if self.class_:
         attrs.append('class="%s"' % escape(self.class_))
     for (key, val) in self.attrs.items():
         attrs.append('%s="%s"' % (escape(key), escape(val)))
     return ' '.join(attrs)
Esempio n. 9
0
 def __str__(self):
     if type(self.size) == str and 'x' in self.size:
         rows,size = ( int(v) for v in self.size.split('x') )
     else:
         rows,size = 4, self.size
     return literal( input_textarea_template.format( name=escape(self.name),
                     label=escape(self.label), value=escape(self.value),
                     class_div = 'form-group',
                     class_label = 'col-md-%d control-label' % self.offset,
                     class_value = 'col-md-%d' % size,
                     rows = rows,
                     class_input = 'form-control',
                     extra_control = literal(self.extra_control) if self.extra_control else '',
                     style = 'style="font-family:monospace;"'
                 ) )
Esempio n. 10
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("")
    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)
Esempio n. 11
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)
Esempio n. 12
0
 def __str__(self):
     if self.info:
         if self.info.startswith('popup:'):
             info = '<div class="col-md-1 form-control-static"><a class="js-newWindow" data-popup="width=400,height=200,scrollbars=yes" href="%s"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></a></div>' % self.info[6:]
         else:
             info = ''
     else:
         info = ''
     return literal( input_password_template.format( name=escape(self.name),
                     label=escape(self.label), value=escape(self.value),
                     class_div = 'form-group' + (' has-error' if self.error else ''),
                     class_label = 'col-md-%d control-label' % self.offset,
                     class_value = 'col-md-%d' % self.size,
                     class_input = 'form-control',
                     help_span = self.help(),
                     info = info,
                 ) )
Esempio n. 13
0
    def url_func(changeset):
        author = escape(changeset.author)
        date = changeset.date
        message = escape(changeset.message)
        tooltip_html = ("<b>Author:</b> %s<br/>"
                        "<b>Date:</b> %s</b><br/>"
                        "<b>Message:</b> %s") % (author, date, message)

        lnk_format = show_id(changeset)
        uri = link_to(
                lnk_format,
                url('changeset_home', repo_name=repo_name,
                    revision=changeset.raw_id),
                style=get_color_string(changeset.raw_id),
                **{'data-toggle': 'popover',
                   'data-content': tooltip_html}
              )

        uri += '\n'
        return uri
Esempio n. 14
0
def jshtml(val):
    """HTML escapes a string value, then converts the resulting string
    to its corresponding JavaScript representation (see `js`).

    This is used when a plain-text string (possibly containing special
    HTML characters) will be used by a script in an HTML context (e.g.
    element.innerHTML or jQuery's 'html' method).

    If in doubt, err on the side of using `jshtml` over `js`, since it's
    better to escape too much than too little.
    """
    return js(escape(val))
Esempio n. 15
0
def highlight(text, phrase, case_sensitive=False, class_="highlight", **attrs):
    """Highlight all occurrences of ``phrase`` in ``text``.

    This inserts "<strong class="highlight">...</strong>" around every
    occurrence.

    Arguments:
    
    ``text``: 
        The full text.
    
    ``phrase``: 
        A phrase to find in the text. This may be a string, a list of strings, 
        or a compiled regular expression. If a string, it's regex-escaped and
        compiled. If a list, all of the strings will be highlighted.  This is
        done by regex-escaping all elements and then joining them using the
        regex "|" token.

    ``case_sensitive``:
        If false (default), the phrases are searched in a case-insensitive
        manner. No effect if ``phrase`` is a regex object.

    ``class_``:
        CSS class for the <strong> tag.

    ``**attrs``:
        Additional HTML attributes for the <strong> tag.
    """
    if not phrase or not text:
        return text
    text = escape(text)
    if case_sensitive:
        flags = 0  # No flags.
    else:
        flags = re.IGNORECASE
    if isinstance(phrase, six.string_types):
        pat = re.escape(phrase)
        rx = re.compile(pat, flags)
    elif isinstance(phrase, (list, tuple)):
        parts = [re.escape(x) for x in phrase]
        pat = "|".join(parts)
        rx = re.compile(pat, flags)
    else:
        rx = phrase

    def repl(m):
        return HTML.tag("strong", m.group(), class_=class_, **attrs)

    return lit_sub(rx, repl, text)
Esempio n. 16
0
 def __init__(self, **kwargs):
     self.name = kwargs.get('name', '').strip()
     self.class_ = escape(kwargs.get('class_', ''))
     self.id = kwargs.get('id', '').strip()
     if not self.id:
         self.id = self.name
     self.container = None
     self.contents = []
     self.elements = {}
     self.attrs = {}
     for (key, val) in kwargs.items():
         key = key.lower()
         if key in ['name', 'class_', 'id']:
             continue
         self.attrs[key] = val
Esempio n. 17
0
def highlight(text, phrase, case_sensitive=False, class_="highlight", **attrs):
    """Highlight all occurrences of ``phrase`` in ``text``.

    This inserts "<strong class="highlight">...</strong>" around every
    occurrence.

    Arguments:
    
    ``text``: 
        The full text.
    
    ``phrase``: 
        A phrase to find in the text. This may be a string, a list of strings, 
        or a compiled regular expression. If a string, it's regex-escaped and
        compiled. If a list, all of the strings will be highlighted.  This is
        done by regex-escaping all elements and then joining them using the
        regex "|" token.

    ``case_sensitive``:
        If false (default), the phrases are searched in a case-insensitive
        manner. No effect if ``phrase`` is a regex object.

    ``class_``:
        CSS class for the <strong> tag.

    ``**attrs``:
        Additional HTML attributes for the <strong> tag.
    """
    if not phrase or not text:
        return text
    text = escape(text)
    if case_sensitive:
        flags = 0   # No flags.
    else:
        flags = re.IGNORECASE
    if isinstance(phrase, six.string_types):
        pat = re.escape(phrase)
        rx = re.compile(pat, flags)
    elif isinstance(phrase, (list, tuple)):
        parts = [re.escape(x) for x in phrase]
        pat = "|".join(parts)
        rx = re.compile(pat, flags)
    else:
        rx = phrase
    def repl(m):
        return HTML.tag("strong", m.group(), class_=class_, **attrs)
    return lit_sub(rx, repl, text)
Esempio n. 18
0
def gravatar_div(email_address, cls='', size=30, **div_attributes):
    """Return an html literal with a span around a gravatar if they are enabled.
    Extra keyword parameters starting with 'div_' will get the prefix removed
    and '_' changed to '-' and be used as attributes on the div. The default
    class is 'gravatar'.
    """
    from tg import tmpl_context as c
    if not c.visual.use_gravatar:
        return ''
    if 'div_class' not in div_attributes:
        div_attributes['div_class'] = "gravatar"
    attributes = []
    for k, v in sorted(div_attributes.items()):
        assert k.startswith('div_'), k
        attributes.append(' %s="%s"' % (k[4:].replace('_', '-'), escape(v)))
    return literal("""<span%s>%s</span>""" %
                   (''.join(attributes),
                    gravatar(email_address, cls=cls, size=size)))
Esempio n. 19
0
def test_double_escape():
    quoted = escape(u'This string is "quoted"')
    eq_(quoted, u'This string is &#34;quoted&#34;')
    dbl_quoted = escape(quoted)
    eq_(quoted, dbl_quoted)
Esempio n. 20
0
 def __str__(self):
     return literal( form_template.format( name=escape(self.name),
                             action = self.action,
                             method = self.method,
                             contents = '\n'.join( escape(c) for c in self.contents ),
                     ) )
Esempio n. 21
0
 def __str__(self):
     return literal( '<input type="hidden" id="%s" name="%s" value="%s" />' %
                     (escape(self.id or self.name), escape(self.name), escape(self.value)) )
Esempio n. 22
0
def highlight(text, phrase, highlighter=None, case_sensitive=False, 
    class_="highlight", **attrs):
    """Highlight all occurrences of ``phrase`` in ``text``.

    This inserts "<strong class="highlight">...</strong>" around every
    occurrence.

    Arguments:
    
    ``text``: 
        The full text.
    
    ``phrase``: 
        A phrase to find in the text. This may be a string, a list of strings, 
        or a compiled regular expression. If a string, it's regex-escaped and
        compiled. If a list, all of the strings will be highlighted.  This is
        done by regex-escaping all elements and then joining them using the
        regex "|" token.

    ``highlighter``:
        Deprecated.  A replacement expression for the regex substitution.
        This was deprecated because it bypasses the HTML builder and creates
        tags via string mangling.  The previous default was '<strong
        class="highlight">\\1</strong>', which mimics the normal behavior of
        this function.  ``phrase`` must be a string if ``highlighter`` is
        specified.  Overrides ``class_`` and ``attrs_`` arguments.

    ``case_sensitive``:
        If false (default), the phrases are searched in a case-insensitive
        manner. No effect if ``phrase`` is a regex object.

    ``class_``:
        CSS class for the <strong> tag.

    ``**attrs``:
        Additional HTML attributes for the <strong> tag.

    Changed in WebHelpers 1.0b2: new implementation using HTML builder.
    Allow ``phrase`` to be list or regex.  Deprecate ``highlighter`` and
    change its default value to None. Add ``case_sensitive``, ``class_``,
    and ``**attrs`` arguments.
    """
    if not phrase or not text:
        return text
    text = escape(text)
    if case_sensitive:
        flags = 0   # No flags.
    else:
        flags = re.IGNORECASE
    if highlighter:
        return _legacy_highlight(text, phrase, highlighter, flags)
    if isinstance(phrase, basestring):
        pat = re.escape(phrase)
        rx = re.compile(pat, flags)
    elif isinstance(phrase, (list, tuple)):
        parts = [re.escape(x) for x in phrase]
        pat = "|".join(parts)
        rx = re.compile(pat, flags)
    else:
        rx = phrase
    def repl(m):
        return HTML.strong(m.group(), class_=class_, **attrs)
    return lit_sub(rx, repl, text)
Esempio n. 23
0
def mail_to(email_address, name=None, cc=None, bcc=None, subject=None, 
    body=None, replace_at=None, replace_dot=None, encode=None, **html_attrs):
    """Create a link tag for starting an email to the specified 
    ``email_address``.
    
    This ``email_address`` is also used as the name of the link unless
    ``name`` is specified. Additional HTML options, such as class or
    id, can be passed in the ``html_attrs`` hash.
    
    You can also make it difficult for spiders to harvest email address
    by obfuscating them.
    
    Examples::
    
        >>> mail_to("*****@*****.**", "My email", encode = "javascript")
        literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b\\'))\\n//]]>\\n</script>')
    
        >>> mail_to("*****@*****.**", "My email", encode = "hex")
        literal(u'<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>')
    
    You can also specify the cc address, bcc address, subject, and body
    parts of the message header to create a complex e-mail using the 
    corresponding ``cc``, ``bcc``, ``subject``, and ``body`` keyword 
    arguments. Each of these options are URI escaped and then appended
    to the ``email_address`` before being output. **Be aware that 
    javascript keywords will not be escaped and may break this feature 
    when encoding with javascript.**
    
    Examples::
    
        >>> mail_to("*****@*****.**", "My email", cc="*****@*****.**", bcc="*****@*****.**", subject="This is an example email", body= "This is the body of the message.")
        literal(u'<a href="mailto:[email protected]?cc=ccaddress%40domain.com&amp;bcc=bccaddress%40domain.com&amp;subject=This%20is%20an%20example%20email&amp;body=This%20is%20the%20body%20of%20the%20message.">My email</a>')
        
    """
    extras = []
    for item in ('cc', cc), ('bcc', bcc), ('subject', subject), ('body', body):
        option = item[1]
        if option:
            if not isinstance(option, literal):
                item = (item[0], escape(option))
            extras.append(item)
    options_query = urllib.urlencode(extras).replace("+", "%20")
    protocol = 'mailto:'

    email_address_obfuscated = email_address
    if replace_at:
        email_address_obfuscated = email_address_obfuscated.replace('@', 
            replace_at)
    if replace_dot:
        email_address_obfuscated = email_address_obfuscated.replace('.', 
            replace_dot)

    if encode == 'hex':
        email_address_obfuscated = HTML.literal(''.join(
            ['&#%d;' % ord(x) for x in email_address_obfuscated]))
        protocol = HTML.literal(''.join(['&#%d;' % ord(x) for x in protocol]))

        word_re = re.compile('\w')
        encoded_parts = []
        for x in email_address:
            if word_re.match(x):
                encoded_parts.append('%%%x' % ord(x))
            else:
                encoded_parts.append(x)
        email_address = HTML.literal(''.join(encoded_parts))

    url = HTML.literal(protocol + email_address)
    if options_query:
        url += HTML.literal('?') + options_query
    html_attrs['href'] = url

    tag = HTML.a(name or email_address_obfuscated, **html_attrs)

    if encode == 'javascript':
        tmp = "document.write('%s');" % tag
        string = ''.join(['%%%x' % ord(x) for x in tmp])
        return HTML.script(
            HTML.literal("\n//<![CDATA[\neval(unescape('%s'))\n//]]>\n" % string),
                         type="text/javascript")
    else:
        return tag
Esempio n. 24
0
 def __str__(self):
     return literal( '<%s %s>\n%s\n</%s>' % ( self._tag, self.attributes(),
                                     '\n'.join( escape(c) for c in self.contents ),
                                     self._tag ) )
Esempio n. 25
0
 def test_double_escape(self):
     quoted = escape('This string is "quoted"')
     assert quoted == "This string is &#34;quoted&#34;"
     dbl_quoted = escape(quoted)
     assert quoted == dbl_quoted
Esempio n. 26
0
def mail_to(email_address, name=None, cc=None, bcc=None, subject=None, 
    body=None, replace_at=None, replace_dot=None, encode=None, **html_attrs):
    """Create a link tag for starting an email to the specified 
    ``email_address``.
    
    This ``email_address`` is also used as the name of the link unless
    ``name`` is specified. Additional HTML options, such as class or
    id, can be passed in the ``html_attrs`` hash.
    
    You can also make it difficult for spiders to harvest email address
    by obfuscating them.
    
    Examples::
    
        >>> mail_to("*****@*****.**", "My email", encode = "javascript")
        literal(u'<script type="text/javascript">\\n//<![CDATA[\\neval(unescape(\\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b\\'))\\n//]]>\\n</script>')
    
        >>> mail_to("*****@*****.**", "My email", encode = "hex")
        literal(u'<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>')
    
    You can also specify the cc address, bcc address, subject, and body
    parts of the message header to create a complex e-mail using the 
    corresponding ``cc``, ``bcc``, ``subject``, and ``body`` keyword 
    arguments. Each of these options are URI escaped and then appended
    to the ``email_address`` before being output. **Be aware that 
    javascript keywords will not be escaped and may break this feature 
    when encoding with javascript.**
    
    Examples::
    
        >>> mail_to("*****@*****.**", "My email", cc="*****@*****.**", bcc="*****@*****.**", subject="This is an example email", body= "This is the body of the message.")
        literal(u'<a href="mailto:[email protected]?cc=ccaddress%40domain.com&amp;bcc=bccaddress%40domain.com&amp;subject=This%20is%20an%20example%20email&amp;body=This%20is%20the%20body%20of%20the%20message.">My email</a>')
        
    """
    extras = []
    for item in ('cc', cc), ('bcc', bcc), ('subject', subject), ('body', body):
        option = item[1]
        if option:
            if not isinstance(option, literal):
                item = (item[0], escape(option))
            extras.append(item)
    options_query = urlencode(extras).replace("+", "%20")
    protocol = 'mailto:'

    email_address_obfuscated = email_address
    if replace_at:
        email_address_obfuscated = email_address_obfuscated.replace('@', 
            replace_at)
    if replace_dot:
        email_address_obfuscated = email_address_obfuscated.replace('.', 
            replace_dot)

    if encode == 'hex':
        email_address_obfuscated = HTML.literal(''.join(
            ['&#%d;' % ord(x) for x in email_address_obfuscated]))
        protocol = HTML.literal(''.join(['&#%d;' % ord(x) for x in protocol]))

        word_re = re.compile('\w')
        encoded_parts = []
        for x in email_address:
            if word_re.match(x):
                encoded_parts.append('%%%x' % ord(x))
            else:
                encoded_parts.append(x)
        email_address = HTML.literal(''.join(encoded_parts))

    url = HTML.literal(protocol + email_address)
    if options_query:
        url += HTML.literal('?') + options_query
    html_attrs['href'] = url

    tag = HTML.tag("a", name or email_address_obfuscated, **html_attrs)

    if encode == 'javascript':
        tmp = "document.write('%s');" % tag
        string = ''.join(['%%%x' % ord(x) for x in tmp])
        return HTML.tag("script",
            HTML.literal("\n//<![CDATA[\neval(unescape('%s'))\n//]]>\n" % string),
                         type="text/javascript")
    else:
        return tag
Esempio n. 27
0
 def test_double_escape(self):
     quoted = escape('This string is "quoted"')
     assert quoted == "This string is &#34;quoted&#34;"
     dbl_quoted = escape(quoted)
     assert quoted == dbl_quoted