Exemplo n.º 1
0
 def convert_to_html(self, line):
     """Convert style tags to html"""
     chunks = tag_split_re.split(line)
     if len(chunks) == 1:
         # optimization in case there are no markup tags in the text at all
         return html_escape(self.smartquotes(line), False)
     result = []
     close_tags_stack = []
     chunks.append("</>")  # add a reset-all-styles sentinel
     for chunk in chunks:
         html_tags = style_tags_html.get(chunk)
         if html_tags:
             chunk = html_tags[0]
             close_tags_stack.append(html_tags[1])
         elif chunk == "</>":
             while close_tags_stack:
                 result.append(close_tags_stack.pop())
             continue
         elif chunk == "<clear>":
             self.html_special.append("clear")
         elif chunk:
             if chunk.startswith("</"):
                 chunk = "<" + chunk[2:]
                 html_tags = style_tags_html.get(chunk)
                 if html_tags:
                     chunk = html_tags[1]
                     if close_tags_stack:
                         close_tags_stack.pop()
             else:
                 # normal text (not a tag)
                 chunk = html_escape(self.smartquotes(chunk), False)
         result.append(chunk)
     return "".join(result)
Exemplo n.º 2
0
def export_links(links, output_file):
    print(BOOKMARK_HEADER, file=output_file)

    for l in links:
        parms = {
            'url': html_escape(l['long_url']),
            'title': html_escape(l.get('title', None) or ''),
            'add_timestamp': l['created_at'],
            'tags': '',
            'private': '1' if l['private'] else '0',
            'description': html_escape(l.get('text', '')),
        }

        if 'shares' in l and not parms['description']:
            share_links = [SHARE_TEMPLATE.format(**{k: html_escape(v) if isinstance(v, str) else v
                                                    for k, v in i.items()})
                                                 for i in l['shares'] if i['share_type'] != 'email']
            if len(share_links) > 1:
                parms['description'] = '<ul><li>%s</li></ul>' % '</li><li>'.join(share_links)
            else:
                parms['description'] = '<br>'.join(share_links)

        print(BOOKMARK_TEMPLATE.format(**parms),
              file=output_file)

    print(BOOKMARK_FOOTER, file=output_file)
Exemplo n.º 3
0
 def convert_to_html(self, line):
     """Convert style tags to html"""
     chunks = tag_split_re.split(line)
     if len(chunks) == 1:
         # optimization in case there are no markup tags in the text at all
         return html_escape(self.smartquotes(line), False)
     result = []
     close_tags_stack = []
     chunks.append("</>")  # add a reset-all-styles sentinel
     for chunk in chunks:
         html_tags = style_tags_html.get(chunk)
         if html_tags:
             chunk = html_tags[0]
             close_tags_stack.append(html_tags[1])
         elif chunk == "</>":
             while close_tags_stack:
                 result.append(close_tags_stack.pop())
             continue
         elif chunk == "<clear>":
             self.html_special.append("clear")
         elif chunk:
             if chunk.startswith("</"):
                 chunk = "<" + chunk[2:]
                 html_tags = style_tags_html.get(chunk)
                 if html_tags:
                     chunk = html_tags[1]
                     if close_tags_stack:
                         close_tags_stack.pop()
             else:
                 # normal text (not a tag)
                 chunk = html_escape(self.smartquotes(chunk), False)
         result.append(chunk)
     return "".join(result)
Exemplo n.º 4
0
    def get_backend_icon(self):
        is_perfect = (
            self.backend_status is not None
        ) and self.backend_status.startswith("1 -")
        is_good = (self.backend_status is not None) and (
            self.backend_status.startswith("0 -")
            or self.backend_status.startswith("1 -")
        )
        is_provisioning = (
            self.backend_status is None
            or self.backend_status == "Provisioning in progress"
            or self.backend_status == ""
        )

        # returns (icon_name, tooltip)
        if (
            (self.enacted is not None)
            and (self.enacted >= self.updated and is_good)
            or is_perfect
        ):
            return ("success", "successfully enacted")
        else:
            if is_good or is_provisioning:
                return (
                    "clock",
                    "Pending sync, last_status = "
                    + html_escape(self.backend_status, quote=True),
                )
            else:
                return ("error", html_escape(self.backend_status, quote=True))
Exemplo n.º 5
0
def send_to_stage(push):
    assert push.state in ('accepting', 'onstage')

    checkedin_requests = query.push_requests(push, state='checkedin')
    if checkedin_requests:
        if push.state != 'onstage':
            push.state = 'onstage'

            push.put()

        for request in checkedin_requests:
            request.state = 'onstage'
            if request.no_testing:
                set_request_tested(request, bust_caches=False)
            else:
                owner_email = request.owner.email()

                send_mail(
                    to=[owner_email, config.mail_to],
                    subject='Re: ' + request.subject,
                    body='Please check your changes on stage.\n' + config.url(push.uri))

                im_fields = dict(
                    pushmaster_email=html_escape(push.owner.email()),
                    pushmaster_name=html_escape(push.owner.nickname()),
                    request_subject=html_escape(request.subject),
                    uri=html_escape(config.url(push.uri)),
                    )
                send_im(owner_email, '<a href="mailto:%(pushmaster_email)s">%(pushmaster_name)s</a> requests that you check your changes on stage for <a href="%(uri)s">%(request_subject)s</a>.' % im_fields)
                request.put()

        push.bust_requests_cache()

    return push
Exemplo n.º 6
0
def reject_request(request, rejector, reason=None):
    push = request.push

    request.push = None
    request.state = 'rejected'
    if reason:
        request.reject_reason = reason

    request.put()
    query.bust_request_caches()
    if push is not None:
        push.bust_requests_cache()

    im_fields = dict(
        rejector_email=html_escape(rejector.email()),
        rejector_name=html_escape(rejector.nickname()),
        request_subject=html_escape(request.subject),
        uri=html_escape(config.url(request.uri)),
        reason=html_escape(reason),
        )
    send_im(request.owner.email(), '<a href="mailto:%(rejector_email)s">%(rejector_name)s</a> rejected your request <a href="%(uri)s">%(request_subject)s</a>: %(reason)s' % im_fields)

    send_mail(
        to=[request.owner.email(), config.mail_to],
        subject='Re: ' + request.subject,
        body="""This request was rejected.\n\n%s\n\n%s""" % (reason, config.url(request.uri)),
        )

    return request
Exemplo n.º 7
0
 def get_backend_icon(self):
     # returns (icon_name, tooltip)
     if (self.enacted is not None) and self.enacted >= self.updated or self.backend_status.startswith("1 -"):
         return ("success", "successfully enacted")
     else:
         if ((self.backend_status is not None) and self.backend_status.startswith("0 -")) or self.backend_status == "Provisioning in progress" or self.backend_status=="":
             return ("clock", html_escape(self.backend_status, quote=True))
         else:
             return ("error", html_escape(self.backend_status, quote=True))
Exemplo n.º 8
0
 def to_escaped_dict(self):
     ret = {}
     for k, v in self.to_dict().items():
         if v is None:
             ret[k] = ''
             continue
         try:
             ret[k] = html_escape(v, True)
         except Exception as e:
             ret[k] = html_escape(repr(v), True)
     return ret
Exemplo n.º 9
0
 def to_escaped_dict(self):
     ret = {}
     for k, v in self.to_dict().items():
         if v is None:
             ret[k] = ''
             continue
         try:
             ret[k] = html_escape(v, True)
         except Exception as e:
             ret[k] = html_escape(repr(v), True)
     return ret
Exemplo n.º 10
0
    def get_backend_icon(self):
        is_good = (self.backend_status is not None) and (self.backend_status.startswith("0 -") or self.backend_status.startswith("1 -"))
        is_provisioning = self.backend_status is None or self.backend_status == "Provisioning in progress" or self.backend_status==""

        # returns (icon_name, tooltip)
        if (self.enacted is not None) and self.enacted >= self.updated and is_good:
            return ("success", "successfully enacted")
        else:
            if is_good or is_provisioning:
                return ("clock", "Pending sync, last_status = " + html_escape(self.backend_status, quote=True))
            else:
                return ("error", html_escape(self.backend_status, quote=True))
Exemplo n.º 11
0
def filterName(name, encode=True):
	if name is not None:
		if encode is True:
			name = html_escape(name.replace('\xc2\x86', '').replace('\xc2\x87', ''), quote=True)
		else:
			name = name.replace('\xc2\x86', '').replace('\xc2\x87', '')
	return name
Exemplo n.º 12
0
 def wsgi_handle_input(self, environ, parameters, start_response):
     session = environ["wsgi.session"]
     conn = session.get("player_connection")
     if not conn:
         return self.wsgi_internal_server_error(start_response,
                                                "not logged in")
     cmd = parameters.get("cmd", "")
     if cmd and "autocomplete" in parameters:
         suggestions = conn.io.tab_complete(cmd, self.driver)
         if suggestions:
             conn.io.html_to_browser.append(
                 "<br><p><em>Suggestions:</em></p>")
             conn.io.html_to_browser.append("<p class='txt-monospaced'>" +
                                            " &nbsp; ".join(suggestions) +
                                            "</p>")
         else:
             conn.io.html_to_browser.append("<p>No matching commands.</p>")
     else:
         cmd = html_escape(cmd, False)
         if cmd:
             if conn.io.dont_echo_next_cmd:
                 conn.io.dont_echo_next_cmd = False
             else:
                 conn.io.html_to_browser.append(
                     "<span class='txt-userinput'>%s</span>" % cmd)
         conn.player.store_input_line(cmd)
     start_response('200 OK', [('Content-Type', 'text/plain')])
     return []
def convertDesc(val, encode=True):
	if val is not None:
		if encode is True:
			return html_escape(unicode(val, 'utf_8', errors='ignore').encode('utf_8', 'ignore'), quote=True).replace(u'\x8a', '\n')
		else:
			return unicode(val, 'utf_8', errors='ignore').encode('utf_8', 'ignore')
	return val
def filterName(name, encode=True):
	if name is not None:
		if encode is True:
			name = html_escape(name.replace('\xc2\x86', '').replace('\xc2\x87', ''), quote=True)
		else:
			name = name.replace('\xc2\x86', '').replace('\xc2\x87', '')
	return name
Exemplo n.º 15
0
 def test_escape_html_nosub2(self):
     substart = "<sub>"
     subend = "</sub>"
     teststring = "<escape & skip sub tags>"
     resstring = xml_util.escape_html_nosub(substart + teststring + subend)
     goalstring = substart + html_escape(teststring) + subend
     self.assertTrue(resstring == goalstring, "{0}\nshould be\n{1}".format(resstring, goalstring))
Exemplo n.º 16
0
def convertDesc(val, encode=True):
	if val is not None:
		if encode is True:
			return html_escape(unicode(val, 'utf_8', errors='ignore').encode('utf_8', 'ignore'), quote=True).replace(u'\x8a', '\n')
		else:
			return unicode(val, 'utf_8', errors='ignore').encode('utf_8', 'ignore')
	return val
Exemplo n.º 17
0
 def handle_data(self, data):
     """Process collected character data."""
     if not self._open_omitted_tags:
         # stack empty -> not in omit mode
         line = html_escape(data)
         print(line.decode('utf-8')
               if PY2 and isinstance(line, bytes) else line,
               end='')
Exemplo n.º 18
0
 def test_escape_html_nosub2(self):
     substart = "<sub>"
     subend = "</sub>"
     teststring = "<escape & skip sub tags>"
     resstring = xml_util.escape_html_nosub(substart + teststring + subend)
     goalstring = substart + html_escape(teststring) + subend
     self.assertTrue(resstring == goalstring, \
         "{0}\nshould be\n{1}".format(resstring,goalstring))
Exemplo n.º 19
0
 def __call__(self, req):
     req.add_sub(
         'syncclient',
         '</body>',
         ('<script src="%s"></script>'
          % (html_escape(self.syncclient))),
         replace=False)
     return self.static_app
Exemplo n.º 20
0
    def append_match(item, words):

        text = item.rendered
        text = tag_strip.sub(' ', text)

        sentences = []

        def matcher(match):
            return '<b>%s</b>' % match.group()

        if regex:
            for each in regex.finditer(text):
                sentence = text[max(each.start() - 35, 0): each.end() + 40]
                sentence = regex_ext.sub(matcher, sentence)
                sentence = sentence.strip()
                if each.start() > 0 and not sentence[0].isupper():
                    sentence = '...%s' % sentence
                if each.end() < len(text):
                    sentence = '%s...' % sentence
                sentences.append(sentence.strip())
                if len(sentences) > 3:
                    break

        if isinstance(item, BlogItem):
            title = html_escape(item.title)
            if regex_ext:
                title = regex_ext.sub(matcher, title)
            date = item.pub_date
            type_ = 'blog'
        else:
            if not item.blogitem:
                item.correct_blogitem_parent()
            title = (
                "Comment on <em>%s</em>" % html_escape(item.blogitem.title)
            )
            date = item.add_date
            type_ = 'comment'

        documents.append({
            'title': title,
            'summary': '<br>'.join(sentences),
            'date': date,
            'url': item.get_absolute_url(),
            'type': type_,
        })
Exemplo n.º 21
0
def format_tokens_row(tokens, tuple_offset):
    token_cell_template = '<td bgcolor="{color}">{token}<br><small>{prob}</small></td>'
    cells = []
    for t in tokens:
        log_prob = -t[tuple_offset + 1]
        cells.append(token_cell_template.format(token=html_escape(t[tuple_offset], quote=True),
                                                prob=format_number(np.exp(log_prob), 0),
                                                color=web_color(color_log_prob(log_prob))))
    return ''.join(cells)
Exemplo n.º 22
0
    def append_match(item, words):

        text = item.rendered
        text = tag_strip.sub(' ', text)

        sentences = []

        def matcher(match):
            return '<b>%s</b>' % match.group()

        if regex:
            for each in regex.finditer(text):
                sentence = text[max(each.start() - 35, 0):each.end() + 40]
                sentence = regex_ext.sub(matcher, sentence)
                sentence = sentence.strip()
                if each.start() > 0 and not sentence[0].isupper():
                    sentence = '...%s' % sentence
                if each.end() < len(text):
                    sentence = '%s...' % sentence
                sentences.append(sentence.strip())
                if len(sentences) > 3:
                    break

        if isinstance(item, BlogItem):
            title = html_escape(item.title)
            if regex_ext:
                title = regex_ext.sub(matcher, title)
            date = item.pub_date
            type_ = 'blog'
        else:
            if not item.blogitem:
                item.correct_blogitem_parent()
            title = ("Comment on <em>%s</em>" %
                     html_escape(item.blogitem.title))
            date = item.add_date
            type_ = 'comment'

        documents.append({
            'title': title,
            'summary': '<br>'.join(sentences),
            'date': date,
            'url': item.get_absolute_url(),
            'type': type_,
        })
Exemplo n.º 23
0
Arquivo: output.py Projeto: icio/crul
def output_sitemap(crawl):
    print dedent('''
        <?xml version="1.0" encoding="utf-8"?>
        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    ''').strip()
    for page in crawl:
        print '  <url><loc>%s</loc></url>' % html_escape(page.url or page.canonical_url)
    print '</urlset>'
Exemplo n.º 24
0
def html_colors(qstr='', limit=None):
    qstr = html_escape(qfont_decode(qstr, glyph_translation=True))
    qstr = qstr.replace('^^', '^')

    if limit is not None and limit > 0:
        qstr = limit_printable_characters(qstr, limit)

    html = _dec_colors.sub(lambda match: _dec_spans[int(match.group(1))], qstr)
    html = _hex_colors.sub(hex_repl, html)
    return html + "</span>" * len(_all_colors.findall(qstr))
Exemplo n.º 25
0
def html_colors(qstr='', limit=None):
    qstr = html_escape(qfont_decode(qstr, glyph_translation=True))
    qstr = qstr.replace('^^', '^')

    if limit is not None and limit > 0:
        qstr = limit_printable_characters(qstr, limit)

    html = _dec_colors.sub(lambda match: _dec_spans[int(match.group(1))], qstr)
    html = _hex_colors.sub(hex_repl, html)
    return html + "</span>" * len(_all_colors.findall(qstr))
Exemplo n.º 26
0
 def __init__(self, name=None, dest_file=None):
     assert(name is not None)
     assert(dest_file is not None)
     self.name = name
     self.html_id = self.tag2html_id(name)
     self.html_name = html_escape(name)
     self.dest_file = dest_file
     self.html_dest_file = "%s.html" % splitext(dest_file)[0]
     self.link_text =  self.link_for_tag(self.html_name, self.html_id, self.html_dest_file) # 
     self.local_link_text  =  self.link_for_local_tag(self.html_name, self.html_id, self.html_dest_file) # 
     self.ref_text = self.ref_for_tag(self.html_id)
Exemplo n.º 27
0
 def menuRenderItems(self, vals):
   cnt = 0
   for item in self.items:
     if hasattr(item, 'id'): cnt = item.id()
     print '<option label="%s" id="%s" value="%s" name="%s"' % \
           (item, cnt, cnt, html_escape(str(item), 1)),
     if item in vals: print "selected",
     print ">", item, '</option>'
     cnt = cnt+1
     pass
   return
Exemplo n.º 28
0
def format_value(value, suppress_colors=False):
    if isinstance(value, (list, tuple)) and len(value) == 3 and isinstance(value[0], Number):
        color = web_color(value)
        if suppress_colors:
            value = NotPresent()
        else:
            value = [int(c) for c in value]
    else:
        color = '#fff'
    value_repr = html_escape(repr(value).decode('unicode_escape').encode('utf-8'), quote=True)
    return '<td bgcolor="{color}">{value}</td>'.format(color=color, value=value_repr)
Exemplo n.º 29
0
 def menuRenderItems(self, vals):
     cnt = 0
     for item in self.items:
         if hasattr(item, 'id'): cnt = item.id()
         print '<option label="%s" id="%s" value="%s" name="%s"' % \
               (item, cnt, cnt, html_escape(str(item), 1)),
         if item in vals: print "selected",
         print ">", item, '</option>'
         cnt = cnt + 1
         pass
     return
Exemplo n.º 30
0
 def apply(self):
   source, boundary, end = self.source, self.boundary, self.end
   if self.start is not None:
     res_list = []
     start = self.start
     if boundary != start:
       res_list.append(source[boundary : start])
     url = source[start : end]
     if not self.has_text:
       # strip pieces that may not belong to URL
       while True:
         last_of_url = url[-1]
         if last_of_url == ")" and "(" not in url or last_of_url in ".,;:?!\"'":
           # last ")" is not a part of URL unless there's an "(" earlier in it;
           # common punctuation is usually not a part of URL
           end -= 1
           url = source[start : end]
         else:
           break
     if self.has_text:
       after_end = end + 1 # including the space
       # cut out the link text
       maybe_quote = source[after_end : after_end+1]
       if maybe_quote == '"':
         text_frags, start = QuoteWrapper(source, after_end).apply()
       else:
         # skip to next space
         hit = self.SPACE_RE.search(source, after_end+1)
         if hit:
           start = hit.start()
         else:
           start = len(source) # had no space till EOL
         text_frags = applyQueue(source[after_end : start])
     else:
       text_frags = [url]
       start = end
     proto_pos = url.find("://")
     if proto_pos > 0:
       proto = self.PROTO_CLASS_MAP.get(url[:proto_pos], self.PROTO_CLASS_MAP.get("*", None))
     else:
       proto = None
     if any(bad_char in url for bad_char in '<>"'): # being defensive
       url = html_escape(url, True)  
     res_list.extend(('<a href="', url, '"'))
     if proto:
       res_list.extend((' class="', proto, '"'))
     res_list.append('>')
     res_list.extend(text_frags)
     res_list.append("</a>")
   else:
     # no start
     start = boundary
     res_list = []
   return (res_list, start)
Exemplo n.º 31
0
 def buttonItems(self, selected_values, type):
   id = self.id
   buttons = []
   cnt=0
   for item in self.items:
     s = html_escape(str(item), 1)
     b = Input(s, id=id, name=id, value=cnt, type=type, label=s)
     if s in selected_values: b.props['checked']=None
     cnt=cnt+1
     buttons.append(b)
     pass
   return buttons
Exemplo n.º 32
0
 def render(self, val=None):
   opts = ' disabled' if (self.oneTime) else ''
   if val == None: val = self.value() or '' 
   val = html_escape(val.strip(), 1)
   if opts: print '<input type=hidden id="%s" name="%s" value="%s">' % (self.id, self.id, val)
   if self.rows > 1:
     print "<textarea id='%s' name='%s' rows=%d cols=%d%s>%s</textarea>" % \
           (self.id, self.id, self.rows, self.cols, opts, val),
   else:
     print '<input type=%s id="%s" name="%s" size=%d maxlength=%d value="%s" %s>' % \
           ('text' if self.rows==1 else 'password',
            self.id, self.id, self.cols, self.maxlen, val, opts)
Exemplo n.º 33
0
 def buttonItems(self, selected_values, type):
     id = self.id
     buttons = []
     cnt = 0
     for item in self.items:
         s = html_escape(str(item), 1)
         b = Input(s, id=id, name=id, value=cnt, type=type, label=s)
         if s in selected_values: b.props['checked'] = None
         cnt = cnt + 1
         buttons.append(b)
         pass
     return buttons
Exemplo n.º 34
0
 def write(self, data, escape=True):
     if not escape:
         self.body.write(str(data))
     elif hasattr(data, 'xml') and callable(data.xml):
         self.body.write(data.xml())
     else:
         # make it a string
         if not isinstance(data, (str, unicodeT)):
             data = str(data)
         elif isinstance(data, unicodeT):
             data = data.encode('utf8', 'xmlcharrefreplace')
         data = html_escape(data, True).replace("'", "&#x27;")
         self.body.write(data)
Exemplo n.º 35
0
def hyphenate(text, dic):
    """Hyphenate a `text` using `dic`tionary for display in browser."""
    # HTML escape needs to be done *after* the hyphenation, otherwise the
    # entities are hyphenated. Thus there is a two step process:
    # 1. Hyphenate with a special marker
    # 2. replace marker with the actual entity
    if dic is None:
        hyphenated = text
    else:
        words = text.split(u' ')
        hyphenated = u' '.join(
            [dic.inserted(word, SOFT_HYPHEN) for word in words])
    escaped = html_escape(hyphenated)
    return escaped.replace(SOFT_HYPHEN, SOFT_HYPHEN_HTML)
Exemplo n.º 36
0
    def send_error_msgtxt(self, code, message, headers=None):
        "text will be in a <pre> bloc"
        if headers is None:
            headers = {}

        if isinstance(message, (list, tuple)):
            message = ''.join(message)
        elif isinstance(message, dict):
            message = repr(message)

        self.send_error_explain(code,
                                ''.join(("<pre>\n", html_escape(message, True), "</pre>\n")), # pylint: disable=deprecated-method
                                headers,
                                "text/html")
Exemplo n.º 37
0
 def buttonRenderItems(self, vals, type):
   cnt = 0
   print self.header
   for item in self.items:
     if cnt % self.columns == 0: print '<tr>'
     print '<td align=right>'
     print '<input type=%s id=%s name=%s value="%s" label="%s"' % \
           (type, self.id, self.id, cnt, html_escape(str(item),1))
     if item in vals: 
       print "checked",
     print "></td><td align=left><font face=sans-serif size=-1>", item, "</font></td><td>&nbsp;</td>"
     cnt = cnt + 1
   print self.footer
   return
Exemplo n.º 38
0
 def render(self, val=None):
     opts = ' disabled' if (self.oneTime) else ''
     if val == None: val = self.value() or ''
     val = html_escape(val.strip(), 1)
     if opts:
         print '<input type=hidden id="%s" name="%s" value="%s">' % (
             self.id, self.id, val)
     if self.rows > 1:
         print "<textarea id='%s' name='%s' rows=%d cols=%d%s>%s</textarea>" % \
               (self.id, self.id, self.rows, self.cols, opts, val),
     else:
         print '<input type=%s id="%s" name="%s" size=%d maxlength=%d value="%s" %s>' % \
               ('text' if self.rows==1 else 'password',
                self.id, self.id, self.cols, self.maxlen, val, opts)
Exemplo n.º 39
0
 def buttonRenderItems(self, vals, type):
     cnt = 0
     print self.header
     for item in self.items:
         if cnt % self.columns == 0: print '<tr>'
         print '<td align=right>'
         print '<input type=%s id=%s name=%s value="%s" label="%s"' % \
               (type, self.id, self.id, cnt, html_escape(str(item),1))
         if item in vals:
             print "checked",
         print "></td><td align=left><font face=sans-serif size=-1>", item, "</font></td><td>&nbsp;</td>"
         cnt = cnt + 1
     print self.footer
     return
Exemplo n.º 40
0
def escaped_with_field_highlighted(form_html, field_name):
    """
    Return escaped HTML source code suitable for displaying;
    fields with name==field_name are highlighted.
    """
    form = load_html(form_html)
    for elem in form.xpath('.//*[@name="{}"]'.format(field_name)):
        add_text_before(elem, '__START__')
        add_text_after(elem, '__END__')
    text = html_tostring(form)
    text = html_escape(text).replace(
        '__START__', '<span style="font-size:large;color:#000">').replace(
            '__END__', '</span>')
    return text
Exemplo n.º 41
0
def build_search_page(
    verse_list="",
    verses="",
    strongs_morph="",
    context=0,
    min_range="Genesis",
    max_range="Revelation",
    verse_ref="Genesis 1:1",
    devotional_date="today",
    search_terms="",
):
    """ Build the search page and return a dictionary.

    """

    drop_list = [
        {"name": "context_dropdown", "id": "dcontext", "href": "#", "label": "Context", "value": context},
        {
            "name": "range_dropdown",
            "id": "drange",
            "href": "#",
            "label": "Range",
            "min_range": min_range,
            "max_range": max_range,
        },
        {"name": "lookup_dropdown", "id": "dlookup", "href": "#", "label": "Reference", "reference": verse_ref},
        {
            "name": "devotional_dropdown",
            "id": "ddevotional",
            "href": "#",
            "label": "Devotional",
            "date": devotional_date,
        },
    ]

    dropdowns = "\n".join([template(i["name"], **i) for i in drop_list])

    return template(
        "biblesearch",
        verse_list=verse_list,
        verses=verses,
        strongs_morph=strongs_morph,
        dropdowns=dropdowns,
        search_terms=html_escape(search_terms),
    )
Exemplo n.º 42
0
 def do_get(self):
     log_name = self.get_argument('log_name')
     with open(os.path.join(config.GlobalSettings.LOGFILES_DIR, log_name), 'rt') as fp:
         lines = []
         for line in (html_escape(l) for l in fp.readlines()):
             if ' [W] ' in line:
                 css_class = 'log-warn'
             elif ' [E] ' in line:
                 css_class = 'log-error'
             elif ' [C] ' in line:
                 css_class = 'log-critical'
             elif ' [I] ' in line:
                 css_class = 'log-info'
             else:
                 css_class = 'log-addit'
             lines.append("<span class='%s'>%s</span>" % (css_class, line))
         reply = {'lines' : '<br>'.join(lines)}
     self.finish(reply)
Exemplo n.º 43
0
 def convert_json_node(self, json_input):
     """
         Dispatch JSON input according to the outermost type and process it
         to generate the super awesome HTML format.
         We try to adhere to duck typing such that users can just pass all kinds
         of funky objects to json2html that *behave* like dicts and lists and other
         basic JSON types.
     """
     if type(json_input) in text_types:
         if self.escape:
             return html_escape(text(json_input))
         else:
             return text(json_input)
     if hasattr(json_input, 'items'):
         return self.convert_object(json_input)
     if hasattr(json_input, '__iter__') and hasattr(json_input, '__getitem__'):
         return self.convert_list(json_input)
     return text(json_input)
Exemplo n.º 44
0
 def do_get(self):
     log_name = self.get_argument('log_name')
     with open(os.path.join(config.GlobalSettings.LOGFILES_DIR, log_name),
               'rt') as fp:
         lines = []
         for line in (html_escape(l) for l in fp.readlines()):
             if ' [W] ' in line:
                 css_class = 'log-warn'
             elif ' [E] ' in line:
                 css_class = 'log-error'
             elif ' [C] ' in line:
                 css_class = 'log-critical'
             elif ' [I] ' in line:
                 css_class = 'log-info'
             else:
                 css_class = 'log-addit'
             lines.append("<span class='%s'>%s</span>" % (css_class, line))
         reply = {'lines': '<br>'.join(lines)}
     self.finish(reply)
Exemplo n.º 45
0
 def wsgi_handle_about(self, environ, parameters, start_response):
     # about page
     if "license" in parameters:
         return self.wsgi_handle_license(environ, parameters, start_response)
     start_response("200 OK", [('Content-Type', 'text/html; charset=utf-8')])
     resource = vfs.internal_resources["web/about_mud.html"]
     player_table = ["<br><p><em>Connected players:</em></p><pre>"]
     for name, conn in self.driver.all_players.items():
         player_table.append(html_escape("Name:  %s   connection: %s" % (name, conn.io)))
     player_table.append("</pre>")
     player_table = "\n".join(player_table)
     txt = resource.data.format(tale_version=tale_version_str,
                                story_version=self.driver.config.version,
                                story_name=self.driver.config.name,
                                uptime="%d:%02d:%02d" % self.driver.uptime,
                                starttime=self.driver.server_started,
                                num_players=len(self.driver.all_players),
                                player_table=player_table)
     return [txt.encode("utf-8")]
Exemplo n.º 46
0
def safe_str(x):
    try:
        # For Python2, it can be int, long, float
        if IS_PY2:
            if isinstance(x, (int, long, float)):
                x = str(x)
        else:
            # For Python3, it can be int, float
            if isinstance(x, (int, float)):
                x = str(x)

        x = x.encode('ascii', 'xmlcharrefreplace') if hasattr(x,
                                                              'encode') else x

        if not IS_PY2:
            x = x.decode('utf-8')
    except Exception:
        pass
    return html_escape(x, False)
Exemplo n.º 47
0
 def handle_starttag(self, tag, attrs):
     """Process the starting of a new element."""
     if tag in self.omit_tags:
         _logger.debug('omitting: "%s"', tag)
         self._open_omitted_tags.append(tag)
     if not self._open_omitted_tags:
         # stack empty -> not in omit mode
         if '@' in tag:
             # email address in angular brackets
             print('&lt;%s&gt;' % tag, end='')
             return
         if (tag == 'li') and (self._open_tags[-1] == 'li'):
             _logger.debug(
                 'opened "li" without closing previous "li", adding closing tag'
             )
             self.handle_endtag('li')
         attributes = []
         for attr_name, attr_value in attrs:
             if attr_name in self.omit_attrs:
                 _logger.debug('omitting "%s" attribute of "%s"', attr_name,
                               tag)
                 continue
             if attr_value is None:
                 _logger.debug(
                     'no value for "%s" attribute of "%s", adding empty value',
                     attr_name, tag)
                 attr_value = ''
             markup = '%(name)s="%(value)s"' % {
                 'name': attr_name,
                 'value': html_escape(attr_value, quote=True)
             }
             attributes.append(markup)
         line = '<%(tag)s%(attrs)s%(slash)s>' % {
             'tag': tag,
             'attrs':
             (' ' + ' '.join(attributes)) if len(attributes) > 0 else '',
             'slash': ' /' if tag in self.SELF_CLOSING_TAGS else ''
         }
         print(line, end='')
         if tag not in self.SELF_CLOSING_TAGS:
             self._open_tags.append(tag)
Exemplo n.º 48
0
    def write( self, value ):
        """ Writes the arbitrary Python value ``value`` as HTML to the internal
        buffers. """
        self.stack.append( value )
        
        if hasattr( value, '__html__' ): value.__html__( self )

        elif isinstance( value, basestring ):
            unesc = value if isinstance(value, unicode) \
                    else value.decode(self.encoding)
            self.current.append(html_escape(unesc, True))

        elif isinstance( value, Iterable ):
            for item in value: self.write( item )

        elif isinstance( value, Callable ): self.write( value() )

        else: self.current.append(unicode(value))
        
        self.stack.pop()
        return self
Exemplo n.º 49
0
def gensmileys():
    current_protocol = None
    for l in SMILEYS_INDEX.split("\n"):
        l = l.strip()
        if not l:
            continue
        if l.startswith("#"):
            continue
        if l.startswith("["):
            proto_name = l.strip("[]").lower()
            if proto_name == "xmpp":
                current_protocol = yobotproto.YOBOT_JABBER
            elif proto_name == "aim":
                current_protocol = yobotproto.YOBOT_AIM
            elif proto_name == "msn":
                current_protocol = yobotproto.YOBOT_MSN
            elif proto_name == "yahoo":
                current_protocol = yobotproto.YOBOT_YAHOO
            elif proto_name == "default":
                current_protocol = DEFAULT_SCHEME
            else:
                current_protocol = UNUSED
            continue
        
        if not current_protocol:
            continue
        items = l.split()
        name, emotes = items[0], items[1:]
        for emote in emotes:
            htmled = html_escape(emote)
            
            htmlescaped.resourcetable[(htmled, current_protocol)] = name
            htmlescaped.addsmiley(current_protocol, htmled)
            
            plain.resourcetable[(emote, current_protocol)] = name
            plain.addsmiley(current_protocol, emote)
            
    for o in (plain, htmlescaped):
        for k, v in o.allsmileys.items():
            o.regexp[k] = re.compile("(%s)" % ("|".join([re.escape(s) for s in sorted(v,key=len, reverse=True)])))
Exemplo n.º 50
0
    def post(self):
        if not self.handle_authentication():
            return
        backendformeditorfile = "backend_form_editor.html"
        table = self.get_argument("table")
        response = {"table": table}
        self.dbi.execute(
                "PRAGMA TABLE_INFO({0});".format(table))
        tableschema = [(x[1], x[2]) for x in self.dbi.fetchall()]

        self.dbi.execute("SELECT rowid,* FROM {0};".format(table))
        tablerows = self.dbi.fetchall()
        escapefunction = lambda x: html_escape("%s" % x)
        tablerows = [map(escapefunction, x) for x in tablerows]
        renderedtemplate = self.render_string(
                                backendformeditorfile,
                                schema=tableschema,
                                rows=tablerows,
                                table=table)
        response["table"] = table
        response["editortemplate"] = renderedtemplate
        self.write(response)
Exemplo n.º 51
0
 def wsgi_handle_about(self, environ, parameters, start_response):
     # about page
     if "license" in parameters:
         return self.wsgi_handle_license(environ, parameters,
                                         start_response)
     start_response("200 OK",
                    [('Content-Type', 'text/html; charset=utf-8')])
     resource = vfs.internal_resources["web/about_mud.html"]
     player_table = []
     for name, conn in self.driver.all_players.items():
         player_table.append(
             html_escape("Name:  %s   connection: %s" % (name, conn.io)))
     player_table.append("</pre>")
     player_table = "\n".join(player_table)
     txt = resource.data.format(tale_version=tale_version_str,
                                story_version=self.driver.config.version,
                                story_name=self.driver.config.name,
                                uptime="%d:%02d:%02d" % self.driver.uptime,
                                starttime=self.driver.server_started,
                                num_players=len(self.driver.all_players),
                                player_table=player_table)
     return [txt.encode("utf-8")]
Exemplo n.º 52
0
 def wsgi_handle_input(self, environ, parameters, start_response):
     session = environ["wsgi.session"]
     conn = session.get("player_connection")
     if not conn:
         return self.wsgi_internal_server_error(start_response, "not logged in")
     cmd = parameters.get("cmd", "")
     if cmd and "autocomplete" in parameters:
         suggestions = conn.io.tab_complete(cmd, self.driver)
         if suggestions:
             conn.io.html_to_browser.append("<br><p><em>Suggestions:</em></p>")
             conn.io.html_to_browser.append("<p class='txt-monospaced'>" + " &nbsp; ".join(suggestions) + "</p>")
         else:
             conn.io.html_to_browser.append("<p>No matching commands.</p>")
     else:
         cmd = html_escape(cmd, False)
         if cmd:
             if conn.io.dont_echo_next_cmd:
                 conn.io.dont_echo_next_cmd = False
             else:
                 conn.io.html_to_browser.append("<span class='txt-userinput'>%s</span>" % cmd)
         conn.player.store_input_line(cmd)
     start_response("200 OK", [("Content-Type", "text/plain")])
     return []
Exemplo n.º 53
0
 def do_sub(m):
     c = m.groupdict()
     if c["htmlchars"]:
         return html_escape(c["htmlchars"], quote=False)
     if c["lineend"]:
         return "<br>"
     elif c["space"]:
         t = m.group().replace("\t", u"&nbsp;" * tabstop)
         t = t.replace(" ", "&nbsp;")
         return t
     elif c["space"] == "\t":
         return " " * tabstop
     else:
         url = m.group("protocol")
         if url.startswith(" "):
             prefix = " "
             url = url[1:]
         else:
             prefix = ""
         last = m.groups()[-1]
         if last in ["\n", "\r", "\r\n"]:
             last = "<br>"
         return u'{0}<a href="{1}">{2}</a>{3}'.format(
             prefix, url, url, last)
Exemplo n.º 54
0
 def handle_starttag(self, tag, attrs):
     """Process the starting of a new element."""
     if tag in self.omit_tags:
         _logger.debug('omitting: "%s"', tag)
         self._open_omitted_tags.append(tag)
     if not self._open_omitted_tags:
         # stack empty -> not in omit mode
         if '@' in tag:
             # email address in angular brackets
             print('&lt;%s&gt;' % tag, end='')
             return
         if (tag == 'li') and (self._open_tags[-1] == 'li'):
             _logger.debug('opened "li" without closing previous "li", adding closing tag')
             self.handle_endtag('li')
         attributes = []
         for attr_name, attr_value in attrs:
             if attr_name in self.omit_attrs:
                 _logger.debug('omitting "%s" attribute of "%s"', attr_name, tag)
                 continue
             if attr_value is None:
                 _logger.debug('no value for "%s" attribute of "%s", adding empty value',
                               attr_name, tag)
                 attr_value = ''
             markup = '%(name)s="%(value)s"' % {
                 'name': attr_name,
                 'value': html_escape(attr_value, quote=True)
             }
             attributes.append(markup)
         line = '<%(tag)s%(attrs)s%(slash)s>' % {
             'tag': tag,
             'attrs': (' ' + ' '.join(attributes)) if len(attributes) > 0 else '',
             'slash': ' /' if tag in self.SELF_CLOSING_TAGS else ''
         }
         print(line, end='')
         if tag not in self.SELF_CLOSING_TAGS:
             self._open_tags.append(tag)
Exemplo n.º 55
0
 def math(self, text):
     return '$%s$' % html_escape(text)
Exemplo n.º 56
0
 def test_escape_html_nosub(self):
     teststring = "<tag1> ampersand here: & </tag1>"
     resstring = self.patent._escape_html_nosub(teststring)
     goalstring = html_escape(teststring)
     self.assertTrue(resstring == goalstring, \
         "{0}\nshould be\n{1}".format(resstring,goalstring))
Exemplo n.º 57
0
 def escape_html(self, text):
     return html_escape(text)
Exemplo n.º 58
0
def _(wr, s):
    wr.current.append(html_escape(s, True).encode(wr.encoding, "strict"))