WC_Helper_Sanitization::sanitize_csspublic staticWC 1.0

Sanitize CSS markup from API responses for safe rendering in admin pages.

Method of the class: WC_Helper_Sanitization{}

No Hooks.

Returns

String. Sanitized CSS safe for inclusion in style blocks.

Usage

$result = WC_Helper_Sanitization::sanitize_css( $css );
$css(string) (required)
The raw CSS to sanitize.

WC_Helper_Sanitization::sanitize_css() code WC 10.3.3

public static function sanitize_css( $css ) {
	// Handle non-string inputs (return empty string).
	if ( ! is_string( $css ) ) {
		return '';
	}

	// Remove potentially harmful constructs.
	$css = preg_replace( '/@import\s+[^;]+;?/', '', $css );

	// Block all data URIs.
	$css = preg_replace( '/url\s*\(\s*([\'"]?)data:/i', 'url($1invalid:', $css );

	// Only allow URLs from specific trusted domains and their subdomains.
	$css = preg_replace_callback(
		'/url\s*\(\s*([\'"]?)(https?:\/\/[^)]+)\1\s*\)/i',
		function ( $matches ) {
			$url   = $matches[2];
			$quote = $matches[1];

			// Check if URL belongs to allowed domains.
			if ( preg_match(
				'/^https?:\/\/(([\w-]+\.)*woocommerce\.com|' .
				'([\w-]+\.)*woocommerce\.test|' .
				'([\w-]+\.)*WordPress\.com|' .
				'([\w-]+\.)*wp\.com)/ix',
				$url
			) ) {
				// URL is from a trusted domain, keep it.
				return "url({$quote}{$url}{$quote})";
			} else {
				// URL is not from a trusted domain, make it ineffective.
				return "url({$quote}#blocked-url{$quote})";
			}
		},
		$css
	);

	// Preserve all asterisks by temporarily replacing them.
	$css = str_replace( '*', '__PRESERVED_ASTERISK__', $css );

	// Remove HTML tags and PHP.
	$css = wp_strip_all_tags( $css );

	// Remove any JavaScript events.
	$css = preg_replace( '/\s*expression\s*\(.*?\)/', '', $css );
	$css = preg_replace( '/\s*javascript\s*:/', '', $css );

	// Block other potentially dangerous protocols.
	$css = preg_replace( '/(behavior|eval|calc|mocha)(\s*:|\s*\()/i', 'blocked', $css );

	// Restore all asterisks.
	$css = str_replace( '__PRESERVED_ASTERISK__', '*', $css );

	// We assume relative and root-relative URLs are safe because they point to resources on the same domain.

	// Limit size of CSS to prevent DoS.
	$css = substr( $css, 0, 100000 );

	return $css;
}