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