* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Escape
{
/**
* The internal singleton escaper instance
*/
protected static Escaper|null $escaper = null;
/**
* Escape common HTML attributes data
*
* This can be used to put untrusted data into typical attribute values
* like width, name, value, etc.
*
* This should not be used for complex attributes like href, src, style,
* or any of the event handlers like onmouseover.
* Use esc($string, 'js') for event handler attributes, esc($string, 'url')
* for src attributes and esc($string, 'css') for style attributes.
*
*
content
* content
* content
*/
public static function attr(string $string): string
{
return static::escaper()->escapeHtmlAttr($string);
}
/**
* Escape HTML style property values
*
* This can be used to put untrusted data into a stylesheet or a style tag.
*
* Stay away from putting untrusted data into complex properties like url,
* behavior, and custom (-moz-binding). You should also not put untrusted data
* into IE’s expression property value which allows JavaScript.
*
*
*
* text
*/
public static function css(string $string): string
{
return static::escaper()->escapeCss($string);
}
/**
* Get the escaper instance (and create if needed)
*/
protected static function escaper(): Escaper
{
return static::$escaper ??= new Escaper('utf-8');
}
/**
* Escape HTML element content
*
* This can be used to put untrusted data directly into the HTML body somewhere.
* This includes inside normal tags like div, p, b, td, etc.
*
* Escapes &, <, >, ", and ' with HTML entity encoding to prevent switching
* into any execution context, such as script, style, or event handlers.
*
* ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...
* ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...
*/
public static function html(string $string): string
{
return static::escaper()->escapeHtml($string);
}
/**
* Escape JavaScript data values
*
* This can be used to put dynamically generated JavaScript code
* into both script blocks and event-handler attributes.
*
*
*
*
*/
public static function js(string $string): string
{
return static::escaper()->escapeJs($string);
}
/**
* Escape URL parameter values
*
* This can be used to put untrusted data into HTTP GET parameter values.
* This should not be used to escape an entire URI.
*
*
link
*/
public static function url(string $string): string
{
return rawurlencode($string);
}
/**
* Escape XML element content
*
* Removes offending characters that could be wrongfully interpreted as XML markup.
*
* The following characters are reserved in XML and will be replaced with their
* corresponding XML entities:
*
* ' is replaced with '
* " is replaced with "
* & is replaced with &
* < is replaced with <
* > is replaced with >
*/
public static function xml(string $string): string
{
return htmlspecialchars($string, ENT_QUOTES | ENT_XML1, 'UTF-8');
}
}