Skip to content

Commit d628af2

Browse files
committed
Call cgi.escape only on python 2. Replace with html.escapeif it can be
found.
1 parent 2741c7d commit d628af2

File tree

7 files changed

+63
-29
lines changed

7 files changed

+63
-29
lines changed

roundup/cgi/TAL/TALGenerator.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
from .TALDefs import parseSubstitution
2626
from .TranslationContext import TranslationContext, DEFAULT_DOMAIN
2727

28+
try:
29+
from html import escape as html_escape # python 3
30+
except ImportError:
31+
from cgi import escape as html_escape # python 2 fallback
32+
2833
I18N_REPLACE = 1
2934
I18N_CONTENT = 2
3035
I18N_EXPRESSION = 3
@@ -261,7 +266,7 @@ def emitRawText(self, text):
261266
self.emit("rawtext", text)
262267

263268
def emitText(self, text):
264-
self.emitRawText(cgi.escape(text))
269+
self.emitRawText(html_escape(text))
265270

266271
def emitDefines(self, defines):
267272
for part in TALDefs.splitParts(defines):

roundup/cgi/actions.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111
from roundup.anypy.strings import StringIO
1212
import roundup.anypy.random_ as random_
1313

14+
try:
15+
from html import escape as html_escape # python 3
16+
except ImportError:
17+
from cgi import escape as html_escape # python 2 fallback
18+
1419
import time
1520
from datetime import timedelta
1621

@@ -1351,7 +1356,7 @@ def handle(self):
13511356
self.client.response_code = 400
13521357
raise exceptions.NotFound(
13531358
self._('Column "%(column)s" not found in %(class)s')
1354-
% {'column': cgi.escape(cname), 'class': request.classname})
1359+
% {'column': html_escape(cname), 'class': request.classname})
13551360

13561361
# full-text search
13571362
if request.search_text:
@@ -1506,7 +1511,7 @@ def handle(self):
15061511
self.client.response_code = 400
15071512
raise exceptions.NotFound(
15081513
self._('Column "%(column)s" not found in %(class)s')
1509-
% {'column': cgi.escape(cname), 'class': request.classname})
1514+
% {'column': html_escape(cname), 'class': request.classname})
15101515

15111516
# full-text search
15121517
if request.search_text:

roundup/cgi/cgitb.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@
1010
import sys, os, keyword, linecache, tokenize, inspect, cgi
1111
import pydoc, traceback
1212

13+
try:
14+
from html import escape as html_escape # python 3
15+
except ImportError:
16+
from cgi import escape as html_escape # python 2 fallback
17+
1318
from roundup.cgi import templating, TranslationService
1419
from roundup.anypy.strings import s2b
1520

@@ -41,12 +46,12 @@ def niceDict(indent, dict):
4146
for k in sorted(dict):
4247
v = dict[k]
4348
l.append('<tr><td><strong>%s</strong></td><td>%s</td></tr>'%(k,
44-
cgi.escape(repr(v))))
49+
html_escape(repr(v))))
4550
return '\n'.join(l)
4651

4752
def pt_html(context=5, i18n=None):
4853
_ = get_translator(i18n)
49-
esc = cgi.escape
54+
esc = html_escape
5055
exc_info = [esc(str(value)) for value in sys.exc_info()[:2]]
5156
l = [_('<h1>Templating Error</h1>\n'
5257
'<p><b>%(exc_type)s</b>: %(exc_value)s</p>\n'
@@ -102,7 +107,7 @@ def pt_html(context=5, i18n=None):
102107
<table style="font-size: 80%%; color: gray">
103108
<tr><th class="header" align="left">%s</th></tr>
104109
<tr><td><pre>%s</pre></td></tr>
105-
</table>''' % (_('Full traceback:'), cgi.escape(''.join(
110+
</table>''' % (_('Full traceback:'), html_escape(''.join(
106111
traceback.format_exception(*sys.exc_info())
107112
))))
108113
l.append('<p>&nbsp;</p>')

roundup/cgi/exceptions.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
__docformat__ = 'restructuredtext'
55

66
from roundup.exceptions import LoginError, Unauthorised
7-
import cgi
7+
8+
try:
9+
from html import escape as html_escape # python 3
10+
except ImportError:
11+
from cgi import escape as html_escape # python 2 fallback
812

913
class HTTPException(BaseException):
1014
pass
@@ -62,6 +66,6 @@ def __str__(self):
6266
<body class="body" marginwidth="0" marginheight="0">
6367
<p class="error-message">%s</p>
6468
</body></html>
65-
"""%cgi.escape(self.args[0])
69+
"""%html_escape(self.args[0])
6670

6771
# vim: set filetype=python sts=4 sw=4 et si :

roundup/cgi/templating.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
import textwrap
2626
import time, hashlib
2727

28+
try:
29+
from html import escape as html_escape # python 3
30+
except ImportError:
31+
from cgi import escape as html_escape # python 2 fallback
32+
2833
from roundup.anypy import urllib_
2934
from roundup import hyperdb, date, support
3035
from roundup import i18n
@@ -430,7 +435,7 @@ def _set_input_default_args(dic):
430435
pass
431436

432437
def cgi_escape_attrs(**attrs):
433-
return ' '.join(['%s="%s"'%(k,cgi.escape(str(v), True))
438+
return ' '.join(['%s="%s"'%(k,html_escape(str(v), True))
434439
for k,v in sorted(attrs.items())])
435440

436441
def input_html4(**attrs):
@@ -1044,7 +1049,7 @@ def history(self, direction='descending', dre=re.compile('^\d+$'),
10441049
if labelprop is not None and \
10451050
labelprop != 'id':
10461051
label = linkcl.get(linkid, labelprop)
1047-
label = cgi.escape(label)
1052+
label = html_escape(label)
10481053
except IndexError:
10491054
comments['no_link'] = self._(
10501055
"<strike>The linked node"
@@ -1069,7 +1074,7 @@ def history(self, direction='descending', dre=re.compile('^\d+$'),
10691074
# there's no labelprop!
10701075
if labelprop is not None and labelprop != 'id':
10711076
try:
1072-
label = cgi.escape(linkcl.get(args[k],
1077+
label = html_escape(linkcl.get(args[k],
10731078
labelprop))
10741079
except IndexError:
10751080
comments['no_link'] = self._(
@@ -1109,7 +1114,7 @@ def history(self, direction='descending', dre=re.compile('^\d+$'),
11091114
current[k] = val
11101115

11111116
elif isinstance(prop, hyperdb.String) and args[k]:
1112-
val = cgi.escape(args[k])
1117+
val = html_escape(args[k])
11131118
cell.append('%s: %s'%(self._(k), val))
11141119
if k in current and current[k] is not None:
11151120
cell[-1] += ' -> %s'%current[k]
@@ -1155,7 +1160,7 @@ def history(self, direction='descending', dre=re.compile('^\d+$'),
11551160
if dre.match(user):
11561161
user = self._db.user.get(user, 'username')
11571162
l.append('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>'%(
1158-
date_s, cgi.escape(user), self._(action), arg_s))
1163+
date_s, html_escape(user), self._(action), arg_s))
11591164
if comments:
11601165
l.append(self._(
11611166
'<tr><td colspan=4><strong>Note:</strong></td></tr>'))
@@ -1490,13 +1495,13 @@ def plain(self, escape=0, hyperlink=0):
14901495
if self._value is None:
14911496
return ''
14921497
if escape:
1493-
s = cgi.escape(str(self._value))
1498+
s = html_escape(str(self._value))
14941499
else:
14951500
s = str(self._value)
14961501
if hyperlink:
14971502
# no, we *must* escape this text
14981503
if not escape:
1499-
s = cgi.escape(s)
1504+
s = html_escape(s)
15001505
s = self.hyper_re.sub(self._hyper_repl, s)
15011506
return s
15021507

@@ -1520,11 +1525,11 @@ def wrapped(self, escape=1, hyperlink=1):
15201525
return ''
15211526
s = '\n'.join(textwrap.wrap(str(self._value), 80))
15221527
if escape:
1523-
s = cgi.escape(s)
1528+
s = html_escape(s)
15241529
if hyperlink:
15251530
# no, we *must* escape this text
15261531
if not escape:
1527-
s = cgi.escape(s)
1532+
s = html_escape(s)
15281533
s = self.hyper_re.sub(self._hyper_repl, s)
15291534
return s
15301535

@@ -1584,7 +1589,7 @@ def multiline(self, escape=0, rows=5, cols=40, **kwargs):
15841589
if self._value is None:
15851590
value = ''
15861591
else:
1587-
value = cgi.escape(str(self._value))
1592+
value = html_escape(str(self._value))
15881593

15891594
value = '&quot;'.join(value.split('"'))
15901595
name = self._formname
@@ -1612,7 +1617,7 @@ def email(self, escape=1):
16121617
else:
16131618
value = value.replace('.', ' ')
16141619
if escape:
1615-
value = cgi.escape(value)
1620+
value = html_escape(value)
16161621
return value
16171622

16181623
class PasswordHTMLProperty(HTMLProperty):
@@ -1629,7 +1634,7 @@ def plain(self, escape=0):
16291634
except AttributeError:
16301635
value = self._('[hidden]')
16311636
if escape:
1632-
value = cgi.escape(value)
1637+
value = html_escape(value)
16331638
return value
16341639

16351640
def field(self, size=30, **kwargs):
@@ -2091,7 +2096,7 @@ def plain(self, escape=0):
20912096
else :
20922097
value = self._value
20932098
if escape:
2094-
value = cgi.escape(value)
2099+
value = html_escape(value)
20952100
return value
20962101

20972102
def field(self, showid=0, size=None, **kwargs):
@@ -2243,7 +2248,7 @@ def menu(self, size=None, height=None, showid=0, additional=[], value=None,
22432248
tr = str
22442249
if translate:
22452250
tr = self._
2246-
lab = cgi.escape(tr(lab))
2251+
lab = html_escape(tr(lab))
22472252
l.append('<option %svalue="%s">%s</option>'%(s, optionid, lab))
22482253
l.append('</select>')
22492254
return '\n'.join(l)
@@ -2342,7 +2347,7 @@ def plain(self, escape=0):
23422347
labels.append(label)
23432348
value = ', '.join(labels)
23442349
if escape:
2345-
value = cgi.escape(value)
2350+
value = html_escape(value)
23462351
return value
23472352

23482353
def field(self, size=30, showid=0, **kwargs):
@@ -2479,7 +2484,7 @@ def menu(self, size=None, height=None, showid=0, additional=[],
24792484
tr = str
24802485
if translate:
24812486
tr = self._
2482-
lab = cgi.escape(tr(lab))
2487+
lab = html_escape(tr(lab))
24832488
l.append('<option %svalue="%s">%s</option>'%(s, optionid,
24842489
lab))
24852490
l.append('</select>')
@@ -3082,7 +3087,7 @@ def url_quote(self, url):
30823087

30833088
def html_quote(self, html):
30843089
"""HTML-quote the supplied text."""
3085-
return cgi.escape(html)
3090+
return html_escape(html)
30863091

30873092
def __getattr__(self, name):
30883093
"""Try the tracker's templating_utils."""

roundup/cgi/wsgi_handler.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88
import cgi
99
import weakref
1010

11+
try:
12+
from html import escape as html_escape # python 3
13+
except ImportError:
14+
from cgi import escape as html_escape # python 2 fallback
15+
1116
import roundup.instance
1217
from roundup.cgi import TranslationService
1318
from roundup.anypy import http_
@@ -69,7 +74,7 @@ def __call__(self, environ, start_response):
6974
client.main()
7075
except roundup.cgi.client.NotFound:
7176
request.start_response([('Content-Type', 'text/html')], 404)
72-
request.wfile.write(s2b('Not found: %s'%cgi.escape(client.path)))
77+
request.wfile.write(s2b('Not found: %s'%html_escape(client.path)))
7378

7479
# all body data has been written using wfile
7580
return []

roundup/scripts/roundup_server.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
# --/
3737

3838

39-
import errno, cgi, getopt, io, os, socket, sys, traceback, time
39+
import errno, getopt, io, os, socket, sys, traceback, time
4040

4141
try:
4242
# Python 3.
@@ -57,6 +57,11 @@
5757
except ImportError:
5858
SSL = None
5959

60+
try:
61+
from html import escape as html_escape # python 3
62+
except ImportError:
63+
from cgi import escape as html_escape # python 2 fallback
64+
6065
# python version check
6166
from roundup import configuration, version_check
6267
from roundup import __version__ as roundup_version
@@ -243,7 +248,7 @@ def run_cgi(self):
243248
s = StringIO()
244249
traceback.print_exc(None, s)
245250
self.wfile.write(b"<pre>")
246-
self.wfile.write(s2b(cgi.escape(s.getvalue())))
251+
self.wfile.write(s2b(html_escape(s.getvalue())))
247252
self.wfile.write(b"</pre>\n")
248253
else:
249254
# user feedback
@@ -289,7 +294,7 @@ def index(self):
289294
for tracker in keys:
290295
w(s2b('<li><a href="%(tracker_url)s/index">%(tracker_name)s</a>\n'%{
291296
'tracker_url': urllib_.quote(tracker),
292-
'tracker_name': cgi.escape(tracker)}))
297+
'tracker_name': html_escape(tracker)}))
293298
w(b'</ol></body></html>')
294299

295300
def inner_run_cgi(self):

0 commit comments

Comments
 (0)