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