Merge "Introduce ApiMaxLagInfo hook"
[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 = 0x100;
65
66 /**
67 * If set, attempts to fix invalid json.
68 *
69 * @since 1.24
70 */
71 const TRY_FIXING = 0x200;
72
73 /**
74 * If set, strip comments from input before parsing as JSON.
75 *
76 * @since 1.25
77 */
78 const STRIP_COMMENTS = 0x400;
79
80 /**
81 * Characters problematic in JavaScript.
82 *
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.
85 */
86 private static $badChars = [
87 "\u{2028}", // U+2028 LINE SEPARATOR
88 "\u{2029}", // U+2029 PARAGRAPH SEPARATOR
89 ];
90
91 /**
92 * Escape sequences for characters listed in FormatJson::$badChars.
93 */
94 private static $badCharsEscaped = [
95 '\u2028', // U+2028 LINE SEPARATOR
96 '\u2029', // U+2029 PARAGRAPH SEPARATOR
97 ];
98
99 /**
100 * Returns the JSON representation of a value.
101 *
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.
104 *
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.
108 *
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
115 */
116 public static function encode( $value, $pretty = false, $escaping = 0 ) {
117 if ( !is_string( $pretty ) ) {
118 $pretty = $pretty ? ' ' : false;
119 }
120
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 ) {
130 return false;
131 }
132
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 );
139 }
140
141 if ( $pretty !== "\t" ) {
142 // Change the tab indent to the provided indent
143 $json = str_replace( "\t", $pretty, $json );
144 }
145 }
146 }
147 if ( $escaping & self::UTF8_OK ) {
148 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
149 }
150
151 return $json;
152 }
153
154 /**
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.
158 *
159 * @param string $value The JSON string being decoded
160 * @param bool $assoc When true, returned objects will be converted into associative arrays.
161 *
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.
166 */
167 public static function decode( $value, $assoc = false ) {
168 return json_decode( $value, $assoc );
169 }
170
171 /**
172 * Decodes a JSON string.
173 * Unlike FormatJson::decode(), if $value represents null value, it will be
174 * properly decoded as valid.
175 *
176 * @param string $value The JSON string being decoded
177 * @param int $options A bit field that allows FORCE_ASSOC, TRY_FIXING,
178 * STRIP_COMMENTS
179 * @return Status If valid JSON, the value is available in $result->getValue()
180 */
181 public static function parse( $value, $options = 0 ) {
182 if ( $options & self::STRIP_COMMENTS ) {
183 $value = self::stripComments( $value );
184 }
185 $assoc = ( $options & self::FORCE_ASSOC ) !== 0;
186 $result = json_decode( $value, $assoc );
187 $code = json_last_error();
188
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.
196 $count = 0;
197 $value =
198 preg_replace( '/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/', '$1',
199 $value, -1, $count );
200 if ( $count > 0 ) {
201 $result = json_decode( $value, $assoc );
202 if ( JSON_ERROR_NONE === json_last_error() ) {
203 // Report warning
204 $st = Status::newGood( $result );
205 $st->warning( wfMessage( 'json-warn-trailing-comma' )->numParams( $count ) );
206 return $st;
207 }
208 }
209 }
210
211 switch ( $code ) {
212 case JSON_ERROR_NONE:
213 return Status::newGood( $result );
214 default:
215 return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
216 case JSON_ERROR_DEPTH:
217 $msg = 'json-error-depth';
218 break;
219 case JSON_ERROR_STATE_MISMATCH:
220 $msg = 'json-error-state-mismatch';
221 break;
222 case JSON_ERROR_CTRL_CHAR:
223 $msg = 'json-error-ctrl-char';
224 break;
225 case JSON_ERROR_SYNTAX:
226 $msg = 'json-error-syntax';
227 break;
228 case JSON_ERROR_UTF8:
229 $msg = 'json-error-utf8';
230 break;
231 case JSON_ERROR_RECURSION:
232 $msg = 'json-error-recursion';
233 break;
234 case JSON_ERROR_INF_OR_NAN:
235 $msg = 'json-error-inf-or-nan';
236 break;
237 case JSON_ERROR_UNSUPPORTED_TYPE:
238 $msg = 'json-error-unsupported-type';
239 break;
240 }
241 return Status::newFatal( $msg );
242 }
243
244 /**
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.
248 *
249 * @param string $json
250 * @return string JSON with comments removed
251 */
252 public static function stripComments( $json ) {
253 // Ensure we have a string
254 $str = (string)$json;
255 $buffer = '';
256 $maxLen = strlen( $str );
257 $mark = 0;
258
259 $inString = false;
260 $inComment = false;
261 $multiline = false;
262
263 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
264 switch ( $str[$idx] ) {
265 case '"':
266 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
267 if ( !$inComment && $lookBehind !== '\\' ) {
268 // Either started or ended a string
269 $inString = !$inString;
270 }
271 break;
272
273 case '/':
274 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] : '';
275 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
276 if ( $inString ) {
277 continue;
278
279 } elseif ( !$inComment &&
280 ( $lookAhead === '/' || $lookAhead === '*' )
281 ) {
282 // Transition into a comment
283 // Add characters seen to buffer
284 $buffer .= substr( $str, $mark, $idx - $mark );
285 // Consume the look ahead character
286 $idx++;
287 // Track state
288 $inComment = true;
289 $multiline = $lookAhead === '*';
290
291 } elseif ( $multiline && $lookBehind === '*' ) {
292 // Found the end of the current comment
293 $mark = $idx + 1;
294 $inComment = false;
295 $multiline = false;
296 }
297 break;
298
299 case "\n":
300 if ( $inComment && !$multiline ) {
301 // Found the end of the current comment
302 $mark = $idx + 1;
303 $inComment = false;
304 }
305 break;
306 }
307 }
308 if ( $inComment ) {
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.
313 $mark = $maxLen;
314 }
315 // Add final chunk to buffer before returning
316 return $buffer . substr( $str, $mark, $maxLen - $mark );
317 }
318 }