Merge "Split change_tag sql patch"
[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 /**
29 * Skip escaping most characters above U+007F for readability and compactness.
30 * This encoding option saves 3 to 8 bytes (uncompressed) for each such character;
31 * however, it could break compatibility with systems that incorrectly handle UTF-8.
32 *
33 * @since 1.22
34 */
35 const UTF8_OK = 1;
36
37 /**
38 * Skip escaping the characters '<', '>', and '&', which have special meanings in
39 * HTML and XML.
40 *
41 * @warning Do not use this option for JSON that could end up in inline scripts.
42 * - HTML5, §4.3.1.2 Restrictions for contents of script elements
43 * - XML 1.0 (5th Ed.), §2.4 Character Data and Markup
44 *
45 * @since 1.22
46 */
47 const XMLMETA_OK = 2;
48
49 /**
50 * Skip escaping as many characters as reasonably possible.
51 *
52 * @warning When generating inline script blocks, use FormatJson::UTF8_OK instead.
53 *
54 * @since 1.22
55 */
56 const ALL_OK = 3;
57
58 /**
59 * Characters problematic in JavaScript.
60 *
61 * @note These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF)
62 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
63 */
64 private static $badChars = array(
65 "\xe2\x80\xa8", // U+2028 LINE SEPARATOR
66 "\xe2\x80\xa9", // U+2029 PARAGRAPH SEPARATOR
67 );
68
69 /**
70 * Escape sequences for characters listed in FormatJson::$badChars.
71 */
72 private static $badCharsEscaped = array(
73 '\u2028', // U+2028 LINE SEPARATOR
74 '\u2029', // U+2029 PARAGRAPH SEPARATOR
75 );
76
77 /**
78 * Returns the JSON representation of a value.
79 *
80 * @note Empty arrays are encoded as numeric arrays, not as objects, so cast any associative
81 * array that might be empty to an object before encoding it.
82 *
83 * @note In pre-1.22 versions of MediaWiki, using this function for generating inline script
84 * blocks may result in an XSS vulnerability, and quite likely will in XML documents
85 * (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
86 *
87 * @param mixed $value The value to encode. Can be any type except a resource.
88 * @param bool $pretty If true, add non-significant whitespace to improve readability.
89 * @param int $escaping Bitfield consisting of _OK class constants
90 * @return string|bool: String if successful; false upon failure
91 */
92 public static function encode( $value, $pretty = false, $escaping = 0 ) {
93 if ( defined( 'JSON_UNESCAPED_UNICODE' ) ) {
94 return self::encode54( $value, $pretty, $escaping );
95 }
96 return self::encode53( $value, $pretty, $escaping );
97 }
98
99 /**
100 * Decodes a JSON string.
101 *
102 * @param string $value The JSON string being decoded
103 * @param bool $assoc When true, returned objects will be converted into associative arrays.
104 *
105 * @return mixed: the value encoded in JSON in appropriate PHP type.
106 * `null` is returned if the JSON cannot be decoded or if the encoded data is deeper than
107 * the recursion limit.
108 */
109 public static function decode( $value, $assoc = false ) {
110 return json_decode( $value, $assoc );
111 }
112
113 /**
114 * JSON encoder wrapper for PHP >= 5.4, which supports useful encoding options.
115 *
116 * @param mixed $value
117 * @param bool $pretty
118 * @param int $escaping
119 * @return string|bool
120 */
121 private static function encode54( $value, $pretty, $escaping ) {
122 // PHP escapes '/' to prevent breaking out of inline script blocks using '</script>',
123 // which is hardly useful when '<' and '>' are escaped (and inadequate), and such
124 // escaping negatively impacts the human readability of URLs and similar strings.
125 $options = JSON_UNESCAPED_SLASHES;
126 $options |= $pretty ? JSON_PRETTY_PRINT : 0;
127 $options |= ( $escaping & self::UTF8_OK ) ? JSON_UNESCAPED_UNICODE : 0;
128 $options |= ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
129 $json = json_encode( $value, $options );
130 if ( $json === false ) {
131 return false;
132 }
133 if ( $escaping & self::UTF8_OK ) {
134 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
135 }
136 return $json;
137 }
138
139 /**
140 * JSON encoder wrapper for PHP 5.3, which lacks native support for some encoding options.
141 * Therefore, the missing options are implemented here purely in PHP code.
142 *
143 * @param mixed $value
144 * @param bool $pretty
145 * @param int $escaping
146 * @return string|bool
147 */
148 private static function encode53( $value, $pretty, $escaping ) {
149 $options = ( $escaping & self::XMLMETA_OK ) ? 0 : ( JSON_HEX_TAG | JSON_HEX_AMP );
150 $json = json_encode( $value, $options );
151 if ( $json === false ) {
152 return false;
153 }
154
155 // Emulate JSON_UNESCAPED_SLASHES. Because the JSON contains no unescaped slashes
156 // (only escaped slashes), a simple string replacement works fine.
157 $json = str_replace( '\/', '/', $json );
158
159 if ( $escaping & self::UTF8_OK ) {
160 // JSON hex escape sequences follow the format \uDDDD, where DDDD is four hex digits
161 // indicating the equivalent UTF-16 code unit's value. To most efficiently unescape
162 // them, we exploit the JSON extension's built-in decoder.
163 // * We escape the input a second time, so any such sequence becomes \\uDDDD.
164 // * To avoid interpreting escape sequences that were in the original input,
165 // each double-escaped backslash (\\\\) is replaced with \\\u005c.
166 // * We strip one of the backslashes from each of the escape sequences to unescape.
167 // * Then the JSON decoder can perform the actual unescaping.
168 $json = str_replace( "\\\\\\\\", "\\\\\\u005c", addcslashes( $json, '\"' ) );
169 $json = json_decode( preg_replace( "/\\\\\\\\u(?!00[0-7])/", "\\\\u", "\"$json\"" ) );
170 $json = str_replace( self::$badChars, self::$badCharsEscaped, $json );
171 }
172
173 if ( $pretty ) {
174 return self::prettyPrint( $json );
175 }
176 return $json;
177 }
178
179 /**
180 * Adds non-significant whitespace to an existing JSON representation of an object.
181 * Only needed for PHP < 5.4, which lacks the JSON_PRETTY_PRINT option.
182 *
183 * @param string $json
184 * @return string
185 */
186 private static function prettyPrint( $json ) {
187 $buf = '';
188 $indent = 0;
189 $json = strtr( $json, array( '\\\\' => '\\\\', '\"' => "\x01" ) );
190 for ( $i = 0, $n = strlen( $json ); $i < $n; $i += $skip ) {
191 $skip = 1;
192 switch ( $json[$i] ) {
193 case ':':
194 $buf .= ': ';
195 break;
196 case '[':
197 case '{':
198 ++$indent;
199 // falls through
200 case ',':
201 $buf .= $json[$i] . "\n" . str_repeat( ' ', $indent );
202 break;
203 case ']':
204 case '}':
205 $buf .= "\n" . str_repeat( ' ', --$indent ) . $json[$i];
206 break;
207 case '"':
208 $skip = strcspn( $json, '"', $i + 1 ) + 2;
209 $buf .= substr( $json, $i, $skip );
210 break;
211 default:
212 $skip = strcspn( $json, ',]}"', $i + 1 ) + 1;
213 $buf .= substr( $json, $i, $skip );
214 }
215 }
216 return str_replace( "\x01", '\"', preg_replace( '/ +$/m', '', $buf ) );
217 }
218 }