MediaWiki  REL1_22
CSSJanus.php
Go to the documentation of this file.
00001 <?php
00037 class CSSJanus {
00038     // Patterns defined as null are built dynamically by buildPatterns()
00039     private static $patterns = array(
00040         'tmpToken' => '`TMP`',
00041         'nonAscii' => '[\200-\377]',
00042         'unicode' => '(?:(?:\\[0-9a-f]{1,6})(?:\r\n|\s)?)',
00043         'num' => '(?:[0-9]*\.[0-9]+|[0-9]+)',
00044         'unit' => '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)',
00045         'body_selector' => 'body\s*{\s*',
00046         'direction' => 'direction\s*:\s*',
00047         'escape' => null,
00048         'nmstart' => null,
00049         'nmchar' => null,
00050         'ident' => null,
00051         'quantity' => null,
00052         'possibly_negative_quantity' => null,
00053         'color' => null,
00054         'url_special_chars' => '[!#$%&*-~]',
00055         'valid_after_uri_chars' => '[\'\"]?\s*',
00056         'url_chars' => null,
00057         'lookahead_not_open_brace' => null,
00058         'lookahead_not_closing_paren' => null,
00059         'lookahead_for_closing_paren' => null,
00060         'lookahead_not_letter' => '(?![a-zA-Z])',
00061         'lookbehind_not_letter' => '(?<![a-zA-Z])',
00062         'chars_within_selector' => '[^\}]*?',
00063         'noflip_annotation' => '\/\*\s*@noflip\s*\*\/',
00064         'noflip_single' => null,
00065         'noflip_class' => null,
00066         'comment' => '/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//',
00067         'direction_ltr' => null,
00068         'direction_rtl' => null,
00069         'left' => null,
00070         'right' => null,
00071         'left_in_url' => null,
00072         'right_in_url' => null,
00073         'ltr_in_url' => null,
00074         'rtl_in_url' => null,
00075         'cursor_east' => null,
00076         'cursor_west' => null,
00077         'four_notation_quantity' => null,
00078         'four_notation_color' => null,
00079         'border_radius' => null,
00080         'box_shadow' => null,
00081         'text_shadow1' => null,
00082         'text_shadow2' => null,
00083         'bg_horizontal_percentage' => null,
00084         'bg_horizontal_percentage_x' => null,
00085     );
00086 
00090     private static function buildPatterns() {
00091         if ( !is_null( self::$patterns['escape'] ) ) {
00092             // Patterns have already been built
00093             return;
00094         }
00095 
00096         $patterns =& self::$patterns;
00097         $patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
00098         $patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
00099         $patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
00100         $patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
00101         $patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
00102         $patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
00103         $patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
00104         $patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
00105         $patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>|\(|\))*?{)";
00106         $patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
00107         $patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
00108         $patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
00109         $patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
00110         $patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
00111         $patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
00112         $patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
00113         $patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
00114         $patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
00115         $patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
00116         $patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
00117         $patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
00118         $patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
00119         $patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
00120         $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";
00121         $patterns['four_notation_color'] = "/(-color\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s*[;}])/i";
00122         $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";
00123         $patterns['box_shadow'] = "/(box-shadow\s*:\s*(?:inset\s*)?){$patterns['possibly_negative_quantity']}/i";
00124         $patterns['text_shadow1'] = "/(text-shadow\s*:\s*){$patterns['color']}(\s*){$patterns['possibly_negative_quantity']}/i";
00125         $patterns['text_shadow2'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}/i";
00126         // The two regexes below are parenthesized differently then in the original implementation to make the
00127         // callback's job more straightforward
00128         $patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*[^%]*?)(-?{$patterns['num']})(%\s*(?:{$patterns['quantity']}|{$patterns['ident']}))/";
00129         $patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']})(%)/";
00130     }
00131 
00139     public static function transform( $css, $swapLtrRtlInURL = false, $swapLeftRightInURL = false ) {
00140         // We wrap tokens in ` , not ~ like the original implementation does.
00141         // This was done because ` is not a legal character in CSS and can only
00142         // occur in URLs, where we escape it to %60 before inserting our tokens.
00143         $css = str_replace( '`', '%60', $css );
00144 
00145         self::buildPatterns();
00146 
00147         // Tokenize single line rules with /* @noflip */
00148         $noFlipSingle = new CSSJanus_Tokenizer( self::$patterns['noflip_single'], '`NOFLIP_SINGLE`' );
00149         $css = $noFlipSingle->tokenize( $css );
00150 
00151         // Tokenize class rules with /* @noflip */
00152         $noFlipClass = new CSSJanus_Tokenizer( self::$patterns['noflip_class'], '`NOFLIP_CLASS`' );
00153         $css = $noFlipClass->tokenize( $css );
00154 
00155         // Tokenize comments
00156         $comments = new CSSJanus_Tokenizer( self::$patterns['comment'], '`C`' );
00157         $css = $comments->tokenize( $css );
00158 
00159         // LTR->RTL fixes start here
00160         $css = self::fixDirection( $css );
00161         if ( $swapLtrRtlInURL ) {
00162             $css = self::fixLtrRtlInURL( $css );
00163         }
00164 
00165         if ( $swapLeftRightInURL ) {
00166             $css = self::fixLeftRightInURL( $css );
00167         }
00168         $css = self::fixLeftAndRight( $css );
00169         $css = self::fixCursorProperties( $css );
00170         $css = self::fixFourPartNotation( $css );
00171         $css = self::fixBorderRadius( $css );
00172         $css = self::fixBackgroundPosition( $css );
00173         $css = self::fixShadows( $css );
00174 
00175         // Detokenize stuff we tokenized before
00176         $css = $comments->detokenize( $css );
00177         $css = $noFlipClass->detokenize( $css );
00178         $css = $noFlipSingle->detokenize( $css );
00179 
00180         return $css;
00181     }
00182 
00195     private static function fixDirection( $css ) {
00196         $css = preg_replace( self::$patterns['direction_ltr'],
00197             '$1' . self::$patterns['tmpToken'], $css );
00198         $css = preg_replace( self::$patterns['direction_rtl'], '$1ltr', $css );
00199         $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
00200 
00201         return $css;
00202     }
00203 
00209     private static function fixLtrRtlInURL( $css ) {
00210         $css = preg_replace( self::$patterns['ltr_in_url'], self::$patterns['tmpToken'], $css );
00211         $css = preg_replace( self::$patterns['rtl_in_url'], 'ltr', $css );
00212         $css = str_replace( self::$patterns['tmpToken'], 'rtl', $css );
00213 
00214         return $css;
00215     }
00216 
00222     private static function fixLeftRightInURL( $css ) {
00223         $css = preg_replace( self::$patterns['left_in_url'], self::$patterns['tmpToken'], $css );
00224         $css = preg_replace( self::$patterns['right_in_url'], 'left', $css );
00225         $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
00226 
00227         return $css;
00228     }
00229 
00235     private static function fixLeftAndRight( $css ) {
00236         $css = preg_replace( self::$patterns['left'], self::$patterns['tmpToken'], $css );
00237         $css = preg_replace( self::$patterns['right'], 'left', $css );
00238         $css = str_replace( self::$patterns['tmpToken'], 'right', $css );
00239 
00240         return $css;
00241     }
00242 
00248     private static function fixCursorProperties( $css ) {
00249         $css = preg_replace( self::$patterns['cursor_east'],
00250             '$1' . self::$patterns['tmpToken'], $css );
00251         $css = preg_replace( self::$patterns['cursor_west'], '$1e-resize', $css );
00252         $css = str_replace( self::$patterns['tmpToken'], 'w-resize', $css );
00253 
00254         return $css;
00255     }
00256 
00269     private static function fixFourPartNotation( $css ) {
00270         $css = preg_replace( self::$patterns['four_notation_quantity'], '$1$2$3$8$5$6$7$4$9', $css );
00271         $css = preg_replace( self::$patterns['four_notation_color'], '$1$2$3$8$5$6$7$4$9', $css );
00272         return $css;
00273     }
00274 
00282     private static function fixBorderRadius( $css ) {
00283         // Undo four_notation_quantity
00284         $css = preg_replace( self::$patterns['border_radius'], '$1$2$3$8$5$6$7$4$9', $css );
00285         // Do the real thing
00286         $css = preg_replace( self::$patterns['border_radius'], '$1$4$3$2$5$8$7$6$9', $css );
00287 
00288         return $css;
00289     }
00290 
00297     private static function fixShadows( $css ) {
00298         // Flips the sign of a CSS value, possibly with a unit.
00299         // (We can't just negate the value with unary minus due to the units.)
00300         $flipSign = function ( $cssValue ) {
00301             // Don't mangle zeroes
00302             if ( intval( $cssValue ) === 0 ) {
00303                 return $cssValue;
00304             } elseif ( $cssValue[0] === '-' ) {
00305                 return substr( $cssValue, 1 );
00306             } else {
00307                 return "-" . $cssValue;
00308             }
00309         };
00310 
00311         $css = preg_replace_callback( self::$patterns['box_shadow'], function ( $matches ) use ( $flipSign ) {
00312             return $matches[1] . $flipSign( $matches[2] );
00313         }, $css );
00314 
00315         $css = preg_replace_callback( self::$patterns['text_shadow1'], function ( $matches ) use ( $flipSign ) {
00316             return $matches[1] . $matches[2] . $matches[3] . $flipSign( $matches[4] );
00317         }, $css );
00318 
00319         $css = preg_replace_callback( self::$patterns['text_shadow2'], function ( $matches ) use ( $flipSign ) {
00320             return $matches[1] . $flipSign( $matches[2] );
00321         }, $css );
00322 
00323         return $css;
00324     }
00325 
00331     private static function fixBackgroundPosition( $css ) {
00332         $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage'],
00333             array( 'self', 'calculateNewBackgroundPosition' ), $css );
00334         if ( $replaced !== null ) {
00335             // Check for null; sometimes preg_replace_callback() returns null here for some weird reason
00336             $css = $replaced;
00337         }
00338         $replaced = preg_replace_callback( self::$patterns['bg_horizontal_percentage_x'],
00339             array( 'self', 'calculateNewBackgroundPosition' ), $css );
00340         if ( $replaced !== null ) {
00341             $css = $replaced;
00342         }
00343 
00344         return $css;
00345     }
00346 
00352     private static function calculateNewBackgroundPosition( $matches ) {
00353         return $matches[1] . ( 100 - $matches[2] ) . $matches[3];
00354     }
00355 }
00356 
00362 class CSSJanus_Tokenizer {
00363     private $regex, $token;
00364     private $originals;
00365 
00371     public function __construct( $regex, $token ) {
00372         $this->regex = $regex;
00373         $this->token = $token;
00374         $this->originals = array();
00375     }
00376 
00383     public function tokenize( $str ) {
00384         return preg_replace_callback( $this->regex, array( $this, 'tokenizeCallback' ), $str );
00385     }
00386 
00391     private function tokenizeCallback( $matches ) {
00392         $this->originals[] = $matches[0];
00393         return $this->token;
00394     }
00395 
00402     public function detokenize( $str ) {
00403         // PHP has no function to replace only the first occurrence or to
00404         // replace occurrences of the same string with different values,
00405         // so we use preg_replace_callback() even though we don't really need a regex
00406         return preg_replace_callback( '/' . preg_quote( $this->token, '/' ) . '/',
00407             array( $this, 'detokenizeCallback' ), $str );
00408     }
00409 
00414     private function detokenizeCallback( $matches ) {
00415         $retval = current( $this->originals );
00416         next( $this->originals );
00417 
00418         return $retval;
00419     }
00420 }