wfMerge() now works if $wgDiff3 contains spaces
[lhc/web/wiklou.git] / includes / libs / CSSJanus.php
1 <?php
2 /**
3 * PHP port of CSSJanus.
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 * This is a PHP port of CSSJanus, a utility that transforms CSS style sheets
25 * written for LTR to RTL.
26 *
27 * The original Python version of CSSJanus is Copyright 2008 by Google Inc. and
28 * is distributed under the Apache license. This PHP port is Copyright 2010 by
29 * Roan Kattouw and is dual-licensed under the GPL (as in the comment above) and
30 * the Apache (as in the original code) licenses.
31 *
32 * Original code: http://code.google.com/p/cssjanus/source/browse/trunk/cssjanus.py
33 * License of original code: http://code.google.com/p/cssjanus/source/browse/trunk/LICENSE
34 * @author Roan Kattouw
35 *
36 */
37 class CSSJanus {
38 // Patterns defined as null are built dynamically by buildPatterns()
39 private static $patterns = array(
40 'tmpToken' => '`TMP`',
41 'nonAscii' => '[\200-\377]',
42 'unicode' => '(?:(?:\\[0-9a-f]{1,6})(?:\r\n|\s)?)',
43 'num' => '(?:[0-9]*\.[0-9]+|[0-9]+)',
44 'unit' => '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)',
45 'body_selector' => 'body\s*{\s*',
46 'direction' => 'direction\s*:\s*',
47 'escape' => null,
48 'nmstart' => null,
49 'nmchar' => null,
50 'ident' => null,
51 'quantity' => null,
52 'possibly_negative_quantity' => null,
53 'color' => null,
54 'url_special_chars' => '[!#$%&*-~]',
55 'valid_after_uri_chars' => '[\'\"]?\s*',
56 'url_chars' => null,
57 'lookahead_not_open_brace' => null,
58 'lookahead_not_closing_paren' => null,
59 'lookahead_for_closing_paren' => null,
60 'lookbehind_not_letter' => '(?<![a-zA-Z])',
61 'chars_within_selector' => '[^\}]*?',
62 'noflip_annotation' => '\/\*\s*@noflip\s*\*\/',
63 'noflip_single' => null,
64 'noflip_class' => null,
65 'comment' => '/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//',
66 'direction_ltr' => null,
67 'direction_rtl' => null,
68 'left' => null,
69 'right' => null,
70 'left_in_url' => null,
71 'right_in_url' => null,
72 'ltr_in_url' => null,
73 'rtl_in_url' => null,
74 'cursor_east' => null,
75 'cursor_west' => null,
76 'four_notation_quantity' => null,
77 'four_notation_color' => null,
78 'bg_horizontal_percentage' => null,
79 'bg_horizontal_percentage_x' => null,
80 );
81
82 /**
83 * Build patterns we can't define above because they depend on other patterns.
84 */
85 private static function buildPatterns() {
86 if ( !is_null( self::$patterns['escape'] ) ) {
87 // Patterns have already been built
88 return;
89 }
90
91 $patterns =& self::$patterns;
92 $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
93 $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
94 $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
95 $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
96 $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
97 $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
98 $patterns['color'] = "(#?{$patterns['nmchar']}+)";
99 $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
100 $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>)*?{)";
101 $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
102 $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
103 $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
104 $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
105 $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
106 $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
107 $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
108 $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
109 $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
110 $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
111 $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
112 $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
113 $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
114 $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
115 $patterns['four_notation_quantity'] = "/{$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}/i";
116 $patterns['four_notation_color'] = "/(-color\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}/i";
117 // The two regexes below are parenthesized differently then in the original implementation to make the
118 // callback's job more straightforward
119 $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*[^%]*?)(-?{$patterns['num']})(%\s*(?:{$patterns['quantity']}|{$patterns['ident']}))/";
120 $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']})(%)/";
121 }
122
123 /**
124 * Transform an LTR stylesheet to RTL
125 * @param $css String: stylesheet to transform
126 * @param $swapLtrRtlInURL Boolean: If true, swap 'ltr' and 'rtl' in URLs
127 * @param $swapLeftRightInURL Boolean: If true, swap 'left' and 'right' in URLs
128 * @return string Transformed stylesheet
129 */
130 public static function transform( $css, $swapLtrRtlInURL = false, $swapLeftRightInURL = false ) {
131 // We wrap tokens in ` , not ~ like the original implementation does.
132 // This was done because ` is not a legal character in CSS and can only
133 // occur in URLs, where we escape it to %60 before inserting our tokens.
134 $css = str_replace( '`', '%60', $css );
135
136 self::buildPatterns();
137
138 // Tokenize single line rules with /* @noflip */
139 $noFlipSingle = new CSSJanus_Tokenizer( self::$patterns['noflip_single'], '`NOFLIP_SINGLE`' );
140 $css = $noFlipSingle->tokenize( $css );
141
142 // Tokenize class rules with /* @noflip */
143 $noFlipClass = new CSSJanus_Tokenizer( self::$patterns['noflip_class'], '`NOFLIP_CLASS`' );
144 $css = $noFlipClass->tokenize( $css );
145
146 // Tokenize comments
147 $comments = new CSSJanus_Tokenizer( self::$patterns['comment'], '`C`' );
148 $css = $comments->tokenize( $css );
149
150 // LTR->RTL fixes start here
151 $css = self::fixDirection( $css );
152 if ( $swapLtrRtlInURL ) {
153 $css = self::fixLtrRtlInURL( $css );
154 }
155
156 if ( $swapLeftRightInURL ) {
157 $css = self::fixLeftRightInURL( $css );
158 }
159 $css = self::fixLeftAndRight( $css );
160 $css = self::fixCursorProperties( $css );
161 $css = self::fixFourPartNotation( $css );
162 $css = self::fixBackgroundPosition( $css );
163
164 // Detokenize stuff we tokenized before
165 $css = $comments->detokenize( $css );
166 $css = $noFlipClass->detokenize( $css );
167 $css = $noFlipSingle->detokenize( $css );
168
169 return $css;
170 }
171
172 /**
173 * Replace direction: ltr; with direction: rtl; and vice versa.
174 *
175 * The original implementation only does this inside body selectors
176 * and misses "body\n{\ndirection:ltr;\n}". This function does not have
177 * these problems.
178 *
179 * See http://code.google.com/p/cssjanus/issues/detail?id=15 and
180 * TODO: URL
181 * @param $css string
182 * @return string
183 */
184 private static function fixDirection( $css ) {
185 $css = preg_replace( self::$patterns['direction_ltr'],
186 '$1' . self::$patterns['tmpToken'], $css );
187 $css = preg_replace( self::$patterns['direction_rtl'], '$1ltr', $css );
188 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
189
190 return $css;
191 }
192
193 /**
194 * Replace 'ltr' with 'rtl' and vice versa in background URLs
195 * @param $css string
196 * @return string
197 */
198 private static function fixLtrRtlInURL( $css ) {
199 $css = preg_replace( self::$patterns['ltr_in_url'], self::$patterns['tmpToken'], $css );
200 $css = preg_replace( self::$patterns['rtl_in_url'], 'ltr', $css );
201 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
202
203 return $css;
204 }
205
206 /**
207 * Replace 'left' with 'right' and vice versa in background URLs
208 * @param $css string
209 * @return string
210 */
211 private static function fixLeftRightInURL( $css ) {
212 $css = preg_replace( self::$patterns['left_in_url'], self::$patterns['tmpToken'], $css );
213 $css = preg_replace( self::$patterns['right_in_url'], 'left', $css );
214 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
215
216 return $css;
217 }
218
219 /**
220 * Flip rules like left: , padding-right: , etc.
221 * @param $css string
222 * @return string
223 */
224 private static function fixLeftAndRight( $css ) {
225 $css = preg_replace( self::$patterns['left'], self::$patterns['tmpToken'], $css );
226 $css = preg_replace( self::$patterns['right'], 'left', $css );
227 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
228
229 return $css;
230 }
231
232 /**
233 * Flip East and West in rules like cursor: nw-resize;
234 * @param $css string
235 * @return string
236 */
237 private static function fixCursorProperties( $css ) {
238 $css = preg_replace( self::$patterns['cursor_east'],
239 '$1' . self::$patterns['tmpToken'], $css );
240 $css = preg_replace( self::$patterns['cursor_west'], '$1e-resize', $css );
241 $css = str_replace( self::$patterns['tmpToken'], 'w-resize', $css );
242
243 return $css;
244 }
245
246 /**
247 * Swap the second and fourth parts in four-part notation rules like
248 * padding: 1px 2px 3px 4px;
249 *
250 * Unlike the original implementation, this function doesn't suffer from
251 * the bug where whitespace is not preserved when flipping four-part rules
252 * and four-part color rules with multiple whitespace characters between
253 * colors are not recognized.
254 * See http://code.google.com/p/cssjanus/issues/detail?id=16
255 * @param $css string
256 * @return string
257 */
258 private static function fixFourPartNotation( $css ) {
259 $css = preg_replace( self::$patterns['four_notation_quantity'], '$1$2$7$4$5$6$3', $css );
260 $css = preg_replace( self::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4', $css );
261
262 return $css;
263 }
264
265 /**
266 * Flip horizontal background percentages.
267 * @param $css string
268 * @return string
269 */
270 private static function fixBackgroundPosition( $css ) {
271 $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage'],
272 array( 'self', 'calculateNewBackgroundPosition' ), $css );
273 if ( $replaced !== null ) {
274 // Check for null; sometimes preg_replace_callback() returns null here for some weird reason
275 $css = $replaced;
276 }
277 $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage_x'],
278 array( 'self', 'calculateNewBackgroundPosition' ), $css );
279 if ( $replaced !== null ) {
280 $css = $replaced;
281 }
282
283 return $css;
284 }
285
286 /**
287 * Callback for calculateNewBackgroundPosition()
288 * @param $matches array
289 * @return string
290 */
291 private static function calculateNewBackgroundPosition( $matches ) {
292 return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
293 }
294 }
295
296 /**
297 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
298 * to protect from being janused.
299 * @author Roan Kattouw
300 */
301 class CSSJanus_Tokenizer {
302 private $regex, $token;
303 private $originals;
304
305 /**
306 * Constructor
307 * @param $regex string Regular expression whose matches to replace by a token.
308 * @param $token string Token
309 */
310 public function __construct( $regex, $token ) {
311 $this->regex = $regex;
312 $this->token = $token;
313 $this->originals = array();
314 }
315
316 /**
317 * Replace all occurrences of $regex in $str with a token and remember
318 * the original strings.
319 * @param $str String to tokenize
320 * @return string Tokenized string
321 */
322 public function tokenize( $str ) {
323 return preg_replace_callback( $this->regex, array( $this, 'tokenizeCallback' ), $str );
324 }
325
326 /**
327 * @param $matches array
328 * @return string
329 */
330 private function tokenizeCallback( $matches ) {
331 $this->originals[] = $matches[0];
332 return $this->token;
333 }
334
335 /**
336 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
337 * detokenized in exactly the SAME ORDER.
338 * @param $str String: previously run through tokenize()
339 * @return string Original string
340 */
341 public function detokenize( $str ) {
342 // PHP has no function to replace only the first occurrence or to
343 // replace occurrences of the same string with different values,
344 // so we use preg_replace_callback() even though we don't really need a regex
345 return preg_replace_callback( '/' . preg_quote( $this->token, '/' ) . '/',
346 array( $this, 'detokenizeCallback' ), $str );
347 }
348
349 /**
350 * @param $matches
351 * @return mixed
352 */
353 private function detokenizeCallback( $matches ) {
354 $retval = current( $this->originals );
355 next( $this->originals );
356
357 return $retval;
358 }
359 }