3 * PHP port of CSSJanus.
4 * https://github.com/cssjanus/php-cssjanus
6 * Copyright 2008 Google Inc.
7 * Copyright 2010 Roan Kattouw
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
25 * This is a PHP port of CSSJanus, a utility that transforms CSS style sheets
26 * written for LTR to RTL.
28 * Original code: http://code.google.com/p/cssjanus/source/browse/trunk/cssjanus.py
30 * @author Lindsey Simon <elsigh@google.com>
31 * @author Roan Kattouw
34 // Patterns defined as null are built dynamically by buildPatterns()
35 private static $patterns = array(
36 'tmpToken' => '`TMP`',
37 'nonAscii' => '[\200-\377]',
38 'unicode' => '(?:(?:\\[0-9a-f]{1,6})(?:\r\n|\s)?)',
39 'num' => '(?:[0-9]*\.[0-9]+|[0-9]+)',
40 'unit' => '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)',
41 'body_selector' => 'body\s*{\s*',
42 'direction' => 'direction\s*:\s*',
48 'possibly_negative_quantity' => null,
50 'url_special_chars' => '[!#$%&*-~]',
51 'valid_after_uri_chars' => '[\'\"]?\s*',
53 'lookahead_not_open_brace' => null,
54 'lookahead_not_closing_paren' => null,
55 'lookahead_for_closing_paren' => null,
56 'lookahead_not_letter' => '(?![a-zA-Z])',
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,
67 'left_in_url' => null,
68 'right_in_url' => null,
71 'cursor_east' => null,
72 'cursor_west' => null,
73 'four_notation_quantity' => null,
74 'four_notation_color' => null,
75 'border_radius' => null,
77 'text_shadow1' => null,
78 'text_shadow2' => null,
79 'bg_horizontal_percentage' => null,
80 'bg_horizontal_percentage_x' => null,
81 'suffix' => '(\s*(?:!important\s*)?[;}])'
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
93 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
94 $patterns =& self::$patterns;
95 $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
96 $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
97 $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
98 $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
99 $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
100 $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
101 $patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
102 $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
103 $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>|\(|\)|\[|\]|=|\*=|~=|\^=|'[^']*'])*?{)";
104 $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
105 $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
106 $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
107 $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
108 $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
109 $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
110 $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
111 $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
112 $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
113 $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
114 $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
115 $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
116 $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
117 $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
118 $patterns['four_notation_quantity_props'] = "((?:margin|padding|border-width)\s*:\s*)";
119 $patterns['four_notation_quantity'] = "/{$patterns['four_notation_quantity_props']}{$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}{$patterns['suffix']}/i";
120 $patterns['four_notation_color'] = "/((?:-color|border-style)\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}{$patterns['suffix']}/i";
121 // border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ]
122 $patterns['border_radius'] = '/(border-radius\s*:\s*)' . $patterns['possibly_negative_quantity']
123 . '(?:(?:\s+' . $patterns['possibly_negative_quantity'] . ')(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?)?'
124 . '(?:(?:(?:\s*\/\s*)' . $patterns['possibly_negative_quantity'] . ')(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?)?' . $patterns['suffix']
126 $patterns['box_shadow'] = "/(box-shadow\s*:\s*(?:inset\s*)?){$patterns['possibly_negative_quantity']}/i";
127 $patterns['text_shadow1'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}(\s*){$patterns['color']}/i";
128 $patterns['text_shadow2'] = "/(text-shadow\s*:\s*){$patterns['color']}(\s*){$patterns['possibly_negative_quantity']}/i";
129 $patterns['text_shadow3'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}/i";
130 $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*(?:[^:;}\s]+\s+)*?)({$patterns['quantity']})/i";
131 $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']}%)/i";
132 $patterns['translate_x'] = "/(transform\s*:[^;]*)(translateX\s*\(\s*){$patterns['possibly_negative_quantity']}(\s*\))/i";
133 $patterns['translate'] = "/(transform\s*:[^;]*)(translate\s*\(\s*){$patterns['possibly_negative_quantity']}((?:\s*,\s*{$patterns['possibly_negative_quantity']}){0,2}\s*\))/i";
134 // @codingStandardsIgnoreEnd
139 * Transform an LTR stylesheet to RTL
140 * @param string $css Stylesheet to transform
141 * @param array|bool $options Options array or value of transformDirInUrl option (back-compat)
142 * @param bool $options['transformDirInUrl'] Transform directions in URLs (ltr/rtl). Default: false.
143 * @param bool $options['transformEdgeInUrl'] Transform edges in URLs (left/right). Default: false.
144 * @param bool $transformEdgeInUrl [optional] For back-compat
145 * @return string Transformed stylesheet
147 public static function transform($css, $options = array(), $transformEdgeInUrl = false) {
148 if (!is_array($options)) {
150 'transformDirInUrl' => (bool)$options,
151 'transformEdgeInUrl' => (bool)$transformEdgeInUrl,
157 'transformDirInUrl' => false,
158 'transformEdgeInUrl' => false,
161 // We wrap tokens in ` , not ~ like the original implementation does.
162 // This was done because ` is not a legal character in CSS and can only
163 // occur in URLs, where we escape it to %60 before inserting our tokens.
164 $css = str_replace('`', '%60', $css);
166 self::buildPatterns();
168 // Tokenize single line rules with /* @noflip */
169 $noFlipSingle = new CSSJanusTokenizer(self::$patterns['noflip_single'], '`NOFLIP_SINGLE`');
170 $css = $noFlipSingle->tokenize($css);
172 // Tokenize class rules with /* @noflip */
173 $noFlipClass = new CSSJanusTokenizer(self::$patterns['noflip_class'], '`NOFLIP_CLASS`');
174 $css = $noFlipClass->tokenize($css);
177 $comments = new CSSJanusTokenizer(self::$patterns['comment'], '`C`');
178 $css = $comments->tokenize($css);
180 // LTR->RTL fixes start here
181 $css = self::fixDirection($css);
182 if ($options['transformDirInUrl']) {
183 $css = self::fixLtrRtlInURL($css);
186 if ($options['transformEdgeInUrl']) {
187 $css = self::fixLeftRightInURL($css);
189 $css = self::fixLeftAndRight($css);
190 $css = self::fixCursorProperties($css);
191 $css = self::fixFourPartNotation($css);
192 $css = self::fixBorderRadius($css);
193 $css = self::fixBackgroundPosition($css);
194 $css = self::fixShadows($css);
195 $css = self::fixTranslate($css);
197 // Detokenize stuff we tokenized before
198 $css = $comments->detokenize($css);
199 $css = $noFlipClass->detokenize($css);
200 $css = $noFlipSingle->detokenize($css);
206 * Replace direction: ltr; with direction: rtl; and vice versa.
208 * The original implementation only does this inside body selectors
209 * and misses "body\n{\ndirection:ltr;\n}". This function does not have
212 * See https://code.google.com/p/cssjanus/issues/detail?id=15
217 private static function fixDirection($css) {
219 self::$patterns['direction_ltr'],
220 '$1' . self::$patterns['tmpToken'],
223 $css = preg_replace(self::$patterns['direction_rtl'], '$1ltr', $css);
224 $css = str_replace(self::$patterns['tmpToken'], 'rtl', $css);
230 * Replace 'ltr' with 'rtl' and vice versa in background URLs
234 private static function fixLtrRtlInURL($css) {
235 $css = preg_replace(self::$patterns['ltr_in_url'], self::$patterns['tmpToken'], $css);
236 $css = preg_replace(self::$patterns['rtl_in_url'], 'ltr', $css);
237 $css = str_replace(self::$patterns['tmpToken'], 'rtl', $css);
243 * Replace 'left' with 'right' and vice versa in background URLs
247 private static function fixLeftRightInURL($css) {
248 $css = preg_replace(self::$patterns['left_in_url'], self::$patterns['tmpToken'], $css);
249 $css = preg_replace(self::$patterns['right_in_url'], 'left', $css);
250 $css = str_replace(self::$patterns['tmpToken'], 'right', $css);
256 * Flip rules like left: , padding-right: , etc.
260 private static function fixLeftAndRight($css) {
261 $css = preg_replace(self::$patterns['left'], self::$patterns['tmpToken'], $css);
262 $css = preg_replace(self::$patterns['right'], 'left', $css);
263 $css = str_replace(self::$patterns['tmpToken'], 'right', $css);
269 * Flip East and West in rules like cursor: nw-resize;
273 private static function fixCursorProperties($css) {
275 self::$patterns['cursor_east'],
276 '$1' . self::$patterns['tmpToken'],
279 $css = preg_replace(self::$patterns['cursor_west'], '$1e-resize', $css);
280 $css = str_replace(self::$patterns['tmpToken'], 'w-resize', $css);
286 * Swap the second and fourth parts in four-part notation rules like
287 * padding: 1px 2px 3px 4px;
289 * Unlike the original implementation, this function doesn't suffer from
290 * the bug where whitespace is not preserved when flipping four-part rules
291 * and four-part color rules with multiple whitespace characters between
292 * colors are not recognized.
293 * See https://code.google.com/p/cssjanus/issues/detail?id=16
297 private static function fixFourPartNotation($css) {
298 $css = preg_replace(self::$patterns['four_notation_quantity'], '$1$2$3$8$5$6$7$4$9', $css);
299 $css = preg_replace(self::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4$9', $css);
304 * Swaps appropriate corners in border-radius values.
309 private static function fixBorderRadius($css) {
310 return preg_replace_callback(
311 self::$patterns['border_radius'],
312 array('self', 'calculateBorderRadius'),
318 * Callback for fixBorderRadius()
319 * @param $matches array
322 private static function calculateBorderRadius($matches) {
324 $firstGroup = array_filter(array_slice($matches, 2, 4), function ($match) {
325 return $match !== '';
327 $secondGroup = array_filter(array_slice($matches, 6, 4), function ($match) {
328 return $match !== '';
330 $post = $matches[10] ?: '';
333 $values = self::flipBorderRadiusValues($firstGroup)
334 . ' / ' . self::flipBorderRadiusValues($secondGroup);
336 $values = self::flipBorderRadiusValues($firstGroup);
339 return $pre . $values . $post;
343 * Callback for fixBorderRadius()
344 * @param array $values Matched values
345 * @return string Flipped values
347 private static function flipBorderRadiusValues($values) {
348 switch (count($values)) {
350 $values = array($values[1], $values[0], $values[3], $values[2]);
353 $values = array($values[1], $values[0], $values[1], $values[2]);
356 $values = array($values[1], $values[0]);
359 $values = array($values[0]);
362 return implode(' ', $values);
366 * Flips the sign of a CSS value, possibly with a unit.
368 * We can't just negate the value with unary minus due to the units.
370 * @param $cssValue string
373 private static function flipSign($cssValue) {
374 // Don't mangle zeroes
375 if (floatval($cssValue) === 0.0) {
377 } elseif ($cssValue[0] === '-') {
378 return substr($cssValue, 1);
380 return "-" . $cssValue;
385 * Negates horizontal offset in box-shadow and text-shadow rules.
390 private static function fixShadows($css) {
391 $css = preg_replace_callback(self::$patterns['box_shadow'], function ($matches) {
392 return $matches[1] . self::flipSign($matches[2]);
395 $css = preg_replace_callback(self::$patterns['text_shadow1'], function ($matches) {
396 return $matches[1] . $matches[2] . $matches[3] . self::flipSign($matches[4]);
399 $css = preg_replace_callback(self::$patterns['text_shadow2'], function ($matches) {
400 return $matches[1] . $matches[2] . $matches[3] . self::flipSign($matches[4]);
403 $css = preg_replace_callback(self::$patterns['text_shadow3'], function ($matches) {
404 return $matches[1] . self::flipSign($matches[2]);
411 * Negates horizontal offset in tranform: translate()
416 private static function fixTranslate($css) {
417 $css = preg_replace_callback(self::$patterns['translate'], function ($matches) {
418 return $matches[1] . $matches[2] . self::flipSign($matches[3]) . $matches[4];
421 $css = preg_replace_callback(self::$patterns['translate_x'], function ($matches) {
422 return $matches[1] . $matches[2] . self::flipSign($matches[3]) . $matches[4];
429 * Flip horizontal background percentages.
433 private static function fixBackgroundPosition($css) {
434 $replaced = preg_replace_callback(
435 self::$patterns['bg_horizontal_percentage'],
436 array('self', 'calculateNewBackgroundPosition'),
439 if ($replaced !== null) {
440 // preg_replace_callback() sometimes returns null
443 $replaced = preg_replace_callback(
444 self::$patterns['bg_horizontal_percentage_x'],
445 array('self', 'calculateNewBackgroundPosition'),
448 if ($replaced !== null) {
456 * Callback for fixBackgroundPosition()
457 * @param $matches array
460 private static function calculateNewBackgroundPosition($matches) {
461 $value = $matches[2];
462 if (substr($value, -1) === '%') {
463 $idx = strpos($value, '.');
464 if ($idx !== false) {
465 $len = strlen($value) - $idx - 2;
466 $value = number_format(100 - (float)$value, $len) . '%';
468 $value = (100 - (float)$value) . '%';
471 return $matches[1] . $value;
476 * Utility class used by CSSJanus that tokenizes and untokenizes things we want
477 * to protect from being janused.
478 * @author Roan Kattouw
480 class CSSJanusTokenizer {
487 * @param string $regex Regular expression whose matches to replace by a token.
488 * @param string $token Token
490 public function __construct($regex, $token) {
491 $this->regex = $regex;
492 $this->token = $token;
493 $this->originals = array();
497 * Replace all occurrences of $regex in $str with a token and remember
498 * the original strings.
499 * @param string $str to tokenize
500 * @return string Tokenized string
502 public function tokenize($str) {
503 return preg_replace_callback($this->regex, array($this, 'tokenizeCallback'), $str);
507 * @param $matches array
510 private function tokenizeCallback($matches) {
511 $this->originals[] = $matches[0];
516 * Replace tokens with their originals. If multiple strings were tokenized, it's important they be
517 * detokenized in exactly the SAME ORDER.
518 * @param string $str previously run through tokenize()
519 * @return string Original string
521 public function detokenize($str) {
522 // PHP has no function to replace only the first occurrence or to
523 // replace occurrences of the same string with different values,
524 // so we use preg_replace_callback() even though we don't really need a regex
525 return preg_replace_callback(
526 '/' . preg_quote($this->token, '/') . '/',
527 array($this, 'detokenizeCallback'),
536 private function detokenizeCallback($matches) {
537 $retval = current($this->originals);
538 next($this->originals);