MediaWiki master
FormatJson.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Json;
10
12
24 public const UTF8_OK = 1;
25
36 public const XMLMETA_OK = 2;
37
45 public const ALL_OK = self::UTF8_OK | self::XMLMETA_OK;
46
53 public const FORCE_ASSOC = 0x100;
54
60 public const TRY_FIXING = 0x200;
61
67 public const STRIP_COMMENTS = 0x400;
68
82 public static function encode( $value, $pretty = false, $escaping = 0 ) {
83 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
84 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
85 // escaping negatively impacts the human readability of URLs and similar strings.
86 $options = JSON_UNESCAPED_SLASHES;
87 if ( $pretty || is_string( $pretty ) ) {
88 $options |= JSON_PRETTY_PRINT;
89 }
90 if ( $escaping & self::UTF8_OK ) {
91 $options |= JSON_UNESCAPED_UNICODE;
92 }
93 if ( !( $escaping & self::XMLMETA_OK ) ) {
94 $options |= JSON_HEX_TAG | JSON_HEX_AMP;
95 }
96 $json = json_encode( $value, $options );
97
98 if ( is_string( $pretty ) && $pretty !== ' ' && $json !== false ) {
99 // Change the four-space indent to the provided indent.
100 // The regex matches four spaces either at the start of a line or immediately
101 // after the previous match. $pretty should contain only whitespace characters,
102 // so there should be no need to call StringUtils::escapeRegexReplacement().
103 $json = preg_replace( '/ {4}|.*+\n\K {4}/A', $pretty, $json );
104 }
105
106 return $json;
107 }
108
132 public static function decode( $value, $assoc = false ) {
133 return json_decode( $value, $assoc );
134 }
135
146 public static function parse( $value, $options = 0 ) {
147 if ( $options & self::STRIP_COMMENTS ) {
148 $value = self::stripComments( $value );
149 }
150 $assoc = ( $options & self::FORCE_ASSOC ) !== 0;
151 $result = json_decode( $value, $assoc );
152 $code = json_last_error();
153
154 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
155 // The most common error is the trailing comma in a list or an object.
156 // We cannot simply replace /,\s*[}\]]/ because it could be inside a string value.
157 // But we could use the fact that JSON does not allow multi-line string values,
158 // And remove trailing commas if they are et the end of a line.
159 // JSON only allows 4 control characters: [ \t\r\n]. So we must not use '\s' for matching.
160 // Regex match ,]<any non-quote chars>\n or ,\n] with optional spaces/tabs.
161 $count = 0;
162 $value =
163 preg_replace( '/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/', '$1',
164 $value, -1, $count );
165 if ( $count > 0 ) {
166 $result = json_decode( $value, $assoc );
167 if ( json_last_error() === JSON_ERROR_NONE ) {
168 // Report warning
169 $st = Status::newGood( $result );
170 $st->warning( wfMessage( 'json-warn-trailing-comma' )->numParams( $count ) );
171 return $st;
172 }
173 }
174 }
175
176 // JSON_ERROR_RECURSION, JSON_ERROR_INF_OR_NAN, JSON_ERROR_UNSUPPORTED_TYPE,
177 // are all encode errors that we don't need to care about here.
178 switch ( $code ) {
179 case JSON_ERROR_NONE:
180 return Status::newGood( $result );
181 default:
182 return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
183 case JSON_ERROR_DEPTH:
184 $msg = 'json-error-depth';
185 break;
186 case JSON_ERROR_STATE_MISMATCH:
187 $msg = 'json-error-state-mismatch';
188 break;
189 case JSON_ERROR_CTRL_CHAR:
190 $msg = 'json-error-ctrl-char';
191 break;
192 case JSON_ERROR_SYNTAX:
193 $msg = 'json-error-syntax';
194 break;
195 case JSON_ERROR_UTF8:
196 $msg = 'json-error-utf8';
197 break;
198 case JSON_ERROR_INVALID_PROPERTY_NAME:
199 $msg = 'json-error-invalid-property-name';
200 break;
201 case JSON_ERROR_UTF16:
202 $msg = 'json-error-utf16';
203 break;
204 }
205 return Status::newFatal( $msg );
206 }
207
216 public static function stripComments( $json ) {
217 // Ensure we have a string
218 $str = (string)$json;
219 $buffer = '';
220 $maxLen = strlen( $str );
221 $mark = 0;
222
223 $inString = false;
224 $inComment = false;
225 $multiline = false;
226
227 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
228 switch ( $str[$idx] ) {
229 case '"':
230 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
231 if ( !$inComment && $lookBehind !== '\\' ) {
232 // Either started or ended a string
233 $inString = !$inString;
234 }
235 break;
236
237 case '/':
238 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] : '';
239 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
240 if ( $inString ) {
241 break;
242
243 } elseif ( !$inComment &&
244 ( $lookAhead === '/' || $lookAhead === '*' )
245 ) {
246 // Transition into a comment
247 // Add characters seen to buffer
248 $buffer .= substr( $str, $mark, $idx - $mark );
249 // Consume the look ahead character
250 $idx++;
251 // Track state
252 $inComment = true;
253 $multiline = $lookAhead === '*';
254
255 } elseif ( $multiline && $lookBehind === '*' ) {
256 // Found the end of the current comment
257 $mark = $idx + 1;
258 $inComment = false;
259 $multiline = false;
260 }
261 break;
262
263 case "\n":
264 if ( $inComment && !$multiline ) {
265 // Found the end of the current comment
266 $mark = $idx + 1;
267 $inComment = false;
268 }
269 break;
270 }
271 }
272 if ( $inComment ) {
273 // Comment ends with input
274 // Technically we should check to ensure that we aren't in
275 // a multiline comment that hasn't been properly ended, but this
276 // is a strip filter, not a validating parser.
277 $mark = $maxLen;
278 }
279 // Add final chunk to buffer before returning
280 return $buffer . substr( $str, $mark, $maxLen - $mark );
281 }
282}
284class_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:44