[documentos]defescape(text):""" Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. This function always escapes its input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """returnmark_safe(force_text(text).replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('"','&quot;').replace("'",'&#39;'))

_js_escapes={ord('\\'):'\\u005C',ord('\''):'\\u0027',ord('"'):'\\u0022',ord('>'):'\\u003E',ord('<'):'\\u003C',ord('&'):'\\u0026',ord('='):'\\u003D',ord('-'):'\\u002D',ord(';'):'\\u003B',ord('\u2028'):'\\u2028',ord('\u2029'):'\\u2029'}# Escape every ASCII character with a value less than 32._js_escapes.update((ord('%c'%z),'\\u%04X'%z)forzinrange(32))@keep_lazy(six.text_type,SafeText)defescapejs(value):"""Hex encodes characters for use in JavaScript strings."""returnmark_safe(force_text(value).translate(_js_escapes))

[documentos]defconditional_escape(text):""" Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ifhasattr(text,'__html__'):returntext.__html__()else:returnescape(text)

[documentos]defformat_html(format_string,*args,**kwargs):""" Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """args_safe=map(conditional_escape,args)kwargs_safe={k:conditional_escape(v)for(k,v)insix.iteritems(kwargs)}returnmark_safe(format_string.format(*args_safe,**kwargs_safe))

[documentos]defformat_html_join(sep,format_string,args_generator):""" A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """returnmark_safe(conditional_escape(sep).join(format_html(format_string,*tuple(args))forargsinargs_generator))

[documentos]defstrip_tags(value):"""Returns the given HTML with all tags stripped."""# Note: in typical case this loop executes _strip_once once. Loop condition# is redundant, but helps to reduce number of executions of _strip_once.value=force_text(value)while'<'invalueand'>'invalue:new_value=_strip_once(value)iflen(new_value)>=len(value):# _strip_once was not able to detect more tags or length increased# due to http://bugs.python.org/issue20288# (affects Python 2 < 2.7.7 and Python 3 < 3.3.5)breakvalue=new_valuereturnvalue

@keep_lazy_textdefstrip_spaces_between_tags(value):"""Returns the given HTML with spaces between tags removed."""returnre.sub(r'>\s+<','><',force_text(value))defsmart_urlquote(url):"Quotes a URL if it isn't already quoted."defunquote_quote(segment):segment=unquote(force_str(segment))# Tilde is part of RFC3986 Unreserved Characters# http://tools.ietf.org/html/rfc3986#section-2.3# See also http://bugs.python.org/issue16285segment=quote(segment,safe=RFC3986_SUBDELIMS+RFC3986_GENDELIMS+str('~'))returnforce_text(segment)# Handle IDN before quoting.try:scheme,netloc,path,query,fragment=urlsplit(url)exceptValueError:# invalid IPv6 URL (normally square brackets in hostname part).returnunquote_quote(url)try:netloc=netloc.encode('idna').decode('ascii')# IDN -> ACEexceptUnicodeError:# invalid domain partreturnunquote_quote(url)ifquery:# Separately unquoting key/value, so as to not mix querystring separators# included in query values. See #22267.query_parts=[(unquote(force_str(q[0])),unquote(force_str(q[1])))forqinparse_qsl(query,keep_blank_values=True)]# urlencode will take care of quotingquery=urlencode(query_parts)path=unquote_quote(path)fragment=unquote_quote(fragment)returnurlunsplit((scheme,netloc,path,query,fragment))@keep_lazy_textdefurlize(text,trim_url_limit=None,nofollow=False,autoescape=False):""" Converts any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in the link text longer than this limit will be truncated to trim_url_limit-3 characters and appended with an ellipsis. If nofollow is True, the links will get a rel="nofollow" attribute. If autoescape is True, the link text and URLs will be autoescaped. """safe_input=isinstance(text,SafeData)deftrim_url(x,limit=trim_url_limit):iflimitisNoneorlen(x)<=limit:returnxreturn'%s...'%x[:max(0,limit-3)]defunescape(text,trail):""" If input URL is HTML-escaped, unescape it so as we can safely feed it to smart_urlquote. For example: http://example.com?x=1&amp;y=&lt;2&gt; => http://example.com?x=1&y=<2> """unescaped=(text+trail).replace('&amp;','&').replace('&lt;','<').replace('&gt;','>').replace('&quot;','"').replace('&#39;',"'")iftrailandunescaped.endswith(trail):# Remove trail for unescaped if it was not consumed by unescapeunescaped=unescaped[:-len(trail)]eliftrail==';':# Trail was consumed by unescape (as end-of-entity marker), move it to texttext+=trailtrail=''returntext,unescaped,traildeftrim_punctuation(lead,middle,trail):""" Trim trailing and wrapping punctuation from `middle`. Return the items of the new state. """# Continue trimming until middle remains unchanged.trimmed_something=Truewhiletrimmed_something:trimmed_something=False# Trim trailing punctuation.match=TRAILING_PUNCTUATION_RE.match(middle)ifmatch:middle=match.group(1)trail=match.group(2)+trailtrimmed_something=True# Trim wrapping punctuation.foropening,closinginWRAPPING_PUNCTUATION:ifmiddle.startswith(opening):middle=middle[len(opening):]lead+=openingtrimmed_something=True# Keep parentheses at the end only if they're balanced.if(middle.endswith(closing)andmiddle.count(closing)==middle.count(opening)+1):middle=middle[:-len(closing)]trail=closing+trailtrimmed_something=Truereturnlead,middle,trailwords=word_split_re.split(force_text(text))fori,wordinenumerate(words):if'.'inwordor'@'inwordor':'inword:# lead: Current punctuation trimmed from the beginning of the word.# middle: Current state of the word.# trail: Current punctuation trimmed from the end of the word.lead,middle,trail='',word,''# Deal with punctuation.lead,middle,trail=trim_punctuation(lead,middle,trail)# Make URL we want to point to.url=Nonenofollow_attr=' rel="nofollow"'ifnofollowelse''ifsimple_url_re.match(middle):middle,middle_unescaped,trail=unescape(middle,trail)url=smart_urlquote(middle_unescaped)elifsimple_url_2_re.match(middle):middle,middle_unescaped,trail=unescape(middle,trail)url=smart_urlquote('http://%s'%middle_unescaped)elif':'notinmiddleandsimple_email_re.match(middle):local,domain=middle.rsplit('@',1)try:domain=domain.encode('idna').decode('ascii')exceptUnicodeError:continueurl='mailto:%s@%s'%(local,domain)nofollow_attr=''# Make link.ifurl:trimmed=trim_url(middle)ifautoescapeandnotsafe_input:lead,trail=escape(lead),escape(trail)trimmed=escape(trimmed)middle='<a href="%s"%s>%s</a>'%(escape(url),nofollow_attr,trimmed)words[i]=mark_safe('%s%s%s'%(lead,middle,trail))else:ifsafe_input:words[i]=mark_safe(word)elifautoescape:words[i]=escape(word)elifsafe_input:words[i]=mark_safe(word)elifautoescape:words[i]=escape(word)return''.join(words)defavoid_wrapping(value):""" Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """returnvalue.replace(" ","\xa0")