/**
  * Apply JShrink 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', 'Minifier', array('file' => $this->_settings['path']));
     if (!class_exists('JShrink\\Minifier')) {
         throw new Exception(sprintf('Cannot not load filter class "%s".', 'JShrink\\Minifier'));
     }
     return JShrink\Minifier::minify($content, array('flaggedComments' => $this->_settings['flaggedComments']));
 }
Beispiel #2
0
 protected function jsParser()
 {
     if (inDeveloperMode()) {
         return $this->text;
     }
     //If the JSMIn extension is loaded, use that as it can be as much as 1000x faster than JShrink
     if (extension_loaded("jsmin")) {
         return @jsmin($this->text);
     }
     if (!empty($GLOBALS['sugar_config']['uglify'])) {
         $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
         $process = proc_open($GLOBALS['sugar_config']['uglify'], $descriptorspec, $pipes);
         if (is_resource($process)) {
             fwrite($pipes[0], $this->text);
             fclose($pipes[0]);
             $out = stream_get_contents($pipes[1]);
             fclose($pipes[1]);
             proc_close($process);
             return $out;
         }
     }
     require_once 'jssource/Minifier.php';
     return JShrink\Minifier::minify($this->text);
 }
Beispiel #3
0
 /**
  * @dataProvider uglifyProvider
  */
 public function testUglify($unminified, $minified)
 {
     require_once 'src/JShrink/Minifier.php';
     $this->assertEquals(JShrink\Minifier::minify($unminified), $minified);
 }
Beispiel #4
0
	<link rel="shortcut icon" type="image/png" href="images/favicon.png"/>
	<link rel="icon" type="image/png" sizes="72x72" href="images/favicon-72px.png" />

	<?php 
foreach (array("lib/prototype.js", "lib/scriptaculous/scriptaculous.js?load=effects,controls", "lib/dojo/dojo.js", "lib/dojo/tt-rss-layer.js", "errors.php?mode=js") as $jsfile) {
    echo javascript_tag($jsfile);
}
?>

	<script type="text/javascript">
		require({cache:{}});
	<?php 
require_once 'lib/jshrink/Minifier.php';
foreach (PluginHost::getInstance()->get_plugins() as $n => $p) {
    if (method_exists($p, "get_prefs_js")) {
        echo JShrink\Minifier::minify($p->get_prefs_js());
    }
}
print get_minified_js(array("../lib/CheckBoxTree", "functions", "deprecated", "prefs", "PrefFeedTree", "PrefFilterTree", "PrefLabelTree"));
init_js_translations();
?>
	</script>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<script type="text/javascript">
		Event.observe(window, 'load', function() {
			init();
		});
	</script>
Beispiel #5
0
/**
 * Minifies the given JavaScript using UglifyJS.
 * @param  String $content  The JavaScript content.
 * @return String           Minified JavaScript.
 */
function _minifyJS($content)
{
    global $useUglify, $noMinify;
    if ($noMinify) {
        return $content;
    }
    $uglify = shell_exec('which uglifyjs 2>&1');
    //if -u was passed, force uglify as it will produce smaller file output
    if (!$useUglify || empty($uglify)) {
        //If the JSMIn extension is loaded, use that as it can be as much as 1000x faster than JShrink
        if (extension_loaded("jsmin")) {
            return jsmin($content);
        }
    }
    //next fall back to uglify
    if (!empty($uglify)) {
        $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
        $process = proc_open($uglify, $descriptorspec, $pipes);
        if (is_resource($process)) {
            fwrite($pipes[0], $content);
            fclose($pipes[0]);
            $out = stream_get_contents($pipes[1]);
            fclose($pipes[1]);
            proc_close($process);
            return $out;
        }
    }
    //Finally attempt to use JShrink
    if (file_exists('Minifier.php')) {
        require_once 'Minifier.php';
    } elseif (file_exists('../jssource/Minifier.php')) {
        require_once '../jssource/Minifier.php';
    } else {
        //No minifier found, just return the content
        return $content;
    }
    return JShrink\Minifier::minify($content);
}
 /**
  * @param $contents
  * @return string
  */
 private function minifyJS($contents)
 {
     if (!$contents) {
         return "";
     }
     return JShrink\Minifier::minify($contents, array('flaggedComments' => false));
     //return Minify_JS_ClosureCompiler::minify($contents);
 }
function get_minified_js($files)
{
    require_once 'lib/jshrink/Minifier.php';
    $rv = '';
    foreach ($files as $js) {
        if (!isset($_GET['debug'])) {
            $cached_file = CACHE_DIR . "/js/" . basename($js) . ".js";
            if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/{$js}.js")) {
                $rv .= file_get_contents($cached_file);
            } else {
                $minified = JShrink\Minifier::minify(file_get_contents("js/{$js}.js"));
                file_put_contents($cached_file, $minified);
                $rv .= $minified;
            }
        } else {
            $rv .= file_get_contents("js/{$js}.js");
        }
    }
    return $rv;
}
Beispiel #8
0
 /**
  * Private function to handle minification of file contents
  * Supports CSS and JS files
  *
  * @access private
  * @param string $src_file
  * @param bool $run_minification (default true)
  * @return string $content
  */
 private function minify_contents($src_file, $run_minification = true)
 {
     global $messages;
     $this->source = @file_get_contents($src_file);
     //Log the error and continue if we can't get the file contents
     if (!$this->source) {
         $this->messages[]['Minifier ERROR'] = 'Unable to retrieve the contents of ' . $src_file . '.  Skipping at ' . __LINE__ . ' in ' . basename(__FILE__);
         //This will cause  potential js errors, but allow the script to continue processing while notifying the user via console
         $this->source = '';
     }
     $this->type = strtolower(pathinfo($src_file, PATHINFO_EXTENSION));
     $this->output = '';
     /**
      * If the filename indicates that the contents are already minified, we'll just return the contents
      * If the switch is flipped (useful for loading things such as jquery via google cdn)
      */
     if (preg_match('/\\.min\\./i', $src_file) || $run_minification === false) {
         return $this->source;
     } else {
         if (!empty($this->type) && $this->type == 'css') {
             $this->content = $this->source;
             //If the param is set to merge images into the css before minifying...
             if ($this->merge_images) {
                 $this->content = $this->merge_images($src_file, $this->content);
             }
             /* remove comments */
             $this->content = preg_replace('!/\\*[^*]*\\*+([^/][^*]*\\*+)*/!', '', $this->content);
             /* remove tabs, spaces, newlines, etc. */
             $this->content = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '     '), '', $this->content);
             /* remove other spaces before/after ; */
             $this->content = preg_replace(array('(( )+{)', '({( )+)'), '{', $this->content);
             $this->content = preg_replace(array('(( )+})', '(}( )+)', '(;( )*})'), '}', $this->content);
             $this->content = preg_replace(array('(;( )+)', '(( )+;)'), ';', $this->content);
         }
         //end $this->type == 'css'
         if (!empty($this->type) && $this->type == 'js') {
             $this->content = $this->source;
             /**
              * Migrated preg_replace and str_replace custom minification to use google closure API
              * OR jsMin on 15-Jun-2013 due to js minification irregularities with most regex's: 
              * https://github.com/tedivm/JShrink
              * https://developers.google.com/closure/compiler/
              * Accomodates lack of local file for JShrink by getting contents from github
              * and writing to a local file for the class (just in case)
              * If bool is passed for 'closure' => true during class initiation, cURL request processes
              */
             if ($this->use_closure) {
                 //Build the data array
                 $data = array('compilation_level' => 'SIMPLE_OPTIMIZATIONS', 'output_format' => 'text', 'output_info' => 'compiled_code', 'js_code' => urlencode($this->content));
                 //Compile it into a post compatible format
                 $fields_string = '';
                 foreach ($data as $key => $value) {
                     $fields_string .= $key . '=' . $value . '&';
                 }
                 rtrim($fields_string, '&');
                 //Initiate and execute the curl request
                 $h = curl_init();
                 curl_setopt($h, CURLOPT_URL, 'http://closure-compiler.appspot.com/compile');
                 curl_setopt($h, CURLOPT_POST, true);
                 curl_setopt($h, CURLOPT_POSTFIELDS, $fields_string);
                 curl_setopt($h, CURLOPT_HEADER, false);
                 curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
                 $result = curl_exec($h);
                 $this->content = $result;
                 //close connection
                 curl_close($h);
             } else {
                 //Not using google closure, default to JShrink but make sure the file exists
                 if (!file_exists(dirname(__FILE__) . '/jShrink.php')) {
                     $this->messages[]['Minifier Log'] = 'jShrink does not exist locally.  Retrieving...';
                     $this->handle = fopen(dirname(__FILE__) . '/jShrink.php', 'w');
                     $this->jshrink = file_get_contents('https://raw.github.com/tedivm/JShrink/master/src/JShrink/Minifier.php');
                     fwrite($this->handle, $this->jshrink);
                     fclose($this->handle);
                 }
                 //Include jsmin
                 require_once dirname(__FILE__) . '/jShrink.php';
                 //Minify the javascript
                 $this->content = JShrink\Minifier::minify($this->content, array('flaggedComments' => false));
             }
             //end if( !$this->use_closure )
         }
         //end $this->type == 'js'
         //Add to the output and return it
         $this->output .= $this->content;
         return $this->output;
     }
 }
Beispiel #9
0
function get_minified_js($files)
{
    require_once 'lib/jshrink/Minifier.php';
    $rv = '';
    foreach ($files as $js) {
        if (!isset($_GET['debug'])) {
            $cached_file = CACHE_DIR . "/js/" . basename($js) . ".js";
            if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/{$js}.js")) {
                list($header, $contents) = explode("\n", file_get_contents($cached_file), 2);
                if ($header && $contents) {
                    list($htag, $hversion) = explode(":", $header);
                    if ($htag == "tt-rss" && $hversion == VERSION) {
                        $rv .= $contents;
                        continue;
                    }
                }
            }
            $minified = JShrink\Minifier::minify(file_get_contents("js/{$js}.js"));
            file_put_contents($cached_file, "tt-rss:" . VERSION . "\n" . $minified);
            $rv .= $minified;
        } else {
            $rv .= file_get_contents("js/{$js}.js");
            // no cache in debug mode
        }
    }
    return $rv;
}
Beispiel #10
0
 public static function minify($js, $options = null)
 {
     if (empty($js)) {
         return null;
     }
     require_once e_HANDLER . "jsshrink/Minifier.php";
     return JShrink\Minifier::minify($js, $options);
 }
Beispiel #11
0
 /**
  * Private function to handle minification of file contents
  * Supports CSS and JS files
  *
  * @access private
  * @param string $src_file
  * @param bool $run_minification (default true)
  * @return string $content
  */
 private function minify_contents($src_file, $run_minification = true)
 {
     //<<GEOmin Remplace les répertoires des url relatifs au fichier CSS d'origine
     global $scr_directory;
     $ods = explode('/', str_replace('../', '', $this->output_directory));
     $sfs = explode('/', pathinfo($src_file, PATHINFO_DIRNAME));
     foreach ($ods as $k => $v) {
         if ($ods[$k] == $sfs[$k]) {
             unset($sfs[$k]);
         }
     }
     $scr_directory = implode('/', $sfs) . (count($sfs) ? '/' : '');
     //>>GEOmin
     $this->source = @file_get_contents('../' . $src_file);
     //Log the error and continue if we can't get the file contents
     if (!$this->source) {
         self::$messages[]['Minifier ERROR'] = 'Unable to retrieve the contents of ' . $src_file . '.  Skipping at ' . __LINE__ . ' in ' . basename(__FILE__);
         //This will cause  potential js errors, but allow the script to continue processing while notifying the user via console
         $this->source = '';
     }
     $this->type = strtolower(pathinfo($src_file, PATHINFO_EXTENSION));
     $this->output = '';
     /**
      * If the filename indicates that the contents are already minified, we'll just return the contents
      * If the switch is flipped (useful for loading things such as jquery via google cdn)
      */
     if (preg_match('/\\.min\\./i', $src_file) || $run_minification === false) {
         return $this->source;
     } else {
         if (!empty($this->type) && $this->type == 'css') {
             $this->content = $this->source;
             //If the param is set to merge images into the css before minifying...
             if ($this->settings['encode']) {
                 $this->content = $this->merge_images($src_file, $this->content);
             }
             /* remove comments */
             if ($this->settings['remove_comments']) {
                 $this->content = preg_replace('!/\\*[^*]*\\*+([^/][^*]*\\*+)*/!', '', $this->content);
             }
             /* remove tabs, spaces, newlines, etc. */
             $this->content = preg_replace('/(\\s\\s+|\\t|\\n)/', ' ', $this->content);
             /* remove other spaces before/after ; */
             $this->content = preg_replace(array('(( )+{)', '({( )+)'), '{', $this->content);
             $this->content = preg_replace(array('(( )+})', '(}( )+)', '(;( )*})'), '}', $this->content);
             $this->content = preg_replace(array('(;( )+)', '(( )+;)'), ';', $this->content);
             //<<GEOmin Remplace les répertoires des url relatifs au fichier CSS d'origine
             $this->content = preg_replace_callback('/url\\([\'|\\"]?([a-z@A-Z0-9\\/\\.\\-]*)[\'|\\"]?\\)/', function ($matches) {
                 global $scr_directory;
                 $source = preg_replace('/[a-z@A-Z0-9]*\\/\\.\\.\\//', '', $scr_directory . $matches[1]);
                 $destination = 'images/' . str_replace('/', '-', $source);
                 copy('../' . $source, '../dist/' . $destination);
                 return 'url("' . $destination . '")';
             }, $this->content);
             $this->content = str_replace("}", "}\n", $this->content);
             //>>GEOmin
         }
         //end $this->type == 'css'
         if (!empty($this->type) && $this->type == 'js') {
             $this->content = $this->source;
             /**
              * Migrated preg_replace and str_replace custom minification to use google closure API
              * OR jShrink on 15-Jun-2013 due to js minification irregularities with most regex's: 
              * https://github.com/tedious/JShrink
              * https://developers.google.com/closure/compiler/
              * https://developers.google.com/closure/compiler/docs/api-ref
              * Accomodates lack of local file for JShrink by getting contents from github
              * and writing to a local file for the class (just in case)
              * If bool is passed for 'closure' => true during class initiation, cURL request processes
              */
             if ($this->settings['closure']) {
                 //Build the data array
                 $data = array('compilation_level' => 'SIMPLE_OPTIMIZATIONS', 'output_format' => 'json', 'output_info' => 'compiled_code', 'js_code' => urlencode($this->content));
                 //Compile it into a post compatible format
                 $fields_string = '';
                 foreach ($data as $key => $value) {
                     $fields_string .= $key . '=' . $value . '&';
                 }
                 rtrim($fields_string, '&');
                 //Initiate and execute the curl request
                 $h = curl_init();
                 curl_setopt($h, CURLOPT_URL, 'http://closure-compiler.appspot.com/compile');
                 curl_setopt($h, CURLOPT_POST, true);
                 curl_setopt($h, CURLOPT_POSTFIELDS, $fields_string);
                 curl_setopt($h, CURLOPT_HEADER, false);
                 curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
                 $result = curl_exec($h);
                 $result_raw = json_decode($result, true);
                 //If we've made too many requests, or passed bad data, our js will be broken
                 if (isset($result_raw['serverErrors']) && !empty($result_raw['serverErrors'])) {
                     $e_code = $result_raw['serverErrors'][0]['code'];
                     $e_message = $result_raw['serverErrors'][0]['error'];
                     self::$messages[]['Minifier ERROR'] = $e_code . ': ' . $e_message . ' File: ' . basename($src_file) . '.  Returning unminified contents.';
                 } else {
                     $this->content = $result_raw['compiledCode'];
                 }
                 //close connection
                 curl_close($h);
             } else {
                 //Not using google closure, default to JShrink but make sure the file exists
                 if (!file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'jShrink.php')) {
                     self::$messages[]['Minifier Log'] = 'jShrink does not exist locally.  Retrieving...';
                     $this->handle = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'jShrink.php', 'w');
                     $this->jshrink = file_get_contents('https://raw.github.com/tedivm/JShrink/master/src/JShrink/Minifier.php');
                     fwrite($this->handle, $this->jshrink);
                     fclose($this->handle);
                 }
                 //Include jShrink
                 require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'jShrink.php';
                 //Minify the javascript
                 $this->content = JShrink\Minifier::minify($this->content, array('flaggedComments' => $this->settings['remove_comments'])) . PHP_EOL;
             }
             //end if( !$this->settings['closure'] )
         }
         //end $this->type == 'js'
         //<<GEOmin
         echo "{$src_file}<br/>";
         $debug_file = str_replace('/', '-', $src_file);
         switch ($sfs[0]) {
             case 'leafletjs.com':
                 $credit = preg_replace('/([0-z-\\.]*)\\/([0-z-\\.]*)\\/(.*)/', 'http://leafletjs.com/download.html  --  Leaflet $2  --  $3', $src_file);
                 break;
             case 'github.com':
                 $credit = preg_replace('/([0-z-\\.]*\\/[0-z-\\.]*\\/[0-z-\\.]*)\\/(.*)/', 'http://$1  --  $2', $src_file);
                 break;
             case 'src':
                 $credit = 'http://github.com/Dominique92/MyLeaflet -- ' . $src_file;
                 $debug_file = str_replace('src', 'github.com-Dominique92-MyLeaflet', $debug_file);
             default:
         }
         $this->output .= "\n/*\n * {$credit} (" . round(strlen($this->content) / 1024, 1) . " kb)\n */\n";
         $this->src .= $this->extension == 'js' ? "\ndocument.write('<script type=\"text/javascript\" src=\"'+racineSources+'../{$src_file}\"></script>');" : "\n@import url(\"../{$src_file}\");";
         if ($this->extension == 'js') {
             copy('../' . $src_file, "../dist/src/{$debug_file}");
         }
         $this->debug .= $this->extension == 'js' ? "\ndocument.write('<script type=\"text/javascript\" src=\"'+racineSources+'{$debug_file}\"></script>');" : "\n@import url(\"{$debug_file}\");";
         //>>GEOmin
         //Add to the output and return it
         $this->output .= $this->content;
         return $this->output;
     }
 }
 /**
  * Asset Scripts Action
  *
  * @return null
  */
 public static function assetScriptAction()
 {
     $pagename = get_query_var('pagename');
     $files = get_query_var('files');
     $fingerprint = get_query_var('fingerprint');
     // check if on mg_asset_js page and have 'files' parameter
     if ($pagename == 'mg_asset_js' && $files) {
         $content = '';
         $lastModified = new \DateTime('-1 year');
         // initialize cached resource file location
         $cachedResourceFile = MgCacheHelper::$cacheDir . '/' . $fingerprint . '.js';
         // create new cached resource, save to cache directory
         if (!file_exists($cachedResourceFile)) {
             // turn files parameter into array
             $fileArray = explode(',', $files);
             if (is_array($fileArray) && count($fileArray)) {
                 // loop over array of files
                 foreach ($fileArray as $file) {
                     if ($scriptPath = realpath(MgCacheHelper::$webRoot . $file)) {
                         // get timestamp for most recently modified file
                         $localLastModified = new \DateTime(date("F d Y H:i:s", filemtime($scriptPath)));
                         if ($localLastModified > $lastModified) {
                             $lastModified = $localLastModified;
                         }
                         // get contents of each file
                         $content .= file_get_contents($scriptPath);
                     }
                 }
                 // strip whitespace and comments from $content
                 if (MgAssetHelper::$minify) {
                     $content = JShrink\Minifier::minify($content);
                 }
             }
             // save contents
             if (!empty($content)) {
                 if (!is_writable(dirname($cachedResourceFile))) {
                     mkdir(dirname($cachedResourceFile), 0775, true);
                 }
                 if (is_writable(dirname($cachedResourceFile))) {
                     file_put_contents($cachedResourceFile, $content);
                 }
             }
         }
         // read cached resource to buffer
         if (file_exists($cachedResourceFile)) {
             ob_start();
             readfile($cachedResourceFile);
             $content = ob_get_contents();
             ob_end_clean();
             $lastModified = new \DateTime(date("F d Y H:i:s", filemtime($cachedResourceFile)));
         }
         // output
         if (empty($content)) {
             header('HTTP/1.1 404 Not Found');
         } else {
             header('HTTP/1.1 200 OK');
             header('Content-Type: text/javascript');
             header('Content-Length: ' . strlen($content));
             header('Expires: ' . date('D, d M Y H:i:s e', strtotime('+1 year')));
             header('Cache-Control: max-age=31556926');
             header('Last-Modified: ' . $lastModified->format('D, d M Y H:i:s e'));
             header('Date: ' . $lastModified->format('D, d M Y H:i:s e'));
             header('Pragma: cache');
             header('Vary: Accept-Encoding');
             header('X-Content-Type-Options: nosniff');
             header('Accept-Ranges: bytes');
             echo $content;
         }
         exit;
     }
 }
Beispiel #13
0
// Add css from plugins
foreach (PluginHost::getInstance()->get_plugins() as $n => $p) {
    if (method_exists($p, "get_css")) {
        $template_vars['css_plugins'] .= $p->get_css();
    }
}
// Add js files
foreach (array("lib/prototype.js", "lib/scriptaculous/scriptaculous.js?load=effects,controls", "lib/dojo/dojo.js", "lib/dojo/tt-rss-layer.js", "errors.php?mode=js") as $jsfile) {
    array_push($template_vars['js_files'], javascript_tag_array($jsfile));
}
// Add raw js
require_once 'lib/jshrink/Minifier.php';
$template_vars['js'] .= get_minified_js(array("tt-rss", "functions", "feedlist", "viewfeed", "FeedTree", "PluginHost"));
foreach (PluginHost::getInstance()->get_plugins() as $n => $p) {
    if (method_exists($p, "get_js")) {
        $template_vars['js'] .= JShrink\Minifier::minify($p->get_js());
    }
}
$template_vars['js'] .= init_js_translations_return();
// Toolbar buttons from plugins
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_TOOLBAR_BUTTON) as $p) {
    array_push($template_vars['hook_toolbar_buttons'], $p->hook_toolbar_button());
}
// Action items from plugins
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ACTION_ITEM) as $p) {
    array_push($template_vars['hook_action_items'], $p->hook_action_item());
}
// Hide logout?
if ($_SESSION["hide_logout"]) {
    $template_vars['hide_logout'] = true;
}
 private function process_resource($file, $type)
 {
     $sources = $this->settings[$type]["files"][$file];
     $vars = $this->settings[$type]["vars"];
     clearstatcache();
     $theme_root = THEMES_DIR . $this->theme;
     $theme_url = $this->base_url . "/" . basename(THEMES_DIR) . "/" . $this->theme;
     $cache_root = CACHE_DIR . "resources/";
     $cache_file = $cache_root . $file . "." . $type;
     $cache_modified = file_exists($cache_file) ? filemtime($cache_file) : 0;
     $last_modified = 0;
     foreach ($sources as $source) {
         $m = file_exists($theme_root . "/{$source}") ? filemtime($theme_root . "/{$source}") : 0;
         if ($m > $last_modified) {
             $last_modified = $m;
         }
     }
     if (!file_exists($cache_file) || $last_modified > $cache_modified || $this->debug === true) {
         $data = "";
         foreach ($sources as $source) {
             $data .= file_exists($theme_root . "/{$source}") ? file_get_contents($theme_root . "/{$source}") . "\n" : "";
         }
         $keys = array('$base_url', 'base_url', '$theme_url', 'theme_url');
         $vals = array($this->base_url, $this->base_url, $theme_url, $theme_url);
         if (is_array($vars)) {
             foreach ($vars as $key => $val) {
                 $keys[] = '$' . $key;
                 $vals[] = $val;
             }
         }
         $data = str_replace($keys, $vals, $data);
         $min_lib = ROOT_DIR . "vendor/nano_resources/" . $type . ".php";
         if ($this->settings[$type]["minify"] && file_exists($min_lib)) {
             require $min_lib;
             if ($type === "js") {
                 $data = JShrink\Minifier::minify($data, array("flaggedComments" => false));
             } else {
                 if ($type === "css") {
                     $data = CssMin::minify($data);
                 }
             }
             $data = trim($data);
         }
         if (!is_dir($cache_root)) {
             mkdir($cache_root, 0755, true);
         }
         $datestamp = date('Y-m-d H:i:s');
         file_put_contents($cache_file, "/* CACHED : {$datestamp} */\n" . $data);
         if ($type === "js") {
             header("Content-type: text/javascript");
         } else {
             header("Content-Type: text/css");
         }
         $data = "/* RENDERED : {$datestamp} */\n" . $data;
         header("Content-length: " . strlen($data));
         die($data);
     } else {
         if (function_exists("apache_request_headers")) {
             $headers = apache_request_headers();
             $ims = isset($headers["If-Modified-Since"]) ? $headers["If-Modified-Since"] : 0;
         } else {
             $ims = $_SERVER["HTTP_IF_MODIFIED_SINCE"];
         }
         if (!$ims || strtotime($ims) != $cache_modified) {
             if ($type === "js") {
                 header("Content-type: text/javascript");
             } else {
                 header("Content-Type: text/css");
             }
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", $cache_modified) . ' GMT', true, 200);
             header("Content-length: " . filesize($cache_file));
             readfile($cache_file);
             die;
         } else {
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", $cache_modified) . ' GMT', true, 304);
             header("Content-length: " . filesize($cache_file));
             die;
         }
     }
 }
 /**
  * Compress each languages
  * @param string $language The language of source code
  * @param string $code The source code
  * @return string Compressed code
  */
 public static function _compressor($language, $code = "", $minInline)
 {
     /**
      * Skip if file size is > 500KB
      */
     if (mb_strlen($code, '8bit') > 500000) {
         return $code;
     } else {
         if ($language == "css") {
             /**
              * What kind of css stuff should it convert
              */
             $minifier = new MatthiasMullie\Minify\CSS();
             $minifier->add($code);
             return $minifier->minify();
         } else {
             if ($language == "js") {
                 return JShrink\Minifier::minify($code);
             } else {
                 if ($language == "html") {
                     $html = new Tinyfier_HTML_Tool();
                     if ($minInline) {
                         return $html->process($code, array("compress_all" => true));
                     } else {
                         return $html->process($code, array("compress_all" => false));
                     }
                 }
             }
         }
     }
 }
Beispiel #16
0
<?php

require_once dirname(__DIR__) . '/Bright.php';
require_once dirname(__DIR__) . '/3rdparty/JShrink/Minifier.php';
$scriptsPath = dirname(__DIR__) . '/js/';
$resultScriptFile = dirname(__DIR__) . '/js/bright.js';
$packedScriptFile = dirname(__DIR__) . '/js/bright.min.js';
br()->log('Working in ' . $scriptsPath);
$result = '';
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.typeCheck.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.storage.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.eventQueue.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.request.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.flagsHolder.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.dataSource.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.dataGrid.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.dataCombo.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.editable.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.ui.js');
$result .= br()->fs()->loadFromFile($scriptsPath . 'br.clipboard.js');
br()->log('Saving to ' . $resultScriptFile);
$notMinified = $result;
br()->fs()->saveToFile($resultScriptFile, $notMinified);
br()->log('Saving to ' . $packedScriptFile);
$minified = JShrink\Minifier::minify($result);
$minified = '/* jshint ignore:start */' . $minified . '/* jshint ignore:end */';
br()->fs()->saveToFile($packedScriptFile, $minified);