diff --git a/phpBB/includes/functions.php b/phpBB/includes/functions.php index d7088ac129..5d8a92b63b 100644 --- a/phpBB/includes/functions.php +++ b/phpBB/includes/functions.php @@ -4893,6 +4893,53 @@ function phpbb_http_login($param) trigger_error('NOT_AUTHORISED'); } +/** +* Escapes and quotes a string for use as an HTML/XML attribute value. +* +* This is a port of Python xml.sax.saxutils quoteattr. +* +* The function will attempt to choose a quote character in such a way as to +* avoid escaping quotes in the string. If this is not possible the string will +* be wrapped in double quotes and double quotes will be escaped. +* +* @param string $data The string to be escaped +* @param array $entities Associative array of additional entities to be escaped +* @return string Escaped and quoted string +*/ +function phpbb_quoteattr($data, $entities = null) +{ + $data = str_replace('&', '&', $data); + $data = str_replace('>', '>', $data); + $data = str_replace('<', '<', $data); + + $data = str_replace("\n", ' ', $data); + $data = str_replace("\r", ' ', $data); + $data = str_replace("\t", ' ', $data); + + if (!empty($entities)) + { + $data = str_replace(array_keys($entities), array_values($entities), $data); + } + + if (strpos($data, '"') !== false) + { + if (strpos($data, "'") !== false) + { + $data = '"' . str_replace('"', '"', $data) . '"'; + } + else + { + $data = "'" . $data . "'"; + } + } + else + { + $data = '"' . $data . '"'; + } + + return $data; +} + /** * Generate page header */ diff --git a/tests/functions/quoteattr_test.php b/tests/functions/quoteattr_test.php new file mode 100644 index 0000000000..9d2a7d470e --- /dev/null +++ b/tests/functions/quoteattr_test.php @@ -0,0 +1,44 @@ +', null, '"<a>"'), + array('&', null, '"&amp;"'), + array('"hello"', null, "'\"hello\"'"), + array("'hello'", null, "\"'hello'\""), + array("\"'", null, "\""'\""), + array("a\nb", null, '"a b"'), + array("a\r\nb", null, '"a b"'), + array("a\tb", null, '"a b"'), + array('a b', null, '"a b"'), + array('"a 'z'), '"zoo"'), + array('', array('a' => '&'), '"<&>"'), + ); + } + + /** + * @dataProvider quoteattr_test_data + */ + public function test_quoteattr($input, $entities, $expected) + { + $output = phpbb_quoteattr($input, $entities); + + $this->assertEquals($expected, $output); + } +}