Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / json / FormatJson.php
blobf85ee920daaa06e2ffe6f05035e2fa3526dc7f26
1 <?php
2 /**
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
20 * @file
23 /**
24 * JSON formatter wrapper class
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.
32 * @since 1.22
34 const UTF8_OK = 1;
36 /**
37 * Skip escaping the characters '<', '>', and '&', which have special meanings in
38 * HTML and XML.
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
44 * @since 1.22
46 const XMLMETA_OK = 2;
48 /**
49 * Skip escaping as many characters as reasonably possible.
51 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
53 * @since 1.22
55 const ALL_OK = 3;
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.
62 * @since 1.24
64 const FORCE_ASSOC = 0x100;
66 /**
67 * If set, attempts to fix invalid json.
69 * @since 1.24
71 const TRY_FIXING = 0x200;
73 /**
74 * If set, strip comments from input before parsing as JSON.
76 * @since 1.25
78 const STRIP_COMMENTS = 0x400;
80 /**
81 * Regex that matches whitespace inside empty arrays and objects.
83 * This doesn't affect regular strings inside the JSON because those can't
84 * have a real line break (\n) in them, at this point they are already escaped
85 * as the string "\n" which this doesn't match.
87 * @private
89 const WS_CLEANUP_REGEX = '/(?<=[\[{])\n\s*+(?=[\]}])/';
91 /**
92 * Characters problematic in JavaScript.
94 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
95 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
97 private static $badChars = array(
98 "\xe2\x80\xa8", // U+2028 LINE SEPARATOR
99 "\xe2\x80\xa9", // U+2029 PARAGRAPH SEPARATOR
103 * Escape sequences for characters listed in FormatJson::$badChars.
105 private static $badCharsEscaped = array(
106 '\u2028', // U+2028 LINE SEPARATOR
107 '\u2029', // U+2029 PARAGRAPH SEPARATOR
111 * Returns the JSON representation of a value.
113 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
114 * array that might be empty to an object before encoding it.
116 * @note In pre-1.22 versions of MediaWiki, using this function for generating inline script
117 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
118 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
120 * @param mixed $value The value to encode. Can be any type except a resource.
121 * @param string|bool $pretty If a string, add non-significant whitespace to improve
122 * readability, using that string for indentation. If true, use the default indent
123 * string (four spaces).
124 * @param int $escaping Bitfield consisting of _OK class constants
125 * @return string|false String if successful; false upon failure
127 public static function encode( $value, $pretty = false, $escaping = 0 ) {
128 if ( !is_string( $pretty ) ) {
129 $pretty = $pretty ? ' ' : false;
132 if ( defined( 'JSON_UNESCAPED_UNICODE' ) ) {
133 return self::encode54( $value, $pretty, $escaping );
136 return self::encode53( $value, $pretty, $escaping );
140 * Decodes a JSON string. It is recommended to use FormatJson::parse(),
141 * which returns more comprehensive result in case of an error, and has
142 * more parsing options.
144 * @param string $value The JSON string being decoded
145 * @param bool $assoc When true, returned objects will be converted into associative arrays.
147 * @return mixed The value encoded in JSON in appropriate PHP type.
148 * `null` is returned if $value represented `null`, if $value could not be decoded,
149 * or if the encoded data was deeper than the recursion limit.
150 * Use FormatJson::parse() to distinguish between types of `null` and to get proper error code.
152 public static function decode( $value, $assoc = false ) {
153 return json_decode( $value, $assoc );
157 * Decodes a JSON string.
158 * Unlike FormatJson::decode(), if $value represents null value, it will be
159 * properly decoded as valid.
161 * @param string $value The JSON string being decoded
162 * @param int $options A bit field that allows FORCE_ASSOC, TRY_FIXING,
163 * STRIP_COMMENTS
164 * @return Status If valid JSON, the value is available in $result->getValue()
166 public static function parse( $value, $options = 0 ) {
167 if ( $options & self::STRIP_COMMENTS ) {
168 $value = self::stripComments( $value );
170 $assoc = ( $options & self::FORCE_ASSOC ) !== 0;
171 $result = json_decode( $value, $assoc );
172 $code = json_last_error();
174 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
175 // The most common error is the trailing comma in a list or an object.
176 // We cannot simply replace /,\s*[}\]]/ because it could be inside a string value.
177 // But we could use the fact that JSON does not allow multi-line string values,
178 // And remove trailing commas if they are et the end of a line.
179 // JSON only allows 4 control characters: [ \t\r\n]. So we must not use '\s' for matching.
180 // Regex match ,]<any non-quote chars>\n or ,\n] with optional spaces/tabs.
181 $count = 0;
182 $value =
183 preg_replace( '/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/', '$1',
184 $value, - 1, $count );
185 if ( $count > 0 ) {
186 $result = json_decode( $value, $assoc );
187 if ( JSON_ERROR_NONE === json_last_error() ) {
188 // Report warning
189 $st = Status::newGood( $result );
190 $st->warning( wfMessage( 'json-warn-trailing-comma' )->numParams( $count ) );
191 return $st;
196 switch ( $code ) {
197 case JSON_ERROR_NONE:
198 return Status::newGood( $result );
199 default:
200 return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
201 case JSON_ERROR_DEPTH:
202 $msg = 'json-error-depth';
203 break;
204 case JSON_ERROR_STATE_MISMATCH:
205 $msg = 'json-error-state-mismatch';
206 break;
207 case JSON_ERROR_CTRL_CHAR:
208 $msg = 'json-error-ctrl-char';
209 break;
210 case JSON_ERROR_SYNTAX:
211 $msg = 'json-error-syntax';
212 break;
213 case JSON_ERROR_UTF8:
214 $msg = 'json-error-utf8';
215 break;
216 case JSON_ERROR_RECURSION:
217 $msg = 'json-error-recursion';
218 break;
219 case JSON_ERROR_INF_OR_NAN:
220 $msg = 'json-error-inf-or-nan';
221 break;
222 case JSON_ERROR_UNSUPPORTED_TYPE:
223 $msg = 'json-error-unsupported-type';
224 break;
226 return Status::newFatal( $msg );
230 * JSON encoder wrapper for PHP >= 5.4, which supports useful encoding options.
232 * @param mixed $value
233 * @param string|bool $pretty
234 * @param int $escaping
235 * @return string|false
237 private static function encode54( $value, $pretty, $escaping ) {
238 static $bug66021;
239 if ( $pretty !== false && $bug66021 === null ) {
240 $bug66021 = json_encode( array(), JSON_PRETTY_PRINT ) !== '[]';
243 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
244 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
245 // escaping negatively impacts the human readability of URLs and similar strings.
246 $options = JSON_UNESCAPED_SLASHES;
247 $options |= $pretty !== false ? JSON_PRETTY_PRINT : 0;
248 $options |= ( $escaping & self::UTF8_OK ) ? JSON_UNESCAPED_UNICODE : 0;
249 $options |= ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
250 $json = json_encode( $value, $options );
251 if ( $json === false ) {
252 return false;
255 if ( $pretty !== false ) {
256 // Workaround for <https://bugs.php.net/bug.php?id=66021>
257 if ( $bug66021 ) {
258 $json = preg_replace( self::WS_CLEANUP_REGEX, '', $json );
260 if ( $pretty !== ' ' ) {
261 // Change the four-space indent to a tab indent
262 $json = str_replace( "\n ", "\n\t", $json );
263 while ( strpos( $json, "\t " ) !== false ) {
264 $json = str_replace( "\t ", "\t\t", $json );
267 if ( $pretty !== "\t" ) {
268 // Change the tab indent to the provided indent
269 $json = str_replace( "\t", $pretty, $json );
273 if ( $escaping & self::UTF8_OK ) {
274 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
277 return $json;
281 * JSON encoder wrapper for PHP 5.3, which lacks native support for some encoding options.
282 * Therefore, the missing options are implemented here purely in PHP code.
284 * @param mixed $value
285 * @param string|bool $pretty
286 * @param int $escaping
287 * @return string|false
289 private static function encode53( $value, $pretty, $escaping ) {
290 $options = ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
291 $json = json_encode( $value, $options );
292 if ( $json === false ) {
293 return false;
296 // Emulate JSON_UNESCAPED_SLASHES. Because the JSON contains no unescaped slashes
297 // (only escaped slashes), a simple string replacement works fine.
298 $json = str_replace( '\/', '/', $json );
300 if ( $escaping & self::UTF8_OK ) {
301 // JSON hex escape sequences follow the format \uDDDD, where DDDD is four hex digits
302 // indicating the equivalent UTF-16 code unit's value. To most efficiently unescape
303 // them, we exploit the JSON extension's built-in decoder.
304 // * We escape the input a second time, so any such sequence becomes \\uDDDD.
305 // * To avoid interpreting escape sequences that were in the original input,
306 // each double-escaped backslash (\\\\) is replaced with \\\u005c.
307 // * We strip one of the backslashes from each of the escape sequences to unescape.
308 // * Then the JSON decoder can perform the actual unescaping.
309 $json = str_replace( "\\\\\\\\", "\\\\\\u005c", addcslashes( $json, '\"' ) );
310 $json = json_decode( preg_replace( "/\\\\\\\\u(?!00[0-7])/", "\\\\u", "\"$json\"" ) );
311 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
314 if ( $pretty !== false ) {
315 return self::prettyPrint( $json, $pretty );
318 return $json;
322 * Adds non-significant whitespace to an existing JSON representation of an object.
323 * Only needed for PHP < 5.4, which lacks the JSON_PRETTY_PRINT option.
325 * @param string $json
326 * @param string $indentString
327 * @return string
329 private static function prettyPrint( $json, $indentString ) {
330 $buf = '';
331 $indent = 0;
332 $json = strtr( $json, array( '\\\\' => '\\\\', '\"' => "\x01" ) );
333 for ( $i = 0, $n = strlen( $json ); $i < $n; $i += $skip ) {
334 $skip = 1;
335 switch ( $json[$i] ) {
336 case ':':
337 $buf .= ': ';
338 break;
339 case '[':
340 case '{':
341 ++$indent;
342 // falls through
343 case ',':
344 $buf .= $json[$i] . "\n" . str_repeat( $indentString, $indent );
345 break;
346 case ']':
347 case '}':
348 $buf .= "\n" . str_repeat( $indentString, --$indent ) . $json[$i];
349 break;
350 case '"':
351 $skip = strcspn( $json, '"', $i + 1 ) + 2;
352 $buf .= substr( $json, $i, $skip );
353 break;
354 default:
355 $skip = strcspn( $json, ',]}"', $i + 1 ) + 1;
356 $buf .= substr( $json, $i, $skip );
359 $buf = preg_replace( self::WS_CLEANUP_REGEX, '', $buf );
361 return str_replace( "\x01", '\"', $buf );
365 * Remove multiline and single line comments from an otherwise valid JSON
366 * input string. This can be used as a preprocessor for to allow JSON
367 * formatted configuration files to contain comments.
369 * @param string $json
370 * @return string JSON with comments removed
372 public static function stripComments( $json ) {
373 // Ensure we have a string
374 $str = (string) $json;
375 $buffer = '';
376 $maxLen = strlen( $str );
377 $mark = 0;
379 $inString = false;
380 $inComment = false;
381 $multiline = false;
383 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
384 switch ( $str[$idx] ) {
385 case '"':
386 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
387 if ( !$inComment && $lookBehind !== '\\' ) {
388 // Either started or ended a string
389 $inString = !$inString;
391 break;
393 case '/':
394 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] : '';
395 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
396 if ( $inString ) {
397 continue;
399 } elseif ( !$inComment &&
400 ( $lookAhead === '/' || $lookAhead === '*' )
402 // Transition into a comment
403 // Add characters seen to buffer
404 $buffer .= substr( $str, $mark, $idx - $mark );
405 // Consume the look ahead character
406 $idx++;
407 // Track state
408 $inComment = true;
409 $multiline = $lookAhead === '*';
411 } elseif ( $multiline && $lookBehind === '*' ) {
412 // Found the end of the current comment
413 $mark = $idx + 1;
414 $inComment = false;
415 $multiline = false;
417 break;
419 case "\n":
420 if ( $inComment && !$multiline ) {
421 // Found the end of the current comment
422 $mark = $idx + 1;
423 $inComment = false;
425 break;
428 if ( $inComment ) {
429 // Comment ends with input
430 // Technically we should check to ensure that we aren't in
431 // a multiline comment that hasn't been properly ended, but this
432 // is a strip filter, not a validating parser.
433 $mark = $maxLen;
435 // Add final chunk to buffer before returning
436 return $buffer . substr( $str, $mark, $maxLen - $mark );