MediaWiki REL1_35
FormatJson.php
Go to the documentation of this file.
1<?php
34 public const UTF8_OK = 1;
35
46 public const XMLMETA_OK = 2;
47
55 public const ALL_OK = self::UTF8_OK | self::XMLMETA_OK;
56
63 public const FORCE_ASSOC = 0x100;
64
70 public const TRY_FIXING = 0x200;
71
77 public const STRIP_COMMENTS = 0x400;
78
96 public static function encode( $value, $pretty = false, $escaping = 0 ) {
97 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
98 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
99 // escaping negatively impacts the human readability of URLs and similar strings.
100 $options = JSON_UNESCAPED_SLASHES;
101 if ( $pretty || is_string( $pretty ) ) {
102 $options |= JSON_PRETTY_PRINT;
103 }
104 if ( $escaping & self::UTF8_OK ) {
105 $options |= JSON_UNESCAPED_UNICODE;
106 }
107 if ( !( $escaping & self::XMLMETA_OK ) ) {
108 $options |= JSON_HEX_TAG | JSON_HEX_AMP;
109 }
110 $json = json_encode( $value, $options );
111
112 if ( is_string( $pretty ) && $pretty !== ' ' && $json !== false ) {
113 // Change the four-space indent to the provided indent.
114 // The regex matches four spaces either at the start of a line or immediately
115 // after the previous match. $pretty should contain only whitespace characters,
116 // so there should be no need to call StringUtils::escapeRegexReplacement().
117 $json = preg_replace( '/ {4}|.*+\n\K {4}/A', $pretty, $json );
118 }
119
120 return $json;
121 }
122
146 public static function decode( $value, $assoc = false ) {
147 return json_decode( $value, $assoc );
148 }
149
160 public static function parse( $value, $options = 0 ) {
161 if ( $options & self::STRIP_COMMENTS ) {
162 $value = self::stripComments( $value );
163 }
164 $assoc = ( $options & self::FORCE_ASSOC ) !== 0;
165 $result = json_decode( $value, $assoc );
166 $code = json_last_error();
167
168 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
169 // The most common error is the trailing comma in a list or an object.
170 // We cannot simply replace /,\s*[}\]]/ because it could be inside a string value.
171 // But we could use the fact that JSON does not allow multi-line string values,
172 // And remove trailing commas if they are et the end of a line.
173 // JSON only allows 4 control characters: [ \t\r\n]. So we must not use '\s' for matching.
174 // Regex match ,]<any non-quote chars>\n or ,\n] with optional spaces/tabs.
175 $count = 0;
176 $value =
177 preg_replace( '/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/', '$1',
178 $value, -1, $count );
179 if ( $count > 0 ) {
180 $result = json_decode( $value, $assoc );
181 if ( json_last_error() === JSON_ERROR_NONE ) {
182 // Report warning
183 $st = Status::newGood( $result );
184 $st->warning( wfMessage( 'json-warn-trailing-comma' )->numParams( $count ) );
185 return $st;
186 }
187 }
188 }
189
190 // JSON_ERROR_RECURSION, JSON_ERROR_INF_OR_NAN,
191 // JSON_ERROR_UNSUPPORTED_TYPE, JSON_ERROR_INVALID_PROPERTY_NAME,
192 // are all encode errors that we don't need to care about here.
193 switch ( $code ) {
194 case JSON_ERROR_NONE:
195 return Status::newGood( $result );
196 default:
197 return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
198 case JSON_ERROR_DEPTH:
199 $msg = 'json-error-depth';
200 break;
201 case JSON_ERROR_STATE_MISMATCH:
202 $msg = 'json-error-state-mismatch';
203 break;
204 case JSON_ERROR_CTRL_CHAR:
205 $msg = 'json-error-ctrl-char';
206 break;
207 case JSON_ERROR_SYNTAX:
208 $msg = 'json-error-syntax';
209 break;
210 case JSON_ERROR_UTF8:
211 $msg = 'json-error-utf8';
212 break;
213 case JSON_ERROR_UTF16:
214 $msg = 'json-error-utf16';
215 break;
216 }
217 return Status::newFatal( $msg );
218 }
219
228 public static function stripComments( $json ) {
229 // Ensure we have a string
230 $str = (string)$json;
231 $buffer = '';
232 $maxLen = strlen( $str );
233 $mark = 0;
234
235 $inString = false;
236 $inComment = false;
237 $multiline = false;
238
239 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
240 switch ( $str[$idx] ) {
241 case '"':
242 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
243 if ( !$inComment && $lookBehind !== '\\' ) {
244 // Either started or ended a string
245 $inString = !$inString;
246 }
247 break;
248
249 case '/':
250 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] : '';
251 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
252 if ( $inString ) {
253 break;
254
255 } elseif ( !$inComment &&
256 ( $lookAhead === '/' || $lookAhead === '*' )
257 ) {
258 // Transition into a comment
259 // Add characters seen to buffer
260 $buffer .= substr( $str, $mark, $idx - $mark );
261 // Consume the look ahead character
262 $idx++;
263 // Track state
264 $inComment = true;
265 $multiline = $lookAhead === '*';
266
267 } elseif ( $multiline && $lookBehind === '*' ) {
268 // Found the end of the current comment
269 $mark = $idx + 1;
270 $inComment = false;
271 $multiline = false;
272 }
273 break;
274
275 case "\n":
276 if ( $inComment && !$multiline ) {
277 // Found the end of the current comment
278 $mark = $idx + 1;
279 $inComment = false;
280 }
281 break;
282 }
283 }
284 if ( $inComment ) {
285 // Comment ends with input
286 // Technically we should check to ensure that we aren't in
287 // a multiline comment that hasn't been properly ended, but this
288 // is a strip filter, not a validating parser.
289 $mark = $maxLen;
290 }
291 // Add final chunk to buffer before returning
292 return $buffer . substr( $str, $mark, $maxLen - $mark );
293 }
294}
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
JSON formatter wrapper class.
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
static parse( $value, $options=0)
Decodes a JSON string.
const FORCE_ASSOC
If set, treat JSON objects '{...}' as associative arrays.
const TRY_FIXING
If set, attempt to fix invalid JSON.
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
const STRIP_COMMENTS
If set, strip comments from input before parsing as JSON.
static decode( $value, $assoc=false)
Decodes a JSON string.
const ALL_OK
Skip escaping as many characters as reasonably possible.
const XMLMETA_OK
Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML.
static stripComments( $json)
Remove multiline and single line comments from an otherwise valid JSON input string.