function prepare($source, $min = true) { if ($min) { $source = \CssMin::minify($source); } return trim($source); }
/** * */ public function load($resource, $type = null) { $publishPath = $this->pathHelper->joinPaths($this->assetDirectory, $resource); $tmpPath = $this->pathHelper->joinPaths(sys_get_temp_dir(), $resource); $fs = $this->getFilesystem(); if ($this->debugMode) { $fs->dumpFile($tmpPath, "/* --- composition: {$resource} ---*/"); } $tmpFile = fopen($tmpPath, "a"); foreach ($this->compositions[$resource] as $asset) { $path = $this->locator->locate($asset); switch ($type) { case 'css': if (preg_match('/\\.min\\.css/', $asset)) { $content = file_get_contents($path); } else { $content = \CssMin::minify(file_get_contents($path)); } break; default: $content = file_get_contents($path); } if ($this->debugMode) { fwrite($tmpFile, "\n\n/* --- asset: {$asset} ({$path}) ---*/\n\n" . $content); } } fclose($tmpFile); if ($this->publishMode && $resource !== null) { $fs->copy($tmpPath, $publishPath); } return $tmpPath; }
public function __invoke($file, $minify = null) { if (!is_file($this->getOptions()->getPublicDir() . $file)) { throw new \InvalidArgumentException('File "' . $this->getOptions()->getPublicDir() . $file . '" not found.'); } $less = new \lessc(); $info = pathinfo($file); $newFile = $this->getOptions()->getDestinationDir() . $info['filename'] . '.' . filemtime($this->getOptions()->getPublicDir() . $file) . '.css'; $_file = $this->getOptions()->getPublicDir() . $newFile; if (!is_file($_file)) { $globPattern = $this->getOptions()->getPublicDir() . $this->getOptions()->getDestinationDir() . $info['filename'] . '.*.css'; foreach (Glob::glob($globPattern, Glob::GLOB_BRACE) as $match) { if (preg_match("/^" . $info['filename'] . "\\.[0-9]{10}\\.css\$/", basename($match))) { unlink($match); } } $compiledFile = new \SplFileObject($_file, 'w'); $result = $less->compileFile($this->getOptions()->getPublicDir() . $file); if (is_null($minify) && $this->getOptions()->getMinify() || $minify === true) { $result = \CssMin::minify($result); } $compiledFile->fwrite($result); } return $newFile; }
/** * Apply CssMin to $content. * * @param string $filename target filename * @param string $content Content to filter. * @throws Exception * @return string */ public function output($filename, $content) { App::import('Vendor', 'cssmin', array('file' => $this->_settings['path'])); if (!class_exists('CssMin')) { throw new Exception(sprintf('Cannot not load filter class "%s".', 'CssMin')); } return CssMin::minify($content); }
/** * */ public function load($resource, $type = null) { $publishPath = $this->pathHelper->joinPaths($this->assetDirectory, $resource); $tmpPath = $this->pathHelper->joinPaths(sys_get_temp_dir(), $resource); $path = $this->locator->locate($resource); $fs = $this->getFilesystem(); $fs->dumpFile($tmpPath, null); switch ($type) { case 'css': // minify only if it isnt already minified if (preg_match('/\\.min\\.css/', $resource)) { $content = file_get_contents($path); } else { $content = \CssMin::minify(file_get_contents($path)); } break; default: $content = file_get_contents($path); } file_put_contents($tmpPath, $content); if ($this->publishMode && $resource !== null) { $fs->copy($tmpPath, $publishPath); } return $tmpPath; }
/** * minify css and return css link * if minify is disabled: return direct css links * * @return string with html tag * @param array $stylesheets with css files */ public function minifycss($stylesheets) { if (Zend_Registry::get('config')->cache->enable == 1 && Zend_Registry::get('config')->cache->minifycss == 1) { // check file $target = Zend_Registry::get('config')->pub->path . 'stylesheets/' . Zend_Registry::get('config')->cache->minifiedcssfile; $targeturl = 'stylesheets/' . Zend_Registry::get('config')->cache->minifiedcssfile; if (file_exists($target)) { return "<link rel=\"stylesheet\" media=\"screen, handheld, projection, tv\" href=\"" . $targeturl . "\" />\n"; } // load and minify files $all = ""; foreach ($stylesheets as $css) { $csscontent = file_get_contents(Zend_Registry::get('config')->pub->path . $css); $csscontent = CssMin::minify($csscontent); $all .= $csscontent; } file_put_contents($target, $all); return "<link rel=\"stylesheet\" media=\"screen, handheld, projection, tv\" href=\"" . $targeturl . "\" />\n"; } else { $ret = ""; foreach ($stylesheets as $css) { $ret = $ret . "<link rel=\"stylesheet\" media=\"screen, handheld, projection, tv\" href=\"" . $css . "\" />\n"; } return $ret; } }
/** */ public function apply($in, $params = []) { require_php_lib('cssmin'); if (!class_exists('\\CssMin')) { throw new Exception('Assets: class \\CssMin not found'); return $in; } return \CssMin::minify($in); }
/** * New resource file update handler. * * @param string $resource Resource full path * @param string $extension Resource extension * @param string $content Compiled output resource content */ public function renderer($resource, &$extension, &$content) { // If CSS resource has been updated if ($extension === 'css') { // Read updated CSS resource file and compile it $content = \CssMin::minify($content); } elseif ($extension === 'js') { $content = \JShrink\Minifier::minify($content); } }
public function filterDump(AssetInterface $asset) { $filters = $this->filters; $plugins = $this->plugins; if (isset($filters['ImportImports']) && true === $filters['ImportImports']) { if ($dir = $asset->getSourceDirectory()) { $filters['ImportImports'] = array('BasePath' => $dir); } else { unset($filters['ImportImports']); } } $asset->setContent(\CssMin::minify($asset->getContent(), $filters, $plugins)); }
public function filterDump(AssetInterface $asset) { $filters = $this->filters; $plugins = $this->plugins; if (isset($filters['ImportImports']) && true === $filters['ImportImports']) { $root = $asset->getSourceRoot(); $path = $asset->getSourcePath(); if ($root && $path) { $filters['ImportImports'] = array('BasePath' => dirname($root . '/' . $path)); } else { unset($filters['ImportImports']); } } $asset->setContent(\CssMin::minify($asset->getContent(), $filters, $plugins)); }
public function packer($file, $type) { if (!file_exists($file)) { return; } $fileDst = preg_replace('/\\.(js|css)$/', '.min.\\1', $file); if ($type == "js") { $minContent = JSMin::minify(file_get_contents($file)); } else { $minContent = CssMin::minify(file_get_contents($file)); } echo "[01;41m " . $file . " [0m -> [32;40m" . $fileDst . "[0m\n"; file_put_contents($fileDst, $minContent); echo shell_exec("git add " . $fileDst); }
protected function createComponentCss() { $cssLoader = new \WebLoader\CssLoader(null, null, true); $cssLoader->sourcePath = __DIR__ . "/css"; $cssLoader->tempUri = $this->tempUri; $cssLoader->tempPath = $this->tempPath; foreach ($this->css as $css) { $cssLoader->addFile($css); } $cssLoader->filter(); $cssLoader->filters[] = function ($code) { return \CssMin::minify($code); }; return $cssLoader; }
public function filterDump(AssetInterface $asset) { $filters = $this->filters; $plugins = $this->plugins; if (isset($filters['ImportImports']) && true === $filters['ImportImports']) { // find the base path $sourceUrl = $asset->getSourceUrl(); if (self::isAbsoluteUrl($sourceUrl) || self::isAbsolutePath($sourceUrl)) { $filters['ImportImports'] = array('BasePath' => dirname($sourceUrl)); } elseif ($this->baseDir) { $filters['ImportImports'] = array('BasePath' => $this->baseDir); if ('.' != ($dir = dirname($sourceUrl))) { $filters['ImportImports']['BasePath'] .= '/' . $dir; } } } $asset->setContent(\CssMin::minify($asset->getContent(), $filters, $plugins)); }
public function renderCss($critical = false, $type = null, $isMobile = false) { if ($critical) { $this->renderCssCritical($type, $isMobile); } else { $config = $this->getPresenter()->context->parameters['scriptLoader']['css' . ($isMobile ? '_mobile' : '')]; if (!$this->getPresenter()->context->parameters['scriptLoader']['enable']) { if (!is_null($config['default'])) { foreach ($config['default'] as $css) { echo '<link rel="stylesheet" media="screen,projection,tv" href="/' . $css . '">'; } } } else { $cache = new Cache($this->getPresenter()->storage, 'scriptLoader'); if (is_null($cache->load('css' . ($isMobile ? '_mobile' : '')))) { //zminimalizuju $cssFile = ''; $cssFiles = array(); if (!is_null($config['default'])) { foreach ($config['default'] as $css) { $cssFile .= \CssMin::minify(file_get_contents($this->getPresenter()->context->parameters['wwwDir'] . '/' . $css)); $cssFiles[] = $this->getPresenter()->context->parameters['wwwDir'] . '/' . $css; } } $cache->save('css' . ($isMobile ? '_mobile' : ''), true, array(Cache::FILES => $cssFiles)); file_put_contents($this->getPresenter()->context->parameters['wwwDir'] . '/css/css.css', $cssFile); } echo '<script> var cb = function() { var l = document.createElement(\'link\'); l.rel = \'stylesheet\'; l.href = \'/css/css.css\'; var h = document.getElementsByTagName(\'head\')[0]; h.parentNode.insertBefore(l, h); }; var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame; if (raf) raf(cb); else window.addEventListener(\'load\', cb); </script>'; //echo '<link rel="stylesheet" media="screen,projection,tv" href="/css/css.css">'; } } }
protected function minify($scripts, $ext, $output) { $path = $this->rootDir(); $outfile = "{$path}/{$output}"; if (file_exists($outfile)) { if ($this->ttl == -1) { // never recompile return true; } $fileage = time() - filemtime($outfile); if ($fileage < $this->ttl) { return true; } } $str = $this->join_files($scripts); switch ($ext) { case "css": switch ($this->cssmin) { case "cssmin": $packed = \CssMin::minify($str); break; default: $packed = $str; } break; case "js": switch ($this->jsmin) { case "packer": $packer = new \JavaScriptPacker($str, "Normal", true, false); $packed = $packer->pack(); break; case "jshrink": $packed = \JShrink\Minifier::minify($str); break; default: $packed = $str; } break; } $this->fileClient->put($outfile, $packed); }
public function compileLessFile( $less_file = '', $css_file = '', $css_min_file = '' ){ global $wp_filesystem; if( empty( $less_file ) ) $less_file = dirname( __FILE__ ) . '/assets/css/style.less'; if( empty( $css_file ) ) $css_file = dirname( __FILE__ ) . '/assets/css/style.css'; if( empty( $css_min_file ) ) $css_min_file = dirname( __FILE__ ) . '/assets/css/style.min.css'; // Write less file if ( is_writable( $css_file ) && is_writable( $css_min_file ) ) { if ( ! class_exists( 'lessc' ) ){ include( dirname( __FILE__ ) . '/lib/lessc.inc.php' ); } if ( ! class_exists( 'cssmin' ) ){ include( dirname( __FILE__ ) . '/lib/cssmin.inc.php' ); } try { $less = new lessc; $compiled_css = $less->compileFile( $less_file ); if ( $compiled_css != '' ){ $wp_filesystem->put_contents( $css_file, $compiled_css ); $compiled_css_min = CssMin::minify( $compiled_css ); if ( $compiled_css_min != '' ) $wp_filesystem->put_contents( $css_min_file, $compiled_css_min ); } } catch ( exception $ex ) { //echo ( __( 'Could not compile .less:', 'sass' ) . ' ' . $ex->getMessage() ); } } }
public function minify($format, $content, $compression_option = "remote") { if ($format == "js") { if ($compression_option == "remote") { return $this->getMinified($this->urlJS, $content); // remote compression } else { require "vendor/JShrink/Minifier.php"; return \JShrink\Minifier::minify($content); // local compression } } if ($format == "css") { if ($compression_option == "remote") { return $this->getMinified($this->urlCSS, $content); // remote compression } else { require "vendor/cssmin/cssmin-v3.0.1-minified.php"; return CssMin::minify($content); // local compression } } }
/** * Get a file's content, minified. * @param string $path The file path. * @return string The file's content, minified. */ public function executeGetMinified($path) { $manager = $this->managers()->getManagerOf('file'); if (!$manager->exists($path)) { throw new \RuntimeException('"' . $path . '" : no such file or directory', 404); } $out = $manager->read($path); if ($manager->extension($manager->filename($path)) != 'min' && false) { $ext = $manager->extension($path); switch ($ext) { case 'js': $out = \JSMinPlus::minify($out); break; case 'css': $minifier = new \CssMin(); $out = $minifier->minify($out); break; default: throw new \RuntimeException('Cannot minify "' . $path . '" : unsupported file type', 406); } } $this->responseContent->setChannel(1, $out); }
/** * minifies css if DEBUG mode is disabled * * @return minified css * @param css to minify */ private function minifyCss($content) { if (\F3::get('DEBUG') != 0) { return $content; } return \CssMin::minify($content); }
/** * Optmize css, strip any spaces and newline * @param string $data input css data * @return string optmized css data */ private function optimizeCssCode($code) { require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'CssMin.php'; return CssMin::minify($code, $this->backendOptions['CssMin']['filters'], $this->backendOptions['CssMin']['plugins']); }
$type = 'images'; } if (file_exists($minifiedPathname) && filemtime($minifiedPathname) > filemtime($pathname)) { // Is het cache bestand up2date? echo ' "' . $filename . '" (cached) '; flush(); $minifiedSize = filesize($minifiedPathname); $fullSize = filesize($pathname); } else { // Het bestand moet (opnieuw) geminified worden echo " Processing: \"" . $filename . "\""; flush(); $script = file_get_contents($pathname); $fullSize = strlen($script); if ($type === 'css') { $minifiedScript = \CssMin::minify($script); } elseif ($type === 'javascript') { $minifiedScript = \JSMinPlus::minify($script); } else { $minifiedScript = ImageOptimizer::minify($script, $filename); } if ($minifiedScript === false) { // Is het minify proces mislukt? $minifiedScript = $script; // Gebruik dan het orginele bestand. } $minifiedSize = strlen($minifiedScript); mkdirs(dirname($minifiedPathname) . '/'); if (file_put_contents($minifiedPathname, $minifiedScript) === false) { echo "\n FAILED.\n"; exit;
public static function css($css) { return CssMin::minify($css); }
/** * Dumps a CSS/JS file * * @param $name * @param $mimetype */ function dump($name, $mimetype, $cachekey) { global $cachedirdrupal; global $nocache; global $config; $starttime = microtime(true); $excludes = array(); $dependencies = array(); $patterns = array(); $filetype = substr(strrchr($name, '.'), 1); $output = ''; $minify = isset($_REQUEST['min']); $debugjavascript = $filetype === 'js' && isset($_REQUEST['debug']); if ($debugjavascript) { $output .= '// load js files in a synchronous way' . PHP_EOL; } // check whether the file is in drupal cache if (!is_dir($cachedirdrupal)) { mkdir($cachedirdrupal, 0755); } $cachefile = $cachedirdrupal . '/terrific-' . $cachekey . '-' . $name; if ($nocache || !is_file($cachefile)) { // collect excluded pattern & (less/scss) dependencies & patterns foreach ($config->assets->{$name} as $pattern) { $firstchar = substr($pattern, 0, 1); if ($firstchar === '!') { $excludes[] = substr($pattern, 1); } else { if ($firstchar === '+') { $dependencies[] = substr($pattern, 1); } else { $patterns[] = $pattern; } } } $dependencies = get_files($dependencies); $excludes = array_merge($dependencies, $excludes); $files = get_files($patterns, $excludes); foreach ($files as $entry) { if (!$debugjavascript) { $format = substr(strrchr($entry, '.'), 1); $output .= compile(BASE . $entry, $format, $dependencies); } else { $output .= "document.write('<script type=\"text/javascript\" src=\"{$entry}\"><\\/script>');" . PHP_EOL; } } if ($minify) { switch ($filetype) { case 'css': require BASE . 'app/library/cssmin/cssmin.php'; $output = CssMin::minify($output); break; case 'js': require BASE . 'app/library/jshrink/Minifier.php'; $output = \JShrink\Minifier::minify($output); break; } } $time_taken = microtime(TRUE) - $starttime; $output = get_asset_banner($name, $filetype, $minify, $time_taken) . $output; file_put_contents($cachefile, $output); } else { $output = file_get_contents($cachefile); } ob_start("ob_gzhandler"); header('Content-Type: ' . $mimetype); echo $output; ob_end_flush(); }
case 'n': case 'nomin': $nomin = true; break; default: $skin = 'gstyle'; $nomin = false; } } // Files $files = array('js' => array('js/submodules/jmicro/jmicro', 'js/main', 'js/lib/view/utils', 'js/lib/controller/controller', 'js/lib/model/stack', 'js/lib/helpers/grader', 'js/lib/helpers/tagrandcolor', 'js/lib/view/control/togglebutton', 'js/lib/view/indicator/graph', 'js/lib/view/indicator/gauge', 'js/lib/view/indicator/barchart', 'js/lib/view/indicator/histogram', 'js/lib/view/layout/layout', 'js/lib/view/layout/mainpanel', 'js/lib/view/layout/console', 'js/lib/view/layout/sidebar', 'js/lib/view/stack/backtrace', 'js/lib/view/stack/tree', 'js/plugins/inspector', 'js/plugins/metrics', 'js/plugins/stack', 'js/plugins/duration', 'js/plugins/memory', 'js/plugins/calls', 'js/plugins/groups', 'js/plugins/files', 'js/plugins/searchengine'), 'css' => array('css/default', 'css/' . $skin)); $path = dirname(__FILE__) . '/built/forp.min.js'; $target = fopen($path, 'w+'); try { $js = $css = ''; foreach ($files['js'] as $file) { $js .= file_get_contents(dirname(__FILE__) . '/' . $file . '.js'); } foreach ($files['css'] as $file) { $css .= file_get_contents(dirname(__FILE__) . '/' . $file . '.css'); } $js = str_replace(array_keys($php_var), array_values($php_var), $js); $css = str_replace(array_keys($php_var), array_values($php_var), $css); // Inject CSS fwrite($target, str_replace('%forp.css%', CssMin::minify($css), '/** forp-ui (c) 2013 Anthony Terrien **/' . ($nomin ? $js : JSMin::minify($js)))); echo "File " . $path . " built\n"; } catch (Exception $ex) { echo "Fatal error : " . $ex->getMessage() . "\n\n"; echo $ex->getTraceAsString(); } fclose($target);
/** * Компилирует медиа файлы * @todo сделать возможность встройки картинок base64 * @param array $files * @param type $extension * @return boolean|string * @throws Kohana_Exception */ protected function compile_media(array $files, $extension, $no_compress_scripts = array()) { if (count($files) == 0) { return false; } $files_sum = $files; sort($files_sum); $sum = crc32(implode($files_sum)); unset($files_sum); $uri = "media/{$sum}.{$extension}"; $minified_file = DOCROOT . $uri; if (!file_exists($minified_file)) { $files_paths = array(); foreach ($files as $file) { $file_path = Kohana::find_file("media", $file, $extension); if ($file_path === false) { if (file_exists($file)) { $file_path = $file; } else { throw new Kohana_Exception("media file '{file}.{extension}' not founded", array("{file}" => $file, "{extension}" => $extension)); } } $files_paths[] = array('file' => $file, 'path' => $file_path); } $sources = array(); foreach ($files_paths as $file_path_data) { $file_path = $file_path_data['path']; $file1 = $file_path_data['file']; if (file_exists($file_path)) { if (array_search($file1, $no_compress_scripts) === false) { if ($extension == self::JS_EXT) { $sources[] = "\n\n/*{$file_path}*/\n\n" . JSMin::minify(file_get_contents($file_path)); } else { $minified_css = CssMin::minify(file_get_contents($file_path)); //Надо заменить относительные пути в css $dir_url = Door::path_to_uri(dirname($file_path)); $dir_path = dirname($file_path); /*if(preg_match_all("/url\\(([^\\)]+)\\)/", $minified_css, $results)) { for($i = 0; $i < count($results[0]); $i++) { $url = str_replace(array('"',"'"),"",$results[1][$i]); if(strpos($url, "data:") === false) { $from = $results[0][$i]; $to = "url(/".$dir_url."/".$url.")"; $minified_css = str_replace($from, $to, $minified_css); } } }*/ if (preg_match_all("/url\\(([^\\)]+)\\)/", $minified_css, $results)) { for ($i = 0; $i < count($results[0]); $i++) { $url = str_replace(array('"', "'"), "", $results[1][$i]); if (strpos($url, "data:") === false && strpos($url, "http:") === false) { $path_to_media_file = $dir_path . "/" . $url; if (!file_exists($path_to_media_file)) { continue; } $size = null; $from = $results[0][$i]; $to = ""; try { $size = getimagesize($path_to_media_file); } catch (Exception $e) { } if ($size !== false && filesize($path_to_media_file) < 5120) { $to = "url(\"data:{$size['mime']};base64," . base64_encode(file_get_contents($path_to_media_file)) . "\")"; } else { $to = "url(/" . $dir_url . "/" . $url . ")"; } $minified_css = str_replace($from, $to, $minified_css); } } } while (preg_match_all("#url\\([^\\)]*/([^/]+)/\\.\\./#", $minified_css, $results)) { for ($i = 0; $i < count($results[0]); $i++) { $minified_css = str_replace("/" . $results[1][$i] . "/../", "/", $minified_css); } } $sources[] = "\n\n" . $minified_css; } } else { $sources[] = file_get_contents($file_path); } } else { throw new Kohana_Exception("file '{file}' not founded", array("{file}" => $file_path)); } } $minified = implode("", $sources); unset($sources); file_put_contents($minified_file, $minified); } return $minified_file; }
/** * Generate CSS from the less file when changing colours. * * @access public * @return void */ function woocommerce_compile_less_styles() { global $woocommerce; $colors = get_option('woocommerce_frontend_css_colors'); $base_file = $woocommerce->plugin_path() . '/assets/css/woocommerce-base.less'; $less_file = $woocommerce->plugin_path() . '/assets/css/woocommerce.less'; $css_file = $woocommerce->plugin_path() . '/assets/css/woocommerce.css'; // Write less file if (is_writable($base_file) && is_writable($css_file)) { // Colours changed - recompile less if (!class_exists('lessc')) { include_once 'includes/lessc.inc.php'; } if (!class_exists('cssmin')) { include_once 'includes/cssmin.inc.php'; } try { // Set default if colours not set if (!$colors['primary']) { $colors['primary'] = '#ad74a2'; } if (!$colors['secondary']) { $colors['secondary'] = '#f7f6f7'; } if (!$colors['highlight']) { $colors['highlight'] = '#85ad74'; } if (!$colors['content_bg']) { $colors['content_bg'] = '#ffffff'; } if (!$colors['subtext']) { $colors['subtext'] = '#777777'; } // Write new color to base file $color_rules = "\n@primary: \t\t" . $colors['primary'] . ";\n@primarytext: \t" . woocommerce_light_or_dark($colors['primary'], 'desaturate(darken(@primary,50%),18%)', 'desaturate(lighten(@primary,50%),18%)') . ";\n\n@secondary: \t" . $colors['secondary'] . ";\n@secondarytext: " . woocommerce_light_or_dark($colors['secondary'], 'desaturate(darken(@secondary,60%),18%)', 'desaturate(lighten(@secondary,60%),18%)') . ";\n\n@highlight: \t" . $colors['highlight'] . ";\n@highlightext:\t" . woocommerce_light_or_dark($colors['highlight'], 'desaturate(darken(@highlight,60%),18%)', 'desaturate(lighten(@highlight,60%),18%)') . ";\n\n@contentbg:\t\t" . $colors['content_bg'] . ";\n\n@subtext:\t\t" . $colors['subtext'] . ";\n\t\t\t"; file_put_contents($base_file, $color_rules); $less = new lessc($less_file); $compiled_css = $less->parse(); $compiled_css = CssMin::minify($compiled_css); if ($compiled_css) { file_put_contents($css_file, $compiled_css); } } catch (exception $ex) { wp_die(__('Could not compile woocommerce.less:', 'woocommerce') . ' ' . $ex->getMessage()); } } }
/** * Método que compila los ficheros css y los procesa en función del modo de ejecución * @return AssetsParser * @throws ConfigException */ protected function compileCss() { $base = $this->path . "css" . DIRECTORY_SEPARATOR; if ($this->debug || !file_exists($base . $this->hash . ".css")) { $data = ''; if (0 < count($this->files)) { foreach ($this->files as $file) { $data = $this->processCssLine($file, $base, $data); } } $this->storeContents($base . $this->hash . ".css", \CssMin::minify($data)); unset($cssMinifier); } return $this; }
/** * Implements cssmin compression engine * * @param string $data Source to compress * * @return string */ private function _cssmin($data) { require_once APPPATH . 'libraries/minify/cssmin-v3.0.1.php'; return CssMin::minify($data); }
function minify_css($css, $do_output, $file) { $min = CssMin::minify($css); $min_file = str_replace(".css", ".min.css", $file); return place_file($min_file, $min, $do_output, $file); }
public function minify() { foreach ($this->css as $group) { list($media, $css) = $group; if (preg_match('#^INLINE;#', $css)) { //<style> $css = preg_replace('#^INLINE;#', '', $css); $css = $this->fixurls(ABSPATH . '/index.php', $css); } else { //<link> if ($css !== false && file_exists($css) && is_readable($css)) { $css = $this->fixurls($css, file_get_contents($css)); $css = preg_replace('/\\x{EF}\\x{BB}\\x{BF}/', '', $css); } else { //Couldn't read CSS. Maybe getpath isn't working? $css = ''; } } foreach ($media as $elem) { if (!isset($this->csscode[$elem])) { $this->csscode[$elem] = ''; } $this->csscode[$elem] .= "\n/*FILESTART*/" . $css; } } // Check for duplicate code $md5list = array(); $tmpcss = $this->csscode; foreach ($tmpcss as $media => $code) { $md5sum = md5($code); $medianame = $media; foreach ($md5list as $med => $sum) { //If same code if ($sum === $md5sum) { //Add the merged code $medianame = $med . ', ' . $media; $this->csscode[$medianame] = $code; $md5list[$medianame] = $md5list[$med]; unset($this->csscode[$med], $this->csscode[$media]); unset($md5list[$med]); } } $md5list[$medianame] = $md5sum; } unset($tmpcss); //Manage @imports, while is for recursive import management foreach ($this->csscode as &$thiscss) { // Flag to trigger import reconstitution and var to hold external imports $fiximports = false; $external_imports = ""; while (preg_match_all('#^(/*\\s?)@import.*(?:;|$)#Um', $thiscss, $matches)) { foreach ($matches[0] as $import) { $url = trim(preg_replace('#^.*((?:https?:|ftp:)?//.*\\.css).*$#', '$1', trim($import)), " \t\n\r\v\"'"); $path = $this->getpath($url); $import_ok = false; if (file_exists($path) && is_readable($path)) { $code = addcslashes($this->fixurls($path, file_get_contents($path)), "\\"); $code = preg_replace('/\\x{EF}\\x{BB}\\x{BF}/', '', $code); if (!empty($code)) { $tmp_thiscss = preg_replace('#(/\\*FILESTART\\*/.*)' . preg_quote($import, '#') . '#Us', '/*FILESTART2*/' . $code . '$1', $thiscss); if (!empty($tmp_thiscss)) { $thiscss = $tmp_thiscss; $import_ok = true; unset($tmp_thiscss); } unset($code); } } if (!$import_ok) { // external imports and general fall-back $external_imports .= $import; $thiscss = str_replace($import, '', $thiscss); $fiximports = true; } } $thiscss = preg_replace('#/\\*FILESTART\\*/#', '', $thiscss); $thiscss = preg_replace('#/\\*FILESTART2\\*/#', '/*FILESTART*/', $thiscss); } // add external imports to top of aggregated CSS if ($fiximports) { $thiscss = $external_imports . $thiscss; } } unset($thiscss); // $this->csscode has all the uncompressed code now. $mhtmlcount = 0; foreach ($this->csscode as &$code) { // Check for already-minified code $hash = md5($code); $ccheck = new autoptimizeCache($hash, 'css'); if ($ccheck->check()) { $code = $ccheck->retrieve(); $this->hashmap[md5($code)] = $hash; continue; } unset($ccheck); // Do the imaging! $imgreplace = array(); preg_match_all('#(background[^;}]*url\\((?!data)(.*)\\)[^;}]*)(?:;|$|})#Usm', $code, $matches); if ($this->datauris == true && function_exists('base64_encode') && is_array($matches)) { foreach ($matches[2] as $count => $quotedurl) { $iurl = trim($quotedurl, " \t\n\r\v\"'"); // if querystring, remove it from url if (strpos($iurl, '?') !== false) { $iurl = reset(explode('?', $iurl)); } $ipath = $this->getpath($iurl); $datauri_max_size = 4096; $datauri_max_size = (int) apply_filters('autoptimize_filter_css_datauri_maxsize', $datauri_max_size); $datauri_exclude = apply_filters('autoptimize_filter_css_datauri_exclude', ""); if (!empty($datauri_exclude)) { $no_datauris = array_filter(array_map('trim', explode(",", $datauri_exclude))); foreach ($no_datauris as $no_datauri) { if (strpos($iurl, $no_datauri) !== false) { $ipath = false; break; } } } if ($ipath != false && preg_match('#\\.(jpe?g|png|gif|bmp)$#', $ipath) && file_exists($ipath) && is_readable($ipath) && filesize($ipath) <= $datauri_max_size) { $ihash = md5($ipath); $icheck = new autoptimizeCache($ihash, 'img'); if ($icheck->check()) { // we have the base64 image in cache $headAndData = $icheck->retrieve(); } else { // It's an image and we don't have it in cache, get the type $explA = explode('.', $ipath); $type = end($explA); switch ($type) { case 'jpeg': $dataurihead = 'data:image/jpeg;base64,'; break; case 'jpg': $dataurihead = 'data:image/jpeg;base64,'; break; case 'gif': $dataurihead = 'data:image/gif;base64,'; break; case 'png': $dataurihead = 'data:image/png;base64,'; break; case 'bmp': $dataurihead = 'data:image/bmp;base64,'; break; default: $dataurihead = 'data:application/octet-stream;base64,'; } // Encode the data $base64data = base64_encode(file_get_contents($ipath)); $headAndData = $dataurihead . $base64data; // Save in cache $icheck->cache($headAndData, "text/plain"); } unset($icheck); //Add it to the list for replacement $imgreplace[$matches[1][$count]] = str_replace($quotedurl, $headAndData, $matches[1][$count]) . ";\n*" . str_replace($quotedurl, 'mhtml:%%MHTML%%!' . $mhtmlcount, $matches[1][$count]) . ";\n_" . $matches[1][$count] . ';'; //Store image on the mhtml document $this->mhtml .= "--_\r\nContent-Location:{$mhtmlcount}\r\nContent-Transfer-Encoding:base64\r\n\r\n{$base64data}\r\n"; $mhtmlcount++; } } } else { if (is_array($matches) && !empty($this->cdn_url)) { // change background image urls to cdn-url foreach ($matches[2] as $count => $quotedurl) { $url = trim($quotedurl, " \t\n\r\v\"'"); $cdn_url = $this->url_replace_cdn($url); $imgreplace[$matches[1][$count]] = str_replace($quotedurl, $cdn_url, $matches[1][$count]); } } } if (!empty($imgreplace)) { $code = str_replace(array_keys($imgreplace), array_values($imgreplace), $code); } //Minify if (apply_filters("autoptimize_css_do_minify", true)) { if (class_exists('Minify_CSS_Compressor')) { $tmp_code = trim(Minify_CSS_Compressor::process($code)); } else { if (class_exists('CSSmin')) { $cssmin = new CSSmin(); if (method_exists($cssmin, "run")) { $tmp_code = trim($cssmin->run($code)); } elseif (@is_callable(array($cssmin, "minify"))) { $tmp_code = trim(CssMin::minify($code)); } } } if (!empty($tmp_code)) { $code = $tmp_code; unset($tmp_code); } } $this->hashmap[md5($code)] = $hash; } unset($code); return true; }