31f570d53f0fde8b14962f0bfe192aff01615d00
[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 */
179 private static function fixDirection( $css ) {
180 $css = preg_replace( self::$patterns['direction_ltr'],
181 '$1' . self::$patterns['tmpToken'], $css );
182 $css = preg_replace( self::$patterns['direction_rtl'], '$1ltr', $css );
183 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
184
185 return $css;
186 }
187
188 /**
189 * Replace 'ltr' with 'rtl' and vice versa in background URLs
190 */
191 private static function fixLtrRtlInURL( $css ) {
192 $css = preg_replace( self::$patterns['ltr_in_url'], self::$patterns['tmpToken'], $css );
193 $css = preg_replace( self::$patterns['rtl_in_url'], 'ltr', $css );
194 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
195
196 return $css;
197 }
198
199 /**
200 * Replace 'left' with 'right' and vice versa in background URLs
201 */
202 private static function fixLeftRightInURL( $css ) {
203 $css = preg_replace( self::$patterns['left_in_url'], self::$patterns['tmpToken'], $css );
204 $css = preg_replace( self::$patterns['right_in_url'], 'left', $css );
205 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
206
207 return $css;
208 }
209
210 /**
211 * Flip rules like left: , padding-right: , etc.
212 */
213 private static function fixLeftAndRight( $css ) {
214 $css = preg_replace( self::$patterns['left'], self::$patterns['tmpToken'], $css );
215 $css = preg_replace( self::$patterns['right'], 'left', $css );
216 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
217
218 return $css;
219 }
220
221 /**
222 * Flip East and West in rules like cursor: nw-resize;
223 */
224 private static function fixCursorProperties( $css ) {
225 $css = preg_replace( self::$patterns['cursor_east'],
226 '$1' . self::$patterns['tmpToken'], $css );
227 $css = preg_replace( self::$patterns['cursor_west'], '$1e-resize', $css );
228 $css = str_replace( self::$patterns['tmpToken'], 'w-resize', $css );
229
230 return $css;
231 }
232
233 /**
234 * Swap the second and fourth parts in four-part notation rules like
235 * padding: 1px 2px 3px 4px;
236 *
237 * Unlike the original implementation, this function doesn't suffer from
238 * the bug where whitespace is not preserved when flipping four-part rules
239 * and four-part color rules with multiple whitespace characters between
240 * colors are not recognized.
241 * See http://code.google.com/p/cssjanus/issues/detail?id=16
242 */
243 private static function fixFourPartNotation( $css ) {
244 $css = preg_replace( self::$patterns['four_notation_quantity'], '$1$2$7$4$5$6$3', $css );
245 $css = preg_replace( self::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4', $css );
246
247 return $css;
248 }
249
250 /**
251 * Flip horizontal background percentages.
252 */
253 private static function fixBackgroundPosition( $css ) {
254 $css = preg_replace_callback( self::$patterns['bg_horizontal_percentage'],
255 array( 'self', 'calculateNewBackgroundPosition' ), $css );
256 $css = preg_replace_callback( self::$patterns['bg_horizontal_percentage_x'],
257 array( 'self', 'calculateNewBackgroundPosition' ), $css );
258
259 return $css;
260 }
261
262 /**
263 * Callback for calculateNewBackgroundPosition()
264 */
265 private static function calculateNewBackgroundPosition( $matches ) {
266 return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
267 }
268 }
269
270 /**
271 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
272 * to protect from being janused.
273 * @author Roan Kattouw
274 */
275 class CSSJanus_Tokenizer {
276 private $regex, $token;
277 private $originals;
278
279 /**
280 * Constructor
281 * @param $regex string Regular expression whose matches to replace by a token.
282 * @param $token string Token
283 */
284 public function __construct( $regex, $token ) {
285 $this->regex = $regex;
286 $this->token = $token;
287 $this->originals = array();
288 }
289
290 /**
291 * Replace all occurrences of $regex in $str with a token and remember
292 * the original strings.
293 * @param $str String to tokenize
294 * @return string Tokenized string
295 */
296 public function tokenize( $str ) {
297 return preg_replace_callback( $this->regex, array( $this, 'tokenizeCallback' ), $str );
298 }
299
300 private function tokenizeCallback( $matches ) {
301 $this->originals[] = $matches[0];
302 return $this->token;
303 }
304
305 /**
306 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
307 * detokenized in exactly the SAME ORDER.
308 * @param $str String: previously run through tokenize()
309 * @return string Original string
310 */
311 public function detokenize( $str ) {
312 // PHP has no function to replace only the first occurrence or to
313 // replace occurrences of the same string with different values,
314 // so we use preg_replace_callback() even though we don't really need a regex
315 return preg_replace_callback( '/' . preg_quote( $this->token, '/' ) . '/',
316 array( $this, 'detokenizeCallback' ), $str );
317 }
318
319 private function detokenizeCallback( $matches ) {
320 $retval = current( $this->originals );
321 next( $this->originals );
322
323 return $retval;
324 }
325 }