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
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.
37 * Skip escaping the characters '<', '>', and '&', which have special meanings in
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
49 * Skip escaping as many characters as reasonably possible.
51 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
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.
64 const FORCE_ASSOC
= 0x100;
67 * If set, attempts to fix invalid json.
71 const TRY_FIXING
= 0x200;
74 * If set, strip comments from input before parsing as JSON.
78 const STRIP_COMMENTS
= 0x400;
81 * Characters problematic in JavaScript.
83 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
84 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
86 private static $badChars = [
87 "\u{2028}", // U+2028 LINE SEPARATOR
88 "\u{2029}", // U+2029 PARAGRAPH SEPARATOR
92 * Escape sequences for characters listed in FormatJson::$badChars.
94 private static $badCharsEscaped = [
95 '\u2028', // U+2028 LINE SEPARATOR
96 '\u2029', // U+2029 PARAGRAPH SEPARATOR
100 * Returns the JSON representation of a value.
102 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
103 * array that might be empty to an object before encoding it.
105 * @note In pre-1.22 versions of MediaWiki, using this function for generating inline script
106 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
107 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
109 * @param mixed $value The value to encode. Can be any type except a resource.
110 * @param string|bool $pretty If a string, add non-significant whitespace to improve
111 * readability, using that string for indentation. If true, use the default indent
112 * string (four spaces).
113 * @param int $escaping Bitfield consisting of _OK class constants
114 * @return string|false String if successful; false upon failure
116 public static function encode( $value, $pretty = false, $escaping = 0 ) {
117 if ( !is_string( $pretty ) ) {
118 $pretty = $pretty ?
' ' : false;
121 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
122 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
123 // escaping negatively impacts the human readability of URLs and similar strings.
124 $options = JSON_UNESCAPED_SLASHES
;
125 $options |
= $pretty !== false ? JSON_PRETTY_PRINT
: 0;
126 $options |
= ( $escaping & self
::UTF8_OK
) ? JSON_UNESCAPED_UNICODE
: 0;
127 $options |
= ( $escaping & self
::XMLMETA_OK
) ?
0 : ( JSON_HEX_TAG | JSON_HEX_AMP
);
128 $json = json_encode( $value, $options );
129 if ( $json === false ) {
133 if ( $pretty !== false ) {
134 if ( $pretty !== ' ' ) {
135 // Change the four-space indent to a tab indent
136 $json = str_replace( "\n ", "\n\t", $json );
137 while ( strpos( $json, "\t " ) !== false ) {
138 $json = str_replace( "\t ", "\t\t", $json );
141 if ( $pretty !== "\t" ) {
142 // Change the tab indent to the provided indent
143 $json = str_replace( "\t", $pretty, $json );
147 if ( $escaping & self
::UTF8_OK
) {
148 $json = str_replace( self
::$badChars, self
::$badCharsEscaped, $json );
155 * Decodes a JSON string. It is recommended to use FormatJson::parse(),
156 * which returns more comprehensive result in case of an error, and has
157 * more parsing options.
159 * @param string $value The JSON string being decoded
160 * @param bool $assoc When true, returned objects will be converted into associative arrays.
162 * @return mixed The value encoded in JSON in appropriate PHP type.
163 * `null` is returned if $value represented `null`, if $value could not be decoded,
164 * or if the encoded data was deeper than the recursion limit.
165 * Use FormatJson::parse() to distinguish between types of `null` and to get proper error code.
167 public static function decode( $value, $assoc = false ) {
168 return json_decode( $value, $assoc );
172 * Decodes a JSON string.
173 * Unlike FormatJson::decode(), if $value represents null value, it will be
174 * properly decoded as valid.
176 * @param string $value The JSON string being decoded
177 * @param int $options A bit field that allows FORCE_ASSOC, TRY_FIXING,
179 * @return Status If valid JSON, the value is available in $result->getValue()
181 public static function parse( $value, $options = 0 ) {
182 if ( $options & self
::STRIP_COMMENTS
) {
183 $value = self
::stripComments( $value );
185 $assoc = ( $options & self
::FORCE_ASSOC
) !== 0;
186 $result = json_decode( $value, $assoc );
187 $code = json_last_error();
189 if ( $code === JSON_ERROR_SYNTAX
&& ( $options & self
::TRY_FIXING
) !== 0 ) {
190 // The most common error is the trailing comma in a list or an object.
191 // We cannot simply replace /,\s*[}\]]/ because it could be inside a string value.
192 // But we could use the fact that JSON does not allow multi-line string values,
193 // And remove trailing commas if they are et the end of a line.
194 // JSON only allows 4 control characters: [ \t\r\n]. So we must not use '\s' for matching.
195 // Regex match ,]<any non-quote chars>\n or ,\n] with optional spaces/tabs.
198 preg_replace( '/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/', '$1',
199 $value, -1, $count );
201 $result = json_decode( $value, $assoc );
202 if ( JSON_ERROR_NONE
=== json_last_error() ) {
204 $st = Status
::newGood( $result );
205 $st->warning( wfMessage( 'json-warn-trailing-comma' )->numParams( $count ) );
212 case JSON_ERROR_NONE
:
213 return Status
::newGood( $result );
215 return Status
::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
216 case JSON_ERROR_DEPTH
:
217 $msg = 'json-error-depth';
219 case JSON_ERROR_STATE_MISMATCH
:
220 $msg = 'json-error-state-mismatch';
222 case JSON_ERROR_CTRL_CHAR
:
223 $msg = 'json-error-ctrl-char';
225 case JSON_ERROR_SYNTAX
:
226 $msg = 'json-error-syntax';
228 case JSON_ERROR_UTF8
:
229 $msg = 'json-error-utf8';
231 case JSON_ERROR_RECURSION
:
232 $msg = 'json-error-recursion';
234 case JSON_ERROR_INF_OR_NAN
:
235 $msg = 'json-error-inf-or-nan';
237 case JSON_ERROR_UNSUPPORTED_TYPE
:
238 $msg = 'json-error-unsupported-type';
241 return Status
::newFatal( $msg );
245 * Remove multiline and single line comments from an otherwise valid JSON
246 * input string. This can be used as a preprocessor for to allow JSON
247 * formatted configuration files to contain comments.
249 * @param string $json
250 * @return string JSON with comments removed
252 public static function stripComments( $json ) {
253 // Ensure we have a string
254 $str = (string)$json;
256 $maxLen = strlen( $str );
263 for ( $idx = 0; $idx < $maxLen; $idx++
) {
264 switch ( $str[$idx] ) {
266 $lookBehind = ( $idx - 1 >= 0 ) ?
$str[$idx - 1] : '';
267 if ( !$inComment && $lookBehind !== '\\' ) {
268 // Either started or ended a string
269 $inString = !$inString;
274 $lookAhead = ( $idx +
1 < $maxLen ) ?
$str[$idx +
1] : '';
275 $lookBehind = ( $idx - 1 >= 0 ) ?
$str[$idx - 1] : '';
279 } elseif ( !$inComment &&
280 ( $lookAhead === '/' ||
$lookAhead === '*' )
282 // Transition into a comment
283 // Add characters seen to buffer
284 $buffer .= substr( $str, $mark, $idx - $mark );
285 // Consume the look ahead character
289 $multiline = $lookAhead === '*';
291 } elseif ( $multiline && $lookBehind === '*' ) {
292 // Found the end of the current comment
300 if ( $inComment && !$multiline ) {
301 // Found the end of the current comment
309 // Comment ends with input
310 // Technically we should check to ensure that we aren't in
311 // a multiline comment that hasn't been properly ended, but this
312 // is a strip filter, not a validating parser.
315 // Add final chunk to buffer before returning
316 return $buffer . substr( $str, $mark, $maxLen - $mark );