]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - vendor/cssjanus/cssjanus/src/CSSJanus.php
MediaWiki 1.30.2
[autoinstallsdev/mediawiki.git] / vendor / cssjanus / cssjanus / src / CSSJanus.php
1 <?php
2 /**
3  * PHP port of CSSJanus.
4  * https://github.com/cssjanus/php-cssjanus
5  *
6  * Copyright 2008 Google Inc.
7  * Copyright 2010 Roan Kattouw
8  *
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
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  * @file
22  */
23
24 /**
25  * This is a PHP port of CSSJanus, a utility that transforms CSS style sheets
26  * written for LTR to RTL.
27  *
28  * Original code: http://code.google.com/p/cssjanus/source/browse/trunk/cssjanus.py
29  *
30  * @author Lindsey Simon <elsigh@google.com>
31  * @author Roan Kattouw
32  */
33 class CSSJanus {
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*',
43                 'escape' => null,
44                 'nmstart' => null,
45                 'nmchar' => null,
46                 'ident' => null,
47                 'quantity' => null,
48                 'possibly_negative_quantity' => null,
49                 'color' => null,
50                 'url_special_chars' => '[!#$%&*-~]',
51                 'valid_after_uri_chars' => '[\'\"]?\s*',
52                 'url_chars' => null,
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,
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                 'border_radius' => null,
76                 'box_shadow' => 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*)?[;}])'
82         );
83
84         /**
85          * Build patterns we can't define above because they depend on other patterns.
86          */
87         private static function buildPatterns() {
88                 if (!is_null(self::$patterns['escape'])) {
89                         // Patterns have already been built
90                         return;
91                 }
92
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']
125                         . '/i';
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
135
136         }
137
138         /**
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
146          */
147         public static function transform($css, $options = array(), $transformEdgeInUrl = false) {
148                 if (!is_array($options)) {
149                         $options = array(
150                                 'transformDirInUrl' => (bool)$options,
151                                 'transformEdgeInUrl' => (bool)$transformEdgeInUrl,
152                         );
153                 }
154
155                 // Defaults
156                 $options += array(
157                         'transformDirInUrl' => false,
158                         'transformEdgeInUrl' => false,
159                 );
160
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);
165
166                 self::buildPatterns();
167
168                 // Tokenize single line rules with /* @noflip */
169                 $noFlipSingle = new CSSJanusTokenizer(self::$patterns['noflip_single'], '`NOFLIP_SINGLE`');
170                 $css = $noFlipSingle->tokenize($css);
171
172                 // Tokenize class rules with /* @noflip */
173                 $noFlipClass = new CSSJanusTokenizer(self::$patterns['noflip_class'], '`NOFLIP_CLASS`');
174                 $css = $noFlipClass->tokenize($css);
175
176                 // Tokenize comments
177                 $comments = new CSSJanusTokenizer(self::$patterns['comment'], '`C`');
178                 $css = $comments->tokenize($css);
179
180                 // LTR->RTL fixes start here
181                 $css = self::fixDirection($css);
182                 if ($options['transformDirInUrl']) {
183                         $css = self::fixLtrRtlInURL($css);
184                 }
185
186                 if ($options['transformEdgeInUrl']) {
187                         $css = self::fixLeftRightInURL($css);
188                 }
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);
196
197                 // Detokenize stuff we tokenized before
198                 $css = $comments->detokenize($css);
199                 $css = $noFlipClass->detokenize($css);
200                 $css = $noFlipSingle->detokenize($css);
201
202                 return $css;
203         }
204
205         /**
206          * Replace direction: ltr; with direction: rtl; and vice versa.
207          *
208          * The original implementation only does this inside body selectors
209          * and misses "body\n{\ndirection:ltr;\n}". This function does not have
210          * these problems.
211          *
212          * See https://code.google.com/p/cssjanus/issues/detail?id=15
213          *
214          * @param $css string
215          * @return string
216          */
217         private static function fixDirection($css) {
218                 $css = preg_replace(
219                         self::$patterns['direction_ltr'],
220                         '$1' . self::$patterns['tmpToken'],
221                         $css
222                 );
223                 $css = preg_replace(self::$patterns['direction_rtl'], '$1ltr', $css);
224                 $css = str_replace(self::$patterns['tmpToken'], 'rtl', $css);
225
226                 return $css;
227         }
228
229         /**
230          * Replace 'ltr' with 'rtl' and vice versa in background URLs
231          * @param $css string
232          * @return string
233          */
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);
238
239                 return $css;
240         }
241
242         /**
243          * Replace 'left' with 'right' and vice versa in background URLs
244          * @param $css string
245          * @return string
246          */
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);
251
252                 return $css;
253         }
254
255         /**
256          * Flip rules like left: , padding-right: , etc.
257          * @param $css string
258          * @return string
259          */
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);
264
265                 return $css;
266         }
267
268         /**
269          * Flip East and West in rules like cursor: nw-resize;
270          * @param $css string
271          * @return string
272          */
273         private static function fixCursorProperties($css) {
274                 $css = preg_replace(
275                         self::$patterns['cursor_east'],
276                         '$1' . self::$patterns['tmpToken'],
277                         $css
278                 );
279                 $css = preg_replace(self::$patterns['cursor_west'], '$1e-resize', $css);
280                 $css = str_replace(self::$patterns['tmpToken'], 'w-resize', $css);
281
282                 return $css;
283         }
284
285         /**
286          * Swap the second and fourth parts in four-part notation rules like
287          * padding: 1px 2px 3px 4px;
288          *
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
294          * @param $css string
295          * @return string
296          */
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);
300                 return $css;
301         }
302
303         /**
304          * Swaps appropriate corners in border-radius values.
305          *
306          * @param $css string
307          * @return string
308          */
309         private static function fixBorderRadius($css) {
310                 return preg_replace_callback(
311                         self::$patterns['border_radius'],
312                         array('self', 'calculateBorderRadius'),
313                         $css
314                 );
315         }
316
317         /**
318          * Callback for fixBorderRadius()
319          * @param $matches array
320          * @return string
321          */
322         private static function calculateBorderRadius($matches) {
323                 $pre = $matches[1];
324                 $firstGroup = array_filter(array_slice($matches, 2, 4), function ($match) {
325                         return $match !== '';
326                 });
327                 $secondGroup = array_filter(array_slice($matches, 6, 4), function ($match) {
328                         return $match !== '';
329                 });
330                 $post = $matches[10] ?: '';
331
332                 if ($secondGroup) {
333                         $values = self::flipBorderRadiusValues($firstGroup)
334                                 . ' / ' . self::flipBorderRadiusValues($secondGroup);
335                 } else {
336                         $values = self::flipBorderRadiusValues($firstGroup);
337                 }
338
339                 return $pre . $values . $post;
340         }
341
342         /**
343          * Callback for fixBorderRadius()
344          * @param array $values Matched values
345          * @return string Flipped values
346          */
347         private static function flipBorderRadiusValues($values) {
348                 switch (count($values)) {
349                         case 4:
350                                 $values = array($values[1], $values[0], $values[3], $values[2]);
351                                 break;
352                         case 3:
353                                 $values = array($values[1], $values[0], $values[1], $values[2]);
354                                 break;
355                         case 2:
356                                 $values = array($values[1], $values[0]);
357                                 break;
358                         case 1:
359                                 $values = array($values[0]);
360                                 break;
361                 }
362                 return implode(' ', $values);
363         }
364
365         /**
366          * Flips the sign of a CSS value, possibly with a unit.
367          *
368          * We can't just negate the value with unary minus due to the units.
369          *
370          * @param $cssValue string
371          * @return string
372          */
373         private static function flipSign($cssValue) {
374                 // Don't mangle zeroes
375                 if (floatval($cssValue) === 0.0) {
376                         return $cssValue;
377                 } elseif ($cssValue[0] === '-') {
378                         return substr($cssValue, 1);
379                 } else {
380                         return "-" . $cssValue;
381                 }
382         }
383
384         /**
385          * Negates horizontal offset in box-shadow and text-shadow rules.
386          *
387          * @param $css string
388          * @return string
389          */
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]);
393                 }, $css);
394
395                 $css = preg_replace_callback(self::$patterns['text_shadow1'], function ($matches) {
396                         return $matches[1] . $matches[2] . $matches[3] . self::flipSign($matches[4]);
397                 }, $css);
398
399                 $css = preg_replace_callback(self::$patterns['text_shadow2'], function ($matches) {
400                         return $matches[1] . $matches[2] . $matches[3] . self::flipSign($matches[4]);
401                 }, $css);
402
403                 $css = preg_replace_callback(self::$patterns['text_shadow3'], function ($matches) {
404                         return $matches[1] . self::flipSign($matches[2]);
405                 }, $css);
406
407                 return $css;
408         }
409
410         /**
411          * Negates horizontal offset in tranform: translate()
412          *
413          * @param $css string
414          * @return string
415          */
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];
419                 }, $css);
420
421                 $css = preg_replace_callback(self::$patterns['translate_x'], function ($matches) {
422                         return $matches[1] . $matches[2] . self::flipSign($matches[3]) . $matches[4];
423                 }, $css);
424
425                 return $css;
426         }
427
428         /**
429          * Flip horizontal background percentages.
430          * @param $css string
431          * @return string
432          */
433         private static function fixBackgroundPosition($css) {
434                 $replaced = preg_replace_callback(
435                         self::$patterns['bg_horizontal_percentage'],
436                         array('self', 'calculateNewBackgroundPosition'),
437                         $css
438                 );
439                 if ($replaced !== null) {
440                         // preg_replace_callback() sometimes returns null
441                         $css = $replaced;
442                 }
443                 $replaced = preg_replace_callback(
444                         self::$patterns['bg_horizontal_percentage_x'],
445                         array('self', 'calculateNewBackgroundPosition'),
446                         $css
447                 );
448                 if ($replaced !== null) {
449                         $css = $replaced;
450                 }
451
452                 return $css;
453         }
454
455         /**
456          * Callback for fixBackgroundPosition()
457          * @param $matches array
458          * @return string
459          */
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) . '%';
467                         } else {
468                                 $value = (100 - (float)$value) . '%';
469                         }
470                 }
471                 return $matches[1] . $value;
472         }
473 }
474
475 /**
476  * Utility class used by CSSJanus that tokenizes and untokenizes things we want
477  * to protect from being janused.
478  * @author Roan Kattouw
479  */
480 class CSSJanusTokenizer {
481         private $regex;
482         private $token;
483         private $originals;
484
485         /**
486          * Constructor
487          * @param string $regex Regular expression whose matches to replace by a token.
488          * @param string $token Token
489          */
490         public function __construct($regex, $token) {
491                 $this->regex = $regex;
492                 $this->token = $token;
493                 $this->originals = array();
494         }
495
496         /**
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
501          */
502         public function tokenize($str) {
503                 return preg_replace_callback($this->regex, array($this, 'tokenizeCallback'), $str);
504         }
505
506         /**
507          * @param $matches array
508          * @return string
509          */
510         private function tokenizeCallback($matches) {
511                 $this->originals[] = $matches[0];
512                 return $this->token;
513         }
514
515         /**
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
520          */
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'),
528                         $str
529                 );
530         }
531
532         /**
533          * @param $matches
534          * @return mixed
535          */
536         private function detokenizeCallback($matches) {
537                 $retval = current($this->originals);
538                 next($this->originals);
539
540                 return $retval;
541         }
542 }