Author: Stephen Clay (steve@mrclay.org)
function test_Minify_CSS_UriRewriter()
{
    global $thisDir;
    Minify_CSS_UriRewriter::$debugText = '';
    $in = file_get_contents($thisDir . '/_test_files/css_uriRewriter/in.css');
    $expected = file_get_contents($thisDir . '/_test_files/css_uriRewriter/exp.css');
    $actual = Minify_CSS_UriRewriter::rewrite($in, $thisDir . '/_test_files/css_uriRewriter', $thisDir);
    $passed = assertTrue($expected === $actual, 'Minify_CSS_UriRewriter');
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        echo "\n---Input:\n\n{$in}\n";
        echo "\n---Output: " . strlen($actual) . " bytes\n\n{$actual}\n\n";
        if (!$passed) {
            echo "---Expected: " . strlen($expected) . " bytes\n\n{$expected}\n\n\n";
        }
        // show debugging only when test run directly
        echo "--- Minify_CSS_UriRewriter::\$debugText\n\n", Minify_CSS_UriRewriter::$debugText;
    }
    Minify_CSS_UriRewriter::$debugText = '';
    $in = '../../../../assets/skins/sam/sprite.png';
    $exp = '/yui/assets/skins/sam/sprite.png';
    $actual = Minify_CSS_UriRewriter::rewriteRelative($in, 'sf_root_dir\\web\\yui\\menu\\assets\\skins\\sam', 'sf_root_dir\\web');
    $passed = assertTrue($exp === $actual, 'Minify_CSS_UriRewriter : Issue 99');
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        echo "\n---Input:\n\n{$in}\n";
        echo "\n---Output: " . strlen($actual) . " bytes\n\n{$actual}\n\n";
        if (!$passed) {
            echo "---Expected: " . strlen($exp) . " bytes\n\n{$exp}\n\n\n";
        }
        // show debugging only when test run directly
        echo "--- Minify_CSS_UriRewriter::\$debugText\n\n", Minify_CSS_UriRewriter::$debugText;
    }
}
Example #2
0
 /**
  * Minify a CSS string
  * 
  * @param string $css
  * 
  * @param array $options available options:
  * 
  * 'preserveComments': (default true) multi-line comments that begin
  * with "/*!" will be preserved with newlines before and after to
  * enhance readability.
  * 
  * 'prependRelativePath': (default null) if given, this string will be
  * prepended to all relative URIs in import/url declarations
  * 
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files. For this to work, the files *must* exist and be
  * visible by the PHP process.
  *
  * 'symlinks': (default = array()) If the CSS file is stored in 
  * a symlink-ed directory, provide an array of link paths to
  * target paths, where the link paths are within the document root. Because 
  * paths need to be normalized for this to work, use "//" to substitute 
  * the doc root in the link paths (the array keys). E.g.:
  * <code>
  * array('//symlink' => '/real/target/path') // unix
  * array('//static' => 'D:\\staticStorage')  // Windows
  * </code>
  * 
  * @return string
  */
 static public function minify($css, $options = array()) 
 {
     require_once 'Minify/CSS/Compressor.php';
     if (isset($options['preserveComments']) 
         && !$options['preserveComments']) {
         $css = Minify_CSS_Compressor::process($css, $options);
     } else {
         require_once 'Minify/CommentPreserver.php';
         $css = Minify_CommentPreserver::process(
             $css
             ,array('Minify_CSS_Compressor', 'process')
             ,array($options)
         );
     }
     if (! isset($options['currentDir']) && ! isset($options['prependRelativePath'])) {
         return $css;
     }
     require_once 'Minify/CSS/UriRewriter.php';
     if (isset($options['currentDir'])) {
         return Minify_CSS_UriRewriter::rewrite(
             $css
             ,$options['currentDir']
             ,isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT']
             ,isset($options['symlinks']) ? $options['symlinks'] : array()
         );  
     } else {
         return Minify_CSS_UriRewriter::prepend(
             $css
             ,$options['prependRelativePath']
         );
     }
 }
Example #3
0
 /**
  * Add line numbers in C-style comments
  *
  * This uses a very basic parser easily fooled by comment tokens inside
  * strings or regexes, but, otherwise, generally clean code will not be
  * mangled. URI rewriting can also be performed.
  *
  * @param string $content
  *
  * @param array $options available options:
  *
  * 'id': (optional) string to identify file. E.g. file name/path
  *
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files, and prepend a comment with debugging information about
  * this process.
  *
  * @return string
  */
 public static function minify($content, $options = array())
 {
     $id = isset($options['id']) && $options['id'] ? $options['id'] : '';
     $content = str_replace("\r\n", "\n", $content);
     $lines = explode("\n", $content);
     $numLines = count($lines);
     // determine left padding
     $padTo = strlen($numLines);
     $inComment = false;
     $i = 0;
     $newLines = array();
     while (null !== ($line = array_shift($lines))) {
         if ('' !== $id && 0 == $i % 50) {
             array_push($newLines, '', "/* {$id} */", '');
         }
         ++$i;
         $newLines[] = self::_addNote($line, $i, $inComment, $padTo);
         $inComment = self::_eolInComment($line, $inComment);
     }
     $content = implode("\n", $newLines) . "\n";
     // check for desired URI rewriting
     require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
     $content = Minify_CSS_UriRewriter::rewrite($content, $options);
     return $content;
 }
 public static function minifyCss($css, $options = array())
 {
     w3_require_once(W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php');
     $css = self::_minify('css', $css, $options);
     $css = Minify_CSS_UriRewriter::rewrite($css, $options);
     return $css;
 }
Example #5
0
 /**
  * Minify a CSS string
  * 
  * @param string $css
  * 
  * @param array $options available options:
  * 
  * 'preserveComments': (default true) multi-line comments that begin
  * with "/*!" will be preserved with newlines before and after to
  * enhance readability.
  *
  * 'removeCharsets': (default true) remove all @charset at-rules
  * 
  * 'prependRelativePath': (default null) if given, this string will be
  * prepended to all relative URIs in import/url declarations
  * 
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files. For this to work, the files *must* exist and be
  * visible by the PHP process.
  *
  * 'symlinks': (default = array()) If the CSS file is stored in 
  * a symlink-ed directory, provide an array of link paths to
  * target paths, where the link paths are within the document root. Because 
  * paths need to be normalized for this to work, use "//" to substitute 
  * the doc root in the link paths (the array keys). E.g.:
  * <code>
  * array('//symlink' => '/real/target/path') // unix
  * array('//static' => 'D:\\staticStorage')  // Windows
  * </code>
  *
  * 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
  * see Minify_CSS_UriRewriter::rewrite
  * 
  * @return string
  */
 public static function minify($css, $options = array())
 {
     $options = array_merge(array('compress' => true, 'removeCharsets' => true, 'preserveComments' => true, 'currentDir' => null, 'docRoot' => $_SERVER['DOCUMENT_ROOT'], 'prependRelativePath' => null, 'symlinks' => array()), $options);
     if ($options['removeCharsets']) {
         $css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
     }
     if ($options['compress']) {
         if (!$options['preserveComments']) {
             require_once 'Compressor.php';
             $css = Minify_CSS_Compressor::process($css, $options);
         } else {
             require_once 'CommentPreserver.php';
             require_once 'Compressor.php';
             $css = Minify_CommentPreserver::process($css, array('Minify_CSS_Compressor', 'process'), array($options));
         }
     }
     if (!$options['currentDir'] && !$options['prependRelativePath']) {
         return $css;
     }
     require_once 'UriRewriter.php';
     if ($options['currentDir']) {
         return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot'], $options['symlinks']);
     } else {
         return Minify_CSS_UriRewriter::prepend($css, $options['prependRelativePath']);
     }
 }
Example #6
0
 /**
  * Add line numbers in C-style comments
  *
  * This uses a very basic parser easily fooled by comment tokens inside
  * strings or regexes, but, otherwise, generally clean code will not be 
  * mangled. URI rewriting can also be performed.
  *
  * @param string $content
  * 
  * @param array $options available options:
  * 
  * 'id': (optional) string to identify file. E.g. file name/path
  *
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files, and prepend a comment with debugging information about
  * this process.
  * 
  * @return string 
  */
 public static function minify($content, $options = array())
 {
     $id = isset($options['id']) && $options['id'] ? $options['id'] : '';
     $content = str_replace("\r\n", "\n", $content);
     $lines = explode("\n", $content);
     $numLines = count($lines);
     // determine left padding
     $padTo = strlen($numLines);
     $inComment = false;
     $i = 0;
     $newLines = array();
     while (null !== ($line = array_shift($lines))) {
         if ('' !== $id && 0 == $i % 50) {
             array_push($newLines, '', "/* {$id} */", '');
         }
         ++$i;
         $newLines[] = self::_addNote($line, $i, $inComment, $padTo);
         $inComment = self::_eolInComment($line, $inComment);
     }
     $content = implode("\n", $newLines) . "\n";
     // check for desired URI rewriting
     if (isset($options['currentDir'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         Minify_CSS_UriRewriter::$debugText = '';
         $content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'], isset($options['symlinks']) ? $options['symlinks'] : array(), isset($options['browserCacheId']) ? $options['browserCacheId'] : 0, isset($options['browserCacheExtensions']) ? $options['browserCacheExtensions'] : array());
         $content = "/* Minify_CSS_UriRewriter::\$debugText\n\n" . Minify_CSS_UriRewriter::$debugText . "*/\n" . $content;
     } elseif (isset($options['prependRelativePath'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         Minify_CSS_UriRewriter::$debugText = '';
         $content = Minify_CSS_UriRewriter::prepend($content, $options['prependRelativePath'], isset($options['browserCacheId']) ? $options['browserCacheId'] : 0, isset($options['browserCacheExtensions']) ? $options['browserCacheExtensions'] : array());
     }
     return $content;
 }
Example #7
0
 /**
  * Add line numbers in C-style comments
  *
  * This uses a very basic parser easily fooled by comment tokens inside
  * strings or regexes, but, otherwise, generally clean code will not be 
  * mangled. URI rewriting can also be performed.
  *
  * @param string $content
  * 
  * @param array $options available options:
  * 
  * 'id': (optional) string to identify file. E.g. file name/path
  *
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files, and prepend a comment with debugging information about
  * this process.
  * 
  * @return string 
  */
 public static function minify($content, $options = array())
 {
     $id = isset($options['id']) && $options['id'] ? $options['id'] : '';
     $content = str_replace("\r\n", "\n", $content);
     // Hackily rewrite strings with XPath expressions that are
     // likely to throw off our dumb parser (for Prototype 1.6.1).
     $content = str_replace('"/*"', '"/"+"*"', $content);
     $content = preg_replace('@([\'"])(\\.?//?)\\*@', '$1$2$1+$1*', $content);
     $lines = explode("\n", $content);
     $numLines = count($lines);
     // determine left padding
     $padTo = strlen((string) $numLines);
     // e.g. 103 lines = 3 digits
     $inComment = false;
     $i = 0;
     $newLines = array();
     while (null !== ($line = array_shift($lines))) {
         if ('' !== $id && 0 == $i % 50) {
             array_push($newLines, '', "/* {$id} */", '');
         }
         ++$i;
         $newLines[] = self::_addNote($line, $i, $inComment, $padTo);
         $inComment = self::_eolInComment($line, $inComment);
     }
     $content = implode("\n", $newLines) . "\n";
     // check for desired URI rewriting
     if (isset($options['currentDir'])) {
         //require _once MINIFY_MIN_DIR.'/Minify/CSS/UriRewriter.php';
         Minify_CSS_UriRewriter::$debugText = '';
         $content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'], isset($options['symlinks']) ? $options['symlinks'] : array());
         $content = "/* Minify_CSS_UriRewriter::\$debugText\n\n" . Minify_CSS_UriRewriter::$debugText . "*/\n" . $content;
     }
     return $content;
 }
Example #8
0
 /**
  * Add line numbers in C-style comments
  *
  * This uses a very basic parser easily fooled by comment tokens inside
  * strings or regexes, but, otherwise, generally clean code will not be
  * mangled. URI rewriting can also be performed.
  *
  * @param string $content
  *
  * @param array $options available options:
  *
  * 'id': (optional) string to identify file. E.g. file name/path
  *
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files, and prepend a comment with debugging information about
  * this process.
  *
  * @return string
  */
 public static function minify($content, $options = array())
 {
     $id = isset($options['id']) && $options['id'] ? $options['id'] : '';
     $content = str_replace("\r\n", "\n", $content);
     $lines = explode("\n", $content);
     $numLines = count($lines);
     // determine left padding
     $padTo = strlen((string) $numLines);
     // e.g. 103 lines = 3 digits
     $inComment = false;
     $i = 0;
     $newLines = array();
     while (null !== ($line = array_shift($lines))) {
         if ('' !== $id && 0 == $i % 50) {
             if ($inComment) {
                 array_push($newLines, '', "/* {$id} *|", '');
             } else {
                 array_push($newLines, '', "/* {$id} */", '');
             }
         }
         ++$i;
         $newLines[] = self::_addNote($line, $i, $inComment, $padTo);
         $inComment = self::_eolInComment($line, $inComment);
     }
     $content = implode("\n", $newLines) . "\n";
     // check for desired URI rewriting
     if (isset($options['currentDir'])) {
         Minify_CSS_UriRewriter::$debugText = '';
         $docRoot = isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'];
         $symlinks = isset($options['symlinks']) ? $options['symlinks'] : array();
         $content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], $docRoot, $symlinks);
         $content = "/* Minify_CSS_UriRewriter::\$debugText\n\n" . Minify_CSS_UriRewriter::$debugText . "*/\n" . $content;
     }
     return $content;
 }
Example #9
0
 public static function minify($css, $options = array())
 {
     $options = array_merge(array('remove_bslash' => true, 'compress_colors' => true, 'compress_font-weight' => true, 'lowercase_s' => false, 'optimise_shorthands' => 1, 'remove_last_;' => false, 'case_properties' => 1, 'sort_properties' => false, 'sort_selectors' => false, 'merge_selectors' => 2, 'discard_invalid_properties' => false, 'css_level' => 'CSS2.1', 'preserve_css' => false, 'timestamp' => false, 'template' => 'default'), $options);
     set_include_path(get_include_path() . PATH_SEPARATOR . W3TC_LIB_CSSTIDY_DIR);
     require_once 'class.csstidy.php';
     $csstidy = new csstidy();
     foreach ($options as $option => $value) {
         $csstidy->set_cfg($option, $value);
     }
     $csstidy->load_template($options['template']);
     $csstidy->parse($css);
     $css = $csstidy->print->plain();
     if (isset($options['currentDir']) || isset($options['prependRelativePath'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         $browsercache_id = isset($options['browserCacheId']) ? $options['browserCacheId'] : 0;
         $browsercache_extensions = isset($options['browserCacheExtensions']) ? $options['browserCacheExtensions'] : array();
         if (isset($options['currentDir'])) {
             $document_root = isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'];
             $symlinks = isset($options['symlinks']) ? $options['symlinks'] : array();
             return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $document_root, $symlinks, $browsercache_id, $browsercache_extensions);
         } else {
             return Minify_CSS_UriRewriter::prepend($css, $options['prependRelativePath'], $browsercache_id, $browsercache_extensions);
         }
     }
     return $css;
 }
Example #10
0
 /**
  * Prepend a path to relative URIs in CSS files
  * 
  * @param string $css
  * 
  * @param string $path The path to prepend.
  * 
  * @return string
  */
 public static function prepend($css, $path)
 {
     self::$_prependPath = $path;
     $css = self::_trimUrls($css);
     // append
     $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/', array(self::$className, '_processUriCB'), $css);
     $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array(self::$className, '_processUriCB'), $css);
     self::$_prependPath = null;
     return $css;
 }
 /**
  * Minifies content
  * @param string $content
  * @param array $options
  * @return string
  */
 public static function minify($content, $options = array())
 {
     if (isset($options['currentDir'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         $content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'], isset($options['symlinks']) ? $options['symlinks'] : array());
     } elseif (isset($options['prependRelativePath'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         $content = Minify_CSS_UriRewriter::prepend($content, $options['prependRelativePath']);
     }
     return $content;
 }
Example #12
0
 public function filterDump(AssetInterface $asset)
 {
     $sourceBase = $asset->getSourceRoot();
     $sourcePath = $asset->getSourcePath();
     $targetPath = $asset->getTargetPath();
     if (null === $sourcePath || null === $targetPath || $sourcePath == $targetPath) {
         return;
     }
     $content = \Minify_CSS_UriRewriter::rewrite($asset->getContent(), $sourceBase);
     $asset->setContent($content);
 }
Example #13
0
 /**
  * Minify a CSS string
  *
  * @param string $css
  *
  * @param array $options available options:
  *
  * 'preserveComments': (default true) multi-line comments that begin
  * with "/*!" will be preserved with newlines before and after to
  * enhance readability.
  *
  * 'prependRelativePath': (default null) if given, this string will be
  * prepended to all relative URIs in import/url declarations
  *
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files. For this to work, the files *must* exist and be
  * visible by the PHP process.
  *
  * 'symlinks': (default = array()) If the CSS file is stored in
  * a symlink-ed directory, provide an array of link paths to
  * target paths, where the link paths are within the document root. Because
  * paths need to be normalized for this to work, use "//" to substitute
  * the doc root in the link paths (the array keys). E.g.:
  * <code>
  * array('//symlink' => '/real/target/path') // unix
  * array('//static' => 'D:\\staticStorage')  // Windows
  * </code>
  *
  * @return string
  */
 public static function minify($css, $options = array())
 {
     require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/Compressor.php';
     if (isset($options['preserveComments']) && $options['preserveComments']) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CommentPreserver.php';
         $css = Minify_CommentPreserver::process($css, array('Minify_CSS_Compressor', 'process'), array($options));
     } else {
         $css = Minify_CSS_Compressor::process($css, $options);
     }
     require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
     $css = Minify_CSS_UriRewriter::rewrite($css, $options);
     return $css;
 }
Example #14
0
 /**
  * Minifies content
  * @param string $content
  * @param array $options
  * @return string
  */
 public static function minify($content, $options = array())
 {
     $browsercache_id = isset($options['browserCacheId']) ? $options['browserCacheId'] : 0;
     $browsercache_extensions = isset($options['browserCacheExtensions']) ? $options['browserCacheExtensions'] : array();
     if (isset($options['currentDir'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         $document_root = isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'];
         $symlinks = isset($options['symlinks']) ? $options['symlinks'] : array();
         $content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], $document_root, $symlinks, $browsercache_id, $browsercache_extensions);
     } elseif (isset($options['prependRelativePath'])) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
         $content = Minify_CSS_UriRewriter::prepend($content, $options['prependRelativePath'], $browsercache_id, $browsercache_extensions);
     }
     return $content;
 }
function test_Minify_CSS_UriRewriter()
{
    global $thisDir;
    $in = file_get_contents($thisDir . '/_test_files/css_uriRewriter/in.css');
    $expected = file_get_contents($thisDir . '/_test_files/css_uriRewriter/exp.css');
    $actual = Minify_CSS_UriRewriter::rewrite($in, $thisDir . '/_test_files/css_uriRewriter', $thisDir);
    $passed = assertTrue($expected === $actual, 'Minify_CSS_UriRewriter');
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        echo "\n---Input:\n\n{$in}\n";
        echo "\n---Output: " . strlen($actual) . " bytes\n\n{$actual}\n\n";
        if (!$passed) {
            echo "---Expected: " . strlen($expected) . " bytes\n\n{$expected}\n\n\n";
        }
    }
}
Example #16
0
 public static function minify($css, $options = array())
 {
     $options = array_merge(array('remove_bslash' => true, 'compress_colors' => true, 'compress_font-weight' => true, 'lowercase_s' => false, 'optimise_shorthands' => 1, 'remove_last_;' => false, 'case_properties' => 1, 'sort_properties' => false, 'sort_selectors' => false, 'merge_selectors' => 2, 'discard_invalid_properties' => false, 'css_level' => 'CSS2.1', 'preserve_css' => false, 'timestamp' => false, 'template' => 'default'), $options);
     set_include_path(get_include_path() . PATH_SEPARATOR . W3TC_LIB_DIR . '/CSSTidy');
     require_once 'class.csstidy.php';
     $csstidy = new csstidy();
     foreach ($options as $option => $value) {
         $csstidy->set_cfg($option, $value);
     }
     $csstidy->load_template($options['template']);
     $csstidy->parse($css);
     $css = $csstidy->print->plain();
     $css = Minify_CSS_UriRewriter::rewrite($css, $options);
     return $css;
 }
Example #17
0
 /**
  * Rewrite file relative URIs as root relative in CSS files
  * 
  * @param string $css
  * 
  * @param string $currentDir The directory of the current CSS file.
  *
  * @param string $docRoot The document root of the web site in which 
  * the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
  * 
  * @return string
  */
 public static function rewrite($css, $currentDir, $docRoot = null)
 {
     self::$_docRoot = $docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT'];
     self::$_docRoot = realpath(self::$_docRoot);
     self::$_currentDir = realpath($currentDir);
     // remove ws around urls
     $css = preg_replace('/
             url\\(      # url(
             \\s*
             ([^\\)]+?)  # 1 = URI (really just a bunch of non right parenthesis)
             \\s*
             \\)         # )
         /x', 'url($1)', $css);
     // rewrite
     $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/', array('Minify_CSS_UriRewriter', '_uriCB'), $css);
     $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array('Minify_CSS_UriRewriter', '_uriCB'), $css);
     return $css;
 }
Example #18
0
 /**
  * Minify a CSS string
  * 
  * @param string $css
  * 
  * @param array $options available options:
  * 
  * 'removeCharsets': (default true) remove all @charset at-rules
  *
  * 'prependRelativePath': (default null) if given, this string will be
  * prepended to all relative URIs in import/url declarations
  * 
  * 'currentDir': (default null) if given, this is assumed to be the
  * directory of the current CSS file. Using this, minify will rewrite
  * all relative URIs in import/url declarations to correctly point to
  * the desired files. For this to work, the files *must* exist and be
  * visible by the PHP process.
  *
  * 'symlinks': (default = array()) If the CSS file is stored in 
  * a symlink-ed directory, provide an array of link paths to
  * target paths, where the link paths are within the document root. Because 
  * paths need to be normalized for this to work, use "//" to substitute 
  * the doc root in the link paths (the array keys). E.g.:
  * <code>
  * array('//symlink' => '/real/target/path') // unix
  * array('//static' => 'D:\\staticStorage')  // Windows
  * </code>
  *
  * 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
  * see Minify_CSS_UriRewriter::rewrite
  * 
  * @return string
  */
 public static function minify($css, $options = array())
 {
     $options = array_merge(array('compress' => true, 'removeCharsets' => true, 'currentDir' => null, 'docRoot' => $_SERVER['DOCUMENT_ROOT'], 'prependRelativePath' => null, 'symlinks' => array()), $options);
     if ($options['removeCharsets']) {
         $css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
     }
     if ($options['compress']) {
         $obj = new CSSmin();
         $css = $obj->run($css);
     }
     if (!$options['currentDir'] && !$options['prependRelativePath']) {
         return $css;
     }
     if ($options['currentDir']) {
         return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot'], $options['symlinks']);
     } else {
         return Minify_CSS_UriRewriter::prepend($css, $options['prependRelativePath']);
     }
 }
Example #19
0
 /**
  * Minifies content
  * @param string $content
  * @param array $options
  * @return string
  */
 public static function minify($content, $options = array())
 {
     require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS/UriRewriter.php';
     $content = Minify_CSS_UriRewriter::rewrite($content, $options);
     return $content;
 }
Example #20
0
function yuiCssPort($css, $options)
{
    $compressor = new CSSmin();
    $css = $compressor->run($css, 9999999);
    $css = Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'], isset($options['symlinks']) ? $options['symlinks'] : array());
    return $css;
}
Example #21
0
 /**
  * Given an asset, fetches and returns minified contents.
  *
  * @param Minimee_BaseAssetModel $asset
  * @return String
  */
 protected function minifyAsset($asset)
 {
     craft()->config->maxPowerCaptain();
     switch ($this->type) {
         case MinimeeType::Js:
             if ($this->settings->minifyJsEnabled) {
                 $contents = \JSMin::minify($asset->contents);
             } else {
                 $contents = $asset->contents;
             }
             // Play nice with others by ensuring a semicolon at eof
             if (substr($contents, -1) != ';') {
                 $contents .= ';';
             }
             break;
         case MinimeeType::Css:
             $cssPrependUrl = dirname($asset->filenameUrl) . '/';
             $contents = \Minify_CSS_UriRewriter::prepend($asset->contents, $cssPrependUrl);
             if ($this->settings->minifyCssEnabled) {
                 $contents = \Minify_CSS::minify($contents);
             }
             break;
     }
     return $contents;
 }
Example #22
0
File: sacy.php Project: fjg/sacy
 function getOutput($work_unit)
 {
     $debug = $this->getConfig()->getDebugMode() == 3;
     if ($work_unit['file']) {
         $css = @file_get_contents($work_unit['file']);
         if (!$css) {
             return "/* error accessing file */";
         }
         $source_file = $work_unit['file'];
     } else {
         $css = $work_unit['content'];
         $source_file = $this->getSourceFile();
     }
     if (ExternalProcessorRegistry::typeIsSupported($work_unit['type'])) {
         $opts = array();
         if ($work_unit['paths']) {
             $opts['library_path'] = $work_unit['paths'];
         }
         $css = ExternalProcessorRegistry::getTransformerForType($work_unit['type'])->transform($css, $source_file, $opts);
     } else {
         if ($work_unit['type'] == 'text/x-less') {
             $less = new \lessc();
             $less->importDir = dirname($source_file) . '/';
             #lessphp concatenates without a /
             $css = $less->parse($css);
         }
         if (PhpSassSacy::isAvailable() && $work_unit['type'] == 'text/x-scss') {
             $css = PhpSassSacy::compile($source_file, $work_unit['paths'] ?: array(dirname($source_file)));
         } elseif (in_array($work_unit['type'], array('text/x-scss', 'text/x-sass'))) {
             $config = array('cache' => false, 'debug_info' => $debug, 'line' => $debug, 'load_paths' => $work_unit['paths'] ?: array(dirname($source_file)), 'filename' => $source_file, 'quiet' => true, 'style' => $debug ? 'nested' : 'compressed');
             $sass = new \SassParser($config);
             $css = $sass->toCss($css, false);
             // isFile?
         }
     }
     if ($debug) {
         return \Minify_CSS_UriRewriter::rewrite($css, dirname($source_file), $this->getConfig()->getDocumentRoot(), array());
     } else {
         return \Minify_CSS::minify($css, array('currentDir' => dirname($source_file), 'docRoot' => $this->getConfig()->getDocumentRoot()));
     }
 }
 /**
  * Minify the given $content according to the file type indicated in $filename
  *
  * @param string $filename
  * @param string $content
  * @return string
  */
 protected function minifyFile($filename, $content)
 {
     // if we have a javascript file and jsmin is enabled, minify the content
     $isJS = stripos($filename, '.js');
     require_once 'thirdparty/jsmin/jsmin.php';
     require_once BASE_PATH . '/minify/code/thirdparty/Compressor.php';
     require_once BASE_PATH . '/minify/code/thirdparty/UriRewriter.php';
     increase_time_limit_to();
     if ($isJS) {
         $content = JSMin::minify($content) . ";\n";
     } else {
         $content = Minify_CSS_UriRewriter::rewrite($content, Director::baseFolder() . "/" . dirname($filename), Director::baseFolder());
         $content = Minify_CSS_Compressor::process($content) . "\n";
     }
     return $content;
 }
Example #24
0
 /** 
  * Internal function for (maybe) minifying assets
  * 
  * @param	Type of asset to minify (css/js)
  * @param	Contents to be minified
  * @param	The name of the file being minified (used for logging)
  * @param	mixed A relative path to use, if provided (for css minification)
  * @return	String (maybe) minified contents of file
  */
 protected function _minify($type, $contents, $filename, $rel = FALSE)
 {
     // used in case we need to return orig
     $contents_orig = $contents;
     switch ($type) {
         case 'js':
             /**
              * JS pre-minify hook
              */
             if ($this->EE->extensions->active_hook('minimee_pre_minify_js')) {
                 Minimee_helper::log('Hook `minimee_pre_minify_js` has been activated.', 3);
                 // pass contents to be minified, and instance of self
                 $contents = $this->EE->extensions->call('minimee_pre_minify_js', $contents, $filename, $this);
                 if ($this->EE->extensions->end_script === TRUE) {
                     return $contents;
                 }
                 // re-set $contents_orig in case we need to return
                 $contents_orig = $contents;
             }
             // HOOK END
             // be sure we want to minify
             if ($this->config->is_yes('minify_js')) {
                 // See if JSMinPlus was explicitly requested
                 if ($this->config->js_library == 'jsminplus') {
                     Minimee_helper::log('Running minification with JSMinPlus.', 3);
                     Minimee_helper::library('jsminplus');
                     $contents = JSMinPlus::minify($contents);
                 } else {
                     if ($this->config->js_library == 'jsmin') {
                         Minimee_helper::log('Running minification with JSMin.', 3);
                         Minimee_helper::library('jsmin');
                         $contents = JSMin::minify($contents);
                     }
                 }
             }
             break;
         case 'css':
             /**
              * CSS pre-minify hook
              */
             if ($this->EE->extensions->active_hook('minimee_pre_minify_css')) {
                 Minimee_helper::log('Hook `minimee_pre_minify_css` has been activated.', 3);
                 // pass contents to be minified, relative path, and instance of self
                 $contents = $this->EE->extensions->call('minimee_pre_minify_css', $contents, $filename, $rel, $this);
                 if ($this->EE->extensions->end_script === TRUE) {
                     return $contents;
                 }
                 // copy to $contents_orig in case we need to return
                 $contents_orig = $contents;
             }
             // HOOK END
             // prepend URL if relative path exists & configured to do so
             if ($rel !== FALSE && $this->config->is_yes('css_prepend_mode')) {
                 Minimee_helper::library('css_urirewriter');
                 $contents = Minify_CSS_UriRewriter::prepend($contents, $rel . '/');
                 // copy to $contents_orig in case we need to return
                 $contents_orig = $contents;
             }
             // minify if configured to do so
             if ($this->config->is_yes('minify_css')) {
                 // See if CSSMin was explicitly requested
                 if ($this->config->css_library == 'cssmin') {
                     Minimee_helper::log('Running minification with CSSMin.', 3);
                     Minimee_helper::library('cssmin');
                     $cssmin = new CSSmin(FALSE);
                     $contents = $cssmin->run($contents);
                     unset($cssmin);
                 } else {
                     if ($this->config->css_library == 'minify') {
                         Minimee_helper::log('Running minification with Minify_CSS.', 3);
                         Minimee_helper::library('minify');
                         $contents = Minify_CSS::minify($contents);
                     }
                 }
             }
             break;
     }
     // calculate weight loss
     $before = strlen($contents_orig);
     $after = strlen($contents);
     $diff = $before - $after;
     // quick check that contents are not empty
     if ($after == 0) {
         Minimee_helper::log('Minification has returned an empty string for `' . $filename . '`.', 2);
     }
     // did we actually reduce our file size? It's possible an already minified asset
     // uses a more aggressive algorithm than Minify; in that case, keep original contents
     if ($diff > 0) {
         $diff_formatted = $diff < 100 ? $diff . 'b' : round($diff / 1000, 2) . 'kb';
         $change = round($diff / $before * 100, 2);
         Minimee_helper::log('Minification has reduced ' . $filename . ' by ' . $diff_formatted . ' (' . $change . '%).', 3);
         // add to our running total
         $this->diff_total($diff);
     } else {
         Minimee_helper::log('Minification unable to reduce ' . $filename . ', so using original content.', 3);
         $contents = $contents_orig;
     }
     // cleanup (leave some smaller variables because they may or may not have ever been set)
     unset($contents_orig);
     // return our (maybe) minified contents
     return $contents;
 }
 protected function _Consolidate($Files, $Suffix, $Prefix = '')
 {
     $Token = $Prefix . md5(serialize($Files)) . $Suffix;
     $CacheFile = PATH_CACHE . "/Consolidate/{$Token}";
     if (in_array($Token, $this->ChunkedFiles)) {
         return $Token;
     }
     if (!file_exists($CacheFile)) {
         $ConsolidateFile = '';
         $PathRootParts = split(DS, PATH_ROOT);
         $WebRootParts = split(DS, $this->WebRoot);
         $Base = join(DS, array_slice($PathRootParts, 0, -count($WebRootParts)));
         foreach ($Files as $File) {
             $ConsolidateFile .= "/*\n";
             $ConsolidateFile .= "* Consolidate '{$File['fullhref']}'\n";
             $ConsolidateFile .= "*/\n\n";
             $OriginalFile = PATH_ROOT . DS . $File['href'];
             $FileStr = file_get_contents($OriginalFile);
             if ($FileStr && strtolower($Suffix) == '.css') {
                 $FileStr = Minify_CSS_UriRewriter::rewrite($FileStr, dirname($Base . DS . $this->WebRoot . DS . $File['href']), $Base);
                 $FileStr = Minify_CSS_Compressor::process($FileStr);
             }
             $ConsolidateFile .= trim($FileStr);
             if ($FileStr && strtolower($Suffix) == '.js') {
                 if (substr($ConsolidateFile, -1) != ';') {
                     $ConsolidateFile .= ";";
                 }
             }
             $ConsolidateFile .= "\n\n";
         }
         if (!file_exists(dirname($CacheFile))) {
             mkdir(dirname($CacheFile), 0777, TRUE);
         }
         file_put_contents($CacheFile, $ConsolidateFile);
     }
     if (!in_array($Token, $this->ChunkedFiles)) {
         $this->ChunkedFiles[] = $Token;
     }
     return $Token;
 }
Example #26
0
$cli->addRequiredArg('d')->assertDir()->setDescription('Your webserver\'s DOCUMENT_ROOT: Relative paths will be rewritten relative to this path.');
$cli->addOptionalArg('o')->useAsOutfile()->setDescription('Outfile: If given, output will be placed in this file.');
$cli->addOptionalArg('t')->setDescription('Test run: Return output followed by rewriting algorithm.');
if (!$cli->validate()) {
    echo "USAGE: ./rewrite-uris.php [-t] -d DOC_ROOT [-o OUTFILE] file ...\n";
    if ($cli->isHelpRequest) {
        echo $cli->getArgumentsListing();
    }
    echo "EXAMPLE: ./rewrite-uris.php -v -d../.. ../../min_unit_tests/_test_files/css/paths_rewrite.css ../../min_unit_tests/_test_files/css/comments.css\n    \n";
    exit(0);
}
$outfile = $cli->values['o'];
$testRun = $cli->values['t'];
$docRoot = $cli->values['d'];
$pathRewriter = function ($css, $options) {
    return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot']);
};
$paths = $cli->getPathArgs();
$sources = array();
foreach ($paths as $path) {
    if (is_file($path)) {
        $sources[] = new Minify_Source(array('filepath' => $path, 'minifier' => $pathRewriter, 'minifyOptions' => array('docRoot' => $docRoot)));
    } else {
        $sources[] = new Minify_Source(array('id' => $path, 'content' => "/*** {$path} not found ***/\n", 'minifier' => ''));
    }
}
$combined = Minify::combine($sources) . "\n";
if ($testRun) {
    echo $combined;
    echo Minify_CSS_UriRewriter::$debugText . "\n";
} else {
 /**
  * Prepend a path to relative URIs in CSS files
  *
  * @param string $css
  * @param string $path The path to prepend.
  * @param integer $browserCacheId
  * @param array $browserCacheExtensions
  *
  * @return string
  */
 private static function _prepend($css, $path, $browserCacheId = 0, $browserCacheExtensions = array())
 {
     self::$_prependRelativePath = $path;
     self::$_browserCacheId = $browserCacheId;
     self::$_browserCacheExtensions = $browserCacheExtensions;
     $css = self::_trimUrls($css);
     // append
     $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/', array(self::$className, '_processUriCB'), $css);
     $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array(self::$className, '_processUriCB'), $css);
     return $css;
 }
Example #28
0
function CssEncoder($css, $options = array())
{
    require_once 'Minify/CSS/UriRewriter.php';
    if (isset($options['currentDir'])) {
        return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'], isset($options['symlinks']) ? $options['symlinks'] : array());
    } else {
        return Minify_CSS_UriRewriter::prepend($css, $options['prependRelativePath']);
    }
}
Example #29
0
 private static function _processImportUriCB($m)
 {
     $uri = trim($m[1], '()"\' ');
     //       decho(self::$_currentDir, 'currentDir');
     //       decho(self::$_docRoot, 'docRoot');
     // We want to grab the import.
     if (strpos($uri, '//') !== false) {
         $path = $uri;
     } elseif ($uri[0] == '/') {
         $path = self::_realpath(self::$_docRoot, $uri);
     } else {
         $path = realpath2(self::$_currentDir . '/' . trim($uri, '/\\'));
         if (substr_compare(self::$_docRoot, $path, 0, strlen($path)) != 0) {
             return "/* Error: {$uri} isn't in the webroot. */\n";
         } elseif (substr_compare($path, '.css', -4, 4, true) != 0) {
             return "/* Error: {$uri} must end in .css. */\n";
         }
     }
     $css = file_get_contents($path);
     // Not so fast, we've got to rewrite this file too. What's more, the current dir and path are different.
     $currentDirBak = self::$_currentDir;
     $newCurrentDir = realpath2($currentDirBak . realpath2(dirname($uri)));
     //       echo "
     //       currentDir: $currentDir,
     //       newCurrentDir: $newCurrentDir,
     //       docRoot: $docRoot
     //       uri:$uri\n";
     $css = self::rewrite($css, $newCurrentDir, self::$_docRoot);
     self::$_currentDir = $currentDirBak;
     return "/* @include url('{$uri}'); */\n" . $css;
 }
Example #30
0
 $cssTidy->settings['merge_selectors'] = 2;
 $core_files[$core_name] = "";
 $script_hash[$core_name] = getFileHash($pathToCore . "/{$core_name}");
 $script_size[$core_name] = getFileSize($pathToCore . "/{$core_name}");
 $full_script_size[$core_name] = 0;
 foreach ($core_group as $script) {
     $filePath = $pathToRoot . $script;
     if (file_exists($filePath)) {
         /*
         $core_files[$core_name] .= Minify_CSS::minify(file_get_contents($filePath), array(
             'currentDir' => dirname($filePath)
             ));
         */
         //echo "Proccessing: $filePath<br />\n";
         $full_script_size[$core_name] += getFileSize($filePath);
         $core_files[$core_name] .= Minify_CSS_UriRewriter::rewrite(file_get_contents($filePath), dirname($filePath));
         //$core_files[$core_name] .= Minify_YUICompressor::minifyCss(file_get_contents($filePath), array());
         // $core_files[$core_name] .= Minify_ClosureStylesheets::minify(file_get_contents($filePath), array());
     } else {
         $errors[] = "Unable to find CSS file for {$core_name}: {$filePath}";
         break;
     }
 }
 if (!count($errors)) {
     $core_files[$core_name] = Minify_YUICompressor::minifyCss($core_files[$core_name], array());
     //
     //$core_files[$core_name] = Minify_ClosureStylesheets::minify($core_files[$core_name], array());
     /*
             if($core_name == "core_dining.css"){
        $result = $cssTidy->parse($core_files[$core_name]);
        if($result){