3 * Wrapper for json_encode and json_decode.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * JSON formatter wrapper class
29 * Skip escaping most characters above U+007F for readability and compactness.
30 * This encoding option saves 3 to 8 bytes (uncompressed) for each such character;
31 * however, it could break compatibility with systems that incorrectly handle UTF-8.
38 * Skip escaping the characters '<', '>', and '&', which have special meanings in
41 * @warning Do not use this option for JSON that could end up in inline scripts.
42 * - HTML5, §4.3.1.2 Restrictions for contents of script elements
43 * - XML 1.0 (5th Ed.), §2.4 Character Data and Markup
50 * Skip escaping as many characters as reasonably possible.
52 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
59 * Characters problematic in JavaScript and their corresponding escape sequences.
61 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
62 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
64 private static $badChars = array(
65 "\xe2\x80\xa8" => '\u2028', // LINE SEPARATOR
66 "\xe2\x80\xa9" => '\u2029', // PARAGRAPH SEPARATOR
70 * Returns the JSON representation of a value.
72 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
73 * array that might be empty to an object before encoding it.
75 * @note In pre-1.21 versions of MediaWiki, using this function for generating inline script
76 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
77 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
79 * @param mixed $value The value to encode. Can be any type except a resource.
80 * @param bool $pretty If true, add non-significant whitespace to improve readability.
81 * @param int $escaping Bitfield consisting of _OK class constants
82 * @return string|bool: String if successful; false upon failure
84 public static function encode( $value, $pretty = false, $escaping = 0 ) {
85 if ( version_compare( PHP_VERSION
, '5.4.0', '<' ) ) {
86 return self
::encode53( $value, $pretty, $escaping );
88 return self
::encode54( $value, $pretty, $escaping );
92 * Decodes a JSON string.
94 * @param string $value The JSON string being decoded
95 * @param bool $assoc When true, returned objects will be converted into associative arrays.
97 * @return mixed: the value encoded in JSON in appropriate PHP type.
98 * Values `"true"`, `"false"`, and `"null"` (case-insensitive) are returned as `true`, `false`
99 * and `null` respectively. `null` is returned if the JSON cannot be
100 * decoded or if the encoded data is deeper than the recursion limit.
102 public static function decode( $value, $assoc = false ) {
103 return json_decode( $value, $assoc );
107 * JSON encoder wrapper for PHP >= 5.4, which supports useful encoding options.
109 * @param mixed $value
110 * @param bool $pretty
111 * @param int $escaping
112 * @return string|bool
114 private static function encode54( $value, $pretty, $escaping ) {
115 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
116 // which is hardly useful when '<' and '>' are escaped, and such escaping negatively
117 // impacts the human readability of URLs and similar strings.
118 $options = JSON_UNESCAPED_SLASHES
;
119 $options |
= $pretty ? JSON_PRETTY_PRINT
: 0;
120 $options |
= ( $escaping & self
::UTF8_OK
) ? JSON_UNESCAPED_UNICODE
: 0;
121 $options |
= ( $escaping & self
::XMLMETA_OK
) ?
0 : ( JSON_HEX_TAG | JSON_HEX_AMP
);
122 $json = json_encode( $value, $options );
123 if ( $json === false ) {
126 return ( $escaping & self
::UTF8_OK
) ?
strtr( $json, self
::$badChars ) : $json;
130 * JSON encoder wrapper for PHP 5.3, which lacks native support for some encoding options.
131 * Therefore, the missing options are implemented here purely in PHP code.
133 * @param mixed $value
134 * @param bool $pretty
135 * @param int $escaping
136 * @return string|bool
138 private static function encode53( $value, $pretty, $escaping ) {
139 $options = ( $escaping & self
::XMLMETA_OK
) ?
0 : ( JSON_HEX_TAG | JSON_HEX_AMP
);
140 $json = json_encode( $value, $options );
141 if ( $json === false ) {
144 $json = str_replace( '\\/', '/', $json ); // emulate JSON_UNESCAPED_SLASHES
145 if ( $escaping & self
::UTF8_OK
) {
146 // JSON hex escape sequences follow the format \uDDDD, where DDDD is four hex digits
147 // indicating the equivalent UTF-16 code unit's value. To most efficiently unescape
148 // them, we exploit the JSON extension's built-in decoder.
149 // * We escape the input a second time, so any such sequence becomes \\uDDDD.
150 // * To avoid interpreting escape sequences that were in the original input,
151 // each double-escaped backslash (\\\\) is replaced with \\\u005c.
152 // * We strip one of the backslashes from each of the escape sequences to unescape.
153 // * Then the JSON decoder can perform the actual unescaping.
154 $doubled = str_replace( "\\\\\\\\", "\\\\\\u005c", json_encode( $json ) );
155 $json = json_decode( preg_replace( "/\\\\\\\\u(?!00[0-7])/", "\\\\u", $doubled ) );
156 $json = strtr( $json, self
::$badChars );
158 return $pretty ? self
::prettyPrint( $json ) : $json;
162 * Adds non-significant whitespace to an existing JSON representation of an object.
163 * Only needed for PHP < 5.4, which lacks the JSON_PRETTY_PRINT option.
165 * @param string $json
168 private static function prettyPrint( $json ) {
171 $json = strtr( $json, array( '\\\\' => '\\\\', '\"' => "\x01" ) );
172 for ( $i = 0, $n = strlen( $json ); $i < $n; $i +
= $skip ) {
174 switch ( $json[$i] ) {
180 $indent++
; // falls through
182 $buf .= $json[$i] . "\n" . str_repeat( ' ', $indent );
187 $buf .= "\n" . str_repeat( ' ', $indent ) . $json[$i];
190 $skip = strcspn( $json, '"', $i +
1 ) +
2;
191 $buf .= substr( $json, $i, $skip );
194 $skip = strcspn( $json, ',]}"', $i +
1 ) +
1;
195 $buf .= substr( $json, $i, $skip );
198 return str_replace( "\x01", '\"', preg_replace( '/ +$/m', '', $buf ) );