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