| 1 common.inc | filter_xss_attributes(array $attributes) |
Sanitizes attributes.
Parameters
array $attributes: Attribute values as key => value format.
Return value
array: Sanitized attributes.
Related topics
File
- core/
includes/ common.inc, line 1961 - Common functions that many Backdrop modules will need to reference.
Code
function filter_xss_attributes(array $attributes) {
$new_attributes = array();
foreach ($attributes as $name => $value) {
// The attribute name should be a single attribute, but there is the
// possibility that the name is corrupt. Core's _filter_xss_attributes() can
// cleanly handle sanitizing 'selected href="http://example.com" so we
// provide an allowance for cases where the attribute array is malformed.
// For example given a name of 'selected href' and a value of
// http://example.com we split this into two separate attributes, with the
// value assigned to the last attribute name.
// Explode the attribute name if a space exists.
$names = array_filter(explode(' ', $name));
if (count($names) === 0) {
// Empty attribute names.
continue;
}
// Valueless attributes set the name to the value.
$with_values = array_combine($names, $names);
// Convert the attribute array to a string. If there is only one attribute
// this simply creates a new attribute with a single key-value pair.
$last_name = end($names);
$with_values[$last_name] = $value;
$attribute_string = '';
// Convert class arrays to a string.
if (isset($with_values['class']) && is_array($with_values['class'])) {
$with_values['class'] = implode(' ', $with_values['class']);
}
foreach ($with_values as $valued_attribute => $valued_value) {
$attribute_string .= $valued_attribute . '="' . $valued_value . '" ';
}
// Filter the attributes.
$safe = _filter_xss_attributes($attribute_string);
$safe = array_map(function($value) {
return html_entity_decode($value, ENT_QUOTES, 'UTF-8');
}, $safe);
if (array_key_exists('class', $safe)) {
// The class attribute is expected to be an array.
$safe['class'] = explode(' ', $safe['class']);
}
// Special case for boolean values which are unique to valueless
// attributes.
if (array_key_exists($last_name, $safe) && is_bool($value)) {
$safe[$last_name] = $value;
}
// Add the safe attributes to the new list.
$new_attributes += array_intersect_key($safe, $with_values);
}
return $new_attributes;
}