o
    eU                  	   @   s   d dl mZ d dlZd dlZd dlmZ d dlmZ d dlmZ e	dZ
ddgdgdgd	Ze	d
Zddd eed deddeddD Zede d ejZdZG dd deZG dd dZdd ZG dd dejZdS )    )chainN)unescape)html5lib_shim)
parse_shim)aabbracronymb
blockquotecodeemiliolstrongulhreftitle)r   r   r   )httphttpsmailto c                 C   s   g | ]}t |qS  )chr).0cr   r   C/var/www/html/venv/lib/python3.10/site-packages/bleach/sanitizer.py
<listcomp>*       r   	                []?c                   @   s   e Zd ZdS )NoCssSanitizerWarningN)__name__
__module____qualname__r   r   r   r   r'   5   s    r'   c                   @   s0   e Zd ZdZeeeddddfddZdd ZdS )	Cleanera  Cleaner for cleaning HTML fragments of malicious content

    This cleaner is a security-focused function whose sole purpose is to remove
    malicious content from a string such that it can be displayed as content in
    a web page.

    To use::

        from bleach.sanitizer import Cleaner

        cleaner = Cleaner()

        for text in all_the_yucky_things:
            sanitized = cleaner.clean(text)

    .. Note::

       This cleaner is not designed to use to transform content to be used in
       non-web-page contexts.

    .. Warning::

       This cleaner is not thread-safe--the html parser has internal state.
       Create a separate cleaner per thread!


    FTNc           
      C   s   || _ || _|| _|| _|| _|pg | _|| _tj| j | jddd| _	t
d| _tjddddddd| _|du rjg }t|trC|}nt|tr]g }| D ]}	t|	ttfr\||	 qNd|v rltjd	td
 dS dS dS )a:  Initializes a Cleaner

        :arg set tags: set of allowed tags; defaults to
            ``bleach.sanitizer.ALLOWED_TAGS``

        :arg dict attributes: allowed attributes; can be a callable, list or dict;
            defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES``

        :arg list protocols: allowed list of protocols for links; defaults
            to ``bleach.sanitizer.ALLOWED_PROTOCOLS``

        :arg bool strip: whether or not to strip disallowed elements

        :arg bool strip_comments: whether or not to strip HTML comments

        :arg list filters: list of html5lib Filter classes to pass streamed content through

            .. seealso:: http://html5lib.readthedocs.io/en/latest/movingparts.html#filters

            .. Warning::

               Using filters changes the output of ``bleach.Cleaner.clean``.
               Make sure the way the filters change the output are secure.

        :arg CSSSanitizer css_sanitizer: instance with a "sanitize_css" method for
            sanitizing style attribute values and style text; defaults to None

        F)tagsstripconsume_entitiesnamespaceHTMLElementsetreealwaysT)quote_attr_valuesomit_optional_tagsescape_lt_in_attrsresolve_entitiessanitizealphabetical_attributesNstylez7'style' attribute specified, but css_sanitizer not set.)category)r,   
attributes	protocolsr-   strip_commentsfilterscss_sanitizerr   BleachHTMLParserparsergetTreeWalkerwalkerBleachHTMLSerializer
serializer
isinstancelistdictvaluestupleextendwarningswarnr'   )
selfr,   r:   r;   r-   r<   r=   r>   attributes_valuesrH   r   r   r   __init__V   sN   &




zCleaner.__init__c              	   C   s   t |tsd|jjdd }t||sdS | j|}t| || j	| j
| j| j| j| jd}| jD ]}||d}q4| j|S )zCleans text and returns sanitized result as unicode

        :arg str text: text to be cleaned

        :returns: sanitized text as unicode

        :raises TypeError: if ``text`` is not a text type

        zargument cannot be of z type, zmust be of text typer   )sourceallowed_tagsr:   strip_disallowed_tagsstrip_html_commentsr>   allowed_protocols)rP   )rE   str	__class__r(   	TypeErrorr@   parseFragmentBleachSanitizerFilterrB   r,   r:   r-   r<   r>   r;   r=   rD   render)rM   textmessagedomfilteredfilter_classr   r   r   clean   s*   


zCleaner.clean)	r(   r)   r*   __doc__ALLOWED_TAGSALLOWED_ATTRIBUTESALLOWED_PROTOCOLSrO   r`   r   r   r   r   r+   9   s    
Ur+   c                    sH   t  r S t tr fdd}|S t tr  fdd}|S td)a0  Generates attribute filter function for the given attributes value

    The attributes value can take one of several shapes. This returns a filter
    function appropriate to the attributes value. One nice thing about this is
    that there's less if/then shenanigans in the ``allow_token`` method.

    c                    s`   |  v r |  }t |r|| ||S ||v rdS d v r. d }t |r*|| ||S ||v S dS )NT*F)callable)tagattrvalueattr_valr:   r   r   _attr_filter   s   z.attribute_filter_factory.<locals>._attr_filterc                    s   | v S Nr   )rg   rh   ri   rk   r   r   rl      s   z3attributes needs to be a callable, a list or a dict)rf   rE   rG   rF   
ValueError)r:   rl   r   rk   r   attribute_filter_factory   s   

ro   c                	   @   sr   e Zd ZdZeeeejej	ej
dddf	ddZdd Zd	d
 Zdd Zdd Zdd Zdd Zdd Zdd ZdS )rY   zmhtml5lib Filter that sanitizes text

    This filter can be used anywhere html5lib filters can be used.

    FTNc                 C   sT   t j| | t|| _t|| _t|| _|| _|	| _	|| _
|| _|
| _|| _dS )a_  Creates a BleachSanitizerFilter instance

        :arg source: html5lib TreeWalker stream as an html5lib TreeWalker

        :arg set allowed_tags: set of allowed tags; defaults to
            ``bleach.sanitizer.ALLOWED_TAGS``

        :arg dict attributes: allowed attributes; can be a callable, list or dict;
            defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES``

        :arg list allowed_protocols: allowed list of protocols for links; defaults
            to ``bleach.sanitizer.ALLOWED_PROTOCOLS``

        :arg attr_val_is_uri: set of attributes that have URI values

        :arg svg_attr_val_allows_ref: set of SVG attributes that can have
            references

        :arg svg_allow_local_href: set of SVG elements that can have local
            hrefs

        :arg bool strip_disallowed_tags: whether or not to strip disallowed
            tags

        :arg bool strip_html_comments: whether or not to strip HTML comments

        :arg CSSSanitizer css_sanitizer: instance with a "sanitize_css" method for
            sanitizing style attribute values and style text; defaults to None

        N)r   FilterrO   	frozensetrQ   rT   ro   attr_filterrR   rS   attr_val_is_urisvg_attr_val_allows_refr>   svg_allow_local_href)rM   rP   rQ   r:   rT   rs   rt   ru   rR   rS   r>   r   r   r   rO     s   0



zBleachSanitizerFilter.__init__c                 c   s<    |D ]}|  |}|sqt|tr|E d H  q|V  qd S rm   )sanitize_tokenrE   rF   )rM   token_iteratortokenretr   r   r   sanitize_streamA  s   

z%BleachSanitizerFilter.sanitize_streamc                 c   s    g }|D ]2}|r(|d dkr| | qddd |D dd}g }|V  n|d dkr4| | q|V  qddd |D dd}|V  dS )	z/Merge consecutive Characters tokens in a streamtype
Charactersr   c                 S      g | ]}|d  qS datar   r   
char_tokenr   r   r   r   [  r   z:BleachSanitizerFilter.merge_characters.<locals>.<listcomp>)r   r{   c                 S   r}   r~   r   r   r   r   r   r   i  r   N)appendjoin)rM   rw   characters_bufferrx   	new_tokenr   r   r   merge_charactersM  s,   


z&BleachSanitizerFilter.merge_charactersc                 C   s   |  | tj| S rm   )r   rz   r   rp   __iter__)rM   r   r   r   r   n  s   zBleachSanitizerFilter.__iter__c                 C   s   |d }|dv r|d | j v r| |S | jrdS | |S |dkr7| js5tj|d ddd	d
|d< |S dS |dkr@| |S |S )a  Sanitize a token either by HTML-encoding or dropping.

        Unlike sanitizer.Filter, allowed_attributes can be a dict of {'tag':
        ['attribute', 'pairs'], 'tag': callable}.

        Here callable is a function with two arguments of attribute name and
        value. It should return true of false.

        Also gives the option to strip tags instead of encoding.

        :arg dict token: token to sanitize

        :returns: token or list of tokens

        r{   )StartTagEndTagEmptyTagnameNCommentr   z&quot;z&#x27;)"')entitiesr|   )rQ   allow_tokenrR   disallowed_tokenrS   r   escapesanitize_characters)rM   rx   
token_typer   r   r   rv   s  s"   



z$BleachSanitizerFilter.sanitize_tokenc                 C   s   | dd}|s
|S tt|}||d< d|vr|S g }t|D ]E}|s&q!|dr^t|}|dur^|dkrA|ddd n|d|d	 |t	|d
 d }|r]|d|d q!|d|d q!|S )a  Handles Characters tokens

        Our overridden tokenizer doesn't do anything with entities. However,
        that means that the serializer will convert all ``&`` in Characters
        tokens to ``&amp;``.

        Since we don't want that, we extract entities here and convert them to
        Entity tokens so the serializer will let them be.

        :arg token: the Characters token to work on

        :returns: a list of tokens

        r   r   &Nampr|   )r{   r   Entity)r{   r      )
getINVISIBLE_CHARACTERS_REsubINVISIBLE_REPLACEMENT_CHARr   next_possible_entity
startswithmatch_entityr   len)rM   rx   r   
new_tokenspartentity	remainderr   r   r   r     s.   

z)BleachSanitizerFilter.sanitize_charactersc                 C   s   t |}tdd|}|dd}| }zt|}W n
 ty'   Y dS w |j	r4|j	|v r2|S dS |
dr;|S d|v rJ|dd |v rJ|S d|v sRd	|v rT|S dS )
zChecks a uri value to see if it's allowed

        :arg value: the uri value to sanitize
        :arg allowed_protocols: list of allowed protocols

        :returns: allowed value or None

        z[`\000-\040\177-\240\s]+r   u   �N#:r   r   r   )r   convert_entitiesrer   replacelowerr   urlparsern   schemer   split)rM   ri   rT   normalized_uriparsedr   r   r   sanitize_uri_value  s*   


z(BleachSanitizerFilter.sanitize_uri_valuec           	      C   s   d|v r|i }|d   D ]k\}}|\}}| |d ||sq|| jv r1| || j}|du r/q|}|| jv rHtddt|}|	 }|sFq|}d|d f| j
v rc|dtjd dffv rctd	|rcq|d
krs| jrq| j|}nd}|||< q||d< |S )z-Handles the case where we're allowing the tagr   r   Nzurl\s*\(\s*[^#\s][^)]+?\) )Nr   xlinkr   z
^\s*[^#\s])Nr8   r   )itemsrr   rs   r   rT   rt   r   r   r   r-   ru   r   
namespacessearchr>   sanitize_css)	rM   rx   attrsnamespaced_nameval	namespacer   	new_valuenew_valr   r   r   r     s>   


z!BleachSanitizerFilter.allow_tokenc                 C   s  |d }|dkrd|d  d|d< n^|d rg|dv sJ g }|d   D ]1\\}}}|r4|s4||}}|d u s=|tjvr@|}n
tj|  d| }|d	| d
| d q%d|d  d| d|d< n
d|d  d|d< |dr|d d d  d|d< d|d< |d= |S )Nr{   r   z</r   >r   )r   r   r   r   z="r   <r   selfClosingz/>r|   )r   r   prefixesr   r   r   )rM   rx   r   r   nsr   vr   r   r   r   r   Z  s(   
 
z&BleachSanitizerFilter.disallowed_token)r(   r)   r*   ra   rb   rc   rd   r   rs   rt   ru   rO   rz   r   r   rv   r   r   r   r   r   r   r   r   rY      s(    	
>!+=:ErY   )	itertoolsr   r   rK   xml.sax.saxutilsr   bleachr   r   rq   rb   rc   rd   r   rangeINVISIBLE_CHARACTERScompileUNICODEr   r   UserWarningr'   r+   ro   SanitizerFilterrY   r   r   r   r   <module>   s0    & +