public function minify($inPath, $outPath) { global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength; $extension = $this->getExtension($inPath); $this->output(basename($inPath) . ' -> ' . basename($outPath) . '...'); $inText = file_get_contents($inPath); if ($inText === false) { $this->error("Unable to open file {$inPath} for reading."); exit(1); } $outFile = fopen($outPath, 'w'); if (!$outFile) { $this->error("Unable to open file {$outPath} for writing."); exit(1); } switch ($extension) { case 'js': $outText = JavaScriptMinifier::minify($inText, $this->getOption('js-statements-on-own-line', $wgResourceLoaderMinifierStatementsOnOwnLine), $this->getOption('js-max-line-length', $wgResourceLoaderMinifierMaxLineLength)); break; case 'css': $outText = CSSMin::minify($inText); break; default: $this->error("No minifier defined for extension \"{$extension}\""); } fwrite($outFile, $outText); fclose($outFile); $this->output(" ok\n"); }
/** * Create a redirect that is also valid CSS * * @param Title $destination * @param string $text ignored * @return CssContent */ public function makeRedirectContent(Title $destination, $text = '') { // The parameters are passed as a string so the / is not url-encoded by wfArrayToCgi $url = $destination->getFullURL('action=raw&ctype=text/css', false, PROTO_RELATIVE); $class = $this->getContentClass(); return new $class('/* #REDIRECT */@import ' . CSSMin::buildUrlValue($url) . ';'); }
public function minimizeFiles($files) { $css_out = ''; $webroot = (string) OC::$WEBROOT; foreach ($files as $file_info) { $file = $file_info[0] . '/' . $file_info[2]; $css_out .= '/* ' . $file . ' */' . "\n"; $css = file_get_contents($file); $in_root = false; foreach (OC::$APPSROOTS as $app_root) { if (strpos($file, $app_root['path'] . '/') === 0) { $in_root = rtrim($webroot . $app_root['url'], '/'); break; } } if ($in_root !== false) { $css = str_replace('%appswebroot%', $in_root, $css); $css = str_replace('%webroot%', $webroot, $css); } $remote = $file_info[1]; $remote .= '/'; $remote .= dirname($file_info[2]); $css_out .= CSSMin::remap($css, dirname($file), $remote, true); } if (!defined('DEBUG') || !DEBUG) { $css_out = CSSMin::minify($css_out); } return $css_out; }
/** * Combine multiple text assets into a single file for better http performance this * method generates a new cache file with every symfony cc you can override the cache * by adding ?clearassetcache=1 to the page request. * * @param type string css or js * @param namespace string the combined file namespace (eg. module+action names) * @param response object the sfWebResponse instance * @return string the url for the combiner service */ public function combine($type, $namespace, sfWebResponse $response) { //configure the combiner $type = $type === 'css' ? 'css' : 'js'; $fullname = $type === 'css' ? 'Stylesheets' : 'Javascripts'; $response_getter = 'get' . $fullname; $namespace = StreemeUtil::slugify($namespace); //integrate into symfony's asset globals sfConfig::set(sprintf('symfony.asset.%s_included', strtolower($fullname)), true); //build the cache filename - this file will be regenerated on a symfony cc $path = sprintf('%s/combine/%s/', sfConfig::get('sf_cache_dir'), $type); $filename = sprintf('%s.%s', $namespace, $type); // you can force a cache clear by passing ?clearassetcache=1 to any template if (!is_readable($path . $filename) || @$_GET['clearassetcache'] == 1) { //build one file of all of the css or js files $file_content = ''; //load vendor libraries for minifying assets require_once sfConfig::get('sf_lib_dir') . '/vendor/jsmin/jsmin.php'; require_once sfConfig::get('sf_lib_dir') . '/vendor/cssmin/cssmin.php'; foreach ($response->{$response_getter}() as $file => $options) { if ($type === 'css') { $file_content .= CSSMin::minify(file_get_contents(sfConfig::get('sf_web_dir') . $file)); } else { $file_content .= JSMin::minify(file_get_contents(sfConfig::get('sf_web_dir') . $file)); } } //this file resides in the cache and requires wide permissions for both cli and apache users @umask(00); @mkdir($path, 0777, true); file_put_contents($path . $filename, $file_content); } return sprintf('/service/combine/%s/%s', $type, str_replace('-', '_', $namespace)); }
function show_css($files) { global $root; $hash = ''; foreach ($files as $file) { $path = $root . '/' . $file . '.css'; $hash .= $file . filemtime($path); } $md5 = md5($hash); $cpath = $root . '/resources/c/' . $md5 . '.css'; if (!file_exists($cpath)) { require_once 'CSSMin.php'; $text = ''; foreach ($files as $file) { $path = $root . '/' . $file . '.css'; $text .= file_get_contents($path) . "\n\n"; } if (TEST) { $css = $text; } else { $css = CSSMin::minify($text); } file_put_contents($cpath, $css); } echo '<link rel="stylesheet" href="/resources/c/' . $md5 . '.css" />' . "\n"; }
function minify() { $this->setTemplate(get_template_path("empty")); if (!logged_user()->isAdministrator()) { die("You must be an administrator to run this tool."); } // include libraries include_once LIBRARY_PATH . '/jsmin/JSMin.class.php'; include_once LIBRARY_PATH . '/cssmin/CSSMin.class.php'; // process arguments $minify = isset($_GET['minify']); // process javascripts echo "Concatenating javascripts ... \n"; $files = (include "application/layouts/javascripts.php"); $jsmin = ""; foreach ($files as $file) { $jsmin .= file_get_contents("public/assets/javascript/{$file}") . "\n"; } echo "Done!<br>\n"; if ($minify) { echo "Minifying javascript ... \n"; $jsmin = JSMin::minify($jsmin); echo "Done!<br>\n"; } echo "Writing to file 'ogmin.js' ... "; file_put_contents("public/assets/javascript/ogmin.js", $jsmin); echo "Done!<br>"; echo "<br>"; // process CSS function changeUrls($css, $base) { return preg_replace("/url\\s*\\(\\s*['\"]?([^\\)'\"]*)['\"]?\\s*\\)/i", "url(" . $base . "/\$1)", $css); } function parseCSS($filename, $filebase, $imgbase) { $css = file_get_contents($filebase . $filename); $imports = explode("@import", $css); $cssmin = changeUrls($imports[0], $imgbase); for ($i = 1; $i < count($imports); $i++) { $split = explode(";", $imports[$i], 2); $import = trim($split[0], " \t\n\r\v'\""); $cssmin .= parseCSS($import, $filebase, $imgbase . "/" . dirname($import)); $cssmin .= changeUrls($split[1], $imgbase); } return $cssmin; } echo "Concatenating CSS ... "; $cssmin = parseCSS("website.css", "public/assets/themes/default/stylesheets/", "."); echo "Done!<br>"; if ($minify) { echo "Minifying CSS ... "; $cssmin = CSSMin::minify($cssmin); echo "Done!<br>"; } echo "Writing to file 'ogmin.css' ... "; file_put_contents("public/assets/themes/default/stylesheets/ogmin.css", $cssmin); echo "Done!<br>"; die; }
/** * Convert an image URI to a base64-encoded data URI. * * @par Example: * @code * .fancy-button { * background-image: embed('../images/button-bg.png'); * } * @endcode * @param array $frame * @param lessc $less * @return string */ public static function embed($frame, $less) { $base = pathinfo($less->parser->sourceName, PATHINFO_DIRNAME); $url = trim($less->compileValue($frame), '"\''); $file = realpath($base . '/' . $url); $data = CSSMin::encodeImageAsDataURI($file); $less->addParsedFile($file); return CSSMin::buildUrlValue($data); }
/** * Convert an image URI to a base64-encoded data URI. * * @par Example: * @code * .fancy-button { * background-image: embed('../images/button-bg.png'); * } * @endcode */ public static function embed($frame, $less) { $base = pathinfo($less->parser->sourceName, PATHINFO_DIRNAME); $url = $frame[2][0]; $file = realpath($base . '/' . $url); $data = CSSMin::encodeImageAsDataURI($file); $less->addParsedFile($file); return 'url(' . $data . ')'; }
/** * Get language-specific LESS variables for this module. * * @since 1.27 * @param ResourceLoaderContext $context * @return array */ protected function getLessVars(ResourceLoaderContext $context) { $vars = parent::getLessVars($context); $language = Language::factory($context->getLanguage()); foreach ($language->getImageFiles() as $key => $value) { $vars[$key] = CSSMin::serializeStringValue($value); } return $vars; }
/** * Get language-specific LESS variables for this module. * * @return array */ private function getLessVars(ResourceLoaderContext $context) { $language = Language::factory($context->getLanguage()); // This is very conveniently formatted and we can pass it right through $vars = $language->getImageFiles(); // less.php tries to be helpful and parse our variables as LESS source code foreach ($vars as $key => &$value) { $value = CSSMin::serializeStringValue($value); } return $vars; }
protected function optimize($data, $package, $type) { switch ($type) { case 'javascripts': $data = JSMin::minify($data); break; case 'stylesheets': $data = CSSMin::minify($data); break; } return $data; }
/** * @param $context ResourceLoaderContext * @return array */ public function getStyles(ResourceLoaderContext $context) { $logo = $this->getConfig()->get('Logo'); $logoHD = $this->getConfig()->get('LogoHD'); $styles = parent::getStyles($context); $styles['all'][] = '.mw-wiki-logo { background-image: ' . CSSMin::buildUrlValue($logo) . '; }'; if ($logoHD) { if (isset($logoHD['1.5x'])) { $styles['(-webkit-min-device-pixel-ratio: 1.5), ' . '(min--moz-device-pixel-ratio: 1.5), ' . '(min-resolution: 1.5dppx), ' . '(min-resolution: 144dpi)'][] = '.mw-wiki-logo { background-image: ' . CSSMin::buildUrlValue($logoHD['1.5x']) . ';' . 'background-size: 135px auto; }'; } if (isset($logoHD['2x'])) { $styles['(-webkit-min-device-pixel-ratio: 2), ' . '(min--moz-device-pixel-ratio: 2),' . '(min-resolution: 2dppx), ' . '(min-resolution: 192dpi)'][] = '.mw-wiki-logo { background-image: ' . CSSMin::buildUrlValue($logoHD['2x']) . ';' . 'background-size: 135px auto; }'; } } return $styles; }
function compress($string, $filetype = "php") { if ($filetype === "php") { $string = str_replace("<?php\r", "<?php ", $string); return str_replace(array("\r\n", "\r", "\n", "\t", " ", " ", " "), "", $string); } else { global $Load; if ($filetype === "css") { $Load->library("cssmin", null, null, "minify"); return CSSMin::minify($string); } elseif ($filetype === 'js') { $Load->library("jsmin", null, null, "minify"); return JSMin::minify($string); } } return null; }
/** * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls. * * Available filters are: * - minify-js \see JavaScriptMinifier::minify * - minify-css \see CSSMin::minify * * If $data is empty, only contains whitespace or the filter was unknown, * $data is returned unmodified. * * @param $filter String: Name of filter to run * @param $data String: Text to filter, such as JavaScript or CSS text * @return String: Filtered data, or a comment containing an error message */ protected function filter($filter, $data) { global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength; wfProfileIn(__METHOD__); // For empty/whitespace-only data or for unknown filters, don't perform // any caching or processing if (trim($data) === '' || !in_array($filter, array('minify-js', 'minify-css'))) { wfProfileOut(__METHOD__); return $data; } // Try for cache hit // Use CACHE_ANYTHING since filtering is very slow compared to DB queries $key = wfMemcKey('resourceloader', 'filter', $filter, self::$filterCacheVersion, md5($data)); $cache = wfGetCache(CACHE_ANYTHING); $cacheEntry = $cache->get($key); if (is_string($cacheEntry)) { wfProfileOut(__METHOD__); return $cacheEntry; } $result = ''; // Run the filter - we've already verified one of these will work try { switch ($filter) { case 'minify-js': $result = JavaScriptMinifier::minify($data, $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength); $result .= "\n/* cache key: {$key} */"; break; case 'minify-css': $result = CSSMin::minify($data); $result .= "\n/* cache key: {$key} */"; break; } // Save filtered text to Memcached $cache->set($key, $result); } catch (Exception $exception) { // Return exception as a comment $result = $this->makeComment($exception->__toString()); } wfProfileOut(__METHOD__); return $result; }
/** * Reads a style file. * * This method can be used as a callback for array_map() * * @param $path String: File path of style file to read * @param $flip bool * * @return String: CSS data in script file * @throws MWException if the file doesn't exist */ protected function readStyleFile($path, $flip) { $localPath = $this->getLocalPath($path); if (!file_exists($localPath)) { $msg = __METHOD__ . ": style file not found: \"{$localPath}\""; wfDebugLog('resourceloader', $msg); throw new MWException($msg); } $style = file_get_contents($localPath); if ($flip) { $style = CSSJanus::transform($style, true, false); } $dirname = dirname($path); if ($dirname == '.') { // If $path doesn't have a directory component, don't prepend a dot $dirname = ''; } $dir = $this->getLocalPath($dirname); $remoteDir = $this->getRemotePath($dirname); // Get and register local file references $this->localFileRefs = array_merge($this->localFileRefs, CSSMin::getLocalFileReferences($style, $dir)); return CSSMin::remap($style, $dir, $remoteDir, true); }
/** * 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) { static $autoload_registered; if (!$autoload_registered) { $path = elgg_get_root_path() . 'vendors/minify/lib'; elgg_get_class_loader()->addFallback($path); $autoload_registered = true; } 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); } } }
function pp_enqueue_front_page_scripts() { //enqueue frontend css files $pp_advance_combine_css = get_option('pp_advance_combine_css'); //If enable animation $pp_animation = get_option('pp_animation'); //Get theme cache folder $upload_dir = wp_upload_dir(); $cache_dir = ''; $cache_url = ''; if (isset($upload_dir['basedir'])) { $cache_dir = THEMEUPLOAD; } if (isset($upload_dir['baseurl'])) { $cache_url = THEMEUPLOADURL; } if (!empty($pp_advance_combine_css)) { if (!file_exists($cache_dir . "/combined.css")) { $cssmin = new CSSMin(); $css_arr = array(get_template_directory() . '/css/reset.css', get_template_directory() . '/css/wordpress.css', get_template_directory() . '/css/animation.css', get_template_directory() . '/css/magnific-popup.css', get_template_directory() . '/css/jqueryui/custom.css', get_template_directory() . '/js/mediaelement/mediaelementplayer.css', get_template_directory() . '/js/flexslider/flexslider.css', get_template_directory() . '/css/tooltipster.css', get_template_directory() . '/css/odometer-theme-minimal.css', get_template_directory() . '/css/hw-parallax.css', get_template_directory() . '/css/screen.css'); //If using child theme $pp_child_theme = get_option('pp_child_theme'); if (empty($pp_child_theme)) { $css_arr[] = get_template_directory() . '/css/screen.css'; } else { $css_arr[] = get_template_directory() . '/style.css'; } $cssmin->addFiles($css_arr); // Set original CSS from all files $cssmin->setOriginalCSS(); $cssmin->compressCSS(); $css = $cssmin->printCompressedCSS(); file_put_contents($cache_dir . "combined.css", $css); } wp_enqueue_style("combined_css", $cache_url . "combined.css", false, ""); } else { wp_enqueue_style("reset-css", get_template_directory_uri() . "/css/reset.css", false, ""); wp_enqueue_style("wordpress-css", get_template_directory_uri() . "/css/wordpress.css", false, ""); wp_enqueue_style("animation.css", get_template_directory_uri() . "/css/animation.css", false, "", "all"); wp_enqueue_style("magnific-popup", get_template_directory_uri() . "/css/magnific-popup.css", false, "", "all"); wp_enqueue_style("jquery-ui-css", get_template_directory_uri() . "/css/jqueryui/custom.css", false, ""); wp_enqueue_style("mediaelement", get_template_directory_uri() . "/js/mediaelement/mediaelementplayer.css", false, "", "all"); wp_enqueue_style("flexslider", get_template_directory_uri() . "/js/flexslider/flexslider.css", false, "", "all"); wp_enqueue_style("tooltipster", get_template_directory_uri() . "/css/tooltipster.css", false, "", "all"); wp_enqueue_style("odometer-theme", get_template_directory_uri() . "/css/odometer-theme-minimal.css", false, "", "all"); wp_enqueue_style("hw-parallax.css", get_template_directory_uri() . '/css/hw-parallax.css', false, "", "all"); wp_enqueue_style("screen.css", get_template_directory_uri() . '/css/screen.css', false, "", "all"); } //Check menu layout $tg_menu_layout = tg_menu_layout(); if ($tg_menu_layout == 'leftmenu') { wp_enqueue_style("leftmenu.css", get_template_directory_uri() . '/css/leftmenu.css', false, "", "all"); } //Add Font Awesome Support wp_enqueue_style("fontawesome", get_template_directory_uri() . "/css/font-awesome.min.css", false, "", "all"); if (THEMEDEMO && isset($_GET['menu']) && !empty($_GET['menu'])) { wp_enqueue_style("custom_css", get_template_directory_uri() . "/templates/custom-css.php?menu=" . $_GET['menu'], false, "", "all"); } else { wp_enqueue_style("custom_css", get_template_directory_uri() . "/templates/custom-css.php", false, "", "all"); } $tg_boxed = kirki_get_option('tg_boxed'); if (THEMEDEMO && isset($_GET['boxed']) && !empty($_GET['boxed'])) { $tg_boxed = 1; } if (!empty($tg_boxed) && $tg_menu_layout != 'leftmenu') { wp_enqueue_style("tg_boxed", get_template_directory_uri() . '/css/tg_boxed.css', false, "", "all"); } //If using child theme $pp_child_theme = get_option('pp_child_theme'); if (!empty($pp_child_theme)) { wp_enqueue_style('child_theme', get_stylesheet_directory_uri() . "/style.css", false, "", "all"); } //Get all Google Web font CSS global $tg_google_fonts; $tg_fonts_family = array(); if (is_array($tg_google_fonts) && !empty($tg_google_fonts)) { foreach ($tg_google_fonts as $tg_font) { $tg_fonts_family[] = kirki_get_option($tg_font); } } $tg_fonts_family = array_unique($tg_fonts_family); foreach ($tg_fonts_family as $key => $tg_google_font) { if (!empty($tg_google_font) && $tg_google_font != 'serif' && $tg_google_font != 'sans-serif' && $tg_google_font != 'monospace') { if (!is_ssl()) { wp_enqueue_style('google_font' . $key, "http://fonts.googleapis.com/css?family=" . urlencode($tg_google_font) . ":300,400,700,400italic&subset=latin,cyrillic-ext,greek-ext,cyrillic", false, "", "all"); } else { wp_enqueue_style('google_font' . $key, "https://fonts.googleapis.com/css?family=" . urlencode($tg_google_font) . ":300, 400,700,400italic&subset=latin,cyrillic-ext,greek-ext,cyrillic", false, "", "all"); } } } //Enqueue javascripts wp_enqueue_script("jquery"); $js_path = get_template_directory() . "/js/"; $js_arr = array('jquery.magnific-popup.js', 'jquery.easing.js', 'waypoints.min.js', 'jquery.isotope.js', 'jquery.masory.js', 'jquery.tooltipster.min.js', 'hw-parallax.js', 'custom_plugins.js', 'custom.js'); $js = ""; $pp_advance_combine_js = get_option('pp_advance_combine_js'); if (!empty($pp_advance_combine_js)) { if (!file_exists($cache_dir . "combined.js")) { foreach ($js_arr as $file) { if ($file != 'jquery.js' && $file != 'jquery-ui.js') { $js .= JSMin::minify(file_get_contents($js_path . $file)); } } file_put_contents($cache_dir . "combined.js", $js); } wp_enqueue_script("combined_js", $cache_url . "/combined.js", false, "", true); } else { foreach ($js_arr as $file) { if ($file != 'jquery.js' && $file != 'jquery-ui.js') { wp_enqueue_script($file, get_template_directory_uri() . "/js/" . $file, false, "", true); } } } }
/** * @dataProvider provideMediaStylesheets */ public function testStyleMedia($moduleName, $media, $filename, $css) { $cssText = CSSMin::minify($css->cssText); $this->assertTrue(strpos($cssText, '@media') === false, 'Stylesheets should not both specify "media" and contain @media'); }
/** * Run JavaScript or CSS data through a filter, caching the filtered result for future calls. * * Available filters are: * * - minify-js \see JavaScriptMinifier::minify * - minify-css \see CSSMin::minify * * If $data is empty, only contains whitespace or the filter was unknown, * $data is returned unmodified. * * @param string $filter Name of filter to run * @param string $data Text to filter, such as JavaScript or CSS text * @param string $cacheReport Whether to include the cache key report * @return string Filtered data, or a comment containing an error message */ public function filter($filter, $data, $cacheReport = true) { // For empty/whitespace-only data or for unknown filters, don't perform // any caching or processing if (trim($data) === '' || !in_array($filter, array('minify-js', 'minify-css'))) { return $data; } // Try for cache hit // Use CACHE_ANYTHING since filtering is very slow compared to DB queries $key = wfMemcKey('resourceloader', 'filter', $filter, self::$filterCacheVersion, md5($data)); $cache = wfGetCache(CACHE_ANYTHING); $cacheEntry = $cache->get($key); if (is_string($cacheEntry)) { wfIncrStats("rl-{$filter}-cache-hits"); return $cacheEntry; } $result = ''; // Run the filter - we've already verified one of these will work try { wfIncrStats("rl-{$filter}-cache-misses"); switch ($filter) { case 'minify-js': $result = JavaScriptMinifier::minify($data, $this->config->get('ResourceLoaderMinifierStatementsOnOwnLine'), $this->config->get('ResourceLoaderMinifierMaxLineLength')); if ($cacheReport) { $result .= "\n/* cache key: {$key} */"; } break; case 'minify-css': $result = CSSMin::minify($data); if ($cacheReport) { $result .= "\n/* cache key: {$key} */"; } break; } // Save filtered text to Memcached $cache->set($key, $result); } catch (Exception $e) { MWExceptionHandler::logException($e); wfDebugLog('resourceloader', __METHOD__ . ": minification failed: {$e}"); $this->errors[] = self::formatExceptionNoComment($e); } return $result; }
private static function applyFilter($filter, $data, Config $config) { switch ($filter) { case 'minify-js': return JavaScriptMinifier::minify($data); case 'minify-css': return CSSMin::minify($data); } return $data; }
/** * Get the data: URI that will produce this image. * * @param ResourceLoaderContext $context Any context * @param string|null $variant Variant to get the URI for * @param string $format Format to get the URI for, 'original' or 'rasterized' * @return string */ public function getDataUri(ResourceLoaderContext $context, $variant, $format) { $type = $this->getMimeType($format); $contents = $this->getImageData($context, $variant, $format); return CSSMin::encodeStringAsDataURI($contents, $type); }
/** * Reads a style file. * * This method can be used as a callback for array_map() * * @param string $path File path of style file to read * @param bool $flip * @param ResourceLoaderContext $context (optional) * * @return string CSS data in script file * @throws MWException If the file doesn't exist */ protected function readStyleFile($path, $flip, $context = null) { $localPath = $this->getLocalPath($path); $remotePath = $this->getRemotePath($path); if (!file_exists($localPath)) { $msg = __METHOD__ . ": style file not found: \"{$localPath}\""; wfDebugLog('resourceloader', $msg); throw new MWException($msg); } if ($this->getStyleSheetLang($localPath) === 'less') { $compiler = $this->getLessCompiler($context); $style = $this->compileLessFile($localPath, $compiler); $this->hasGeneratedStyles = true; } else { $style = file_get_contents($localPath); } if ($flip) { $style = CSSJanus::transform($style, true, false); } $localDir = dirname($localPath); $remoteDir = dirname($remotePath); // Get and register local file references $localFileRefs = CSSMin::getAllLocalFileReferences($style, $localDir); foreach ($localFileRefs as $file) { if (file_exists($file)) { $this->localFileRefs[] = $file; } else { $this->missingLocalFileRefs[] = $file; } } return CSSMin::remap($style, $localDir, $remoteDir, true); }
private function generate_file($files = array(), $file_name, $file_type = 'css', $type = '') { if (count($files) == 0) { // While the file wasn't actually created, // there weren't any errors, either. return true; } // Where to save the combined file to. $cache_path = $_SERVER['DOCUMENT_ROOT'] . '/' . self::$asset_base . '/' . self::$asset_cache_folder . '/'; // full file path - without the extension $file_path = $cache_path . $file_name; if (self::$ci->config->item("assets.{$type}_minify")) { $file_path .= ".min"; } $file_path .= "." . $file_type; $modified_time = 0; // Holds the last modified date of all included files. $actual_file_time = 0; // The modified time of the combined file. // If the combined file already exists, // we need to grab the last modified time. if (is_file($file_path)) { $actual_file_time = filemtime($file_path); } foreach ($files as $key => $file) { // Javascript if ($file_type == 'js') { if (is_array($file)) { $app_file = $file['server_path']; } else { $app_file = $_SERVER['DOCUMENT_ROOT'] . '/' . str_replace(base_url(), '', $file); } $app_file = strpos($app_file, '.js') ? $app_file : $app_file . '.js'; $files_array[$key] = $app_file; } else { $app_file = $file['server_path']; $files_array[$key] = $app_file; } if ($file == 'global') { $files_array[$key] = $app_file; } // By this point, we already know that the files exist, // so just grab the modified time. $modified_time = max(filemtime($app_file), $modified_time); } $asset_output = ''; if ($actual_file_time < $modified_time) { // write to the file foreach ($files_array as $key => $file) { $file_output = file_get_contents($file); if (!empty($file_output)) { $asset_output .= $file_output . "\n"; } } switch ($file_type) { case 'js': if (config_item('assets.js_minify')) { $asset_output = JSMin::minify($asset_output); } break; case 'css': if (config_item('assets.css_minify')) { $asset_output = CSSMin::minify($asset_output); } break; default: throw new LoaderException("Unknown file type - {$file_type}."); break; } self::$ci->load->helper('file'); if (!is_dir($cache_path)) { @mkdir($cache_path); } if (!write_file($file_path, $asset_output)) { return FALSE; } } elseif ($actual_file_time == 0) { return FALSE; } return TRUE; }
require_once dirname(__FILE__) . '/css/default/full.css'; foreach ($custom as $dir) { if (file_exists(dirname(__FILE__) . '/css/' . $dir . '/full.css')) { include_once dirname(__FILE__) . '/css/' . $dir . '/full.css'; } } } /** * Load custom CSS files (minified) based on user agent. */ if (isset($_GET['basic'])) { foreach (explode(' ', $_GET['basic']) as $file) { if (Path_Validator::is_safe($file, 'css') && ($contents = Path::get_contents($file))) { echo ' ' . CSSMin::minify($contents); } } } if (User_Agent::is_standard() && isset($_GET['standard'])) { foreach (explode(' ', $_GET['standard']) as $file) { if (Path_Validator::is_safe($file, 'css') && ($contents = Path::get_contents($file))) { echo ' ' . CSSMin::minify($contents); } } } if (User_Agent::is_full() && isset($_GET['full'])) { foreach (explode(' ', $_GET['full']) as $file) { if (Path_Validator::is_safe($file, 'css') && ($contents = Path::get_contents($file))) { echo ' ' . CSSMin::minify($contents); } } }
private static function applyFilter($filter, $data) { $data = trim($data); if ($data) { try { $data = $filter === 'minify-css' ? CSSMin::minify($data) : JavaScriptMinifier::minify($data); } catch (Exception $e) { MWExceptionHandler::logException($e); return null; } } return $data; }
/** * Minify CSS * * @uses __construct() * @uses min() * @param string $js Javascript to be minified * @return string */ public static function go($css) { $cssmin = new CSSMin(); return $cssmin->run($css); }
/** * @param $context ResourceLoaderContext * @return array */ public function getStyles(ResourceLoaderContext $context) { global $wgScriptPath; $styles = array(); foreach ($this->getPages($context) as $titleText => $options) { if ($options['type'] !== 'style') { continue; } $title = Title::newFromText($titleText); if (!$title || $title->isRedirect()) { continue; } $media = isset($options['media']) ? $options['media'] : 'all'; $style = $this->getContent($title); if (strval($style) === '') { continue; } if ($this->getFlip($context)) { $style = CSSJanus::transform($style, true, false); } $style = CSSMin::remap($style, false, $wgScriptPath, true); if (!isset($styles[$media])) { $styles[$media] = array(); } if (strpos($titleText, '*/') === false) { $style = "/* {$titleText} */\n" . $style; } $styles[$media][] = $style; } return $styles; }
/** * Reads a style file. * * This method can be used as a callback for array_map() * * @param $path String: File path of style file to read * @param $flip bool * * @return String: CSS data in script file * @throws MWException if the file doesn't exist */ protected function readStyleFile($path, $flip, ResourceLoaderContext $context) { $localPath = $this->getLocalPath($path); if (!file_exists($localPath)) { throw new MWException(__METHOD__ . ": style file not found: \"{$localPath}\""); } // Wikia - change begin - @author: wladek $style = self::getFileContents($localPath, $context); // Wikia - change end if ($flip) { $style = CSSJanus::transform($style, true, false); } $dirname = dirname($path); if ($dirname == '.') { // If $path doesn't have a directory component, don't prepend a dot $dirname = ''; } $dir = $this->getLocalPath($dirname); $remoteDir = $this->getRemotePath($dirname, $context); // Get and register local file references $this->localFileRefs = array_merge($this->localFileRefs, CSSMin::getLocalFileReferences($style, $dir)); return CSSMin::remap($style, $dir, $remoteDir, true, $this->localBasePath); }
private static function applyFilter($filter, $data, Config $config) { switch ($filter) { case 'minify-js': return JavaScriptMinifier::minify($data, $config->get('ResourceLoaderMinifierStatementsOnOwnLine'), $config->get('ResourceLoaderMinifierMaxLineLength')); case 'minify-css': return CSSMin::minify($data); } return $data; }
/** * Reads a style file. * * This method can be used as a callback for array_map() * * @param string $path File path of style file to read * @param bool $flip * @param ResourceLoaderContext $context * * @return string CSS data in script file * @throws MWException If the file doesn't exist */ protected function readStyleFile($path, $flip, $context) { $localPath = $this->getLocalPath($path); $remotePath = $this->getRemotePath($path); if (!file_exists($localPath)) { $msg = __METHOD__ . ": style file not found: \"{$localPath}\""; wfDebugLog('resourceloader', $msg); throw new MWException($msg); } if ($this->getStyleSheetLang($localPath) === 'less') { $style = $this->compileLessFile($localPath, $context); $this->hasGeneratedStyles = true; } else { $style = file_get_contents($localPath); } if ($flip) { $style = CSSJanus::transform($style, true, false); } $localDir = dirname($localPath); $remoteDir = dirname($remotePath); // Get and register local file references $localFileRefs = CSSMin::getLocalFileReferences($style, $localDir); foreach ($localFileRefs as $file) { if (file_exists($file)) { $this->localFileRefs[] = $file; } else { $this->missingLocalFileRefs[] = $file; } } // Don't cache this call. remap() ensures data URIs embeds are up to date, // and urls contain correct content hashes in their query string. (T128668) return CSSMin::remap($style, $localDir, $remoteDir, true); }