3.4.0-rc1
[phpmyadmin/thilanka.git] / libraries / js_escape.lib.php
blob0773eecce10da8d4ed0d1bf0b742d10c73aec707
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Javascript escaping functions.
6 * @package phpMyAdmin
8 */
10 /**
11 * Format a string so it can be a string inside JavaScript code inside an
12 * eventhandler (onclick, onchange, on..., ).
13 * This function is used to displays a javascript confirmation box for
14 * "DROP/DELETE/ALTER" queries.
16 * @uses PMA_escapeJsString()
17 * @uses PMA_backquote()
18 * @uses is_string()
19 * @uses htmlspecialchars()
20 * @uses str_replace()
21 * @param string $a_string the string to format
22 * @param boolean $add_backquotes whether to add backquotes to the string or not
24 * @return string the formatted string
26 * @access public
28 function PMA_jsFormat($a_string = '', $add_backquotes = true)
30 if (is_string($a_string)) {
31 $a_string = htmlspecialchars($a_string);
32 $a_string = PMA_escapeJsString($a_string);
33 /**
34 * @todo what is this good for?
36 $a_string = str_replace('#', '\\#', $a_string);
39 return (($add_backquotes) ? PMA_backquote($a_string) : $a_string);
40 } // end of the 'PMA_jsFormat()' function
42 /**
43 * escapes a string to be inserted as string a JavaScript block
44 * enclosed by <![CDATA[ ... ]]>
45 * this requires only to escape ' with \' and end of script block
47 * We also remove NUL byte as some browsers (namely MSIE) ignore it and
48 * inserting it anywhere inside </script would allow to bypass this check.
50 * @uses strtr()
51 * @uses preg_replace()
52 * @param string $string the string to be escaped
53 * @return string the escaped string
55 function PMA_escapeJsString($string)
57 return preg_replace('@</script@i', '</\' + \'script',
58 strtr($string, array(
59 "\000" => '',
60 '\\' => '\\\\',
61 '\'' => '\\\'',
62 '"' => '\"',
63 "\n" => '\n',
64 "\r" => '\r')));
67 /**
68 * Prints an javascript assignment with proper escaping of a value
69 * and support for assigning array of strings.
71 * @param string $key Name of value to set
72 * @param mixed $value Value to set, can be either string or array of strings
74 function PMA_printJsValue($key, $value) {
75 echo $key . ' = ';
76 if (is_array($value)) {
77 echo '[';
78 foreach ($value as $id => $val) {
79 echo "'" . PMA_escapeJsString($val) . "',";
81 echo "];\n";
82 } else {
83 echo "'" . PMA_escapeJsString($value) . "';\n";