Merge "Add SelfLinkBeginHook"
[lhc/web/wiklou.git] / includes / json / FormatJson.php
1 <?php
2 /**
3 * Wrapper for json_encode and json_decode.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * JSON formatter wrapper class
25 */
26 class FormatJson {
27 /**
28 * Skip escaping most characters above U+007F for readability and compactness.
29 * This encoding option saves 3 to 8 bytes (uncompressed) for each such character;
30 * however, it could break compatibility with systems that incorrectly handle UTF-8.
31 *
32 * @since 1.22
33 */
34 const UTF8_OK = 1;
35
36 /**
37 * Skip escaping the characters '<', '>', and '&', which have special meanings in
38 * HTML and XML.
39 *
40 * @warning Do not use this option for JSON that could end up in inline scripts.
41 * - HTML5, §4.3.1.2 Restrictions for contents of script elements
42 * - XML 1.0 (5th Ed.), §2.4 Character Data and Markup
43 *
44 * @since 1.22
45 */
46 const XMLMETA_OK = 2;
47
48 /**
49 * Skip escaping as many characters as reasonably possible.
50 *
51 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
52 *
53 * @since 1.22
54 */
55 const ALL_OK = 3;
56
57 /**
58 * Regex that matches whitespace inside empty arrays and objects.
59 *
60 * This doesn't affect regular strings inside the JSON because those can't
61 * have a real line break (\n) in them, at this point they are already escaped
62 * as the string "\n" which this doesn't match.
63 *
64 * @private
65 */
66 const WS_CLEANUP_REGEX = '/(?<=[\[{])\n\s*+(?=[\]}])/';
67
68 /**
69 * Characters problematic in JavaScript.
70 *
71 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
72 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
73 */
74 private static $badChars = array(
75 "\xe2\x80\xa8", // U+2028 LINE SEPARATOR
76 "\xe2\x80\xa9", // U+2029 PARAGRAPH SEPARATOR
77 );
78
79 /**
80 * Escape sequences for characters listed in FormatJson::$badChars.
81 */
82 private static $badCharsEscaped = array(
83 '\u2028', // U+2028 LINE SEPARATOR
84 '\u2029', // U+2029 PARAGRAPH SEPARATOR
85 );
86
87 /**
88 * Returns the JSON representation of a value.
89 *
90 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
91 * array that might be empty to an object before encoding it.
92 *
93 * @note In pre-1.22 versions of MediaWiki, using this function for generating inline script
94 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
95 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
96 *
97 * @param mixed $value The value to encode. Can be any type except a resource.
98 * @param string|bool $pretty If a string, add non-significant whitespace to improve
99 * readability, using that string for indentation. If true, use the default indent
100 * string (four spaces).
101 * @param int $escaping Bitfield consisting of _OK class constants
102 * @return string|bool: String if successful; false upon failure
103 */
104 public static function encode( $value, $pretty = false, $escaping = 0 ) {
105 if ( !is_string( $pretty ) ) {
106 $pretty = $pretty ? ' ' : false;
107 }
108
109 if ( defined( 'JSON_UNESCAPED_UNICODE' ) ) {
110 return self::encode54( $value, $pretty, $escaping );
111 }
112
113 return self::encode53( $value, $pretty, $escaping );
114 }
115
116 /**
117 * Decodes a JSON string.
118 *
119 * @param string $value The JSON string being decoded
120 * @param bool $assoc When true, returned objects will be converted into associative arrays.
121 *
122 * @return mixed The value encoded in JSON in appropriate PHP type.
123 * `null` is returned if the JSON cannot be decoded or if the encoded data is deeper than
124 * the recursion limit.
125 */
126 public static function decode( $value, $assoc = false ) {
127 return json_decode( $value, $assoc );
128 }
129
130 /**
131 * JSON encoder wrapper for PHP >= 5.4, which supports useful encoding options.
132 *
133 * @param mixed $value
134 * @param string|bool $pretty
135 * @param int $escaping
136 * @return string|bool
137 */
138 private static function encode54( $value, $pretty, $escaping ) {
139 static $bug66021;
140 if ( $pretty !== false && $bug66021 === null ) {
141 $bug66021 = json_encode( array(), JSON_PRETTY_PRINT ) !== '[]';
142 }
143
144 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
145 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
146 // escaping negatively impacts the human readability of URLs and similar strings.
147 $options = JSON_UNESCAPED_SLASHES;
148 $options |= $pretty !== false ? JSON_PRETTY_PRINT : 0;
149 $options |= ( $escaping & self::UTF8_OK ) ? JSON_UNESCAPED_UNICODE : 0;
150 $options |= ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
151 $json = json_encode( $value, $options );
152 if ( $json === false ) {
153 return false;
154 }
155
156 if ( $pretty !== false ) {
157 // Workaround for <https://bugs.php.net/bug.php?id=66021>
158 if ( $bug66021 ) {
159 $json = preg_replace( self::WS_CLEANUP_REGEX, '', $json );
160 }
161 if ( $pretty !== ' ' ) {
162 // Change the four-space indent to a tab indent
163 $json = str_replace( "\n ", "\n\t", $json );
164 while ( strpos( $json, "\t " ) !== false ) {
165 $json = str_replace( "\t ", "\t\t", $json );
166 }
167
168 if ( $pretty !== "\t" ) {
169 // Change the tab indent to the provided indent
170 $json = str_replace( "\t", $pretty, $json );
171 }
172 }
173 }
174 if ( $escaping & self::UTF8_OK ) {
175 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
176 }
177
178 return $json;
179 }
180
181 /**
182 * JSON encoder wrapper for PHP 5.3, which lacks native support for some encoding options.
183 * Therefore, the missing options are implemented here purely in PHP code.
184 *
185 * @param mixed $value
186 * @param string|bool $pretty
187 * @param int $escaping
188 * @return string|bool
189 */
190 private static function encode53( $value, $pretty, $escaping ) {
191 $options = ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
192 $json = json_encode( $value, $options );
193 if ( $json === false ) {
194 return false;
195 }
196
197 // Emulate JSON_UNESCAPED_SLASHES. Because the JSON contains no unescaped slashes
198 // (only escaped slashes), a simple string replacement works fine.
199 $json = str_replace( '\/', '/', $json );
200
201 if ( $escaping & self::UTF8_OK ) {
202 // JSON hex escape sequences follow the format \uDDDD, where DDDD is four hex digits
203 // indicating the equivalent UTF-16 code unit's value. To most efficiently unescape
204 // them, we exploit the JSON extension's built-in decoder.
205 // * We escape the input a second time, so any such sequence becomes \\uDDDD.
206 // * To avoid interpreting escape sequences that were in the original input,
207 // each double-escaped backslash (\\\\) is replaced with \\\u005c.
208 // * We strip one of the backslashes from each of the escape sequences to unescape.
209 // * Then the JSON decoder can perform the actual unescaping.
210 $json = str_replace( "\\\\\\\\", "\\\\\\u005c", addcslashes( $json, '\"' ) );
211 $json = json_decode( preg_replace( "/\\\\\\\\u(?!00[0-7])/", "\\\\u", "\"$json\"" ) );
212 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
213 }
214
215 if ( $pretty !== false ) {
216 return self::prettyPrint( $json, $pretty );
217 }
218
219 return $json;
220 }
221
222 /**
223 * Adds non-significant whitespace to an existing JSON representation of an object.
224 * Only needed for PHP < 5.4, which lacks the JSON_PRETTY_PRINT option.
225 *
226 * @param string $json
227 * @param string $indentString
228 * @return string
229 */
230 private static function prettyPrint( $json, $indentString ) {
231 $buf = '';
232 $indent = 0;
233 $json = strtr( $json, array( '\\\\' => '\\\\', '\"' => "\x01" ) );
234 for ( $i = 0, $n = strlen( $json ); $i < $n; $i += $skip ) {
235 $skip = 1;
236 switch ( $json[$i] ) {
237 case ':':
238 $buf .= ': ';
239 break;
240 case '[':
241 case '{':
242 ++$indent;
243 // falls through
244 case ',':
245 $buf .= $json[$i] . "\n" . str_repeat( $indentString, $indent );
246 break;
247 case ']':
248 case '}':
249 $buf .= "\n" . str_repeat( $indentString, --$indent ) . $json[$i];
250 break;
251 case '"':
252 $skip = strcspn( $json, '"', $i + 1 ) + 2;
253 $buf .= substr( $json, $i, $skip );
254 break;
255 default:
256 $skip = strcspn( $json, ',]}"', $i + 1 ) + 1;
257 $buf .= substr( $json, $i, $skip );
258 }
259 }
260 $buf = preg_replace( self::WS_CLEANUP_REGEX, '', $buf );
261
262 return str_replace( "\x01", '\"', $buf );
263 }
264 }