Ticket #2359: 01-core-changes.4.diff
| File 01-core-changes.4.diff, 71.0 kB (added by Michael Radziej <mir@noris.de>, 1 year ago) |
|---|
-
a/django/oldforms/__init__.py
old new 1 1 from django.core import validators 2 2 from django.core.exceptions import PermissionDenied 3 3 from django.utils.html import escape 4 from django.utils.safestring import mark_safe 4 5 from django.conf import settings 5 6 from django.utils.translation import gettext, ngettext 6 7 … … 183 184 184 185 def html_error_list(self): 185 186 if self.errors(): 186 return '<ul class="errorlist"><li>%s</li></ul>' % '</li><li>'.join([escape(e) for e in self.errors()])187 return mark_safe('<ul class="errorlist"><li>%s</li></ul>' % '</li><li>'.join([escape(e) for e in self.errors()])) 187 188 else: 188 return ''189 return mark_safe('') 189 190 190 191 def get_id(self): 191 192 return self.formfield.get_id() … … 217 218 return bool(len(self.errors())) 218 219 219 220 def html_combined_error_list(self): 220 return ''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')])221 return mark_safe(''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')])) 221 222 222 223 class InlineObjectCollection(object): 223 224 "An object that acts like a sparse list of form field collections." … … 404 405 maxlength = 'maxlength="%s" ' % self.maxlength 405 406 if isinstance(data, unicode): 406 407 data = data.encode(settings.DEFAULT_CHARSET) 407 return '<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \408 return mark_safe('<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \ 408 409 (self.input_type, self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', 409 self.field_name, self.length, escape(data), maxlength) 410 self.field_name, self.length, escape(data), maxlength)) 410 411 411 412 def html2python(data): 412 413 return data … … 430 431 data = '' 431 432 if isinstance(data, unicode): 432 433 data = data.encode(settings.DEFAULT_CHARSET) 433 return '<textarea id="%s" class="v%s%s" name="%s" rows="%s" cols="%s">%s</textarea>' % \434 return mark_safe('<textarea id="%s" class="v%s%s" name="%s" rows="%s" cols="%s">%s</textarea>' % \ 434 435 (self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', 435 self.field_name, self.rows, self.cols, escape(data)) 436 self.field_name, self.rows, self.cols, escape(data))) 436 437 437 438 class HiddenField(FormField): 438 439 def __init__(self, field_name, is_required=False, validator_list=None): … … 441 442 self.validator_list = validator_list[:] 442 443 443 444 def render(self, data): 444 return '<input type="hidden" id="%s" name="%s" value="%s" />' % \445 (self.get_id(), self.field_name, escape(data)) 445 return mark_safe('<input type="hidden" id="%s" name="%s" value="%s" />' % \ 446 (self.get_id(), self.field_name, escape(data))) 446 447 447 448 class CheckboxField(FormField): 448 449 def __init__(self, field_name, checked_by_default=False, validator_list=None, is_required=False): … … 456 457 checked_html = '' 457 458 if data or (data is '' and self.checked_by_default): 458 459 checked_html = ' checked="checked"' 459 return '<input type="checkbox" id="%s" class="v%s" name="%s"%s />' % \460 return mark_safe('<input type="checkbox" id="%s" class="v%s" name="%s"%s />' % \ 460 461 (self.get_id(), self.__class__.__name__, 461 self.field_name, checked_html) 462 self.field_name, checked_html)) 462 463 463 464 def html2python(data): 464 465 "Convert value from browser ('on' or '') to a Python boolean" … … 489 490 selected_html = ' selected="selected"' 490 491 output.append(' <option value="%s"%s>%s</option>' % (escape(value), selected_html, escape(display_name))) 491 492 output.append(' </select>') 492 return '\n'.join(output)493 return mark_safe('\n'.join(output)) 493 494 494 495 def isValidChoice(self, data, form): 495 496 str_data = str(data) … … 542 543 output = ['<ul%s>' % (self.ul_class and ' class="%s"' % self.ul_class or '')] 543 544 output.extend(['<li>%s %s</li>' % (d['field'], d['label']) for d in self.datalist]) 544 545 output.append('</ul>') 545 return ''.join(output)546 return mark_safe(''.join(output)) 546 547 def __iter__(self): 547 548 for d in self.datalist: 548 549 yield d … … 557 558 datalist.append({ 558 559 'value': value, 559 560 'name': display_name, 560 'field': '<input type="radio" id="%s" name="%s" value="%s"%s/>' % \561 (self.get_id() + '_' + str(i), self.field_name, value, selected_html) ,562 'label': '<label for="%s">%s</label>' % \561 'field': mark_safe('<input type="radio" id="%s" name="%s" value="%s"%s/>' % \ 562 (self.get_id() + '_' + str(i), self.field_name, value, selected_html)), 563 'label': mark_safe('<label for="%s">%s</label>' % \ 563 564 (self.get_id() + '_' + str(i), display_name), 564 })565 )}) 565 566 return RadioFieldRenderer(datalist, self.ul_class) 566 567 567 568 def isValidChoice(self, data, form): … … 600 601 selected_html = ' selected="selected"' 601 602 output.append(' <option value="%s"%s>%s</option>' % (escape(value), selected_html, escape(choice))) 602 603 output.append(' </select>') 603 return '\n'.join(output)604 return mark_safe('\n'.join(output)) 604 605 605 606 def isValidChoice(self, field_data, all_data): 606 607 # data is something like ['1', '2', '3'] … … 653 654 (self.get_id() + escape(value), self.__class__.__name__, field_name, checked_html, 654 655 self.get_id() + escape(value), choice)) 655 656 output.append('</ul>') 656 return '\n'.join(output)657 return mark_safe('\n'.join(output)) 657 658 658 659 #################### 659 660 # FILE UPLOADS # … … 674 675 raise validators.CriticalValidationError, gettext("The submitted file is empty.") 675 676 676 677 def render(self, data): 677 return '<input type="file" id="%s" class="v%s" name="%s" />' % \678 (self.get_id(), self.__class__.__name__, self.field_name) 678 return mark_safe('<input type="file" id="%s" class="v%s" name="%s" />' % \ 679 (self.get_id(), self.__class__.__name__, self.field_name)) 679 680 680 681 def html2python(data): 681 682 if data is None: -
a/django/template/__init__.py
old new 60 60 from django.template.context import Context, RequestContext, ContextPopException 61 61 from django.utils.functional import curry 62 62 from django.utils.text import smart_split 63 from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping 64 from django.utils.html import escape 63 65 64 66 __all__ = ('Template', 'Context', 'RequestContext', 'compile_string') 65 67 … … 576 578 arg_vals.append(arg) 577 579 else: 578 580 arg_vals.append(resolve_variable(arg, context)) 579 obj = func(obj, *arg_vals) 581 if getattr(func, 'needs_autoescape', False): 582 new_obj = func(obj, autoescape = context.autoescape, *arg_vals) 583 else: 584 new_obj = func(obj, *arg_vals) 585 if getattr(func, 'is_safe', False) and isinstance(obj, SafeData): 586 obj = mark_safe(new_obj) 587 elif isinstance(obj, EscapeData): 588 obj = mark_for_escaping(new_obj) 589 else: 590 obj = new_obj 591 580 592 return obj 581 593 582 594 def args_check(name, func, provided): … … 765 777 766 778 def render(self, context): 767 779 output = self.filter_expression.resolve(context) 768 return self.encode_output(output) 780 encoded_output = self.encode_output(output) 781 if (context.autoescape and not isinstance(encoded_output, SafeData)) or isinstance(encoded_output, EscapeData): 782 return escape(encoded_output) 783 else: 784 return encoded_output 769 785 770 786 class DebugVariableNode(VariableNode): 771 787 def render(self, context): … … 775 791 if not hasattr(e, 'source'): 776 792 e.source = self.source 777 793 raise 778 return self.encode_output(output) 794 encoded_output = self.encode_output(output) 795 if context.autoescape and not isinstance(encoded_output, SafeData): 796 return escape(encoded_output) 797 else: 798 return encoded_output 779 799 780 800 def generic_tag_compiler(params, defaults, name, node_class, parser, token): 781 801 "Returns a template.Node subclass." -
a/django/template/context.py
old new 9 9 10 10 class Context(object): 11 11 "A stack container for variable context" 12 13 autoescape = False 14 12 15 def __init__(self, dict_=None): 13 16 dict_ = dict_ or {} 14 17 self.dicts = [dict_] … … 98 101 processors = tuple(processors) 99 102 for processor in get_standard_processors() + processors: 100 103 self.update(processor(request)) 104 -
a/django/template/defaultfilters.py
old new 3 3 from django.template import resolve_variable, Library 4 4 from django.conf import settings 5 5 from django.utils.translation import gettext 6 from django.utils.safestring import mark_safe, SafeData 6 7 import re 7 8 import random as random_module 8 9 … … 49 50 "Adds slashes - useful for passing strings to JavaScript, for example." 50 51 return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") 51 52 addslashes = stringfilter(addslashes) 53 addslashes.is_safe = True 52 54 53 55 def capfirst(value): 54 56 "Capitalizes the first character of the value" 55 57 return value and value[0].upper() + value[1:] 56 58 capfirst = stringfilter(capfirst) 57 59 capfirst.is_safe = True 60 58 61 def fix_ampersands(value): 59 62 "Replaces ampersands with ``&`` entities" 60 63 from django.utils.html import fix_ampersands 61 64 return fix_ampersands(value) 62 65 fix_ampersands = stringfilter(fix_ampersands) 66 fix_ampersands.is_safe = True 63 67 64 68 def floatformat(text, arg=-1): 65 69 """ … … 93 97 return '%d' % int(f) 94 98 else: 95 99 formatstr = '%%.%df' % abs(d) 96 return formatstr % f 100 return mark_safe(formatstr % f) 101 floatformat.is_safe = True 97 102 98 def linenumbers(value ):103 def linenumbers(value, autoescape = None): 99 104 "Displays text with line numbers" 100 105 from django.utils.html import escape 101 106 lines = value.split('\n') 102 107 # Find the maximum width of the line count, for use with zero padding string format command 103 108 width = str(len(str(len(lines)))) 104 for i, line in enumerate(lines): 105 lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) 106 return '\n'.join(lines) 109 if not autoescape or isinstance(value, SafeData): 110 for i, line in enumerate(lines): 111 lines[i] = ("%0" + width + "d. %s") % (i + 1, line) 112 else: 113 for i, line in enumerate(lines): 114 lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) 115 return mark_safe('\n'.join(lines)) 107 116 linenumbers = stringfilter(linenumbers) 117 linenumbers.is_safe = True 118 linenumbers.needs_autoescape = True 108 119 109 120 def lower(value): 110 121 "Converts a string into all lowercase" 111 122 return value.lower() 112 123 lower = stringfilter(lower) 124 lower.is_safe = True 113 125 114 126 def make_list(value): 115 127 """ … … 118 130 """ 119 131 return list(value) 120 132 make_list = stringfilter(make_list) 133 make_list.is_safe = False 121 134 122 135 def slugify(value): 123 136 "Converts to lowercase, removes non-alpha chars and converts spaces to hyphens" 124 137 value = re.sub('[^\w\s-]', '', value).strip().lower() 125 return re.sub('[-\s]+', '-', value)138 return mark_safe(re.sub('[-\s]+', '-', value)) 126 139 slugify = stringfilter(slugify) 140 slugify.is_safe = True 127 141 128 142 def stringformat(value, arg): 129 143 """ … … 138 152 return ("%" + str(arg)) % value 139 153 except (ValueError, TypeError): 140 154 return "" 155 stringformat.is_safe = True 141 156 142 157 def title(value): 143 158 "Converts a string into titlecase" 144 159 return re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) 145 160 title = stringfilter(title) 161 title.is_safe = False 146 162 147 163 def truncatewords(value, arg): 148 164 """ … … 159 175 value = str(value) 160 176 return truncate_words(value, length) 161 177 truncatewords = stringfilter(truncatewords) 178 truncatewords.is_safe = True 162 179 163 180 def truncatewords_html(value, arg): 164 181 """ … … 180 197 "Converts a string into all uppercase" 181 198 return value.upper() 182 199 upper = stringfilter(upper) 200 upper.is_safe = False 183 201 184 202 def urlencode(value): 185 203 "Escapes a value for use in a URL" … … 188 206 value = str(value) 189 207 return urllib.quote(value) 190 208 urlencode = stringfilter(urlencode) 209 urlencode.is_safe = False 191 210 192 211 def urlize(value): 193 212 "Converts URLs in plain text into clickable links" 194 213 from django.utils.html import urlize 195 return urlize(value, nofollow=True)214 return mark_safe(urlize(value, nofollow=True)) 196 215 urlize = stringfilter(urlize) 216 urlize.is_safe = True 197 217 198 218 def urlizetrunc(value, limit): 199 219 """ … … 203 223 Argument: Length to truncate URLs to. 204 224 """ 205 225 from django.utils.html import urlize 206 return urlize(value, trim_url_limit=int(limit), nofollow=True)226 return mark_safe(urlize(value, trim_url_limit=int(limit), nofollow=True)) 207 227 urlizetrunc = stringfilter(urlizetrunc) 228 urlize.is_safe = True 208 229 209 230 def wordcount(value): 210 231 "Returns the number of words" 211 232 return len(value.split()) 212 233 wordcount = stringfilter(wordcount) 234 wordcount.is_safe = False 213 235 214 236 def wordwrap(value, arg): 215 237 """ … … 220 242 from django.utils.text import wrap 221 243 return wrap(value, int(arg)) 222 244 wordwrap = stringfilter(wordwrap) 245 wordwrap.is_safe = True 223 246 224 247 def ljust(value, arg): 225 248 """ … … 229 252 """ 230 253 return value.ljust(int(arg)) 231 254 ljust = stringfilter(ljust) 255 ljust.is_safe = True 232 256 233 257 def rjust(value, arg): 234 258 """ … … 238 262 """ 239 263 return value.rjust(int(arg)) 240 264 rjust = stringfilter(rjust) 265 rjust.is_safe = True 241 266 242 267 def center(value, arg): 243 268 "Centers the value in a field of a given width" 244 269 return value.center(int(arg)) 245 270 center = stringfilter(center) 271 center.is_safe = True 246 272 247 273 def cut(value, arg): 248 274 "Removes all values of arg from the given string" 249 275 return value.replace(arg, '') 250 276 cut = stringfilter(cut) 277 cut.is_safe = False 251 278 252 279 ################### 253 280 # HTML STRINGS # 254 281 ################### 255 282 256 283 def escape(value): 257 "Escapes a string's HTML" 284 "Marks the value as a string that should not be auto-escaped." 285 from django.utils.safestring import mark_for_escaping 286 return mark_for_escaping(value) 287 escape = stringfilter(escape) 288 escape.is_safe = True 289 290 def force_escape(value): 291 """Escapes a string's HTML. This returns a new string containing the escaped 292 characters (as opposed to "escape", which marks the content for later 293 possible escaping).""" 258 294 from django.utils.html import escape 259 return escape(value)295 return mark_safe(escape(value)) 260 296 escape = stringfilter(escape) 297 force_escape.is_safe = True 261 298 262 def linebreaks(value ):299 def linebreaks(value, autoescape = None): 263 300 "Converts newlines into <p> and <br />s" 264 301 from django.utils.html import linebreaks 265 return linebreaks(value) 302 autoescape = autoescape and not isinstance(value, SafeData) 303 return mark_safe(linebreaks(value, autoescape)) 266 304 linebreaks = stringfilter(linebreaks) 305 linebreaks.is_safe = True 306 linebreaks.needs_autoescape = True 267 307 268 def linebreaksbr(value ):308 def linebreaksbr(value, autoescape = None): 269 309 "Converts newlines into <br />s" 270 return value.replace('\n', '<br />') 310 if autoescape and not isinstance(value, SafeData): 311 from django.utils.html import escape 312 data = escape(value) 313 else: 314 data = value 315 return mark_safe(data.replace('\n', '<br />')) 271 316 linebreaksbr = stringfilter(linebreaksbr) 317 linebreaksbr.is_safe = True 318 linebreaksbr.needs_autoescape = True 319 320 def safe(value): 321 "Marks the value as a string that should not be auto-escaped." 322 from django.utils.safestring import mark_safe 323 return mark_safe(value) 324 safe = stringfilter(safe) 325 safe.is_safe = True 272 326 273 327 def removetags(value, tags): 274 328 "Removes a space separated list of [X]HTML tags from the output" … … 280 334 value = endtag_re.sub('', value) 281 335 return value 282 336 removetags = stringfilter(removetags) 337 removetags.is_safe = True 283 338 284 339 def striptags(value): 285 340 "Strips all [X]HTML tags" 286 341 from django.utils.html import strip_tags 287 342 return strip_tags(value) 288 343 striptags = stringfilter(striptags) 344 striptags.is_safe = True 289 345 290 346 ################### 291 347 # LISTS # … … 299 355 decorated = [(resolve_variable('var.' + arg, {'var' : item}), item) for item in value] 300 356 decorated.sort() 301 357 return [item[1] for item in decorated] 358 dictsort.is_safe = False 302 359 303 360 def dictsortreversed(value, arg): 304 361 """ … … 309 366 decorated.sort() 310 367 decorated.reverse() 311 368 return [item[1] for item in decorated] 369 dictsortreversed.is_safe = False 312 370 313 371 def first(value): 314 372 "Returns the first item in a list" … … 316 374 return value[0] 317 375 except IndexError: 318 376 return '' 377 first.is_safe = True 319 378 320 379 def join(value, arg): 321 380 "Joins a list with a string, like Python's ``str.join(list)``" 322 381 try: 323 returnarg.join(map(smart_string, value))382 data = arg.join(map(smart_string, value)) 324 383 except AttributeError: # fail silently but nicely 325 384 return value 385 safe_args = reduce(lambda lhs, rhs: lhs and isinstance(rhs, SafeData), value, True) 386 if safe_args: 387 return mark_safe(data) 388 else: 389 return data 390 join.is_safe = True 326 391 327 392 def length(value): 328 393 "Returns the length of the value - useful for lists" 329 394 return len(value) 395 length.is_safe = False 330 396 331 397 def length_is(value, arg): 332 398 "Returns a boolean of whether the value's length is the argument" 333 399 return len(value) == int(arg) 400 length.is_safe = False 334 401 335 402 def random(value): 336 403 "Returns a random item from the list" 337 404 return random_module.choice(value) 405 length.is_safe = True 338 406 339 407 def slice_(value, arg): 340 408 """ … … 355 423 356 424 except (ValueError, TypeError): 357 425 return value # Fail silently. 426 slice_.is_safe = True 358 427 359 def unordered_list(value ):428 def unordered_list(value, autoescape = None): 360 429 """ 361 430 Recursively takes a self-nested list and returns an HTML unordered list -- 362 431 WITHOUT opening and closing <ul> tags. … … 377 446 </ul> 378 447 </li> 379 448 """ 449 if autoescape: 450 from django.utils.html import conditional_escape 451 escaper = conditional_escape 452 else: 453 escaper = lambda x: x 454 380 455 def _helper(value, tabs): 381 456 indent = '\t' * tabs 382 457 if value[1]: 383 return '%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent,458 return '%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, escaper(value[0]), indent, 384 459 '\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent) 385 460 else: 386 return '%s<li>%s</li>' % (indent, value[0]) 387 return _helper(value, 1) 461 return '%s<li>%s</li>' % (indent, escaper(value[0])) 462 return mark_safe(_helper(value, 1)) 463 unordered_list.is_safe = True 464 unordered_list.needs_autoescape = True 388 465 389 466 ################### 390 467 # INTEGERS # … … 393 470 def add(value, arg): 394 471 "Adds the arg to the value" 395 472 return int(value) + int(arg) 473 add.is_safe = False 396 474 397 475 def get_digit(value, arg): 398 476 """ … … 412 490 return int(str(value)[-arg]) 413 491 except IndexError: 414 492 return 0 493 get_digit.is_safe = False 415 494 416 495 ################### 417 496 # DATES # … … 425 504 if arg is None: 426 505 arg = settings.DATE_FORMAT 427 506 return format(value, arg) 507 date.is_safe = False 428 508 429 509 def time(value, arg=None): 430 510 "Formats a time according to the given format" … … 434 514 if arg is None: 435 515 arg = settings.TIME_FORMAT 436 516 return time_format(value, arg) 517 time.is_safe = False 437 518 438 519 def timesince(value, arg=None): 439 520 'Formats a date as the time since that date (i.e. "4 days, 6 hours")' … … 443 524 if arg: 444 525 return timesince(arg, value) 445 526 return timesince(value) 527 timesince.is_safe = False 446 528 447 529 def timeuntil(value, arg=None): 448 530 'Formats a date as the time until that date (i.e. "4 days, 6 hours")' … … 453 535 if arg: 454 536 return timesince(arg, value) 455 537 return timesince(datetime.now(), value) 538 timeuntil.is_safe = False 456 539 457 540 ################### 458 541 # LOGIC # … … 461 544 def default(value, arg): 462 545 "If value is unavailable, use given default" 463 546 return value or arg 547 default.is_safe = False 464 548 465 549 def default_if_none(value, arg): 466 550 "If value is None, use given default" 467 551 if value is None: 468 552 return arg 469 553 return value 554 default_if_none.is_safe = False 470 555 471 556 def divisibleby(value, arg): 472 557 "Returns true if the value is devisible by the argument" 473 558 return int(value) % int(arg) == 0 559 divisibleby.is_safe = False 474 560 475 561 def yesno(value, arg=None): 476 562 """ … … 501 587 if value: 502 588 return yes 503 589 return no 590 yesno.is_safe = False 504 591 505 592 ################### 506 593 # MISC # … … 523 610 if bytes < 1024 * 1024 * 1024: 524 611 return "%.1f MB" % (bytes / (1024 * 1024)) 525 612 return "%.1f GB" % (bytes / (1024 * 1024 * 1024)) 613 filesizeformat.is_safe = True 526 614 527 615 def pluralize(value, arg='s'): 528 616 """ … … 550 638 except TypeError: # len() of unsized object 551 639 pass 552 640 return singular_suffix 641 pluralize.is_safe = False 553 642 554 643 def phone2numeric(value): 555 644 "Takes a phone number and converts it in to its numerical equivalent" 556 645 from django.utils.text import phone2numeric 557 646 return phone2numeric(value) 647 phone2numeric.is_safe = True 558 648 559 649 def pprint(value): 560 650 "A wrapper around pprint.pprint -- for debugging, really" … … 563 653 return pformat(value) 564 654 except Exception, e: 565 655 return "Error in formatting:%s" % e 656 pprint.is_safe = True 566 657 567 658 # Syntax: register.filter(name of filter, callback) 568 659 register.filter(add) … … 581 672 register.filter(first) 582 673 register.filter(fix_ampersands) 583 674 register.filter(floatformat) 675 register.filter(force_escape) 584 676 register.filter(get_digit) 585 677 register.filter(join) 586 678 register.filter(length) … … 597 689 register.filter(removetags) 598 690 register.filter(random) 599 691 register.filter(rjust) 692 register.filter(safe) 600 693 register.filter('slice', slice_) 601 694 register.filter(slugify) 602 695 register.filter(stringformat) -
a/django/template/defaulttags.py
old new 4 4 from django.template import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END 5 5 from django.template import get_library, Library, InvalidTemplateLibrary 6 6 from django.conf import settings 7 from django.utils.safestring import mark_safe 7 8 import sys 8 9 9 10 register = Library() 10 11 12 class AutoEscapeControlNode(Node): 13 """Implements the actions of both the autoescape and noautescape tags.""" 14 def __init__(self, setting, nodelist): 15 self.setting, self.nodelist = setting, nodelist 16 17 def render(self, context): 18 old_setting = context.autoescape 19 context.autoescape = self.setting 20 output = self.nodelist.render(context) 21 context.autoescape = old_setting 22 if self.setting: 23 return mark_safe(output) 24 else: 25 return output 26 11 27 class CommentNode(Node): 12 28 def render(self, context): 13 29 return '' … … 41 57 def render(self, context): 42 58 output = self.nodelist.render(context) 43 59 # apply filters 44 return self.filter_expr.resolve(Context({'var': output})) 60 ctxt = Context({'var': output}) 61 ctxt.autoescape = context.autoescape 62 return self.filter_expr.resolve(ctxt) 45 63 46 64 class FirstOfNode(Node): 47 65 def __init__(self, vars): … … 234 252 return '' 235 253 output = [] # list of dictionaries in the format {'grouper': 'key', 'list': [list of contents]} 236 254 for obj in obj_list: 237 grouper = self.expression.resolve(Context({'var': obj}), True) 255 ctxt = Context({'var': obj}) 256 ctxt.autoescape = context.autoescape 257 grouper = self.expression.resolve(ctxt, True) 238 258 # TODO: Is this a sensible way to determine equality? 239 259 if output and repr(output[-1]['grouper']) == repr(grouper): 240 260 output[-1]['list'].append(obj) … … 355 375 return str(int(round(ratio))) 356 376 357 377 #@register.tag 378 def autoescape(parser, token): 379 """ 380 Force autoescape behaviour for this block. 381 """ 382 nodelist = parser.parse(('endautoescape',)) 383 parser.delete_first_token() 384 return AutoEscapeControlNode(True, nodelist) 385 autoescape = register.tag(autoescape) 386 387 #@register.tag 358 388 def comment(parser, token): 359 389 """ 360 390 Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` … … 457 487 458 488 Sample usage:: 459 489 460 {% filter escape|lower %}490 {% filter force_escape|lower %} 461 491 This text will be HTML-escaped, and will appear in lowercase. 462 492 {% endfilter %} 463 493 """ 464 494 _, rest = token.contents.split(None, 1) 465 495 filter_expr = parser.compile_filter("var|%s" % (rest)) 496 for func, unused in filter_expr.filters: 497 if getattr(func, '_decorated_function', func).__name__ in ('escape', 'safe'): 498 raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % func.__name__) 466 499 nodelist = parser.parse(('endfilter',)) 467 500 parser.delete_first_token() 468 501 return FilterNode(filter_expr, nodelist) … … 704 737 ifchanged = register.tag(ifchanged) 705 738 706 739 #@register.tag 740 def noautoescape(parser, token): 741 """ 742 Force autoescape behaviour to be disabled for this block. 743 """ 744 nodelist = parser.parse(('endnoautoescape',)) 745 parser.delete_first_token() 746 return AutoEscapeControlNode(False, nodelist) 747 autoescape = register.tag(noautoescape) 748 749 #@register.tag 707 750 def ssi(parser, token): 708 751 """ 709 752 Output the contents of a given file into the page. -
a/django/utils/html.py
old new 1 1 "HTML utilities suitable for global use." 2 2 3 3 import re, string 4 from django.utils.safestring import SafeData 4 5 5 6 # Configuration for urlize() function 6 7 LEADING_PUNCTUATION = ['(', '<', '<'] … … 27 28 html = str(html) 28 29 return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') 29 30 30 def linebreaks(value): 31 def conditional_escape(html): 32 "Similar to escape(), except that it does not operate on pre-escaped strings" 33 if isinstance(html, SafeData): 34 return html 35 else: 36 return escape(html) 37 38 def linebreaks(value, autoescape = False): 31 39 "Converts newlines into <p> and <br />s" 32 40 value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines 33 41 paras = re.split('\n{2,}', value) 34 paras = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paras] 42 if autoescape: 43 paras = ['<p>%s</p>' % escape(p.strip()).replace('\n', '<br />') for p in paras] 44 else: 45 paras = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paras] 35 46 return '\n\n'.join(paras) 36 47 37 48 def strip_tags(value): -
/dev/null
old new 1 """ 2 Functions for working with "safe strings": strings that can be displayed safely 3 without further escaping in HTML. Here, a "safe string" means that the producer 4 of the string has already turned characters that should not be interpreted by 5 the HTML engine (e.g. '<') into the appropriate entities. 6 """ 7 from django.utils.functional import curry 8 9 class EscapeData(object): 10 pass 11 12 class EscapeString(str, EscapeData): 13 """ 14 A string that should be HTML-escaped when output. 15 """ 16 pass 17 18 class EscapeUnicode(unicode, EscapeData): 19 """ 20 A unicode object that should be HTML-escaped when output. 21 """ 22 pass 23 24 class SafeData(object): 25 pass 26 27 class SafeString(str, SafeData): 28 """ 29 A string subclass that has been specifically marked as "safe" for HTML 30 output purposes. 31 """ 32 def __add__(self, rhs): 33 """ 34 Concatenating a safe string with another safe string or safe unicode 35 object is safe. Otherwise, the result is no longer safe. 36 """ 37 if isinstance(rhs, SafeUnicode): 38 return SafeUnicode(self + rhs) 39 elif isinstance(rhs, SafeString): 40 return SafeString(self + rhs) 41 else: 42 return super(SafeString, self).__add__(rhs) 43 44 def __str__(self): 45 return self 46 47 class SafeUnicode(unicode, SafeData): 48 """ 49 A unicode subclass that has been specifically marked as "safe" for HTML 50 output purposes. 51 """ 52 def __add__(self, rhs): 53 """ 54 Concatenating a safe unicode object with another safe string or safe 55 unicode object is safe. Otherwise, the result is no longer safe. 56 """ 57 if isinstance(rhs, SafeData): 58 return SafeUnicode(self + rhs) 59 else: 60 return super(SafeUnicode, self).__add__(rhs) 61 62 def _proxy_method(self, *args, **kwargs): 63 """ 64 Wrap a call to a normal unicode method up so that we return safe 65 results. The method that is being wrapped is passed in the 'method' 66 argument. 67 """ 68 method = kwargs.pop('method') 69 data = method(self, *args, **kwargs) 70 if isinstance(data, str): 71 return SafeString(data) 72 else: 73 return SafeUnicode(data) 74 75 encode = curry(_proxy_method, method = unicode.encode) 76 decode = curry(_proxy_method, method = unicode.decode) 77 78 79 def mark_safe(s): 80 """ 81 Explicitly mark a string as safe for (HTML) output purposes. The returned 82 object can be used everywhere a string or unicode object is appropriate. 83 84 Can safely be called multiple times on a single string. 85 """ 86 if isinstance(s, SafeData): 87 return s 88 if isinstance(s, str): 89 return SafeString(s) 90 if isinstance(s, unicode): 91 return SafeUnicode(s) 92 return SafeString(str(s)) 93 94 def mark_for_escaping(s): 95 """ 96 Explicitly mark a string as requiring HTML escaping upon output. Has no 97 effect on SafeData subclasses. 98 99 Can be safely called multiple times on a single string (the effect is only 100 applied once). 101 """ 102 if isinstance(s, SafeData) or isinstance(s, EscapeData): 103 return s 104 if isinstance(s, str): 105 return EscapeString(s) 106 if isinstance(s, unicode): 107 return EscapeUnicode(s) 108 return EscapeString(str(s)) 109 -
a/docs/templates.txt
old new 270 270 two similarly-named ``{% block %}`` tags in a template, that template's parent 271 271 wouldn't know which one of the blocks' content to use. 272 272 273 Automatic HTML escaping 274 ======================= 275 276 A very real problem when creating HTML (and other) output using templates and 277 variable substitution is the possibility of accidently inserting some variable 278 value that affects the resulting HTML. For example, a template fragment like 279 280 :: 281 282 Hello, {{ name }}. 283 284 seems like a harmless way to display the user's name. However, if you are 285 displaying data that the user entered directly and they entered their name as 286 287 :: 288 289 <script>alert('hello')</script> 290 291 this would always display a Javascript alert box whenever the page was loaded. 292 Similarly, if you were displaying some data generated by another process and 293 it contained a '<' symbol, you couldn't just dump this straight into your 294 HTML, because it would be treated as the start of an element. The effects of 295 these sorts of problems can vary from merely annoying to allowing exploits via 296 `Cross Site Scripting`_ (XSS) attacks. 297 298 .. _Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting 299 300 In order to provide some protection against these problems, Django provides an 301 auto-escaping template tag. Inside this tag, any data that comes from template 302 variables is examined to see if it contains one of the five HTML characters 303 (<, >, ', " and &) that often need escaping and those characters are converted 304 to their respective HTML entities. 305 306 Because some variables will contain data that is *intended* to be rendered 307 as HTML, template tag and filter writers can mark their output strings as 308 requiring no further escaping. For example, the ``unordered_list`` filter is 309 designed to return raw HTML and we want the template processor to simply 310 display the results as returned, without applying any escaping. That is taken 311 care of by the filter. The template author need do nothing special in that 312 case. 313 314 By default, auto-escaping is not in effect. To enable it inside your template, 315 wrap the affected content in the ``autoescape`` tag, like so:: 316 317 {% autoescape %} 318 Hello {{ name }} 319 {% endautoescape %} 320 321 Since the auto-escaping tag passes its effect onto templates that extend the 322 current one as well as templates included via the ``include`` tag (just like 323 all block tags), if you wrap your main HTML content in an ``autoescape`` tag, 324 you will have automatic escaping applied to all of your content. 325 326 At times, you might want to disable auto-escaping when it would otherwise be 327 in effect. You can do this with the ``noautoescape`` tag. For example:: 328 329 {% autoescape %} 330 Hello {{ name }} 331 332 {% noautoescape %} 333 This will not be auto-escaped: {{ data }}. 334 335 Nor this: {{ other_data }} 336 &
