Python cgi.escape() Examples

The following are 30 code examples of cgi.escape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cgi , or try the search function .
Example #1
Source File: tabulate.py    From python-tabulate with MIT License 6 votes vote down vote up
def _html_row_with_attrs(celltag, unsafe, cell_values, colwidths, colaligns):
    alignment = {
        "left": "",
        "right": ' style="text-align: right;"',
        "center": ' style="text-align: center;"',
        "decimal": ' style="text-align: right;"',
    }
    if unsafe:
        values_with_attrs = [
            "<{0}{1}>{2}</{0}>".format(celltag, alignment.get(a, ""), c)
            for c, a in zip(cell_values, colaligns)
        ]
    else:
        values_with_attrs = [
            "<{0}{1}>{2}</{0}>".format(celltag, alignment.get(a, ""), htmlescape(c))
            for c, a in zip(cell_values, colaligns)
        ]
    rowhtml = "<tr>{}</tr>".format("".join(values_with_attrs).rstrip())
    if celltag == "th":  # it's a header row, create a new table header
        rowhtml = "<table>\n<thead>\n{}\n</thead>\n<tbody>".format(rowhtml)
    return rowhtml 
Example #2
Source File: datastore_viewer.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def input_field(self, name, value, sample_values, back_uri):
    string_value = self.format(value) if value else ''
    sample_values = [self.format(s) for s in sample_values]
    multiline = False
    if value:
      multiline = len(string_value) > 255 or string_value.find('\n') >= 0
    if not multiline:
      for sample_value in sample_values:
        if sample_value and (len(sample_value) > 255 or
                             sample_value.find('\n') >= 0):
          multiline = True
          break
    if multiline:
      return '<textarea name="%s" rows="5" cols="50" %s>%s</textarea>' % (
          cgi.escape(name),
          self.get_placholder_attribute(),
          cgi.escape(string_value))
    else:
      return DataType.input_field(self, name, value, sample_values, back_uri) 
Example #3
Source File: generatereports.py    From binaryanalysis with Apache License 2.0 6 votes vote down vote up
def generateunmatched((picklefile, pickledir, filehash, reportdir, compressed)):

	unmatched_pickle = open(os.path.join(pickledir, picklefile), 'rb')
	unmatches = cPickle.load(unmatched_pickle)
        unmatched_pickle.close()

	htmlfilename = "%s/%s-unmatched.html" % (reportdir, filehash)
	unmatchedhtmlfile = codecs.open(htmlfilename, encoding='utf-8', mode='wb')
	unmatchedhtmlfile.write(u"<html><body><h1>Unmatched strings (%d strings)</h1><p>" % (len(unmatches),))
	for u in unmatches:
		decoded = False
		for i in ['utf-8','ascii','latin-1','euc_jp', 'euc_jis_2004', 'jisx0213', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr','shift_jis','shift_jis_2004','shift_jisx0213']:
			try:
				decodeline = u.decode(i)
				decoded = True
				break
			except Exception, e:
				pass
			if decoded:
				unmatchedhtmlfile.write("u%s<br>\n" % cgi.escape(decodedline))
			else:
				pass 
Example #4
Source File: http_server.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def send_error(self, code, message=None, close=True):
        try:
            short, int = self.responses[code]
        except KeyError:
            short, int = '???', '???'
        if message is None:
            message = short
        explain = int
        content = (self.error_message_format %
                   {'code': code, 'message': cgi.escape(message),
                    'explain': explain})
        self.send_response(code, message)
        self.send_header("Content-Type", self.error_content_type)
        self.send_header('Content-Length', str(len(content)))
        if close:
            self.send_header('Connection', "close")

        self.end_headers()
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
            self.wfile.write(content) 
Example #5
Source File: common.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def run(self, **kwargs):
    random_token = kwargs.pop('random_token')
    kwargs.pop('approve_html', '')
    kwargs.pop('disapprove_html', '')

    approve_url = self.get_callback_url(
        random_token=random_token, choice='approve')
    disapprove_url = self.get_callback_url(
        random_token=random_token, choice='disapprove')

    mail_args = kwargs.copy()
    mail_args['body'] = mail_args['body'] % {
        'approve_url': approve_url,
        'disapprove_url': disapprove_url,
    }
    if 'html' in mail_args:
      mail_args['html'] = mail_args['html'] % {
        'approve_url': cgi.escape(approve_url),
        'disapprove_url': cgi.escape(disapprove_url),
      }
    EmailToContinue._email_message.im_func(**mail_args).send() 
Example #6
Source File: common.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def run(self, **kwargs):
    random_token = kwargs.pop('random_token')
    kwargs.pop('approve_html', '')
    kwargs.pop('disapprove_html', '')

    approve_url = self.get_callback_url(
        random_token=random_token, choice='approve')
    disapprove_url = self.get_callback_url(
        random_token=random_token, choice='disapprove')

    mail_args = kwargs.copy()
    mail_args['body'] = mail_args['body'] % {
        'approve_url': approve_url,
        'disapprove_url': disapprove_url,
    }
    if 'html' in mail_args:
      mail_args['html'] = mail_args['html'] % {
        'approve_url': cgi.escape(approve_url),
        'disapprove_url': cgi.escape(disapprove_url),
      }
    EmailToContinue._email_message.im_func(**mail_args).send() 
Example #7
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        text = params.get('text')

        html_template = """
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title></head>
<body><pre>{}</pre></body>
</html>"""
        # Wrap text preserving existing newlines
        text = '\n'.join(
            wrapped for line in text.splitlines() for wrapped in wrap(
                line, width=70, expand_tabs=False,
                replace_whitespace=False, drop_whitespace=False
            )
        )
        text = escape(text)
        html_content = html_template.format(text)
        pdf_content = HTML(string=html_content).write_pdf()

        b64_content = b64encode(pdf_content).decode()

        return {'pdf': b64_content} 
Example #8
Source File: gaeunit.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def get(self):
        unknown_args = [arg for arg in self.request.arguments()
                        if arg not in ("format", "package", "name")]
        if len(unknown_args) > 0:
            errors = []
            for arg in unknown_args:
                errors.append(_log_error("The request parameter '%s' is not valid." % arg))
            self.error(404)
            self.response.out.write(" ".join(errors))
            return

        format = self.request.get("format", "html")
        package_name = self.request.get("package")
        test_name = self.request.get("name")
        if format == "html":
            self._render_html(package_name, test_name)
        elif format == "plain":
            self._render_plain(package_name, test_name)
        else:
            error = _log_error("The format '%s' is not valid." % cgi.escape(format))
            self.error(404)
            self.response.out.write(error) 
Example #9
Source File: gaeunit.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def django_test_runner(request):
    unknown_args = [arg for (arg, v) in request.REQUEST.items()
                    if arg not in ("format", "package", "name")]
    if len(unknown_args) > 0:
        errors = []
        for arg in unknown_args:
            errors.append(_log_error("The request parameter '%s' is not valid." % arg))
        from django.http import HttpResponseNotFound
        return HttpResponseNotFound(" ".join(errors))

    format = request.REQUEST.get("format", "html")
    package_name = request.REQUEST.get("package")
    test_name = request.REQUEST.get("name")
    if format == "html":
        return _render_html(package_name, test_name)
    elif format == "plain":
        return _render_plain(package_name, test_name)
    else:
        error = _log_error("The format '%s' is not valid." % cgi.escape(format))
        from django.http import HttpResponseServerError
        return HttpResponseServerError(error) 
Example #10
Source File: quoting.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def html_quote(v, encoding=None):
    r"""
    Quote the value (turned to a string) as HTML.  This quotes <, >,
    and quotes:

    >>> html_quote(1)
    '1'
    >>> html_quote(None)
    ''
    >>> html_quote('<hey!>')
    '&lt;hey!&gt;'
    >>> html_quote(u'\u1029')
    '\xe1\x80\xa9'
    """
    encoding = encoding or default_encoding
    if v is None:
        return ''
    elif isinstance(v, str):
        return cgi.escape(v, 1)
    elif isinstance(v, unicode):
        return cgi.escape(v.encode(encoding), 1)
    else:
        return cgi.escape(unicode(v).encode(encoding), 1) 
Example #11
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def _wrap_for_html(self, lines):
        """Wrap the lines in HTML <pre> tag when using HTML format.

        Escape special HTML characters and add <pre> and </pre> tags around
        the given lines if we should be generating HTML as indicated by
        self._contains_html_diff being set to true.
        """
        if self._contains_html_diff:
            yield "<pre style='margin:0'>\n"

            for line in lines:
                yield cgi.escape(line)

            yield "</pre>\n"
        else:
            for line in lines:
                yield line 
Example #12
Source File: util.py    From jbox with MIT License 6 votes vote down vote up
def write_error(sock, status_int, reason, mesg):
    html = textwrap.dedent("""\
    <html>
      <head>
        <title>%(reason)s</title>
      </head>
      <body>
        <h1><p>%(reason)s</p></h1>
        %(mesg)s
      </body>
    </html>
    """) % {"reason": reason, "mesg": cgi.escape(mesg)}

    http = textwrap.dedent("""\
    HTTP/1.1 %s %s\r
    Connection: close\r
    Content-Type: text/html\r
    Content-Length: %d\r
    \r
    %s""") % (str(status_int), reason, len(html), html)
    write_nonblock(sock, http.encode('latin1')) 
Example #13
Source File: debug.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def app_dump():
    lines = ['<table>']

    for attr in sorted(dir(app)):
        attrval = getattr(app, attr)
        lines.append('<tr>')
        lines.append('<td><a href="{url}">{attr}</a></td>'.format(
            url=url_for('debug.app_dump_attr', attr=attr),
            attr=attr))
        lines.append('<td>{_type}</td>'.format(
            _type=cgi.escape(str(type(attrval)))))
        lines.append('<td>{callable}</td>'.format(
            callable=callable(attrval)))
        lines.append('</tr>')

    lines.append('</table>')
    return '\n'.join(lines) 
Example #14
Source File: html.py    From SEM with MIT License 6 votes vote down vote up
def add_annotation_document(self, document, column):
        annotations = document.annotation(column).get_reference_annotations()[::-1]
        content = document.content
        
        parts = []
        last = len(content)
        for annotation in annotations:
            parts.append(cgi.escape(content[annotation.ub : last]).replace(u"\n", u"<br />\n").replace(u"\r<br />", u"<br />\r"))
            parts.append(u'</span>')
            parts.append(cgi.escape(content[annotation.lb : annotation.ub]).replace(u"\n", u"<br />\n").replace(u"\r<br />", u"<br />\r"))
            parts.append(u'<span id="{0}" title="{0}">'.format(annotation.value))
            last = annotation.lb
        parts.append(cgi.escape(content[0:last]).replace(u"\n", u"<br />\n").replace(u"\r<br />", u"<br />\r"))
        
        new_content = u"".join(parts[::-1])
        return new_content 
Example #15
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 6 votes vote down vote up
def checknotif():
    if request.json["product"] == '':
        req = ':' + request.json['vendor'] + ':'
    else:
        req = request.json["vendor"] + ':' + request.json["product"] + ':' + request.json["version"]

    tab = []
    keytab = ['summary']
    for cves in mongo.db.cves.find({'vulnerable_configuration': {'$regex': req}}).sort("Modified", DESCENDING):
        dic = {}
        for key, value in cves.items():
            if key in keytab:
                dic[key] = cgi.escape(value, quote=True)
            else:
                if isinstance(value, datetime):
                    value = str(value)
                dic[key] = value
        tab.append(dic)
    return json.dumps(tab, sort_keys=True, default=json_util.default) 
Example #16
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 6 votes vote down vote up
def searchnotif():
    notification = models.Notification(user_id=current_user.id,
                                       fulltxt=True,
                                       vendor=escape(request.json['searchquery']),
                                       product='',
                                       version='')
    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           fulltxt=notification.fulltxt).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))
    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab")) 
Example #17
Source File: covercp.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def annotated_file(self, filename, statements, excluded, missing):
        source = open(filename, 'r')
        buffer = []
        for lineno, line in enumerate(source.readlines()):
            lineno += 1
            line = line.strip('\n\r')
            empty_the_buffer = True
            if lineno in excluded:
                template = TEMPLATE_LOC_EXCLUDED
            elif lineno in missing:
                template = TEMPLATE_LOC_NOT_COVERED
            elif lineno in statements:
                template = TEMPLATE_LOC_COVERED
            else:
                empty_the_buffer = False
                buffer.append((lineno, line))
            if empty_the_buffer:
                for lno, pastline in buffer:
                    yield template % (lno, cgi.escape(pastline))
                buffer = []
                yield template % (lineno, cgi.escape(line)) 
Example #18
Source File: watchthreads.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def format_environ(environ):
    if environ is None:
        return environ_template.substitute(
            key='---',
            value='No environment registered for this thread yet')
    environ_rows = []
    for key, value in sorted(environ.items()):
        if key in hide_keys:
            continue
        try:
            if key.upper() != key:
                value = repr(value)
            environ_rows.append(
                environ_template.substitute(
                key=cgi.escape(str(key)),
                value=cgi.escape(str(value))))
        except Exception, e:
            environ_rows.append(
                environ_template.substitute(
                key=cgi.escape(str(key)),
                value='Error in <code>repr()</code>: %s' % e)) 
Example #19
Source File: report.py    From report-ng with GNU General Public License v2.0 6 votes vote down vote up
def surround(text, search, tag, inline=True):
        text = escape(text)
        start = text.find('&amp;'+search+'=')
        if start != -1:
            start += 5
        else:
            start = text.find(search+'=')
        if start == -1:
            return text
        else:
            walk = text[start+len(search)+1:]
            end = walk.find('&amp;')
            if end == -1:
                return '<'+['','i'][inline]+'html>'+text[:start]+'<'+tag+'>'+text[start:]+'</'+tag+'>'+'</'+['','i'][inline]+'html>'
            else:
                return '<'+['','i'][inline]+'html>'+text[:start]+'<'+tag+'>'+text[start:start+len(search)+1+end]+'</'+tag+'>'+text[start+len(search)+1+end:]+'</'+['','i'][inline]+'html>'
            return text 
Example #20
Source File: errormiddleware.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def send_report(rep, exc_data, html=True):
    try:
        rep.report(exc_data)
    except:
        output = StringIO()
        traceback.print_exc(file=output)
        if html:
            return """
            <p>Additionally an error occurred while sending the %s report:

            <pre>%s</pre>
            </p>""" % (
                cgi.escape(str(rep)), output.getvalue())
        else:
            return (
                "Additionally an error occurred while sending the "
                "%s report:\n%s" % (str(rep), output.getvalue()))
    else:
        return '' 
Example #21
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 6 votes vote down vote up
def post_analysis_stuff(self, results):
        if results.has_formula():
            self.action_selector.addItem(self.parent.HIGHLIGHT_CODE)
            self.action_selector.addItem(self.parent.GRAPH_DEPENDENCY)
            self.formula_area.setText(self.parent.results.formula)
        if results.has_values():
            self.action_selector.addItem(self.parent.DISASS_UNKNOWN_TARGET)
        self.action_selector.setEnabled(True)
        self.action_button.setEnabled(True)

        report = HTMLReport()
        report.add_title("Results", size=3)
        report.add_table_header(["address", "assertion", "status", "values"])
        addr = make_cell("%x" % results.target)
        status = make_cell(results.get_status(), color=results.color, bold=True)
        vals = ""
        for value in results.values:
            flag = idc.GetFlags(value)
            typ = self.type_to_string(flag)
            vals += "%x type:%s seg:%s fun:%s<br/>" % (value, typ, idc.SegName(value), idc.GetFunctionName(value))
        report.add_table_line([addr, make_cell(cgi.escape(results.query)), status, make_cell(vals)])
        report.end_table()
        data = report.generate()
        self.result_area.setHtml(data) 
Example #22
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 5 votes vote down vote up
def addnotif():
    if request.json['allversion'] is True and request.json['allproduct'] is False:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version='')

    elif request.json['allproduct'] is True:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product='',
                                           version='')
    else:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version=escape(request.json['queryversion'].lower()))

    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           product=notification.product,
                                           version=notification.version).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))

    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab")) 
Example #23
Source File: html.py    From SEM with MIT License 5 votes vote down vote up
def escape_tokens(self, corpus, token_entry):
        """
        Returns a list of (HTML-)escaped token given a corpus and
        an entry where to find the tokens.
        """
        escaped = []
        for sentence in corpus:
            escaped.append([])
            for element in sentence:
                escaped[-1].append(cgi.escape(element[token_entry]))
        return escaped
    
    #==========================================================================
    # document-specific methods
    #========================================================================== 
Example #24
Source File: threaded_extension.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def HandleDispatchError(self, ecb):
        """Handles errors in the Dispatch method.
        
        When a Dispatch method call fails, this method is called to handle
        the exception.  The default implementation formats the traceback
        in the browser.
        """
        ecb.HttpStatusCode = isapicon.HSE_STATUS_ERROR
        #control_block.LogData = "we failed!"
        exc_typ, exc_val, exc_tb = sys.exc_info()
        limit = None
        try:
            try:
                import cgi
                ecb.SendResponseHeaders("200 OK", "Content-type: text/html\r\n\r\n", 
                                        False)
                print >> ecb
                print >> ecb, "<H3>Traceback (most recent call last):</H3>"
                list = traceback.format_tb(exc_tb, limit) + \
                       traceback.format_exception_only(exc_typ, exc_val)
                print >> ecb, "<PRE>%s<B>%s</B></PRE>" % (
                    cgi.escape("".join(list[:-1])), cgi.escape(list[-1]),)
            except ExtensionError:
                # The client disconnected without reading the error body -
                # its probably not a real browser at the other end, ignore it.
                pass
            except:
                print "FAILED to render the error message!"
                traceback.print_exc()
                print "ORIGINAL extension error:"
                traceback.print_exception(exc_typ, exc_val, exc_tb)
        finally:
            # holding tracebacks in a local of a frame that may itself be 
            # part of a traceback used to be evil and cause leaks!
            exc_tb = None
            ecb.DoneWithSession() 
Example #25
Source File: appengine.py    From earthengine with MIT License 5 votes vote down vote up
def _safe_html(s):
  """Escape text to make it safe to display.

  Args:
    s: string, The text to escape.

  Returns:
    The escaped text as a string.
  """
  return cgi.escape(s, quote=1).replace("'", '&#39;') 
Example #26
Source File: url.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def html_quote(v):
    if v is None:
        return ''
    return cgi.escape(str(v), 1) 
Example #27
Source File: template.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def html_quote(value):
    if value is None:
        return ''
    if not isinstance(value, basestring):
        if hasattr(value, '__unicode__'):
            value = unicode(value)
        else:
            value = str(value)
    value = cgi.escape(value, 1)
    if isinstance(value, unicode):
        value = value.encode('ascii', 'xmlcharrefreplace')
    return value 
Example #28
Source File: middleware.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def format_eval_html(exc_data, base_path, counter):
    short_formatter = EvalHTMLFormatter(
        base_path=base_path,
        counter=counter,
        include_reusable=False)
    short_er = short_formatter.format_collected_data(exc_data)
    long_formatter = EvalHTMLFormatter(
        base_path=base_path,
        counter=counter,
        show_hidden_frames=True,
        show_extra_data=False,
        include_reusable=False)
    long_er = long_formatter.format_collected_data(exc_data)
    text_er = formatter.format_text(exc_data, show_hidden_frames=True)
    if short_formatter.filter_frames(exc_data.frames) != \
        long_formatter.filter_frames(exc_data.frames):
        # Only display the full traceback when it differs from the
        # short version
        full_traceback_html = """
    <br>
    <script type="text/javascript">
    show_button('full_traceback', 'full traceback')
    </script>
    <div id="full_traceback" class="hidden-data">
    %s
    </div>
        """ % long_er
    else:
        full_traceback_html = ''
    
    return """
    %s
    %s
    <br>
    <script type="text/javascript">
    show_button('text_version', 'text version')
    </script>
    <div id="text_version" class="hidden-data">
    <textarea style="width: 100%%" rows=10 cols=60>%s</textarea>
    </div>
    """ % (short_er, full_traceback_html, cgi.escape(text_er)) 
Example #29
Source File: middleware.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def html_quote(v):
    """
    Escape HTML characters, plus translate None to ''
    """
    if v is None:
        return ''
    return cgi.escape(str(v), 1) 
Example #30
Source File: formatter.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def format_html(exc_data, include_hidden_frames=False, **ops):
    if not include_hidden_frames:
        return HTMLFormatter(**ops).format_collected_data(exc_data)
    short_er = format_html(exc_data, show_hidden_frames=False, **ops)
    # @@: This should have a way of seeing if the previous traceback
    # was actually trimmed at all
    ops['include_reusable'] = False
    ops['show_extra_data'] = False
    long_er = format_html(exc_data, show_hidden_frames=True, **ops)
    text_er = format_text(exc_data, show_hidden_frames=True, **ops)
    return """
    %s
    <br>
    <script type="text/javascript">
    show_button('full_traceback', 'full traceback')
    </script>
    <div id="full_traceback" class="hidden-data">
    %s
    </div>
    <br>
    <script type="text/javascript">
    show_button('text_version', 'text version')
    </script>
    <div id="text_version" class="hidden-data">
    <textarea style="width: 100%%" rows=10 cols=60>%s</textarea>
    </div>
    """ % (short_er, long_er, cgi.escape(text_er))