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
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
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*',
52 'possibly_negative_quantity' => null,
54 'url_special_chars' => '[!#$%&*-~]',
55 'valid_after_uri_chars' => '[\'\"]?\s*',
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,
71 'left_in_url' => null,
72 'right_in_url' => null,
75 'cursor_east' => null,
76 'cursor_west' => null,
77 'four_notation_quantity' => null,
78 'four_notation_color' => null,
80 'text_shadow1' => null,
81 'text_shadow2' => null,
82 'bg_horizontal_percentage' => null,
83 'bg_horizontal_percentage_x' => null,
87 * Build patterns we can't define above because they depend on other patterns.
89 private static function buildPatterns() {
90 if ( !is_null( self
::$patterns['escape'] ) ) {
91 // Patterns have already been built
95 $patterns =& self
::$patterns;
96 $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
97 $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
98 $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
99 $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
100 $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
101 $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
102 $patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
103 $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
104 $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>)*?{)";
105 $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
106 $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
107 $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
108 $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
109 $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
110 $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
111 $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
112 $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
113 $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
114 $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
115 $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
116 $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
117 $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
118 $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
119 $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";
120 $patterns['four_notation_color'] = "/(-color\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s*[;}])/i";
121 $patterns['box_shadow'] = "/(box-shadow\s*:\s*(?:inset\s*)?){$patterns['possibly_negative_quantity']}/i";
122 $patterns['text_shadow1'] = "/(text-shadow\s*:\s*){$patterns['color']}(\s*){$patterns['possibly_negative_quantity']}/i";
123 $patterns['text_shadow2'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}/i";
124 // The two regexes below are parenthesized differently then in the original implementation to make the
125 // callback's job more straightforward
126 $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*[^%]*?)(-?{$patterns['num']})(%\s*(?:{$patterns['quantity']}|{$patterns['ident']}))/";
127 $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']})(%)/";
131 * Transform an LTR stylesheet to RTL
132 * @param $css String: stylesheet to transform
133 * @param $swapLtrRtlInURL Boolean: If true, swap 'ltr' and 'rtl' in URLs
134 * @param $swapLeftRightInURL Boolean: If true, swap 'left' and 'right' in URLs
135 * @return string Transformed stylesheet
137 public static function transform( $css, $swapLtrRtlInURL = false, $swapLeftRightInURL = false ) {
138 // We wrap tokens in ` , not ~ like the original implementation does.
139 // This was done because ` is not a legal character in CSS and can only
140 // occur in URLs, where we escape it to %60 before inserting our tokens.
141 $css = str_replace( '`', '%60', $css );
143 self
::buildPatterns();
145 // Tokenize single line rules with /* @noflip */
146 $noFlipSingle = new CSSJanus_Tokenizer( self
::$patterns['noflip_single'], '`NOFLIP_SINGLE`' );
147 $css = $noFlipSingle->tokenize( $css );
149 // Tokenize class rules with /* @noflip */
150 $noFlipClass = new CSSJanus_Tokenizer( self
::$patterns['noflip_class'], '`NOFLIP_CLASS`' );
151 $css = $noFlipClass->tokenize( $css );
154 $comments = new CSSJanus_Tokenizer( self
::$patterns['comment'], '`C`' );
155 $css = $comments->tokenize( $css );
157 // LTR->RTL fixes start here
158 $css = self
::fixDirection( $css );
159 if ( $swapLtrRtlInURL ) {
160 $css = self
::fixLtrRtlInURL( $css );
163 if ( $swapLeftRightInURL ) {
164 $css = self
::fixLeftRightInURL( $css );
166 $css = self
::fixLeftAndRight( $css );
167 $css = self
::fixCursorProperties( $css );
168 $css = self
::fixFourPartNotation( $css );
169 $css = self
::fixBackgroundPosition( $css );
170 $css = self
::fixShadows( $css );
172 // Detokenize stuff we tokenized before
173 $css = $comments->detokenize( $css );
174 $css = $noFlipClass->detokenize( $css );
175 $css = $noFlipSingle->detokenize( $css );
181 * Replace direction: ltr; with direction: rtl; and vice versa.
183 * The original implementation only does this inside body selectors
184 * and misses "body\n{\ndirection:ltr;\n}". This function does not have
187 * See http://code.google.com/p/cssjanus/issues/detail?id=15 and
192 private static function fixDirection( $css ) {
193 $css = preg_replace( self
::$patterns['direction_ltr'],
194 '$1' . self
::$patterns['tmpToken'], $css );
195 $css = preg_replace( self
::$patterns['direction_rtl'], '$1ltr', $css );
196 $css = str_replace( self
::$patterns['tmpToken'], 'rtl', $css );
202 * Replace 'ltr' with 'rtl' and vice versa in background URLs
206 private static function fixLtrRtlInURL( $css ) {
207 $css = preg_replace( self
::$patterns['ltr_in_url'], self
::$patterns['tmpToken'], $css );
208 $css = preg_replace( self
::$patterns['rtl_in_url'], 'ltr', $css );
209 $css = str_replace( self
::$patterns['tmpToken'], 'rtl', $css );
215 * Replace 'left' with 'right' and vice versa in background URLs
219 private static function fixLeftRightInURL( $css ) {
220 $css = preg_replace( self
::$patterns['left_in_url'], self
::$patterns['tmpToken'], $css );
221 $css = preg_replace( self
::$patterns['right_in_url'], 'left', $css );
222 $css = str_replace( self
::$patterns['tmpToken'], 'right', $css );
228 * Flip rules like left: , padding-right: , etc.
232 private static function fixLeftAndRight( $css ) {
233 $css = preg_replace( self
::$patterns['left'], self
::$patterns['tmpToken'], $css );
234 $css = preg_replace( self
::$patterns['right'], 'left', $css );
235 $css = str_replace( self
::$patterns['tmpToken'], 'right', $css );
241 * Flip East and West in rules like cursor: nw-resize;
245 private static function fixCursorProperties( $css ) {
246 $css = preg_replace( self
::$patterns['cursor_east'],
247 '$1' . self
::$patterns['tmpToken'], $css );
248 $css = preg_replace( self
::$patterns['cursor_west'], '$1e-resize', $css );
249 $css = str_replace( self
::$patterns['tmpToken'], 'w-resize', $css );
255 * Swap the second and fourth parts in four-part notation rules like
256 * padding: 1px 2px 3px 4px;
258 * Unlike the original implementation, this function doesn't suffer from
259 * the bug where whitespace is not preserved when flipping four-part rules
260 * and four-part color rules with multiple whitespace characters between
261 * colors are not recognized.
262 * See http://code.google.com/p/cssjanus/issues/detail?id=16
266 private static function fixFourPartNotation( $css ) {
267 $css = preg_replace( self
::$patterns['four_notation_quantity'], '$1$2$3$8$5$6$7$4$9', $css );
268 $css = preg_replace( self
::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4$9', $css );
274 * Negates horizontal offset in box-shadow and text-shadow rules.
279 private static function fixShadows( $css ) {
280 // Flips the sign of a CSS value, possibly with a unit.
281 // (We can't just negate the value with unary minus due to the units.)
282 $flipSign = function ( $cssValue ) {
283 // Don't mangle zeroes
284 if ( intval( $cssValue ) === 0 ) {
286 } elseif ( $cssValue[0] === '-' ) {
287 return substr( $cssValue, 1 );
289 return "-" . $cssValue;
293 $css = preg_replace_callback( self
::$patterns['box_shadow'], function ( $matches ) use ( $flipSign ) {
294 return $matches[1] . $flipSign( $matches[2] );
297 $css = preg_replace_callback( self
::$patterns['text_shadow1'], function ( $matches ) use ( $flipSign ) {
298 return $matches[1] . $matches[2] . $matches[3] . $flipSign( $matches[4] );
301 $css = preg_replace_callback( self
::$patterns['text_shadow2'], function ( $matches ) use ( $flipSign ) {
302 return $matches[1] . $flipSign( $matches[2] );
309 * Flip horizontal background percentages.
313 private static function fixBackgroundPosition( $css ) {
314 $replaced = preg_replace_callback( self
::$patterns['bg_horizontal_percentage'],
315 array( 'self', 'calculateNewBackgroundPosition' ), $css );
316 if ( $replaced !== null ) {
317 // Check for null; sometimes preg_replace_callback() returns null here for some weird reason
320 $replaced = preg_replace_callback( self
::$patterns['bg_horizontal_percentage_x'],
321 array( 'self', 'calculateNewBackgroundPosition' ), $css );
322 if ( $replaced !== null ) {
330 * Callback for calculateNewBackgroundPosition()
331 * @param $matches array
334 private static function calculateNewBackgroundPosition( $matches ) {
335 return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
340 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
341 * to protect from being janused.
342 * @author Roan Kattouw
344 class CSSJanus_Tokenizer
{
345 private $regex, $token;
350 * @param $regex string Regular expression whose matches to replace by a token.
351 * @param $token string Token
353 public function __construct( $regex, $token ) {
354 $this->regex
= $regex;
355 $this->token
= $token;
356 $this->originals
= array();
360 * Replace all occurrences of $regex in $str with a token and remember
361 * the original strings.
362 * @param $str String to tokenize
363 * @return string Tokenized string
365 public function tokenize( $str ) {
366 return preg_replace_callback( $this->regex
, array( $this, 'tokenizeCallback' ), $str );
370 * @param $matches array
373 private function tokenizeCallback( $matches ) {
374 $this->originals
[] = $matches[0];
379 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
380 * detokenized in exactly the SAME ORDER.
381 * @param $str String: previously run through tokenize()
382 * @return string Original string
384 public function detokenize( $str ) {
385 // PHP has no function to replace only the first occurrence or to
386 // replace occurrences of the same string with different values,
387 // so we use preg_replace_callback() even though we don't really need a regex
388 return preg_replace_callback( '/' . preg_quote( $this->token
, '/' ) . '/',
389 array( $this, 'detokenizeCallback' ), $str );
396 private function detokenizeCallback( $matches ) {
397 $retval = current( $this->originals
);
398 next( $this->originals
);