Whitelist the <wbr> element.
[mediawiki.git] / includes / libs / CSSJanus.php
blob128d9b90310318c757db7030e4dd84e3d914e7e3
1 <?php
2 /**
3 * PHP port of CSSJanus.
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.
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.
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
20 * @file
23 /**
24 * This is a PHP port of CSSJanus, a utility that transforms CSS style sheets
25 * written for LTR to RTL.
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.
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
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 'bg_horizontal_percentage' => null,
81 'bg_horizontal_percentage_x' => null,
84 /**
85 * Build patterns we can't define above because they depend on other patterns.
87 private static function buildPatterns() {
88 if ( !is_null( self::$patterns['escape'] ) ) {
89 // Patterns have already been built
90 return;
93 $patterns =& self::$patterns;
94 $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
95 $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
96 $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
97 $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
98 $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
99 $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
100 $patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
101 $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
102 $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>|\(|\))*?{)";
103 $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
104 $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
105 $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
106 $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
107 $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
108 $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
109 $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
110 $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
111 $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
112 $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
113 $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
114 $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
115 $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
116 $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
117 $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";
118 $patterns['four_notation_color'] = "/(-color\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s*[;}])/i";
119 $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";
120 // The two regexes below are parenthesized differently then in the original implementation to make the
121 // callback's job more straightforward
122 $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*[^%]*?)(-?{$patterns['num']})(%\s*(?:{$patterns['quantity']}|{$patterns['ident']}))/";
123 $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']})(%)/";
127 * Transform an LTR stylesheet to RTL
128 * @param string $css stylesheet to transform
129 * @param $swapLtrRtlInURL Boolean: If true, swap 'ltr' and 'rtl' in URLs
130 * @param $swapLeftRightInURL Boolean: If true, swap 'left' and 'right' in URLs
131 * @return string Transformed stylesheet
133 public static function transform( $css, $swapLtrRtlInURL = false, $swapLeftRightInURL = false ) {
134 // We wrap tokens in ` , not ~ like the original implementation does.
135 // This was done because ` is not a legal character in CSS and can only
136 // occur in URLs, where we escape it to %60 before inserting our tokens.
137 $css = str_replace( '`', '%60', $css );
139 self::buildPatterns();
141 // Tokenize single line rules with /* @noflip */
142 $noFlipSingle = new CSSJanus_Tokenizer( self::$patterns['noflip_single'], '`NOFLIP_SINGLE`' );
143 $css = $noFlipSingle->tokenize( $css );
145 // Tokenize class rules with /* @noflip */
146 $noFlipClass = new CSSJanus_Tokenizer( self::$patterns['noflip_class'], '`NOFLIP_CLASS`' );
147 $css = $noFlipClass->tokenize( $css );
149 // Tokenize comments
150 $comments = new CSSJanus_Tokenizer( self::$patterns['comment'], '`C`' );
151 $css = $comments->tokenize( $css );
153 // LTR->RTL fixes start here
154 $css = self::fixDirection( $css );
155 if ( $swapLtrRtlInURL ) {
156 $css = self::fixLtrRtlInURL( $css );
159 if ( $swapLeftRightInURL ) {
160 $css = self::fixLeftRightInURL( $css );
162 $css = self::fixLeftAndRight( $css );
163 $css = self::fixCursorProperties( $css );
164 $css = self::fixFourPartNotation( $css );
165 $css = self::fixBorderRadius( $css );
166 $css = self::fixBackgroundPosition( $css );
168 // Detokenize stuff we tokenized before
169 $css = $comments->detokenize( $css );
170 $css = $noFlipClass->detokenize( $css );
171 $css = $noFlipSingle->detokenize( $css );
173 return $css;
177 * Replace direction: ltr; with direction: rtl; and vice versa.
179 * The original implementation only does this inside body selectors
180 * and misses "body\n{\ndirection:ltr;\n}". This function does not have
181 * these problems.
183 * See http://code.google.com/p/cssjanus/issues/detail?id=15 and
184 * TODO: URL
185 * @param $css string
186 * @return string
188 private static function fixDirection( $css ) {
189 $css = preg_replace( self::$patterns['direction_ltr'],
190 '$1' . self::$patterns['tmpToken'], $css );
191 $css = preg_replace( self::$patterns['direction_rtl'], '$1ltr', $css );
192 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
194 return $css;
198 * Replace 'ltr' with 'rtl' and vice versa in background URLs
199 * @param $css string
200 * @return string
202 private static function fixLtrRtlInURL( $css ) {
203 $css = preg_replace( self::$patterns['ltr_in_url'], self::$patterns['tmpToken'], $css );
204 $css = preg_replace( self::$patterns['rtl_in_url'], 'ltr', $css );
205 $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
207 return $css;
211 * Replace 'left' with 'right' and vice versa in background URLs
212 * @param $css string
213 * @return string
215 private static function fixLeftRightInURL( $css ) {
216 $css = preg_replace( self::$patterns['left_in_url'], self::$patterns['tmpToken'], $css );
217 $css = preg_replace( self::$patterns['right_in_url'], 'left', $css );
218 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
220 return $css;
224 * Flip rules like left: , padding-right: , etc.
225 * @param $css string
226 * @return string
228 private static function fixLeftAndRight( $css ) {
229 $css = preg_replace( self::$patterns['left'], self::$patterns['tmpToken'], $css );
230 $css = preg_replace( self::$patterns['right'], 'left', $css );
231 $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
233 return $css;
237 * Flip East and West in rules like cursor: nw-resize;
238 * @param $css string
239 * @return string
241 private static function fixCursorProperties( $css ) {
242 $css = preg_replace( self::$patterns['cursor_east'],
243 '$1' . self::$patterns['tmpToken'], $css );
244 $css = preg_replace( self::$patterns['cursor_west'], '$1e-resize', $css );
245 $css = str_replace( self::$patterns['tmpToken'], 'w-resize', $css );
247 return $css;
251 * Swap the second and fourth parts in four-part notation rules like
252 * padding: 1px 2px 3px 4px;
254 * Unlike the original implementation, this function doesn't suffer from
255 * the bug where whitespace is not preserved when flipping four-part rules
256 * and four-part color rules with multiple whitespace characters between
257 * colors are not recognized.
258 * See http://code.google.com/p/cssjanus/issues/detail?id=16
259 * @param $css string
260 * @return string
262 private static function fixFourPartNotation( $css ) {
263 $css = preg_replace( self::$patterns['four_notation_quantity'], '$1$2$3$8$5$6$7$4$9', $css );
264 $css = preg_replace( self::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4$9', $css );
266 return $css;
270 * Swaps appropriate corners in four-part border-radius rules.
271 * Needs to undo the effect of fixFourPartNotation() on those rules, too.
273 * @param $css string
274 * @return string
276 private static function fixBorderRadius( $css ) {
277 // Undo four_notation_quantity
278 $css = preg_replace( self::$patterns['border_radius'], '$1$2$3$8$5$6$7$4$9', $css );
279 // Do the real thing
280 $css = preg_replace( self::$patterns['border_radius'], '$1$4$3$2$5$8$7$6$9', $css );
282 return $css;
286 * Flip horizontal background percentages.
287 * @param $css string
288 * @return string
290 private static function fixBackgroundPosition( $css ) {
291 $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage'],
292 array( 'self', 'calculateNewBackgroundPosition' ), $css );
293 if ( $replaced !== null ) {
294 // Check for null; sometimes preg_replace_callback() returns null here for some weird reason
295 $css = $replaced;
297 $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage_x'],
298 array( 'self', 'calculateNewBackgroundPosition' ), $css );
299 if ( $replaced !== null ) {
300 $css = $replaced;
303 return $css;
307 * Callback for calculateNewBackgroundPosition()
308 * @param $matches array
309 * @return string
311 private static function calculateNewBackgroundPosition( $matches ) {
312 return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
317 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
318 * to protect from being janused.
319 * @author Roan Kattouw
321 class CSSJanus_Tokenizer {
322 private $regex, $token;
323 private $originals;
326 * Constructor
327 * @param string $regex Regular expression whose matches to replace by a token.
328 * @param string $token Token
330 public function __construct( $regex, $token ) {
331 $this->regex = $regex;
332 $this->token = $token;
333 $this->originals = array();
337 * Replace all occurrences of $regex in $str with a token and remember
338 * the original strings.
339 * @param string $str to tokenize
340 * @return string Tokenized string
342 public function tokenize( $str ) {
343 return preg_replace_callback( $this->regex, array( $this, 'tokenizeCallback' ), $str );
347 * @param $matches array
348 * @return string
350 private function tokenizeCallback( $matches ) {
351 $this->originals[] = $matches[0];
352 return $this->token;
356 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
357 * detokenized in exactly the SAME ORDER.
358 * @param string $str previously run through tokenize()
359 * @return string Original string
361 public function detokenize( $str ) {
362 // PHP has no function to replace only the first occurrence or to
363 // replace occurrences of the same string with different values,
364 // so we use preg_replace_callback() even though we don't really need a regex
365 return preg_replace_callback( '/' . preg_quote( $this->token, '/' ) . '/',
366 array( $this, 'detokenizeCallback' ), $str );
370 * @param $matches
371 * @return mixed
373 private function detokenizeCallback( $matches ) {
374 $retval = current( $this->originals );
375 next( $this->originals );
377 return $retval;