/** * Function to simplify replacements of absolute vs. relative paths when using magicmin * * @access public * @param string $output_filename * @param array $files * @param string $output_directory (just the 'css', 'js' etc... bit) * @param string $type (js, css) * @return string */ function magic_min_merge($output_filename, $files = array(), $output_directory = 'css') { if (empty($files)) { return ''; } require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'class.magic-min.php'; $output_type = strtolower(pathinfo(basename($output_filename), PATHINFO_EXTENSION)); $minified = new Minifier(array('closure' => true, 'echo' => false, 'timer' => false, 'hashed_filenames' => true, 'remove_comments' => true)); switch ($output_type) { case 'css': return '<link rel="stylesheet" href="' . $minified->merge($output_directory . '/' . $output_filename, $output_directory, $files, $output_type) . '" />' . PHP_EOL; break; case 'js': default: return '<script src="' . $minified->merge($output_directory . '/' . $output_filename, $output_directory, $files, $output_type) . '"></script>' . PHP_EOL; break; } }
public static function minify($js, $options = array()) { try { ob_start(); $jshrink = new Minifier(); $js = $jshrink->lock($js); $jshrink->minifyDirectToOutput($js, $options); // Sometimes there's a leading new line, so we trim that out here. $js = ltrim(ob_get_clean()); $js = $jshrink->unlock($js); unset($jshrink); return $js; } catch (\Exception $e) { if (isset($jshrink)) { // Since the breakdownScript function probably wasn't finished // we clean it out before discarding it. $jshrink->clean(); unset($jshrink); } // without this call things get weird, with partially outputted js. ob_end_clean(); throw $e; } }
public static function renderCss($position = 'header', $app = 'front') { $_css = self::sortCssByPriority(); $compress_array = array(); $stylesheet = ''; if (is_array($_css)) { foreach ($_css as $p => $__css) { if (is_array($__css)) { foreach ($__css as $css) { if ($position == 'header' && $css['options'] && $css['options']['position'] == 'footer') { continue; } else { if ($position != 'header' && (!$css['options'] || $css['options']['position'] != 'footer')) { continue; } } if ($css['options'] && $css['options']['condition']) { $stylesheet .= "\t<!--[" . $css['options']['condition'] . "]>\n\t"; } switch ($css['type']) { case 'source': $stylesheet .= "\t" . '<style id="' . $css['id'] . '"' . ($css['options'] && $css['options']['class'] ? ' class="' . $css['options']['class'] . '"' : '') . ' type="text/css">' . "\n\t\t" . $css['css'] . "\n\t</style>\n"; break; case 'src': default: if (DEBUG_MODE == false && $css['options']['compress'] == true) { $compress_path_str .= $css['css']; if (ROOT == '.') { $compress_array[] = ltrim($css['css'], CADB_URI); } else { $compress_array[] = ltrim($css['css'], '/'); } } else { $stylesheet .= "\t" . '<link id="' . $css['id'] . '"' . ($css['options'] && $css['options']['class'] ? ' class="' . $css['options']['class'] . '"' : '') . ' rel="stylesheet" href="' . $css['css'] . '">' . "\n"; } break; } if ($css['options'] && $css['options']['condition']) { $stylesheet .= "\t<![endif]-->\n"; } } } } } if (@count($compress_array) > 0) { $compress_file = CADB_CACHE_PATH . "/compress/" . hash('md5', $compress_path_str) . ".css"; $compress_uri = CADB_DATA_URI . "/cache/compress/" . hash('md5', $compress_path_str) . ".css.php"; if (!file_exists(CADB_CACHE_PATH)) { mkdir(CADB_CACHE_PATH, 0707); chmod(CADB_CACHE_PATH, 0707); } if (!file_exists(CADB_CACHE_PATH . "/compress")) { mkdir(CADB_CACHE_PATH . "/compress", 0707); chmod(CADB_CACHE_PATH . "/compress", 0707); } $vars = array('encode' => true, 'timer' => true, 'gzip' => true, 'closure' => true, 'echo' => false, 'remove_comments' => true); $minified = new \Minifier($vars); $stylesheet .= "\t" . '<link id="cadb_css_' . self::getUniqueID($compress_uri) . '" rel="stylesheet" href="' . CADB_URI . ltrim($minified->merge($compress_file, 'css', $compress_array), CADB_PATH) . '">' . "\n"; } return $stylesheet; }
if ($action_get == "config") { echo json_encode($config); } if ($action_get == "set-config") { $receivedConfig = filter_input(INPUT_GET, "receivedConfig"); $config->updateConfigFile($receivedConfig); echo json_encode(array("response" => "OKAY")); exit; } if ($action_get == "minify") { try { $inputID = filter_input(INPUT_GET, "inputID"); if ($inputID) { $input = LittleHelpers::getObjectFromArray($config->inputs, "inputID", $inputID); $inputFile = $input->inputFile; $htmlString = file_get_contents($inputFile); // deaktiviert das Anzeigen von Warnungen error_reporting(E_ERROR | E_PARSE); $dom = new DOMDocument(); $dom->loadHTML($htmlString); $minifier = new Minifier(); $codes = [Minifier::minifyAndSave("css", $dom, $input, $minifier), Minifier::minifyAndSave("js", $dom, $input, $minifier)]; $status_code = max($codes); http_response_code($status_code); echo json_encode(array("CSS" => $codes[0], "JS" => $codes[1])); } } catch (Exception $ex) { echo 'Exception abgefangen: ', $ex->getMessage(), "\n"; } exit; }
protected function jsParser() { require_once 'include/jssource/Minifier.php'; return Minifier::minify($this->text); }
public function renderJsCritical() { $config = $this->getPresenter()->context->parameters['scriptLoader']['js']; if (!$this->getPresenter()->context->parameters['scriptLoader']['enable']) { foreach ($config['critical'] as $js) { echo '<script src="/' . $js . '"></script>'; } } else { $cache = new Cache($this->getPresenter()->storage, 'scriptLoader'); $jsFile = $cache->load('javascript-critical'); if (is_null($jsFile)) { //zminimalizuju $jsFile = ''; $jsFiles = array(); foreach ($config['critical'] as $js) { $jsFile .= Minifier::minify(file_get_contents($this->getPresenter()->context->parameters['wwwDir'] . '/' . $js), array('flaggedComments' => false)); $jsFiles[] = $this->getPresenter()->context->parameters['wwwDir'] . '/' . $js; } $cache->save('javascript-critical', $jsFile, array(Cache::FILES => $jsFiles)); } echo '<script type="text/javascript">' . $jsFile . '</script>'; } }
function minify($type, $files, $excludes) { if (!in_array($type, array('css', 'js'))) { return $files; } //extract local fylesystem path clean_file_paths($files, $excludes); global $registry; $oc_root = dirname(DIR_APPLICATION); $cache = NULL; $cachefile = NULL; $filename = NULL; if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); } if (!file_exists($oc_root . DS . 'assets')) { mkdir($oc_root . DS . 'assets'); } if (!file_exists($oc_root . DS . 'assets' . DS . $type)) { mkdir($oc_root . DS . 'assets' . DS . $type); } $cachefile = $oc_root . DS . 'assets' . DS . $type . DS . getSSLCachePrefix() . $type . '.cache'; if (!file_exists($cachefile)) { touch($cachefile); file_put_contents($cachefile, json_encode(array())); } $cache = json_decode(file_get_contents($cachefile), true); switch ($type) { case 'js': include_once NITRO_LIB_FOLDER . 'minifier' . DS . 'JSShrink.php'; break; case 'css': if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == '1')) { $webshopUrl = $registry->get('config')->get('config_ssl'); } else { $webshopUrl = $registry->get('config')->get('config_url'); } $webshopUrl = rtrim(preg_replace('~^https?\\:~i', '', $webshopUrl), '/'); include_once NITRO_LIB_FOLDER . 'minifier' . DS . 'CSSMin.php'; break; } foreach ($files as $hash => $file) { $recache = false; if (!is_excluded_file($file, $excludes)) { $filename = $oc_root . DS . trim(str_replace('/', DS, $file), DS); $basefilename = basename($file, '.' . $type); $target = '/assets/' . $type . '/' . getSSLCachePrefix() . 'nitro-mini-' . encode_filename($filename) . '.' . $type; $targetAbsolutePath = $oc_root . DS . trim(str_replace('/', DS, $target), DS); if (!empty($cache[$filename])) { if (!is_url($file) && $cache[$filename] != filemtime($filename)) { $recache = true; } } else { $recache = true; } if ($recache || !file_exists($targetAbsolutePath)) { touch($targetAbsolutePath); $content = is_url($file) ? fetchRemoteContent($file) : file_get_contents($filename); switch ($type) { case 'js': $content = Minifier::minify($content, array('flaggedComments' => false)); break; case 'css': $urlToCurrentDir = is_url($file) ? dirname($file) : $webshopUrl . dirname('/' . trim($file, '/')); $content = preg_replace('/(url\\()(?![\'\\"]?(?:(?:https?\\:\\/\\/)|(?:data\\:)|(?:\\/)))([\'\\"]?)\\/?(?!\\/)/', '$1$2' . $urlToCurrentDir . '/', $content); $content = Nitro_Minify_CSS_Compressor::process($content); break; } file_put_contents($targetAbsolutePath, $content); $cache[$filename] = is_url($file) ? time() : filemtime($filename); } $files[$hash] = trim($target, '/'); } } file_put_contents($cachefile, json_encode($cache)); return $files; }
/** * Minifier::minify takes a string containing javascript and removes * unneeded characters in order to shrink the code without altering it's * functionality. */ public static function minify($js, $options = array()) { try { ob_start(); $currentOptions = array_merge(self::$defaultOptions, $options); if (!isset(self::$jshrink)) { self::$jshrink = new Minifier(); } self::$jshrink->breakdownScript($js, $currentOptions); return ob_get_clean(); } catch (Exception $e) { if (isset(self::$jshrink)) { self::$jshrink->clean(); } ob_end_clean(); throw $e; } }
private function get_script_string($type = 'css') { switch ($type) { case 'css': $farray = array_merge($this->css, $this->appcss); $opentag = "\t\t<link rel=\"stylesheet\" href=\""; $closetag = "\">\n"; $cache_file = $this->compiledcss; break; case 'js': $farray = array_merge($this->javascript, $this->appjs); $opentag = "\t\t<script src=\""; $closetag = "\"></script>\n"; $cache_file = $this->compiledjs; break; } $script_string = ''; if ($this->status == 0) { foreach ($farray as $f) { if (filter_var($f, FILTER_VALIDATE_URL) === FALSE) { $script_string .= $opentag . base_url() . $type . "/" . $f . $closetag; } else { $script_string .= $opentag . $f . $closetag; } } } elseif ($this->status == 1) { //minify just local js/css, remote/CDN js have to be added directly on main template foreach ($farray as $k => $f) { if (filter_var($f, FILTER_VALIDATE_URL) === FALSE) { $local[] = $f; } else { //$remote[]=$f; } } $minify = new Minifier(); $minify->compress($local, $type . "_cache/" . $cache_file, $type); $script_string = $opentag . base_url() . $type . "_cache/" . $cache_file . $closetag; } return $script_string; }
mkdir('../dist'); } if (!is_dir('../dist/images')) { mkdir('../dist/images'); } if (!is_dir('../dist/src')) { mkdir('../dist/src'); } copy('../LICENSE.txt', '../dist/LICENSE.txt'); copy('../proxy.php', '../dist/proxy.php'); copy('../github.com/Dominique92/Leaflet.MapMultiCRS/swiss.html', '../dist/src/swiss.html'); // Script de test des couches SwissTopo file_put_contents('../dist/src/leaflet.css', '@import url("../leaflet.css");'); file_put_contents('../dist/READ.ME', "For production, include:\n<link type=\"text/css\" rel=\"stylesheet\" href=\"leaflet.css\" />\n<script type=\"text/javascript\" src=\"leaflet.js\"></script>\n\nFor debug, include:\n<link type=\"text/css\" rel=\"stylesheet\" href=\"leaflet.css\" />\n<script type=\"text/javascript\" src=\"src/leaflet.js\"></script>\n\nDo not modify the files of this directory:\nthe source of this software is available at : https://github.com/Dominique92/MyLeaflet\n"); // On compresse les librairies $minified = new Minifier(array('encode' => false, 'timer' => false, 'gzip' => false, 'closure' => false, 'remove_comments' => true, 'echo' => false, 'create_new' => true)); preg_match_all('/\\("\\.\\.\\/([a-zA-Z0-9\\-\\/\\.]+)"\\)/', file_get_contents('../src/leaflet.css'), $css_list); $minified->merge('../dist/leaflet.css', '', $css_list[1]); preg_match_all('/\'\\.\\.\\/([a-zA-Z0-9\\-\\/\\.]+)\',/', file_get_contents('../src/leaflet.js'), $js_list); $minified->merge('../dist/leaflet.js', '', $js_list[1]); // Mise à jour pluggins Dominique92 foreach (glob('../github.com/Dominique92/*/*') as $f) { $fs = explode('/', $f); if (is_dir('../../' . $fs[3])) { copy($f, '../../' . $fs[3] . '/' . $fs[4]); echo '<br/>copy ' . $f . ' to ../../' . $fs[3] . '/' . $fs[4]; } } ?> <p>FIN</p> <p><a href=".">RELANCER BUILD</a></p>
public function minify($code) { //---------------------------------------------------------- //init var //---------------------------------------------------------- $chk = array("bool" => true, 'traceID' => "minJs"); //---------------------------------------------------------- if (strpos($this->fileName, "js") !== false) { $content = Minifier::minify($code); } else { if (strpos($this->fileName, "css") !== false) { $content = CssMin::minify($code); } else { if (strpos($this->fileName, "html") !== false) { $content = $code; } } } //---------------------------------------------------------- $chk['result'] = $content; //---------------------------------------------------------- if (is_null($fileLocation)) { $chk['message'] = "code has been successfully minified!!!!!"; } //---------------------------------------------------------- $chk = CreateFile_v0::go($this->fileName, $content, $this->fileLocation, true); //---------------------------------------------------------- Minifier_v0::createDependantFiles($content); //---------------------------------------------------------- return $chk; }
private function minify($assets, $dir) { $css_to_minify = array(); $js_to_minify = array(); foreach ($assets as $asset) { // Don't minify direct assets if (isset($asset['direct']) && $asset['direct']) { continue; } // Only minify public assets if (!isset($asset['public']) || !$asset['public']) { continue; } switch (strtolower($asset['type'])) { case 'css': $css_to_minify[] = $asset['dir']; break; case 'js': $js_to_minify[] = $asset; break; } } $minify_files = array(); /** * CSS minification */ // CSS without base $minify_files[] = array('name' => 'wpurp-public-without-base.css', 'files' => array_unique($css_to_minify)); // CSS with normal base array_unshift($css_to_minify, WPUltimateRecipe::get()->coreDir . '/css/layout_base.css'); $minify_files[] = array('name' => 'wpurp-public.css', 'files' => array_unique($css_to_minify)); // CSS with forced base $css_to_minify[0] = WPUltimateRecipe::get()->coreDir . '/css/layout_base_forced.css'; $minify_files[] = array('name' => 'wpurp-public-forced.css', 'files' => array_unique($css_to_minify)); /** * JS minification */ // Get all the named JS files $js_names = array(); foreach ($js_to_minify as $js) { if (isset($js['name'])) { $js_names[] = $js['name']; } } // Order JS files (max 20 loops) $js_minify_order = array(); $js_ordered_names = array(); for ($i = 0; $i < 20; $i++) { foreach ($js_to_minify as $index => $js) { // Check which dependencies we need to actually resolve right now $actual_deps = array(); if (isset($js['deps'])) { foreach ($js['deps'] as $dep) { if (in_array($dep, $js_names) && !in_array($dep, $js_ordered_names)) { $actual_deps[] = $dep; } } } if (count($actual_deps) == 0) { $js_minify_order[] = $js['dir']; if (isset($js['name'])) { $js_ordered_names[] = $js['name']; } unset($js_to_minify[$index]); } } } if (count($js_to_minify) > 0) { var_dump('WP Ultimate Recipe: JS minification problem'); } $minify_files[] = array('name' => 'wpurp-public.js', 'files' => array_unique($js_minify_order)); /** * Performing the minification */ require_once WPUltimateRecipe::get()->coreDir . '/vendor/magic-min/class.magic-min.php'; $minified = new Minifier(array('echo' => false, 'gzip' => false)); foreach ($minify_files as $minify_file) { // Remove current file (easier while developing) if (is_file($dir . $minify_file['name'])) { unlink($dir . $minify_file['name']); } // Minify $minified->merge($dir . $minify_file['name'], '', $minify_file['files']); } }
<?php include 'image.php'; $img = new Resize_img(); //error_reporting(-1); //ini_set('display_errors', 1); require 'class.magic-min.php'; //Default usage will echo from function calls and leave images untouched $minified = new Minifier(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <title>Carousel Template for Bootstrap</title> <link href="<?php $minified->minify('./stylesheets/bootstrap.css'); ?> " rel="stylesheet" /> <link href="<?php $minified->minify('./stylesheets/carousel.css'); ?> " rel="stylesheet" /> <link href="<?php $minified->minify('./stylesheets/hello.css'); ?>
function minify_js($js) { include 'support/Minifier.php'; return Minifier::minify($js); }
/** * Minimize css files * * @return void */ public function minimize($id_theme, $name) { $msg = null; // check permission $msg = AdmUtils_helper::chk_priv_level($_SESSION['xuid'], 'themes', $id_theme, 4); if (is_null($msg)) { $qs = X4Route_core::get_query_string(); // do action $res = 1; // get the templates in the theme $mod = new Theme_model(); // CSS section $path = PATH . 'themes/' . $name . '/css/'; $items = $mod->get_css($id_theme); foreach ($items as $i) { if (file_exists($path . $i->css . '.css')) { $txt = file_get_contents($path . $i->css . '.css'); $txt = $mod->compress_css($txt); $chk = file_put_contents($path . $i->css . '.min.css', $txt); if (!$chk) { $res = 0; } } } // JS section X4Core_core::auto_load('jshrink_library'); $path = PATH . 'themes/' . $name . '/js/'; $items = $mod->get_js($id_theme); foreach ($items as $i) { if (file_exists($path . $i->js . '.js')) { $txt = file_get_contents($path . $i->js . '.js'); $txt = Minifier::minify($txt, array('flaggedComments' => false)); $chk = file_put_contents($path . $i->js . '.min.js', $txt); if (!$chk) { $res = 0; } } } $result = array(0, $res); // set message $this->dict->get_words(); $msg = AdmUtils_helper::set_msg($result); // set update if ($result[1]) { $msg->update[] = array('element' => $qs['div'], 'url' => urldecode($qs['url']), 'title' => null); } } $this->response($msg); }
/** * Minify Javascript. * * @param string $js Javascript to be minified * * @return string */ public static function minify($js) { $Minifier = new Minifier($js); return $Minifier->min(); }
public static $clean = array('\\(\\s*([^;)]*)\\s*;\\s*([^;)]*)\\s*;\\s*([^;)]*)\\)' => '($1;$2;$3)', 'throw[^};]+[};]' => RegGrp::IGNORE, ';+\\s*([};])' => '$1'); public static $comments = array(';;;[^\\n]*\\n' => '', '(COMMENT1)(\\n\\s*)(REGEXP)?' => '$3$4', '(COMMENT2)\\s*(REGEXP)?' => array(__CLASS__, '_commentParser')); public static function _commentParser($match, $comment = '', $dummy = '', $regexp = '') { if (preg_match('/^\\/\\*@/', $comment) && preg_match('/@\\*\\/$/', $comment)) { $comment = self::$conditionalComments->exec($comment); } else { $comment = ''; } return $comment . ' ' . $regexp; } public static $conditionalComments; public static $concat = array('(STRING1)\\+(STRING1)' => array(__CLASS__, '_concatenater'), '(STRING2)\\+(STRING2)' => array(__CLASS__, '_concatenater')); public static function _concatenater($match, $string1, $plus, $string2) { return substr($string1, 0, -1) . substr($string2, 1); } public static $whitespace = array('\\/\\/@[^\\n]*\\n' => RegGrp::IGNORE, '@\\s+\\b' => '@ ', '\\b\\s+@' => ' @', '(\\d)\\s+(\\.\\s*[a-z\\$_\\[(])' => '$1 $2', '([+-])\\s+([+-])' => '$1 $2', '(\\w)\\s+(\\pL)' => '$1 $2', '\\b\\s+\\$\\s+\\b' => ' $ ', '\\$\\s+\\b' => '$ ', '\\b\\s+\\$' => ' $', '\\b\\s+\\b' => ' ', '\\s+' => ''); } // initialise static object properties //eval("var e=this.encode62=" + this.ENCODE62); Minifier::$clean = Packer::$data->union(new Parser(Minifier::$clean)); Minifier::$concat = new Parser(Minifier::$concat); Minifier::$concat->merge(Packer::$data); Minifier::$comments = Packer::$data->union(new Parser(Minifier::$comments)); Minifier::$conditionalComments = Minifier::$comments->copy(); Minifier::$conditionalComments->putAt(-1, ' $3'); Minifier::$whitespace = Packer::$data->union(new Parser(Minifier::$whitespace)); Minifier::$whitespace->removeAt(2); // conditional comments Minifier::$comments->removeAt(2);
* example.php * * Demonstrates compression functions and minification usage * for stylesheets and javascript files * * @author Bennett Stone * @version 2.5 * @date 02-Jun-2013 * @updated 15-Jun-2013 * @package MagicMin **/ //Include the caching/minification class require 'class.magic-min.php'; //Initialize the class with image encoding, gzip, a timer, and use the google closure API $vars = array('encode' => true, 'timer' => true, 'gzip' => true, 'closure' => true, 'remove_comments' => false); $minified = new Minifier($vars); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <title>Example Usage | Caching and Minification Class</title> <?php /* <!--Output a new merged stylesheet with only the $included_styles included in order--> <?php $included_styles = array( 'css/bootstrap.css', 'https://raw.github.com/zurb/reveal/master/reveal.css', 'css/base/jquery-ui.css'
* for stylesheets and javascript files * * @author Bennett Stone * @version 2.5 * @date 02-Jun-2013 * @updated 15-Jun-2013 * @package MagicMin **/ ini_set('display_errors', 'On'); ini_set('error_reporting', E_ALL); error_reporting(E_ALL); //Include the caching/minification class require 'class.magic-min.php'; //Initialize the class with image encoding, gzip, a timer, and use the google closure API $vars = array('encode' => true, 'timer' => true, 'gzip' => true, 'closure' => true); $minified = new Minifier($vars); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <title>Example Usage | Caching and Minification Class</title> <?php /* <!--Output a new merged stylesheet with only the $included_styles included in order--> <?php */ $included_styles = array('css/bootstrap.css', 'https://raw.github.com/zurb/reveal/master/reveal.css', 'css/base/jquery-ui.css'); //readfile( 'css/bootstrap.css'); ?>