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