Merge "Bidi-isolate extension version on Special:Version"
[lhc/web/wiklou.git] / includes / json / FormatJson.php
1 <?php
2 /**
3 * Wrapper for json_encode and json_decode.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * JSON formatter wrapper class
25 */
26 class FormatJson {
27 /**
28 * Skip escaping most characters above U+007F for readability and compactness.
29 * This encoding option saves 3 to 8 bytes (uncompressed) for each such character;
30 * however, it could break compatibility with systems that incorrectly handle UTF-8.
31 *
32 * @since 1.22
33 */
34 const UTF8_OK = 1;
35
36 /**
37 * Skip escaping the characters '<', '>', and '&', which have special meanings in
38 * HTML and XML.
39 *
40 * @warning Do not use this option for JSON that could end up in inline scripts.
41 * - HTML5, §4.3.1.2 Restrictions for contents of script elements
42 * - XML 1.0 (5th Ed.), §2.4 Character Data and Markup
43 *
44 * @since 1.22
45 */
46 const XMLMETA_OK = 2;
47
48 /**
49 * Skip escaping as many characters as reasonably possible.
50 *
51 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
52 *
53 * @since 1.22
54 */
55 const ALL_OK = 3;
56
57 /**
58 * If set, treat json objects '{...}' as associative arrays. Without this option,
59 * json objects will be converted to stdClass.
60 * The value is set to 1 to be backward compatible with 'true' that was used before.
61 *
62 * @since 1.24
63 */
64 const FORCE_ASSOC = 1;
65
66 /**
67 * Regex that matches whitespace inside empty arrays and objects.
68 *
69 * This doesn't affect regular strings inside the JSON because those can't
70 * have a real line break (\n) in them, at this point they are already escaped
71 * as the string "\n" which this doesn't match.
72 *
73 * @private
74 */
75 const WS_CLEANUP_REGEX = '/(?<=[\[{])\n\s*+(?=[\]}])/';
76
77 /**
78 * Characters problematic in JavaScript.
79 *
80 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
81 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
82 */
83 private static $badChars = array(
84 "\xe2\x80\xa8", // U+2028 LINE SEPARATOR
85 "\xe2\x80\xa9", // U+2029 PARAGRAPH SEPARATOR
86 );
87
88 /**
89 * Escape sequences for characters listed in FormatJson::$badChars.
90 */
91 private static $badCharsEscaped = array(
92 '\u2028', // U+2028 LINE SEPARATOR
93 '\u2029', // U+2029 PARAGRAPH SEPARATOR
94 );
95
96 /**
97 * Returns the JSON representation of a value.
98 *
99 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
100 * array that might be empty to an object before encoding it.
101 *
102 * @note In pre-1.22 versions of MediaWiki, using this function for generating inline script
103 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
104 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
105 *
106 * @param mixed $value The value to encode. Can be any type except a resource.
107 * @param string|bool $pretty If a string, add non-significant whitespace to improve
108 * readability, using that string for indentation. If true, use the default indent
109 * string (four spaces).
110 * @param int $escaping Bitfield consisting of _OK class constants
111 * @return string|bool: String if successful; false upon failure
112 */
113 public static function encode( $value, $pretty = false, $escaping = 0 ) {
114 if ( !is_string( $pretty ) ) {
115 $pretty = $pretty ? ' ' : false;
116 }
117
118 if ( defined( 'JSON_UNESCAPED_UNICODE' ) ) {
119 return self::encode54( $value, $pretty, $escaping );
120 }
121
122 return self::encode53( $value, $pretty, $escaping );
123 }
124
125 /**
126 * Decodes a JSON string.
127 *
128 * @param string $value The JSON string being decoded
129 * @param bool $assoc When true, returned objects will be converted into associative arrays.
130 *
131 * @return mixed The value encoded in JSON in appropriate PHP type.
132 * `null` is returned if the JSON cannot be decoded or if the encoded data is deeper than
133 * the recursion limit.
134 */
135 public static function decode( $value, $assoc = false ) {
136 return json_decode( $value, $assoc );
137 }
138
139 /**
140 * Decodes a JSON string.
141 *
142 * @param string $value The JSON string being decoded
143 * @param int $options A bit field that allows FORCE_ASSOC, TRY_FIXING, WRAP_RESULT
144 * For backward compatibility, FORCE_ASSOC is set to 1 to match the legacy 'true'
145 * @return Status If good, the value is available in $result->getValue()
146 */
147 public static function parse( $value, $options = 0 ) {
148 $assoc = ( $options & self::FORCE_ASSOC ) !== 0;
149 $result = json_decode( $value, $assoc );
150 $code = json_last_error();
151
152 switch ( $code ) {
153 case JSON_ERROR_NONE:
154 return Status::newGood( $result );
155 default:
156 return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
157 case JSON_ERROR_DEPTH:
158 $msg = 'json-error-depth';
159 break;
160 case JSON_ERROR_STATE_MISMATCH:
161 $msg = 'json-error-state-mismatch';
162 break;
163 case JSON_ERROR_CTRL_CHAR:
164 $msg = 'json-error-ctrl-char';
165 break;
166 case JSON_ERROR_SYNTAX:
167 $msg = 'json-error-syntax';
168 break;
169 case JSON_ERROR_UTF8:
170 $msg = 'json-error-utf8';
171 break;
172 case JSON_ERROR_RECURSION:
173 $msg = 'json-error-recursion';
174 break;
175 case JSON_ERROR_INF_OR_NAN:
176 $msg = 'json-error-inf-or-nan';
177 break;
178 case JSON_ERROR_UNSUPPORTED_TYPE:
179 $msg = 'json-error-unsupported-type';
180 break;
181 }
182 return Status::newFatal( $msg );
183 }
184
185 /**
186 * JSON encoder wrapper for PHP >= 5.4, which supports useful encoding options.
187 *
188 * @param mixed $value
189 * @param string|bool $pretty
190 * @param int $escaping
191 * @return string|bool
192 */
193 private static function encode54( $value, $pretty, $escaping ) {
194 static $bug66021;
195 if ( $pretty !== false && $bug66021 === null ) {
196 $bug66021 = json_encode( array(), JSON_PRETTY_PRINT ) !== '[]';
197 }
198
199 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
200 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
201 // escaping negatively impacts the human readability of URLs and similar strings.
202 $options = JSON_UNESCAPED_SLASHES;
203 $options |= $pretty !== false ? JSON_PRETTY_PRINT : 0;
204 $options |= ( $escaping & self::UTF8_OK ) ? JSON_UNESCAPED_UNICODE : 0;
205 $options |= ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
206 $json = json_encode( $value, $options );
207 if ( $json === false ) {
208 return false;
209 }
210
211 if ( $pretty !== false ) {
212 // Workaround for <https://bugs.php.net/bug.php?id=66021>
213 if ( $bug66021 ) {
214 $json = preg_replace( self::WS_CLEANUP_REGEX, '', $json );
215 }
216 if ( $pretty !== ' ' ) {
217 // Change the four-space indent to a tab indent
218 $json = str_replace( "\n ", "\n\t", $json );
219 while ( strpos( $json, "\t " ) !== false ) {
220 $json = str_replace( "\t ", "\t\t", $json );
221 }
222
223 if ( $pretty !== "\t" ) {
224 // Change the tab indent to the provided indent
225 $json = str_replace( "\t", $pretty, $json );
226 }
227 }
228 }
229 if ( $escaping & self::UTF8_OK ) {
230 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
231 }
232
233 return $json;
234 }
235
236 /**
237 * JSON encoder wrapper for PHP 5.3, which lacks native support for some encoding options.
238 * Therefore, the missing options are implemented here purely in PHP code.
239 *
240 * @param mixed $value
241 * @param string|bool $pretty
242 * @param int $escaping
243 * @return string|bool
244 */
245 private static function encode53( $value, $pretty, $escaping ) {
246 $options = ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
247 $json = json_encode( $value, $options );
248 if ( $json === false ) {
249 return false;
250 }
251
252 // Emulate JSON_UNESCAPED_SLASHES. Because the JSON contains no unescaped slashes
253 // (only escaped slashes), a simple string replacement works fine.
254 $json = str_replace( '\/', '/', $json );
255
256 if ( $escaping & self::UTF8_OK ) {
257 // JSON hex escape sequences follow the format \uDDDD, where DDDD is four hex digits
258 // indicating the equivalent UTF-16 code unit's value. To most efficiently unescape
259 // them, we exploit the JSON extension's built-in decoder.
260 // * We escape the input a second time, so any such sequence becomes \\uDDDD.
261 // * To avoid interpreting escape sequences that were in the original input,
262 // each double-escaped backslash (\\\\) is replaced with \\\u005c.
263 // * We strip one of the backslashes from each of the escape sequences to unescape.
264 // * Then the JSON decoder can perform the actual unescaping.
265 $json = str_replace( "\\\\\\\\", "\\\\\\u005c", addcslashes( $json, '\"' ) );
266 $json = json_decode( preg_replace( "/\\\\\\\\u(?!00[0-7])/", "\\\\u", "\"$json\"" ) );
267 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
268 }
269
270 if ( $pretty !== false ) {
271 return self::prettyPrint( $json, $pretty );
272 }
273
274 return $json;
275 }
276
277 /**
278 * Adds non-significant whitespace to an existing JSON representation of an object.
279 * Only needed for PHP < 5.4, which lacks the JSON_PRETTY_PRINT option.
280 *
281 * @param string $json
282 * @param string $indentString
283 * @return string
284 */
285 private static function prettyPrint( $json, $indentString ) {
286 $buf = '';
287 $indent = 0;
288 $json = strtr( $json, array( '\\\\' => '\\\\', '\"' => "\x01" ) );
289 for ( $i = 0, $n = strlen( $json ); $i < $n; $i += $skip ) {
290 $skip = 1;
291 switch ( $json[$i] ) {
292 case ':':
293 $buf .= ': ';
294 break;
295 case '[':
296 case '{':
297 ++$indent;
298 // falls through
299 case ',':
300 $buf .= $json[$i] . "\n" . str_repeat( $indentString, $indent );
301 break;
302 case ']':
303 case '}':
304 $buf .= "\n" . str_repeat( $indentString, --$indent ) . $json[$i];
305 break;
306 case '"':
307 $skip = strcspn( $json, '"', $i + 1 ) + 2;
308 $buf .= substr( $json, $i, $skip );
309 break;
310 default:
311 $skip = strcspn( $json, ',]}"', $i + 1 ) + 1;
312 $buf .= substr( $json, $i, $skip );
313 }
314 }
315 $buf = preg_replace( self::WS_CLEANUP_REGEX, '', $buf );
316
317 return str_replace( "\x01", '\"', $buf );
318 }
319 }