3 * PHP port of CSSJanus.
5 * Copyright 2008 Google Inc.
6 * Copyright 2010 Roan Kattouw
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
24 * This is a PHP port of CSSJanus, a utility that transforms CSS style sheets
25 * written for LTR to RTL.
27 * Original code: http://code.google.com/p/cssjanus/source/browse/trunk/cssjanus.py
29 * @author Lindsey Simon <elsigh@google.com>
30 * @author Roan Kattouw
33 // Patterns defined as null are built dynamically by buildPatterns()
34 private static $patterns = array(
35 'tmpToken' => '`TMP`',
36 'nonAscii' => '[\200-\377]',
37 'unicode' => '(?:(?:\\[0-9a-f]{1,6})(?:\r\n|\s)?)',
38 'num' => '(?:[0-9]*\.[0-9]+|[0-9]+)',
39 'unit' => '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)',
40 'body_selector' => 'body\s*{\s*',
41 'direction' => 'direction\s*:\s*',
47 'possibly_negative_quantity' => null,
49 'url_special_chars' => '[!#$%&*-~]',
50 'valid_after_uri_chars' => '[\'\"]?\s*',
52 'lookahead_not_open_brace' => null,
53 'lookahead_not_closing_paren' => null,
54 'lookahead_for_closing_paren' => null,
55 'lookahead_not_letter' => '(?![a-zA-Z])',
56 'lookbehind_not_letter' => '(?<![a-zA-Z])',
57 'chars_within_selector' => '[^\}]*?',
58 'noflip_annotation' => '\/\*\s*@noflip\s*\*\/',
59 'noflip_single' => null,
60 'noflip_class' => null,
61 'comment' => '/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//',
62 'direction_ltr' => null,
63 'direction_rtl' => null,
66 'left_in_url' => null,
67 'right_in_url' => null,
70 'cursor_east' => null,
71 'cursor_west' => null,
72 'four_notation_quantity' => null,
73 'four_notation_color' => null,
74 'border_radius' => null,
76 'text_shadow1' => null,
77 'text_shadow2' => null,
78 'bg_horizontal_percentage' => null,
79 'bg_horizontal_percentage_x' => null,
83 * Build patterns we can't define above because they depend on other patterns.
85 private static function buildPatterns() {
86 if ( !is_null( self
::$patterns['escape'] ) ) {
87 // Patterns have already been built
91 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
92 $patterns =& self
::$patterns;
93 $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
94 $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
95 $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
96 $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
97 $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
98 $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
99 $patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
100 $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
101 $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>|\(|\)|\[|\]|=|\*=|~=|\^=|'[^']*'])*?{)";
102 $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
103 $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
104 $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
105 $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
106 $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
107 $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
108 $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
109 $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
110 $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
111 $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
112 $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
113 $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
114 $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
115 $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
116 $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";
117 $patterns['four_notation_color'] = "/(-color\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s*[;}])/i";
118 $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";
119 $patterns['box_shadow'] = "/(box-shadow\s*:\s*(?:inset\s*)?){$patterns['possibly_negative_quantity']}/i";
120 $patterns['text_shadow1'] = "/(text-shadow\s*:\s*){$patterns['color']}(\s*){$patterns['possibly_negative_quantity']}/i";
121 $patterns['text_shadow2'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}/i";
122 // The two regexes below are parenthesized differently then in the original implementation to make the
123 // callback's job more straightforward
124 $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*[^%]*?)(-?{$patterns['num']})(%\s*(?:{$patterns['quantity']}|{$patterns['ident']}))/";
125 $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']})(%)/";
126 // @codingStandardsIgnoreEnd
130 * Transform an LTR stylesheet to RTL
131 * @param string $css stylesheet to transform
132 * @param $swapLtrRtlInURL Boolean: If true, swap 'ltr' and 'rtl' in URLs
133 * @param $swapLeftRightInURL Boolean: If true, swap 'left' and 'right' in URLs
134 * @return string Transformed stylesheet
136 public static function transform( $css, $swapLtrRtlInURL = false, $swapLeftRightInURL = false ) {
137 // We wrap tokens in ` , not ~ like the original implementation does.
138 // This was done because ` is not a legal character in CSS and can only
139 // occur in URLs, where we escape it to %60 before inserting our tokens.
140 $css = str_replace( '`', '%60', $css );
142 self
::buildPatterns();
144 // Tokenize single line rules with /* @noflip */
145 $noFlipSingle = new CSSJanusTokenizer( self
::$patterns['noflip_single'], '`NOFLIP_SINGLE`' );
146 $css = $noFlipSingle->tokenize( $css );
148 // Tokenize class rules with /* @noflip */
149 $noFlipClass = new CSSJanusTokenizer( self
::$patterns['noflip_class'], '`NOFLIP_CLASS`' );
150 $css = $noFlipClass->tokenize( $css );
153 $comments = new CSSJanusTokenizer( self
::$patterns['comment'], '`C`' );
154 $css = $comments->tokenize( $css );
156 // LTR->RTL fixes start here
157 $css = self
::fixDirection( $css );
158 if ( $swapLtrRtlInURL ) {
159 $css = self
::fixLtrRtlInURL( $css );
162 if ( $swapLeftRightInURL ) {
163 $css = self
::fixLeftRightInURL( $css );
165 $css = self
::fixLeftAndRight( $css );
166 $css = self
::fixCursorProperties( $css );
167 $css = self
::fixFourPartNotation( $css );
168 $css = self
::fixBorderRadius( $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 );
273 * Swaps appropriate corners in four-part border-radius rules.
274 * Needs to undo the effect of fixFourPartNotation() on those rules, too.
279 private static function fixBorderRadius( $css ) {
280 // Undo four_notation_quantity
281 $css = preg_replace( self
::$patterns['border_radius'], '$1$2$3$8$5$6$7$4$9', $css );
283 $css = preg_replace( self
::$patterns['border_radius'], '$1$4$3$2$5$8$7$6$9', $css );
289 * Negates horizontal offset in box-shadow and text-shadow rules.
294 private static function fixShadows( $css ) {
295 // Flips the sign of a CSS value, possibly with a unit.
296 // (We can't just negate the value with unary minus due to the units.)
297 $flipSign = function ( $cssValue ) {
298 // Don't mangle zeroes
299 if ( floatval( $cssValue ) === 0.0 ) {
301 } elseif ( $cssValue[0] === '-' ) {
302 return substr( $cssValue, 1 );
304 return "-" . $cssValue;
308 $css = preg_replace_callback(
309 self
::$patterns['box_shadow'], function ( $matches ) use ( $flipSign ) {
310 return $matches[1] . $flipSign( $matches[2] );
315 $css = preg_replace_callback(
316 self
::$patterns['text_shadow1'],
317 function ( $matches ) use ( $flipSign ) {
318 return $matches[1] . $matches[2] . $matches[3] . $flipSign( $matches[4] );
323 $css = preg_replace_callback(
324 self
::$patterns['text_shadow2'],
325 function ( $matches ) use ( $flipSign ) {
326 return $matches[1] . $flipSign( $matches[2] );
335 * Flip horizontal background percentages.
339 private static function fixBackgroundPosition( $css ) {
340 $replaced = preg_replace_callback( self
::$patterns['bg_horizontal_percentage'],
341 array( 'self', 'calculateNewBackgroundPosition' ), $css );
342 if ( $replaced !== null ) {
343 // Check for null; sometimes preg_replace_callback() returns null here for some weird reason
346 $replaced = preg_replace_callback( self
::$patterns['bg_horizontal_percentage_x'],
347 array( 'self', 'calculateNewBackgroundPosition' ), $css );
348 if ( $replaced !== null ) {
356 * Callback for calculateNewBackgroundPosition()
357 * @param $matches array
360 private static function calculateNewBackgroundPosition( $matches ) {
361 return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
366 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
367 * to protect from being janused.
368 * @author Roan Kattouw
370 class CSSJanusTokenizer
{
371 private $regex, $token;
376 * @param string $regex Regular expression whose matches to replace by a token.
377 * @param string $token Token
379 public function __construct( $regex, $token ) {
380 $this->regex
= $regex;
381 $this->token
= $token;
382 $this->originals
= array();
386 * Replace all occurrences of $regex in $str with a token and remember
387 * the original strings.
388 * @param string $str to tokenize
389 * @return string Tokenized string
391 public function tokenize( $str ) {
392 return preg_replace_callback( $this->regex
, array( $this, 'tokenizeCallback' ), $str );
396 * @param $matches array
399 private function tokenizeCallback( $matches ) {
400 $this->originals
[] = $matches[0];
405 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
406 * detokenized in exactly the SAME ORDER.
407 * @param string $str previously run through tokenize()
408 * @return string Original string
410 public function detokenize( $str ) {
411 // PHP has no function to replace only the first occurrence or to
412 // replace occurrences of the same string with different values,
413 // so we use preg_replace_callback() even though we don't really need a regex
414 return preg_replace_callback( '/' . preg_quote( $this->token
, '/' ) . '/',
415 array( $this, 'detokenizeCallback' ), $str );
422 private function detokenizeCallback( $matches ) {
423 $retval = current( $this->originals
);
424 next( $this->originals
);