MediaWiki  master
FormatJson.php
Go to the documentation of this file.
1 <?php
26 class FormatJson {
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, JSON_ERROR_UNSUPPORTED_TYPE,
191  // are all encode errors that we don't need to care about here.
192  switch ( $code ) {
193  case JSON_ERROR_NONE:
194  return Status::newGood( $result );
195  default:
196  return Status::newFatal( wfMessage( 'json-error-unknown' )->numParams( $code ) );
197  case JSON_ERROR_DEPTH:
198  $msg = 'json-error-depth';
199  break;
200  case JSON_ERROR_STATE_MISMATCH:
201  $msg = 'json-error-state-mismatch';
202  break;
203  case JSON_ERROR_CTRL_CHAR:
204  $msg = 'json-error-ctrl-char';
205  break;
206  case JSON_ERROR_SYNTAX:
207  $msg = 'json-error-syntax';
208  break;
209  case JSON_ERROR_UTF8:
210  $msg = 'json-error-utf8';
211  break;
212  case JSON_ERROR_INVALID_PROPERTY_NAME:
213  $msg = 'json-error-invalid-property-name';
214  break;
215  case JSON_ERROR_UTF16:
216  $msg = 'json-error-utf16';
217  break;
218  }
219  return Status::newFatal( $msg );
220  }
221 
230  public static function stripComments( $json ) {
231  // Ensure we have a string
232  $str = (string)$json;
233  $buffer = '';
234  $maxLen = strlen( $str );
235  $mark = 0;
236 
237  $inString = false;
238  $inComment = false;
239  $multiline = false;
240 
241  for ( $idx = 0; $idx < $maxLen; $idx++ ) {
242  switch ( $str[$idx] ) {
243  case '"':
244  $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
245  if ( !$inComment && $lookBehind !== '\\' ) {
246  // Either started or ended a string
247  $inString = !$inString;
248  }
249  break;
250 
251  case '/':
252  $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] : '';
253  $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] : '';
254  if ( $inString ) {
255  break;
256 
257  } elseif ( !$inComment &&
258  ( $lookAhead === '/' || $lookAhead === '*' )
259  ) {
260  // Transition into a comment
261  // Add characters seen to buffer
262  $buffer .= substr( $str, $mark, $idx - $mark );
263  // Consume the look ahead character
264  $idx++;
265  // Track state
266  $inComment = true;
267  $multiline = $lookAhead === '*';
268 
269  } elseif ( $multiline && $lookBehind === '*' ) {
270  // Found the end of the current comment
271  $mark = $idx + 1;
272  $inComment = false;
273  $multiline = false;
274  }
275  break;
276 
277  case "\n":
278  if ( $inComment && !$multiline ) {
279  // Found the end of the current comment
280  $mark = $idx + 1;
281  $inComment = false;
282  }
283  break;
284  }
285  }
286  if ( $inComment ) {
287  // Comment ends with input
288  // Technically we should check to ensure that we aren't in
289  // a multiline comment that hasn't been properly ended, but this
290  // is a strip filter, not a validating parser.
291  $mark = $maxLen;
292  }
293  // Add final chunk to buffer before returning
294  return $buffer . substr( $str, $mark, $maxLen - $mark );
295  }
296 }
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
FormatJson\XMLMETA_OK
const XMLMETA_OK
Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML.
Definition: FormatJson.php:46
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1183
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
FormatJson\UTF8_OK
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
Definition: FormatJson.php:34
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:146
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:96
FormatJson
JSON formatter wrapper class.
Definition: FormatJson.php:26
FormatJson\TRY_FIXING
const TRY_FIXING
If set, attempt to fix invalid JSON.
Definition: FormatJson.php:70
FormatJson\FORCE_ASSOC
const FORCE_ASSOC
If set, treat JSON objects '{...}' as associative arrays.
Definition: FormatJson.php:63
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
FormatJson\STRIP_COMMENTS
const STRIP_COMMENTS
If set, strip comments from input before parsing as JSON.
Definition: FormatJson.php:77
FormatJson\parse
static parse( $value, $options=0)
Decodes a JSON string.
Definition: FormatJson.php:160
FormatJson\stripComments
static stripComments( $json)
Remove multiline and single line comments from an otherwise valid JSON input string.
Definition: FormatJson.php:230