public function minify_css($content) { include_once 'lib/cssmin.php'; $compressor = new CSSmin(); $content = $compressor->run($content); return $content; }
public function process($cssFile, $cssv = '1.0') { $baseDir = $this->_cssBaseDir; foreach ($cssFile as $fileName => $data) { $file = $baseDir . $fileName; if (!file_exists($file)) { unset($cssFile[$fileName]); continue; } else { $this->_sum .= $fileName . filemtime($file); } } $this->_sum .= $cssv; $name = hash('crc32b', $this->_sum) . '.css'; if (!file_exists(PUBLIC_DIR . 'temp' . DS . $name)) { $css = ''; foreach ($cssFile as $file => $data) { $css .= file_get_contents($baseDir . $file); } require_once LIBRARIES_DIR . 'Cssmin' . DS . 'Cssmin.php'; $minifier = new CSSmin(); $css = $minifier->run($css); /* * @FIXME */ //$css = $this->minify($css); $this->_css = $this->_fixUrl($css); $this->save($name); } return $name; }
/** * @param string $css * @return string */ private function process($css) { if ($this->mth == 'RW') { /* Reinhold Weber method */ $c = preg_replace('!/\\*[^*]*\\*+([^/][^*]*\\*+)*/!', '', $css); /* remove comments */ $rlt = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $c); /* remove tabs, spaces, newlines, etc. */ } else { $min = new CSSmin(true, false); //YUI Compressor $rlt = $min->run($css); if (strpos($rlt, CSSmin::COMMENT)) { $rlt = false; //bad source } } if (self::$fle[1]) { ++self::$cnt[0]; //new call } ++self::$cnt[1]; // sequent call return $rlt; }
public function beforeAction($action) { $base = Cshop::$rootpath; $jsfilename = $base . "/static/cache/final.js"; if (!file_exists($jsfilename)) { $filename = $base . "/static/js/jquery.js"; $js = file_get_contents($filename); $filename = $base . "/static/js/jquery-ui.js"; $js .= file_get_contents($filename); $filename = $base . "/static/js/jquery.mousewheel.js"; $js .= file_get_contents($filename); $filename = $base . "/static/js/perfect-scrollbar.js"; $js .= file_get_contents($filename); $filename = $base . "/static/js/jquery.placeholder.js"; $js .= file_get_contents($filename); $filename = $base . "/static/js/jquery.noty.packaged.min.js"; $js .= file_get_contents($filename); $filename = $base . "/static/js/script.js"; $js .= file_get_contents($filename); $js = JSMin::minify($js); file_put_contents($jsfilename, $js); } $cssfilename = $base . "/static/cache/final.css"; if (!file_exists($cssfilename)) { $filename = $base . "/static/css/style.css"; $css = file_get_contents($filename); $filename = $base . "/static/css/perfect-scrollbar.css"; $css .= file_get_contents($filename); $minify = new CSSmin(); $css = $minify->run($css, true); file_put_contents($cssfilename, $css); } return parent::beforeAction($action); }
function render_css($css_files = array()) { $output = ''; // Load the necessary compression libraries if needed if ($this->ci->config->item('compress_css')) { require_once './libs/php/cssmin.php'; $CSSmin = new CSSmin(); } // If CSS needs to be combined if ($this->ci->config->item('combine_css')) { // Determine the file name for combined file $contents = array(); foreach ($css_files as $file) { // Compress only local files, ignore the rest if (substr($file, 0, 4) !== 'http') { $content = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $file); $contents[$file] = $this->ci->config->item('compress_css') ? $CSSmin->run($content) : $content; } else { $output .= '<link rel="stylesheet" type="text/css" href="' . $file . '" media="screen" />'; } } $css_code = implode('', $contents); $hash = sha1($css_code); $final_css_file = $_SERVER['DOCUMENT_ROOT'] . '/themes/cache/' . $hash . '.css'; if (!file_exists($final_css_file)) { file_put_contents($final_css_file, $css_code); } $output .= '<link rel="stylesheet" type="text/css" href="' . base_url() . 'themes/cache/' . $hash . '.css" media="screen" />'; } else { foreach ($css_files as $file) { // Compress only local files, ignore the rest if (substr($file, 0, 4) !== 'http') { $hash = sha1_file($_SERVER['DOCUMENT_ROOT'] . $file); $final_css_file = $_SERVER['DOCUMENT_ROOT'] . '/themes/cache/' . $hash . '.css'; if ($this->ci->config->item('compress_css')) { if (!file_exists($final_css_file)) { file_put_contents($final_css_file, $CSSmin->run(file_get_contents($_SERVER['DOCUMENT_ROOT'] . $file))); log_message('debug', 'Assets pipeline created file: ' . $final_css_file); } $output .= '<link rel="stylesheet" type="text/css" href="' . base_url() . 'themes/cache/' . $hash . '.css" media="screen" />'; } else { $output .= '<link rel="stylesheet" type="text/css" href="' . substr(base_url(), 0, -1) . $file . '" media="screen" />'; } } else { $output .= '<link rel="stylesheet" type="text/css" href="' . $file . '" media="screen" />'; } } } return $output; }
/** * 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']); } }
function test_CSSmin() { $files = glob(dirname(__FILE__) . '/_test_files/yuic/*.css'); // some tests may exhaust memory/stack due to string size/PCRE $skip = array(); $cssmin = new CSSmin(); foreach ($files as $file) { if (!empty($skip) && in_array(basename($file), $skip)) { echo "INFO: CSSmin: skipping " . basename($file) . "\n"; continue; } $src = file_get_contents($file); $minExpected = trim(file_get_contents($file . '.min')); $minOutput = trim($cssmin->run($src)); $passed = assertTrue($minExpected == $minOutput, 'CSSmin : ' . basename($file)); if (!$passed && __FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . countBytes($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . countBytes($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . countBytes($src) . " bytes\n\n{$src}\n\n\n"; } } }
include '../cssmin.php'; // Form options parse_str($_POST['options']); $linebreak_pos = trim($linebreak_pos) != '' ? $linebreak_pos : FALSE; $raise_php = isset($raise_php) ? TRUE : FALSE; // Create a new CSSmin object and try to raise PHP settings $compressor = new CSSmin($raise_php); if ($raise_php) { $compressor->set_memory_limit($memory_limit); $compressor->set_max_execution_time($max_execution_time); $compressor->set_pcre_backtrack_limit(1000 * $pcre_backtrack_limit); $compressor->set_pcre_recursion_limit(1000 * $pcre_recursion_limit); } // Compress the CSS code and store data $output = array(); $output['css'] = $compressor->run($_POST['css'], $linebreak_pos); $output['originalSize'] = mb_strlen($_POST['css'], '8bit'); $output['compressedSize'] = mb_strlen($output['css'], '8bit'); $output['bytesSaved'] = $output['originalSize'] - $output['compressedSize']; $output['compressionRatio'] = round($output['bytesSaved'] * 100 / ($output['originalSize'] === 0 ? 1 : $output['originalSize']), 2); // Output data echo json_encode($output); } else { ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>YUI CSS compressor - PHP</title> <link rel="stylesheet" type="text/css" href="third-party/bootstrap/css/bootstrap.min.css">
public function getcontent() { // restore IE hacks $this->content = $this->restore_iehacks($this->content); // restore comments $this->content = $this->restore_comments($this->content); // restore noscript if (strpos($this->content, '%%NOSCRIPT%%') !== false) { $this->content = preg_replace_callback('#%%NOSCRIPT%%(.*?)%%NOSCRIPT%%#is', create_function('$matches', 'return stripslashes(base64_decode($matches[1]));'), $this->content); } // restore noptimize $this->content = $this->restore_noptimize($this->content); //Restore the full content if (!empty($this->restofcontent)) { $this->content .= $this->restofcontent; $this->restofcontent = ''; } // Inject the new stylesheets $replaceTag = array("<title", "before"); $replaceTag = apply_filters('autoptimize_filter_css_replacetag', $replaceTag); if ($this->inline == true) { foreach ($this->csscode as $media => $code) { $this->inject_in_html('<style type="text/css" media="' . $media . '">' . $code . '</style>', $replaceTag); } } else { if ($this->defer == true) { $deferredCssBlock = "<script>function lCss(url,media) {var d=document;var l=d.createElement('link');l.rel='stylesheet';l.type='text/css';l.href=url;l.media=media; d.getElementsByTagName('head')[0].appendChild(l);}function deferredCSS() {"; $noScriptCssBlock = "<noscript>"; $defer_inline_code = $this->defer_inline; $defer_inline_code = apply_filters('autoptimize_filter_css_defer_inline', $defer_inline_code); if (!empty($defer_inline_code)) { $iCssHash = md5($defer_inline_code); $iCssCache = new autoptimizeCache($iCssHash, 'css'); if ($iCssCache->check()) { // we have the optimized inline CSS in cache $defer_inline_code = $iCssCache->retrieve(); } else { if (class_exists('Minify_CSS_Compressor')) { $tmp_code = trim(Minify_CSS_Compressor::process($this->defer_inline)); } else { if (class_exists('CSSmin')) { $cssmin = new CSSmin(); $tmp_code = trim($cssmin->run($defer_inline_code)); } } if (!empty($tmp_code)) { $defer_inline_code = $tmp_code; $iCssCache->cache($defer_inline_code, "text/css"); unset($tmp_code); } } $code_out = '<style type="text/css" media="all">' . $defer_inline_code . '</style>'; $this->inject_in_html($code_out, $replaceTag); } } foreach ($this->url as $media => $url) { $url = $this->url_replace_cdn($url); //Add the stylesheet either deferred (import at bottom) or normal links in head if ($this->defer == true) { $deferredCssBlock .= "lCss('" . $url . "','" . $media . "');"; $noScriptCssBlock .= '<link type="text/css" media="' . $media . '" href="' . $url . '" rel="stylesheet" />'; } else { $this->inject_in_html('<link type="text/css" media="' . $media . '" href="' . $url . '" rel="stylesheet" />', $replaceTag); } } if ($this->defer == true) { $deferredCssBlock .= "}if(window.addEventListener){window.addEventListener('DOMContentLoaded',deferredCSS,false);}else{window.onload = deferredCSS;}</script>"; $noScriptCssBlock .= "</noscript>"; $this->inject_in_html($noScriptCssBlock, array('<title>', 'before')); $this->inject_in_html($deferredCssBlock, array('</body>', 'before')); } } //Return the modified stylesheet return $this->content; }
/** * Build css from provided scss file in template assets */ public function buildSCSS() { /* Generate SCSS variables from properties */ $properties = $this->getProperties(); foreach ($properties as $key => $value) { if (is_string($value) && trim($value) != '') { $this->addSCSS('$' . $key . ": '" . $value . "';"); } } if (class_exists('scssc')) { $this->_css = $this->_scssphp->compile($this->_scss . "\n\r" . $this->_extraSCSS); } /* Do compress if required */ $config = CFactory::getConfig(); if ($config->get('compiler_css_compress', 0) == 1) { $cssMinFile = CFactory::getPath('jomsocial://libraries/vendor/cssmin/cssmin.php'); if ($cssMinFile) { require_once $cssMinFile; $cssMin = new CSSmin(); $this->_css = $cssMin->run($this->_css); } } return $this; }
/** * Minifies simplecache CSS and JS views by handling the "simplecache:generate" hook * * @param string $hook The name of the hook * @param string $type View type (css, js, or unknown) * @param string $content Content of the view * @param array $params Array of parameters * * @return string|null View content minified (if css/js type) * @access private */ function _elgg_views_minify($hook, $type, $content, $params) { if (preg_match('~[\\.-]min\\.~', $params['view'])) { // bypass minification return; } if ($type == 'js') { if (elgg_get_config('simplecache_minify_js')) { return JSMin::minify($content); } } elseif ($type == 'css') { if (elgg_get_config('simplecache_minify_css')) { $cssmin = new CSSmin(); return $cssmin->run($content); } } }
/** * Minify and concatenate CSS. * * @return string */ protected function pipelineCss($group = 'head') { /** @var Cache $cache */ $cache = self::getGrav()['cache']; $key = '?' . $cache->getKey(); // temporary list of assets to pipeline $temp_css = []; // clear no-pipeline assets lists $this->css_no_pipeline = []; $file = md5(json_encode($this->css) . $this->css_minify . $this->css_rewrite . $group) . '.css'; $relative_path = "{$this->base_url}{$this->assets_url}/{$file}"; $absolute_path = $this->assets_dir . $file; // If pipeline exist return it if (file_exists($absolute_path)) { return $relative_path . $key; } // Remove any non-pipeline files foreach ($this->css as $id => $asset) { if ($asset['group'] == $group) { if (!$asset['pipeline']) { $this->css_no_pipeline[$id] = $asset; } else { $temp_css[$id] = $asset; } } } //if nothing found get out of here! if (count($temp_css) == 0) { return false; } $css_minify = $this->css_minify; // If this is a Windows server, and minify_windows is false (default value) skip the // minification process because it will cause Apache to die/crash due to insufficient // ThreadStackSize in httpd.conf - See: https://bugs.php.net/bug.php?id=47689 if (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN' && !$this->css_minify_windows) { $css_minify = false; } // Concatenate files $buffer = $this->gatherLinks($temp_css, CSS_ASSET); if ($css_minify) { $min = new \CSSmin(); $buffer = $min->run($buffer); } // Write file if (strlen(trim($buffer)) > 0) { file_put_contents($absolute_path, $buffer); return $relative_path . $key; } else { return false; } }
public function getCssInline($htmlHeaders, $attributes) { $file = 'inline' . DIRECTORY_SEPARATOR . md5($attributes['value']) . '.css'; $completeFilePath = $this->config['BasePath'] . $this->config['PublicCacheDir'] . $file; if (!file_exists($completeFilePath)) { if (!is_dir(dirname($completeFilePath))) { mkdir(dirname($completeFilePath), 0777, true); } if ($this->config['CssMinify']) { $cssmin = new \CSSmin(); $attributes['value'] = $cssmin->run($attributes['value']); } if ($this->config['CssSpritify']) { $spritify = new Spritify($this->config); $attributes['value'] = $spritify->run($attributes['value']); } File::put_content($completeFilePath, $attributes['value']); } $attributes['href'] = Url::normalizeUrl($this->config['URIBasePath'] . $this->config['PublicCacheDir'] . $file); unset($attributes['value']); if (!$attributes['rel']) { $attributes['rel'] = 'stylesheet'; } if ($this->config['CSSSeparateInline']) { $attributes['media'] = $attributes['media'] ? $attributes['media'] . '_inline' : 'all_inline'; } return $attributes; }
public function parse_string($template, $data = array(), $return = FALSE, $options = array()) { if (!is_array($options)) { $options = array(); } $options = array_merge($this->config, $options); $ci = $this->ci; $is_mx = false; if (!$return) { list($ci, $is_mx) = $this->detect_mx(); } $options['raise_php_limits'] = !empty($options['raise_php_limits']); $parser = new CSSmin($options['raise_php_limits']); if ($options['raise_php_limits']) { if ($options['memory_limit'] != '') { $parser->set_memory_limit($options['memory_limit']); } if ($options['max_execution_time'] != '') { $parser->set_max_execution_time($options['max_execution_time']); } if ($options['pcre_backtrack_limit'] != '') { $parser->set_pcre_backtrack_limit($options['pcre_backtrack_limit']); } if ($options['pcre_recursion_limit'] != '') { $parser->set_pcre_recursion_limit($options['pcre_recursion_limit']); } } $template = $parser->run($template); return $this->output($template, $return, $ci, $is_mx); }
/** * Minify html code. * * @param ResponseInterface $response * * @return ResponseInterface */ protected function minifyHtml(ResponseInterface $response) { $options = ['jsCleanComments' => true]; if ($this->inlineCss) { $cssMinify = new CssMinify(); $options['cssMinifier'] = function ($css) use($cssMinify) { return $cssMinify->run($css); }; } if ($this->inlineJs) { $options['jsMinifier'] = function ($js) { return JsMinify::minify($js); }; } $stream = Middleware::createStream(); $stream->write(HtmlMinify::minify((string) $response->getBody(), $options)); return $response->withBody($stream); }
/** * Сжимает css YUICompressor * @param str $input_css КОД css * @return str min css. * $minicss = Dem::$i->cssmin( file_get_contents( DEMOC_URL . 'styles/' . Dem::$opt['css_file_name'] ) ); */ function cssmin($input_css) { require_once DEMOC_PATH . 'admin/cssmin.php'; $compressor = new CSSmin(); // Override any PHP configuration options before calling run() (optional) // $compressor->set_memory_limit('256M'); // $compressor->set_max_execution_time(120); return $compressor->run($input_css); }
public static function Minificar_JS_CSS() { if (file_exists(dirname(__FILE__) . '/Config/ArchivosMinify.php')) { include "CSSMin.php"; include "JSMin.php"; $MinDebug = "\n"; //$MinDebug = ""; $ArrayMin = (require dirname(__FILE__) . '/Config/ArchivosMinify.php'); $StringJS = ""; foreach ($ArrayMin["js"] as $Archivo) { $JSMin = new JSMin(file_get_contents(dirname(__FILE__) . $Archivo)); $StringJS .= $JSMin->min() . $MinDebug; } file_put_contents(dirname(__FILE__) . "/Cache/devildrey33.min.js", $StringJS); $StringCSS = ""; $CSSMin = new CSSmin(); foreach ($ArrayMin["css"] as $Archivo) { $StringCSS .= $CSSMin->run(file_get_contents(dirname(__FILE__) . $Archivo)); } file_put_contents(dirname(__FILE__) . "/Cache/devildrey33.min.css", $StringCSS); return "Cache actualizada!"; } else { error_log("<span style='color:red'>Error!</span> devildrey33::Minificar_JS_CSS -> el archivo '/Config/ArchivosMinify.php' no existe."); return "Error del servidor"; } }
/** * Simple CSS Minifier * https://github.com/GaryJones/Simple-PHP-CSS-Minification * @param $data Data string to minify */ protected function cssmin($css) { // Normalize whitespace //$css = preg_replace('/\s+/', ' ', $css); // Remove comment blocks, everything between /* and */, unless // preserved with /*! ... */ //$css = preg_replace('/\/\*[^\!](.*?)\*\//', '', $css); // Remove space after , : ; { } //$css = preg_replace('/(,|:|;|\{|}) /', '$1', $css); // Remove space before , ; { } //$css = preg_replace('/ (,|;|\{|})/', '$1', $css); // Strips leading 0 on decimal values (converts 0.5px into .5px) //$css = preg_replace('/(:| )0\.([0-9]+)(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}.${2}${3}', $css); // Strips units if value is 0 (converts 0px to 0) //$css = preg_replace('/(:| )(\.?)0(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}0', $css); // Converts all zeros value into short-hand //$css = preg_replace('/0 0 0 0/', '0', $css); // Shortern 6-character hex color codes to 3-character where possible //$css = preg_replace('/#([a-f0-9])\\1([a-f0-9])\\2([a-f0-9])\\3/i', '#\1\2\3', $css); require_once dirname(__FILE__) . '/cssmin.php'; $min = new CSSmin(false); $css = $min->run($css); return trim($css); }
/** * Minifiy and concatenate CSS files. * * @return string */ protected function cssPipeline() { return $this->pipeline($this->css, '.css', $this->css_dir, function ($buffer) { $min = new \CSSmin(); return $min->run($buffer); }); }
/** * Add asset */ function paf_asset($asset, $type, $block = FALSE) { // Trac files that are blocked in the futire static $blocked = array(); // Exit function if type is not supported if (!in_array($type, array('css', 'js'))) { return; } $js[] = 'paf'; $css[] = 'paf'; // Do nothing if asset not defined if (!in_array($asset, ${$type})) { return; } // Do nothing if already loaded if (in_array("{$type}/{$asset}", $blocked)) { return; } // Mark as blocked if needed if ($block) { $blocked[] = "{$type}/{$asset}"; } // Get source $src = dirname(__FILE__) . "/../assets/{$type}/{$asset}.{$type}"; $o = file_get_contents($src); // Minify source switch ($type) { case 'css': $CSSmin = new CSSmin(); $o = $CSSmin->run($o); case 'js': $o = JSMin::minify($o); } // Wrap in tags $o = sprintf('<%s>%s</%s>', 'css' === $type ? 'style' : 'script', $o, 'css' === $type ? 'style' : 'script'); // Output print $o; }
/** * (non-PHPdoc) * * @see \Core\Asset\ProcessorInterface::process() * */ public function process($content) { $min = new \CSSmin(); return $min->run($content); }
/** * Combine the given array of assets. Minify, if enabled. * Returns new array containing one asset. * * @param array $assets Array of assets. * @param string $type File type (script, style). * * @return array */ public function combine(array $assets, $type) { $paths = array(); $lastmod = 0; foreach ($assets as $asset) { $paths[] = $asset['path']; $mod = @File::lastModified($asset['path']); if ($mod > $lastmod) { $lastmod = $mod; } } if ($this->show_refer) { $file = $this->cache_path . '/casset-' . md5(implode(',', $paths) . $lastmod) . '-' . $this->name; } else { $file = $this->cache_path . '/' . md5(implode(',', $paths) . $lastmod); } $file .= 'script' === $type ? '.js' : '.css'; $combine = false; if (!File::exists($file)) { $combine = true; } else { if (File::lastModified($file) < $lastmod) { $combine = true; } } if ($combine) { $content = ''; foreach ($assets as $asset) { if (!File::exists($asset['path'])) { continue; } $c = File::get($asset['path']); if ($asset['ext'] == 'css' && preg_match_all('~url\\(([\\"\'^\\)]*)?([^\\)]*)([\\"\'^\\)]*)?\\)~i', $c, $match)) { foreach ($match[2] as $row => $link) { $link = UrlFormat::toAbsolute(asset($asset['url']), $link); $c = str_replace($match[0][$row], 'url("' . preg_replace('~^https?:~i', '', $link) . '")', $c); } } if ($this->minify && !(stripos($asset['source'], '.min') || stripos($asset['source'], '-min'))) { switch ($type) { case 'style': $min = new \CSSmin(); $c = $min->run($c); #$c = Compressors\Css::process($c); break; case 'script': $c = \JSMin::minify($c); #$c = Compressors\Js::minify($c); break; } } if ($this->show_refer) { $content .= "/* {$asset['source']} */\n{$c}\n\n"; } else { $content .= "/* --- */\n{$c}\n\n"; } } File::put($file, $content); } return array(array('path' => $file, 'attributes' => array(), 'url' => str_ireplace($this->public_path, '', $file))); }
/** * 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; }
/** * Here go all the actions that have to be performed right before document's HEAD has been rendered. */ function onBeforeCompileHead() { $app = JFactory::getApplication(); $document = JFactory::getDocument(); // Don't proceed when current template is not compatible with EF4 Framework or we are in the Joomla back-end if (empty($this->template) || $app->isAdmin()) { return true; } $params = $app->getTemplate(true)->params; // Handling Facebook's Open Graph if ((bool) $params->get('facebookOpenGraph', true)) { $fbAppId = $params->get('facebookOpenGraphAppID', false); $this->addOpenGraph($fbAppId); } // Removing obsolete CSS stylesheets $css_to_remove = $app->get('jm_remove_stylesheets', array()); if (!empty($css_to_remove) && is_array($css_to_remove)) { foreach ($document->_styleSheets as $url => $cssData) { foreach ($css_to_remove as $oursUrl => $replacement) { if (strpos($url, $oursUrl) !== false) { unset($document->_styleSheets[$url]); if ($replacement && is_array($replacement) && isset($replacement['url']) && isset($replacement['type'])) { switch ($replacement['type']) { case 'css': $document->addStyleSheet($replacement['url'], 'text/css'); break; case 'less': $document->addHeadLink($replacement['url'], 'stylesheet/less'); break; default: break; } } } } } $app->set('jm_remove_stylesheets', false); } // Don't compress CSS/JS when Development Mode or Joomla Debugging is enabled if ($params->get('devmode', 0) || JDEBUG || $app->input->get('option') == 'com_config') { return true; } // Preparing cache folder for CSS/JS compressed files if (JFolder::exists(JMF_TPL_PATH . DIRECTORY_SEPARATOR . 'cache') == false) { if (!JFolder::create(JMF_TPL_PATH . DIRECTORY_SEPARATOR . 'cache')) { if (JDEBUG) { throw new Exception(JText::_('PLG_SYSTEM_JMFRAMEWORK_CACHE_FOLDER_NOT_ACCESSIBLE')); } else { return false; } } } $cssCompress = $params->get('cssCompress', '0') == '1' ? true : false; $jsCompress = $params->get('jsCompress', '0') == '1' ? true : false; // Handling CSS minifications and compression. if ($cssCompress) { $styles = $document->_styleSheets; $compress = array(); $mtime = 0; foreach ($styles as $url => $style) { // Getting stylesheet path $path = $this->getPath($url); if (!$path || !JFile::exists($path)) { continue; } // Getting the last modification time of stylesheet $ftime = filemtime($path); if ($ftime > $mtime) { $mtime = $ftime; } $compress[$url] = $path; } $key = md5(serialize($compress)); $stylepath = JPath::clean(JMF_TPL_PATH . '/cache/jmf_' . $key . '.css'); $cachetime = JFile::exists($stylepath) ? filemtime($stylepath) : 0; $styleurl = JMF_TPL_URL . '/cache/jmf_' . $key . '.css?t=' . $cachetime; // Minify and merge stylesheets only if minified stylesheet isn't cached already or one of the stylesheets was modified if (!JFile::exists($stylepath) || $mtime > $cachetime) { require_once JPath::clean(JMF_FRAMEWORK_PATH . '/includes/libraries/minify/CSSmin.php'); $cssmin = new CSSmin(); $css = array(); $css[] = "/* Joomla-Monster EF4 Framework minify CSS"; $css[] = " * --------------------------------------- */"; foreach ($compress as $url => $path) { $src = JFile::read($path); $src = $this->updateUrls($src, dirname($url)); $css[] = "\n/* src: " . $url . " */"; $css[] = $cssmin->run($src, 1024); } $css = implode("\n", $css); JFile::write($stylepath, $css); } // Removing all merged stylesheets from the head and adding the minified stylesheet instead if (JFile::exists($stylepath)) { $newstyles = array(); $newstyles[$styleurl] = array('mime' => 'text/css', 'media' => null, 'attribs' => array()); foreach ($styles as $url => $data) { if (!array_key_exists($url, $compress)) { $newstyles[$url] = $data; } } $document->_styleSheets = $newstyles; } } // Handling JS minifications and compression. if ($jsCompress) { $scripts = $document->_scripts; $compress = array(); $mtime = 0; foreach ($scripts as $url => $script) { // Getting script path $path = $this->getPath($url); if (!$path || !JFile::exists($path)) { continue; } // Getting the last modification time of script $ftime = filemtime($path); if ($ftime > $mtime) { $mtime = $ftime; } $compress[$url] = $path; } $key = md5(serialize($compress)); $scriptpath = JPath::clean(JMF_TPL_PATH . '/cache/jmf_' . $key . '.js'); $cachetime = JFile::exists($scriptpath) ? filemtime($scriptpath) : 0; $scripturl = JMF_TPL_URL . '/cache/jmf_' . $key . '.js?t=' . $cachetime; // Minify and merge scripts only if minified script isn't cached already or one of the scripts was modified if (!JFile::exists($scriptpath) || $mtime > $cachetime) { require_once JPath::clean(JMF_FRAMEWORK_PATH . '/includes/libraries/minify/JSMin.php'); $js = array(); $js[] = "/* Joomla-Monster EF4 Framework minify JS"; $js[] = " * -------------------------------------- */"; foreach ($compress as $url => $path) { $src = JFile::read($path); $js[] = "\n/* src: " . $url . " */"; $js[] = JSMin::minify($src) . ";"; } $js = implode("\n", $js); JFile::write($scriptpath, $js); } // Removing all merged scripts from the head and adding the minified script instead if (JFile::exists($scriptpath)) { $newscripts = array(); $newscripts[$scripturl] = array('mime' => 'text/javascript', 'defer' => false, 'async' => false); foreach ($scripts as $url => $data) { if (!array_key_exists($url, $compress)) { $newscripts[$url] = $data; } } $document->_scripts = $newscripts; } } }
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; }
/** * Minify and concatenate CSS / JS files. * * @return string */ protected function pipeline($css = true) { /** @var Cache $cache */ $cache = self::getGrav()['cache']; $key = '?' . $cache->getKey(); if ($css) { $file = md5(json_encode($this->css) . $this->js_minify . $this->css_minify . $this->css_rewrite) . '.css'; foreach ($this->css as $id => $asset) { if (!$asset['pipeline']) { $this->css_no_pipeline[] = $asset; unset($this->css[$id]); } } } else { $file = md5(json_encode($this->js) . $this->js_minify . $this->css_minify . $this->css_rewrite) . '.js'; foreach ($this->js as $id => $asset) { if (!$asset['pipeline']) { $this->js_no_pipeline[] = $asset; unset($this->js[$id]); } } } $relative_path = "{$this->base_url}" . basename(ASSETS_DIR) . "/{$file}"; $absolute_path = ASSETS_DIR . $file; // If pipeline exist return it if (file_exists($absolute_path)) { return $relative_path . $key; } $css_minify = $this->css_minify; // If this is a Windows server, and minify_windows is false (default value) skip the // minification process because it will cause Apache to die/crash due to insufficient // ThreadStackSize in httpd.conf - See: https://bugs.php.net/bug.php?id=47689 if (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN' && !$this->css_minify_windows) { $css_minify = false; } // Concatenate files if ($css) { $buffer = $this->gatherLinks($this->css, CSS_ASSET); if ($css_minify) { $min = new \CSSmin(); $buffer = $min->run($buffer); } } else { $buffer = $this->gatherLinks($this->js, JS_ASSET); if ($this->js_minify) { $buffer = \JSMin::minify($buffer); } } // Write file file_put_contents($absolute_path, $buffer); return $relative_path . $key; }
return ''; } $pre_output = $match[0] . "\n" . $pre_output; return ''; }, $buf); } // Move the @import rules on top of the concatenated output. // Only @charset rule are allowed before them. if (false !== strpos($buf, '@import')) { $buf = preg_replace_callback('/(?P<pre_path>@import\\s+(?:url\\s*\\()?[\'"\\s]*)(?P<path>[^\'"\\s](?:https?:\\/\\/.+\\/?)?.+?)(?P<post_path>[\'"\\s\\)]*;)/i', function ($match) use($dirpath) { global $pre_output; if (0 !== strpos($match['path'], 'http') && '/' != $match['path'][0]) { $pre_output .= $match['pre_path'] . ($dirpath == '/' ? '/' : $dirpath . '/') . $match['path'] . $match['post_path'] . "\n"; } else { $pre_output .= $match[0] . "\n"; } return ''; }, $buf); } $buf = $css_minify->run($buf); } if ('application/x-javascript' == $mime_type) { $output .= "{$buf};\n"; } else { $output .= "{$buf}"; } } header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $last_modified) . ' GMT'); header('Content-Length: ' . (strlen($pre_output) + strlen($output))); header("Content-Type: {$mime_type}"); echo $pre_output . $output;
/** * Compile the asset collection and store in a cache file * * @return string Content of the cached file */ public function compile($uid = null) { $cache = $this->_getCacheFilePath($uid); if (is_file($cache)) { return file_get_contents($cache); } $content = ''; if ($this->_mime === 'text/css') { include_once FW_DIR . DS . "lib" . DS . 'vendor' . DS . "minify" . DS . "cssmin.php"; $compressor = new CSSmin(); } else { include_once FW_DIR . DS . "lib" . DS . 'vendor' . DS . "minify" . DS . "jsminplus.php"; } foreach ($this->_files as $file) { $tmp = $file['ext'] === 'less' ? $this->_getLess($file['path']) : file_get_contents($file['path']); if ($file['ext'] === 'css') { $tmp = $this->fixRelativePaths($tmp, $file['uri']); } if ($this->_options['minify'] == true && $file['minified'] == false) { $tmp = $this->_mime === 'text/css' ? $compressor->run($tmp) : JSMinPlus::minify($tmp); } $content .= $tmp . PHP_EOL; } if ($content === '') { return ''; } $content = $this->_checkGzip() ? gzencode($content) : $content; file_put_contents($cache, $content); touch($cache, $this->_timestamp); return $content; }
protected function writeCssFile($key) { $this->makeFilePath($this->filename[$key], $key); if (!file_exists($this->completeFilePath[$key])) { if (!is_dir(dirname($this->completeFilePath[$key]))) { mkdir(dirname($this->completeFilePath[$key]), 0777, true); } if ($this->config['CssMinify']) { $cssmin = new \CSSmin(); $this->content[$key] = $cssmin->run($this->content[$key]); } if ($this->config['CssSpritify']) { $spritify = new Spritify($this->config); $this->content[$key] = $spritify->run($this->content[$key]); } File::put_content($this->completeFilePath[$key], $this->content[$key]); } }
/** * Process asset content * * @param string $content * @return string */ public static function process($content) { $cssmin = new CSSmin(); return $cssmin->run($content); }