
    h!6                     H   U d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	 d dl
mZ d dlmZ d dlZd dlmZ d dlmZ d dlmZ  ej*                  d	      Zh d
h dh ddZddhZ G d d      Z e       Zeed<   d.dedee   dedefdZi Zde defdZ!d/de dede fdZ"d/dedejF                  ded eddf
d!Z$d/dedejF                  ded eddf
d"Z%d0d#ededefd$Z&ded%e'ddfd&Z( e(d'e$        e(d(e%       	 d dl)Z)d d)l*m+Z+ d, Z-d.d-Z.y# e,$ r  G d* d+      Z*Y w xY w)1    N)deepcopy)OptionalUnion)apps)models)etree)Element)settingsz<[^>]*data-cms-[^>]*>>   relhreftarget>   render-pluginidaltnametypetitle>   roleclassstyle)az
cms-plugin*zdata-zaria-c                       e Zd ZdZ	 	 ddeeeee   f      deee      fdZdeee	eeee   f   ee   df   f   fdZ
y)		NH3Parsera  

    NH3Parser

    This class represents a HTML parser for sanitation using NH3. It provides methods to configure the NH3 sanitizer

    Attributes:
    - ALLOWED_TAGS: A set of allowed HTML tags.
    - ALLOWED_ATTRIBUTES: A dictionary mapping HTML tags to sets of allowed attributes for each tag.
    - generic_attribute_prefixes: A set of prefixes that can be used in attribute names to indicate generic attributes.

    Methods:
    - __init__: Initializes the NH3Parser object.
    Nadditional_attributesgeneric_attribute_prefixesc                    |t         }|t        }t        t        j                        | _        t        t        j
                        | _        t        t        j                        t        t        j                        z  | _        || _
        t        j                  j                         D ]  \  }}||v r||   |z  ||<   |||<    |r| xj                  |j                         D ch c]
  }|dk7  s	| c}z  c_        |j                         D ]9  \  }}| j
                  j                  |t                     |z  | j
                  |<   ; y y c c}w )Nr   )cms_additional_attributescms_generic_attribute_prefixesr   nh3ALLOWED_TAGSALLOWED_ATTRIBUTESALLOWED_URL_SCHEMESsetr
   TEXT_ADDITIONAL_PROTOCOLSr   TEXT_ADDITIONAL_ATTRIBUTESitemskeysget)selfr   r   tag
attributeskeys         C/home/dcms/DCMS/lib/python3.12/site-packages/djangocms_text/html.py__init__zNH3Parser.__init__,   sA   
 !($=!%-)G&&.s/?/?&@7?@V@V7W-5c6M6M-NQTU]UwUwQx-x 4N''BBHHJ 	8OC++-B3-G*-T%c*-7%c*		8 !1F1K1K1M!\#QTX[Q[#!\\#8#>#>#@ dZ/3/F/F/J/J3PSPU/VYc/c'',d !!\s   '
E2Ereturnc                 b    | j                   | j                  | j                  | j                  ddS )aq  
        Return a dictionary containing the attributes, tags, generic_attribute_prefixes, and link_rel values for
        immediate passing to the nh3.clean function.

        :return: A dictionary with the following keys:
            - "attributes": A dictionary containing the allowed attributes setting.
            - "tags": The set of allowed tags.
            - "generic_attribute_prefixes": The set of generic attribute prefixes.
            - "link_rel": None

        The dictionary represents the allowed configurations for the method.

        :rtype: dict[str, Union[dict[str, set[str]], set[str], None]]
        N)r,   tagsr   url_schemeslink_rel)r"   r!   r   r#   )r*   s    r.   __call__zNH3Parser.__call__F   s5      11%%*.*I*I33
 	
    NN)__name__
__module____qualname____doc__r   dictstrr$   r/   r   r5    r6   r.   r   r      sy    " @D9=d'S#c(](;<d %-SX$6d4
$sE$sCH}*=s3x*M$NNO 
r6   r   
cms_parserdatafullcleanerr0   c                     t         j                  du r| S |t        j                  dt        d       |xs t
        }t        j                  | fi  |       S )z
    Cleans HTML from XSS vulnerabilities using nh3
    If full is False, only the contents inside <body> will be returned (without
    the <body> tags).
    Fz/full argument is deprecated and will be removed   )category
stacklevel)r
   TEXT_HTML_SANITIZEwarningswarnDeprecationWarningr?   r    clean)r@   rA   rB   s      r.   
clean_htmlrL   b   sT     ""e+='	

 #G99T'WY''r6   poolc                 L    | r"ddj                  | j                               z   S y)a  
    Generate an xpath expression based on the given pool of attributes.

    :param pool: A dictionary of attributes to be included in the xpath expression.
    :type pool: dict

    :return: A string representing the xpath expression.
    :rtype: str
    z//*[@z] | // )joinr(   )rM   s    r.   	get_xpathrQ   z   s$     tyy{333r6   r   admin_objectsc                 N   i } | j                          D ]  \  }}i ||<   	 t        j                  |j                  d      dd  }|rt	        |d      r|j
                  }n|j                  }|j                  |      D ]  }|||   |j                  <     |S # t        $ r Y w xY w)a
  
    Retrieve data from the database.

    Parameters:
    - models (dict): A dictionary mapping model names to lists of object IDs.
    - admin_objects (bool, optional): Flag indicating whether to retrieve latest admin objects
      (e.g., unpublished versions only visible in the admin). Defaults to False.

    Returns:
    - dict: A dictionary containing the retrieved data, with model names as keys and dictionaries of objects as values.
      The inner dictionaries have object IDs as keys and objects as values
    .NrD   admin_manager)id__in)
r'   r   	get_modelsplithasattrrU   objectsfilterr   	Exception)r   rR   resultmodelidsDjangoModelobjs          r.   get_data_from_dbrb      s     F"flln 
su
	..%++c*:2A*>?Ko!F)77)11")))5 ,(+ucff%, M  		s   A4B	B$#B$elemra   attr	edit_modec                     d}t        |d      r#|j                         }|xs d| j                  |<   |s*d| j                  d<   | j                  dk(  r|sd| _        yyyy)	a
  
    Modifies an element's attribute to create a dynamic hyperlink based on the provided model object.
    In case the object has a "get_absolute_url" method, and it returns a non-empty value, the attribute of the
    element will be set to the URL returned by the method.
    Otherwise, the "data-cms-error" attribute of the element will be set to "ref-not-found".

    A hyperlink with a missing reference will be turned into a span element with a "data-cms-error" attribute set to
    "ref-not-found".

    :param elem: The element to modify.
    :type elem: Element
    :param obj: The model object to use for generating the hyperlink.
    :type obj: models.Model
    :param attr: The attribute name to set the generated hyperlink.
    :type attr: str
    :return: None
    rO   get_absolute_url#ref-not-founddata-cms-errorr   spanN)rY   rg   attribr+   rc   ra   rd   re   target_values        r.   dynamic_hrefro      sg    & Ls&'++-(/CD(7$%88s?9DH $-? r6   c                     d}t        |d      r/|j                         }|r|j                         | j                  |<   |sd| j                  d<   yy)a  
    This method modifies the provided element by setting the value of the specified attribute based on the provided
    object. If the object has a "get_absolute_url" method, and it returns a non-empty value, the attribute of the
    element will be set to the URL returned by the method. Otherwise, the "data-cms-error" attribute of the XML
    element will be set to "ref-not-found".

    :param elem: The XML element to modify.
    :type elem: Element
    :param obj: The object to use as the source of the attribute value.
    :type obj: models.Model
    :param attr: The attribute name to modify in the XML element.
    :type attr: str

    :return: None
    :rtype: NoneType
    rO   rg   ri   rj   N)rY   rg   rl   rm   s        r.   dynamic_srcrq      sS    " Ls&'++- # 4 4 6DKK(7$% r6   dyn_htmlc                     t         j                  |       s| S i }t        j                  | t        j                               }|| S t        t              }g }d}|j                  |      D ]  }|j                  j                         D ]  \  }	}
|	t        v s	 |
j                  dd      \  }}|j                         |v r:||j                            j                  t        |j                                      n+t        |j                               h||j                         <   |j!                  |         t#        ||      }|D ]  }|j                  j                         D ]  \  }	}
|	t        v s|	t%        |      d }	 |
j                  dd      \  }}||j                            t        |j                                  }t        |	   ||||       |su|j                  |	=   t        j(                  |d	      j+                  d
      }|j-                  d      j/                  d      }|j-                  d      j/                  d      }|S # t        t        f$ r Y Aw xY w# t&        t        f$ r d}Y w xY w)a  
    Render method to update dynamic attributes in HTML

    Parameters:
    - dyn_html (str): The HTML content with dynamic attributes
    - admin_objects (bool) (optional): Flag to indicate whether to fetch data from admin objects (default: False)
    - remove_attr (bool) (optional): Flag to indicate whether to remove dynamic attributes from the final HTML
      (default: True)

    Returns:
    - str: The updated HTML content with dynamic attributes

    )parserNz	data-cms-:   )rR   )re   html)methodzutf-8z<html>z</html>z<body>z</body>)dyn_attr_patternsearchr   
fromstring
HTMLParserrQ   dynamic_attr_poolxpathrl   r'   rsplitstripaddint	TypeError
ValueErrorappendrb   lenKeyErrortostringdecoderemoveprefixremovesuffix)rr   rR   remove_attrreq_model_objtreer~   update_queueprefixrc   rd   valuer^   pkfrom_dbtarget_attrra   docs                    r.   render_dynamic_attributesr      sK    ""8,MHU-=-=-?@D|'(ELF

5! *;;,,. 
	*KD%(( %S! 4IE2{{}5%ekkm488RXXZI8;BHHJ7Hekkm4 ##D)
	** }MJG *;;,,. 	*KD%(("3v;=1 %S! 4IE2!%++-0RXXZAC "$'c;-XD)	** ..f
-
4
4W
=C


8
$
1
1)
<C


8
$
1
1)
<CJ) ":.  !*- Cs&   BIAI)I&%I&)I=<I=render_funcc                     |t         | <   y )N)r}   )rd   r   s     r.   register_attrr     s    )dr6   zdata-cms-hrefzdata-cms-src)Imagec                       e Zd Zy)PILN)r8   r9   r:   r>   r6   r.   r   r   %  s    r6   r   c                    ddl m} t        j                  s| S t        j
                  j                  d      }t        j                  j                  |      }|j                  |       }d}|j                  d      D ]  }|j                  d      }|j                  d      s'|j                  d	      }	|j                  d
      }
t        j                  d      }|j                  |      }|j!                         }|d   }|d   }|j#                  d      r|j%                  d      d   }	 t'        j(                  |      }	 |j%                  d      d   }t1        j2                  |      }|dk(  s|dk(  rd}n`|dk(  rd}nX|dk(  rd}nPt5        j6                  |      }t1        j2                         }d}|j9                  |d       |j;                  d       |}t=        j>                          d| }tA        ||||	|
      } ||      }|jB                  jE                  |jG                  |      jH                  d   |       d} |rIdjK                  |j                  d      d   jH                  D cg c]  }|jM                          c}      S | S # t*        $ r t'        j,                  |      }Y sw xY w# t.        $ r d}Y pw xY wc c}w )zt
    extracts base64 encoded images from drag and drop actions in browser and saves
    those images as plugins
    rv   )plugin_to_tagdom)r   Fimgsrczdata:widthheightz=data:(?P<mime_type>[^"]*);(?P<encoding>[^"]*),(?P<data>[^"]*)	mime_typer@   ;r   /rO   jpgjpegpnggifJPEGrT   )parent_pluginr   r   Tbody)'utilsr   r
   TEXT_SAVE_IMAGE_FUNCTIONhtml5libtreebuildersgetTreeBuilderhtml5parserr|   parsegetElementsByTagNamegetAttribute
startswithrecompilerz   	groupdictfindrX   base64	b64decoder\   urlsafe_b64decode
IndexErrorioBytesIOr   opensaveseekuuiduuid4img_data_to_plugin
parentNodereplaceChildparseFragment
childNodesrP   toxml)r@   pluginr   tree_builderrt   r   foundr   r   r   r   data_remdrr   
image_data
image_typeimagefile_endingim	new_imagefilenameimage_pluginnew_img_htmlys                            r.   extract_imagesr   )  s   
 %,,((77>L!!,,,,?F
,,t
CE''. 5u%~~g&  )!!(+**]^NN3[[]{O	Z
>>#!,Q/I	>))*5J	"-a0J 

:&*"6K5 K5 K E"B

IKGGIv&NN1Ejjl^1[M2) 
 %\2##F$8$8$F$Q$QRS$TVYZk5l ww3+C+CF+KA+N+Y+YZa	Z[[Q  	>11*=J	>  	J	D [s*   +JJ72K	J43J47KKc                     t         j                  j                  d      d   }t        dj	                  t         j                  j                  d      d d       |g      }t        ||      } || ||||      S )NrT   )fromlist)r   r   )r
   r   rX   
__import__rP   getattr)r   r   r   r   r   	func_namemodulefuncs           r.   r   r   r  sq    1177<R@I2288=crBCF 69%D%eFKKr6   r7   )F)FT)/r   r   r   r   rH   copyr   typingr   r   django.appsr   	django.dbr   r    lxmlr   
lxml.etreer	   djangocms_textr
   r   ry   r   r   r   r?   __annotations__r=   boolrL   r}   r<   rQ   rb   Modelro   rq   r   callabler   r   r   r   ModuleNotFoundErrorr   r   r>   r6   r.   <module>r      s    	 	    "   
   # 2::67 	"I	# 
 #*7!3 ?
 ?
D "
I #(S ( (	 (UX ((  D S T $ 4 <w V\\   Z^ :8g 8FLL 8 8 8Y] 847 7D 7_b 7t* *( *t * o| , nk *FRL_   s   =
D D! D!