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