In CSS content, rewrite file relative URIs as root relative
public static rewrite ( string $css, string $currentDir, string $docRoot = null, array $symlinks = [] ) : string | ||
$css | string | |
$currentDir | string | The directory of the current CSS file. |
$docRoot | string | The document root of the web site in which the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']). |
$symlinks | array | (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.:
array('//symlink' => '/real/target/path') // unix
array('//static' => 'D:\\staticStorage') // Windows
|
Результат | string |
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; }
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; }
/** * 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'] ); } }
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; } }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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']); } }
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); }
/** * 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; }
/** * 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; }
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"; } } }
/** * 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; }
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; }
/** * 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']); } }
/** * Returns content of all included css files. Does also rewrite relative * urls to absolute urls! Array contains different keys for various media types * * @return array */ private function getExternalCSS() { $content = array(); if (!is_array($GLOBALS['TSFE']->pSetup['includeCSS.'])) { $GLOBALS['TSFE']->pSetup['includeCSS.'] = array(); } foreach ($GLOBALS['TSFE']->pSetup['includeCSS.'] as $key => $value) { if (is_array($value)) { continue; } if (!empty($GLOBALS['TSFE']->pSetup['includeCSS.'][$key . '.']['media'])) { $media = $GLOBALS['TSFE']->pSetup['includeCSS.'][$key . '.']['media']; } else { $media = 'all'; } $fileName = $GLOBALS['TSFE']->tmpl->getFileName($value); //remove @charset stuff for webkit browsers $cssContent = preg_replace('%@charset.*;%Ui', '', file_get_contents($fileName)) . "\n"; $content[$media] .= Minify_CSS_UriRewriter::rewrite($cssContent, dirname($fileName)); } return $content; }
/** * Compile full list of files in $this->_cache array * * @return string */ protected function _getCompiledItem() { $fileProcessor = $this->getProcessor(); $path = $fileProcessor->getServerPath($this->getOption('dir') . $fileProcessor->fullFilename(md5(serialize($fileProcessor->getCache())))); if (!file_exists($path)) { // Check if necessary directory is exists $dir = dirname($path); if (!is_dir($dir) && !@mkdir($dir, 0777, true)) { // @todo: Use more specific exception here throw new Zend_View_Exception('Impossible to create destination directory ' . $dir); } $cssContent = ''; foreach ($fileProcessor->getCache() as $css) { $content = file_get_contents($css['filepath']); require_once 'CSS.php'; // Minify by using 3rd-party library $cssContent .= $this->getOption('compress', true) ? Minify_CSS::minify($content, array('prependRelativePath' => dirname($path), 'currentDir' => dirname($css['filepath']), 'symlinks' => $this->getOption('symlinks'))) : Minify_CSS_UriRewriter::rewrite($content, dirname($css['filepath']), $this->_getCompiledItem(''), $this->getOption('symlinks')); $cssContent .= "\n\n"; } // Write css content to cache file file_put_contents($path, $cssContent); $fileProcessor->gzip($path, $cssContent); } return $this->createDataStylesheet(array('href' => $this->getProcessor()->getWebPath($path))); }
private function getCompiledItem() { $compress = Lms_Application::getConfig('optimize', 'css_compress'); $filename = md5(serialize($this->_cache)); $path = self::$cacheDir . $filename . ($compress ? '_compressed' : '') . '.css'; if (!file_exists($path)) { Lms_Debug::debug("Combine css to {$path}..."); Lms_FileSystem::createFolder(dirname($path), 0777, true); $cssContent = ''; foreach ($this->_cache as $css) { $content = file_get_contents($css['filepath']); if ($compress) { $cssContent .= Minify_CSS::minify($content, array('prependRelativePath' => dirname($path), 'currentDir' => dirname($css['filepath']), 'symlinks' => Lms_Application::getConfig('symlinks'))); } else { $cssContent .= Minify_CSS_UriRewriter::rewrite($content, dirname($css['filepath']), $_SERVER['DOCUMENT_ROOT'], Lms_Application::getConfig('symlinks')); } $cssContent .= "\n\n"; Lms_Debug::debug($css['filepath'] . ' ... OK'); } file_put_contents($path, $cssContent); } $url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $path); $item = $this->createDataStylesheet(array('href' => $url)); return $item; }
/** * 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; }
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; }
/** * See {@link combine_files()} * */ private function _process_combined_files($type) { // Make a map of files that could be potentially combined $combinerCheck = array(); foreach ($this->combine_files[$type] as $combinedFile => $sourceItems) { foreach ($sourceItems as $id => $sourceItem) { if (isset($combinerCheck[$sourceItem]) && $combinerCheck[$sourceItem] != $combinedFile) { Kohana::log('alert', "Requirements_Backend::process_combined_files - file '{$sourceItem}' appears in two combined files:" . " '{$combinerCheck[$sourceItem]}' and '{$combinedFile}'"); } $combinerCheck[$sourceItem] = $combinedFile; $combinerCheck[$id] = $combinedFile; } } // Work out the relative URL for the combined files from the base folder $combinedFilesFolder = $this->getCombinedFilesFolder() ? $this->getCombinedFilesFolder() . '/' : ''; // Figure out which ones apply to this pageview $combinedFiles = array(); $newRequirements = array(); foreach ($this->{$type} as $id => $params) { $file = $type == 'js' ? $params : $params['file']; if (isset($combinerCheck[$file])) { $newRequirements[$combinerCheck[$file]] = $type == 'js' ? $combinedFilesFolder . $combinerCheck[$file] : array('file' => $combinedFilesFolder . $combinerCheck[$file]); $combinedFiles[$combinerCheck[$file]] = true; } elseif (isset($combinerCheck[$id])) { $newRequirements[$combinerCheck[$id]] = $type == 'js' ? $combinedFilesFolder . $combinerCheck[$id] : array('file' => $combinedFilesFolder . $combinerCheck[$id]); $combinedFiles[$combinerCheck[$id]] = true; } else { $newRequirements[$id] = $params; } } // Process the combined files $base = DOCROOT; foreach (array_diff_key($combinedFiles, $this->blocked) as $combinedFile => $dummy) { $fileList = $this->combine_files[$type][$combinedFile]; $combinedFilePath = $base . $combinedFilesFolder . $combinedFile; // Check for RTL alternatives if ($type == 'css' and ush_locale::is_rtl_language()) { $has_rtl_files = FALSE; foreach ($fileList as $index => $file) { $rtlFile = substr($file, 0, strpos($file, ".{$type}")) . "-rtl" . substr($file, strpos($file, ".{$type}")); if (file_exists(DOCROOT . $rtlFile)) { $fileList[$index] = $rtlFile; $has_rtl_files = TRUE; } } // Update combined files details, only if the include RTL alternatives // We store the RTL version separate from the LTR version, so we don't regenerate every time someone changes language if ($has_rtl_files) { $combinedFile = substr($combinedFile, 0, -4) . '-rtl.css'; $combinedFilePath = $base . $combinedFilesFolder . $combinedFile; $newRequirements[$combinedFile] = $type == 'js' ? $combinedFilesFolder . $combinedFile : array('file' => $combinedFilesFolder . $combinedFile); } } // Make the folder if necessary if (!file_exists(dirname($combinedFilePath))) { mkdir(dirname($combinedFilePath)); } // If the file isn't writebale, don't even bother trying to make the combined file // Complex test because is_writable fails if the file doesn't exist yet. if (file_exists($combinedFilePath) && !is_writable($combinedFilePath) || !file_exists($combinedFilePath) && !is_writable(dirname($combinedFilePath))) { Kohana::log('alert', "Requirements_Backend::process_combined_files(): Couldn't create '{$combinedFilePath}'"); continue; } // Determine if we need to build the combined include if (file_exists($combinedFilePath) && !isset($_GET['flush'])) { // file exists, check modification date of every contained file $srcLastMod = 0; foreach ($fileList as $file) { $srcLastMod = max(filemtime($base . $file), $srcLastMod); } $refresh = $srcLastMod > filemtime($combinedFilePath); } else { // file doesn't exist, or refresh was explicitly required $refresh = true; } if (!$refresh) { continue; } $combinedData = ""; foreach (array_diff($fileList, $this->blocked) as $id => $file) { $fileContent = file_get_contents($base . $file); // if we have a javascript file and jsmin is enabled, minify the content if ($type == 'js' && $this->combine_js_with_jsmin) { $fileContent = JSMin::minify($fileContent); } if ($type == 'css') { // Rewrite urls in css to be relative to the docroot // Docroot param needs to be actual server docroot, not root of ushahidi site. // Using $_SERVER['DOCUMENT_ROOT']. Should possibly use DOCROOT, but remove Kohana::config('core.site_domain', TRUE); $fileContent = Minify_CSS_UriRewriter::rewrite($fileContent, pathinfo($base . $file, PATHINFO_DIRNAME), $_SERVER['DOCUMENT_ROOT']); // compress css (if enabled) if ($this->combine_css_with_cssmin) { $fileContent = CSSmin::go($fileContent); } } // write a header comment for each file for easier identification and debugging // also the semicolon between each file is required for jQuery to be combinable properly $combinedData .= "/****** FILE: {$file} *****/\n" . $fileContent . "\n" . ($type == 'js' ? ';' : '') . "\n"; } $successfulWrite = false; $fh = fopen($combinedFilePath, 'wb'); if ($fh) { if (fwrite($fh, $combinedData) == strlen($combinedData)) { $successfulWrite = true; } fclose($fh); unset($fh); } // Should we push this to the CDN too? if (Kohana::config("cdn.cdn_store_dynamic_content") and Kohana::config("requirements.cdn_store_combined_files")) { $cdn_combined_path = cdn::upload($combinedFilesFolder . $combinedFile, FALSE); } // Unsuccessful write - just include the regular JS files, rather than the combined one if (!$successfulWrite) { Kohana::log('alert', "Requirements_Backend::process_combined_files(): Couldn't create '{$combinedFilePath}'"); continue; } } // @todo Alters the original information, which means you can't call this // method repeatedly - it will behave different on the second call! $this->{$type} = $newRequirements; }
$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 {
/** * Selects the correct css uri rewriter, and applies it * * @param string $content the contents of the file to rewrite * @param string $filename the original location of the file * @param string $destination_filename the name of the file where the css will be written to * @return string The re-written content */ protected function css_rewrite_uris($content, $filename, $destination_filename) { switch ($this->css_uri_rewriter) { case 'absolute': $rewritten = \Minify_CSS_UriRewriter::rewrite($content, dirname($filename)); break; case 'relative': $rewritten = CssUriRewriterRelative::rewrite_css($content, dirname($filename), dirname($destination_filename)); break; case 'none': $rewritten = $content; break; default: throw new CassetException('Unknown CSS URI rewriter: ' . $this->css_uri_rewriter); break; } return $rewritten; }
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']); } }
$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){
/** * 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; }
/** * Minifies content * @param string $content * @param array $options * @return string */ public static function minify($content, $options = array()) { $content = Minify_CSS_UriRewriter::rewrite($content, $options); return $content; }
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; }
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())); } }