public function actionIndex()
	{
		$incPath = get_include_path();
		$docRoot = $_SERVER['DOCUMENT_ROOT'];
		$_SERVER['DOCUMENT_ROOT'] = dirname(Yii::app()->request->getScriptFile());
		set_include_path(Yii::app()->getExtensionPath()."/minify" . PATH_SEPARATOR . $incPath);
		require 'Minify.php';
		$option['debug'] = $this->_debug;
		$option['maxAge'] = $this->_maxAge;
		$option['bubbleCssImports'] = $this->_bubbleCssImports;
		$option['encodeOutput'] = $this->_encodeOutput;
		$option['encodeMethod'] = $this->_encodeMethod;
		foreach ($this->_symlinks as $link => $target) {
			$link = str_replace('//', realpath($_SERVER['DOCUMENT_ROOT'])."/", $link);
			$link = strtr($link, '/', DIRECTORY_SEPARATOR);
			$option['minifierOptions']['text/css']['symlinks'][$link] = realpath($target);
		}
		Minify::setCache(Yii::app()->getRuntimePath(), $this->_cacheFileLocking);
		if ($this->_errorLogger) {
			require_once 'Minify/Logger.php';
			require_once 'FirePHP.php';
			Minify_Logger::setLogger(FirePHP::getInstance(true));
		}
		$mgv = Yii::app()->getRuntimePath()."/minifyGroups.var";
		$minifyGroups = unserialize(file_get_contents($mgv));
		$option['files'] = $minifyGroups[$_GET['group']];
		Minify::serve('Files', $option);
		set_include_path($incPath);
		$_SERVER['DOCUMENT_ROOT'] = $docRoot;
	}
示例#2
0
 public function initialize()
 {
     $assets = $this->request->getQuery('r');
     if ($assets != null) {
         $this->assetsList = explode(',', $assets);
     }
     set_include_path(LIB_PATH . 'Minify/' . PATH_SEPARATOR . get_include_path());
     \Minify::setCache(new \Minify_Cache_APC());
 }
示例#3
0
 public function action_minify()
 {
     // load config
     $config = Kohana::config('minify');
     //require  MINIFY_MIN_DIR.'/Minify.php';
     Minify::$uploaderHoursBehind = $config['uploaderHoursBehind'];
     Minify::setCache(isset($config['cachePath']) ? $config['cachePath'] : '', $config['cacheFileLocking']);
     if ($config['documentRoot']) {
         $_SERVER['DOCUMENT_ROOT'] = $config['documentRoot'];
     } elseif (0 === stripos(PHP_OS, 'win')) {
         Minify::setDocRoot();
         // IIS may need help
     }
     $config['serveOptions']['minifierOptions']['text/css']['symlinks'] = $config['symlinks'];
     // auto-add targets to allowDirs
     foreach ($config['symlinks'] as $uri => $target) {
         $config['serveOptions']['minApp']['allowDirs'][] = $target;
     }
     if ($config['allowDebugFlag']) {
         if (!empty($_COOKIE['minDebug'])) {
             foreach (preg_split('/\\s+/', $_COOKIE['minDebug']) as $debugUri) {
                 if (false !== strpos($_SERVER['REQUEST_URI'], $debugUri)) {
                     $config['serveOptions']['debug'] = true;
                     break;
                 }
             }
         }
         // allow GET to override
         if (isset($_GET['debug'])) {
             $config['serveOptions']['debug'] = true;
         }
     }
     if ($config['errorLogger']) {
         //require _once MINIFY_MIN_DIR . '/Minify/Logger.php';
         if (true === $config['errorLogger']) {
             //require _once MINIFY_MIN_DIR . '/FirePHP.php';
             Minify_Logger::setLogger(FirePHP::getInstance(true));
         } else {
             Minify_Logger::setLogger($config['errorLogger']);
         }
     }
     // check for URI versioning
     if (preg_match('/&\\d/', $_SERVER['QUERY_STRING'])) {
         $config['serveOptions']['maxAge'] = 31536000;
     }
     if (isset($_GET['g'])) {
         // well need groups config
         $config['serveOptions']['minApp']['groups'] = $config['groupsConfig'];
     }
     if (isset($_GET['f']) || isset($_GET['g'])) {
         // serve!
         Minify::serve('MinApp', $config['serveOptions']);
         exit;
     }
 }
示例#4
0
 public function serve_css($files)
 {
     $opt = array('files' => $this->get_css_files($files), 'contentTypeCharset' => $this->charset);
     /*
      * Bazı sunucularda fpassthru engelli olduğundan problem çıkarabiliyor.
      * Bu durumda fonksiyonun kullanıldığı filelocking seçeneğini FALSE gönderiyoruz.
      * Bu işlemi de function_exists(fpassthru) ile otomatik yapıyoruz.
      */
     Minify::setCache($this->cache_path, function_exists('fpassthru'));
     Minify::serve('Files', $opt);
 }
示例#5
0
 /**
  * Set up groups of files as sources
  * 
  * @param array $options controller and Minify options
  * @return array Minify options
  * 
  */
 public function setupSources($options)
 {
     // PHP insecure by default: realpath() and other FS functions can't handle null bytes.
     if (isset($_GET['files'])) {
         $_GET['files'] = str_replace("", '', (string) $_GET['files']);
     }
     self::_setupDefines();
     if (MINIFY_USE_CACHE) {
         $cacheDir = defined('MINIFY_CACHE_DIR') ? MINIFY_CACHE_DIR : '';
         Minify::setCache($cacheDir);
     }
     $options['badRequestHeader'] = 'HTTP/1.0 404 Not Found';
     $options['contentTypeCharset'] = MINIFY_ENCODING;
     // The following restrictions are to limit the URLs that minify will
     // respond to. Ideally there should be only one way to reference a file.
     if (!isset($_GET['files']) || !preg_match('/^[^,]+\\.(css|js)(,[^,]+\\.\\1)*$/', $_GET['files'], $m) || strpos($_GET['files'], '//') !== false || strpos($_GET['files'], '\\') !== false || preg_match('/(?:^|[^\\.])\\.\\//', $_GET['files'])) {
         return $options;
     }
     $extension = $m[1];
     $files = explode(',', $_GET['files']);
     if (count($files) > MINIFY_MAX_FILES) {
         return $options;
     }
     // strings for prepending to relative/absolute paths
     $prependRelPaths = dirname($_SERVER['SCRIPT_FILENAME']) . DIRECTORY_SEPARATOR;
     $prependAbsPaths = $_SERVER['DOCUMENT_ROOT'];
     $sources = array();
     $goodFiles = array();
     $hasBadSource = false;
     $allowDirs = isset($options['allowDirs']) ? $options['allowDirs'] : MINIFY_BASE_DIR;
     foreach ($files as $file) {
         // prepend appropriate string for abs/rel paths
         $file = ($file[0] === '/' ? $prependAbsPaths : $prependRelPaths) . $file;
         // make sure a real file!
         $file = realpath($file);
         // don't allow unsafe or duplicate files
         if (parent::_fileIsSafe($file, $allowDirs) && !in_array($file, $goodFiles)) {
             $goodFiles[] = $file;
             $srcOptions = array('filepath' => $file);
             $this->sources[] = new Minify_Source($srcOptions);
         } else {
             $hasBadSource = true;
             break;
         }
     }
     if ($hasBadSource) {
         $this->sources = array();
     }
     if (!MINIFY_REWRITE_CSS_URLS) {
         $options['rewriteCssUris'] = false;
     }
     return $options;
 }
示例#6
0
 /**
  * Runs minify
  */
 function process()
 {
     require_once W3TC_LIB_MINIFY_DIR . '/Minify.php';
     require_once W3TC_LIB_MINIFY_DIR . '/HTTP/Encoder.php';
     HTTP_Encoder::$encodeToIe6 = $this->_config->get_boolean('minify.comprss.ie6');
     Minify::$uploaderHoursBehind = $this->_config->get_integer('minify.fixtime');
     Minify::setCache($this->_get_cache());
     $serve_options = $this->_config->get_array('minify.options');
     $serve_options['maxAge'] = $this->_config->get_integer('minify.maxage');
     $serve_options['encodeOutput'] = $this->_config->get_boolean('minify.compress');
     $serve_options['postprocessor'] = array(&$this, 'postprocessor');
     if (stripos(PHP_OS, 'win') === 0) {
         Minify::setDocRoot();
     }
     foreach ($this->_config->get_array('minify.symlinks') as $link => $target) {
         $link = str_replace('//', realpath($_SERVER['DOCUMENT_ROOT']), $link);
         $link = strtr($link, '/', DIRECTORY_SEPARATOR);
         $serve_options['minifierOptions']['text/css']['symlinks'][$link] = realpath($target);
     }
     if ($this->_config->get_boolean('minify.debug')) {
         $serve_options['debug'] = true;
     }
     if ($this->_config->get('minify.debug')) {
         require_once W3TC_LIB_MINIFY_DIR . '/Minify/Logger.php';
         Minify_Logger::setLogger($this);
     }
     if (isset($_GET['f']) || isset($_GET['gg']) && isset($_GET['g']) && isset($_GET['t'])) {
         if (isset($_GET['gg']) && isset($_GET['g']) && isset($_GET['t'])) {
             $serve_options['minApp']['groups'] = $this->get_groups($_GET['gg'], $_GET['t']);
             if ($_GET['t'] == 'js' && (in_array($_GET['g'], array('include', 'include-nb')) && $this->_config->get_boolean('minify.js.combine.header') || in_array($_GET['g'], array('include-footer', 'include-footer-nb')) && $this->_config->get_boolean('minify.js.combine.footer'))) {
                 $serve_options['minifiers']['application/x-javascript'] = array($this, 'minify_stub');
             }
             /**
              * Setup user-friendly cache ID for disk cache
              */
             if ($this->_config->get_string('minify.engine') == 'file') {
                 $cacheId = sprintf('%s.%s.%s', $_GET['gg'], $_GET['g'], $_GET['t']);
                 Minify::setCacheId($cacheId);
             }
         }
         @header('Pragma: public');
         try {
             Minify::serve('MinApp', $serve_options);
         } catch (Exception $exception) {
             printf('<strong>W3 Total Cache Error:</strong> Minify error: %s', $exception->getMessage());
         }
     } else {
         die('This file cannot be accessed directly');
     }
 }
示例#7
0
function test_Lines()
{
    global $thisDir;
    $exp = file_get_contents("{$thisDir}/_test_files/minify/lines_output.js");
    Minify::setCache(null);
    // no cache
    $ret = Minify::serve('Files', array('debug' => true, 'quiet' => true, 'encodeOutput' => false, 'files' => array("{$thisDir}/_test_files/minify/email.js", "{$thisDir}/_test_files/minify/lines_bugs.js", "{$thisDir}/_test_files/minify/QueryString.js", "{$thisDir}/_test_files/js/before.js")));
    $passed = assertTrue($exp === $ret['content'], 'Minify_Lines');
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        echo "\n---Output: " . countBytes($ret['content']) . " bytes\n\n{$ret['content']}\n\n";
        if (!$passed) {
            echo "---Expected: " . countBytes($exp) . " bytes\n\n{$exp}\n\n\n";
        }
    }
}
示例#8
0
文件: Server.php 项目: jos3000/swift
 public function serve()
 {
     // Adapted from index.php and config.php in the Minify distribution
     $min_serveOptions = array();
     $min_uploaderHoursBehind = isset($this->_config['min_uploaderHoursBehind']) ? $this->_config['min_uploaderHoursBehind'] : 0;
     Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
     $min_cacheFileLocking = isset($this->_config['min_cacheFileLocking']) ? $this->_config['min_cacheFileLocking'] : true;
     $min_cachePath = $this->_config['cache_dir'];
     Minify::setCache($min_cachePath, $min_cacheFileLocking);
     $min_symlinks = isset($this->_config['min_symlinks']) ? $this->_config['min_symlinks'] : array();
     foreach ($min_symlinks as $link => $target) {
         $link = str_replace('//', realpath($_SERVER['DOCUMENT_ROOT']), $link);
         $link = strtr($link, '/', DIRECTORY_SEPARATOR);
         $min_serveOptions['minifierOptions']['text/css']['symlinks'][$link] = realpath($target);
     }
     $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
     if (isset($this->_config['debug_minify_logger'])) {
         require_once 'Minify/Logger.php';
         if (true === $this->_config['debug_minify_logger']) {
             require_once 'FirePHP.php';
             Minify_Logger::setLogger(FirePHP::getInstance(true));
         } else {
             Minify_Logger::setLogger($this->_config['debug_minify_logger']);
         }
     }
     // check for URI versioning
     if (!empty($this->_version)) {
         $min_serveOptions['maxAge'] = 31536000;
     } else {
         # don't cache if we are not using a version number
         $min_serveOptions['maxAge'] = 0;
     }
     $min_serveOptions['swift']['files'] = array();
     foreach ($this->_current_modules as $module) {
         if (!empty($this->_config['debug_use_alt_resources']) && !empty($this->_config['modules'][$module]['debug_path'])) {
             $min_serveOptions['swift']['files'][] = $this->_config['modules'][$module]['debug_path'];
         } else {
             $min_serveOptions['swift']['files'][] = $this->_config['modules'][$module]['path'];
         }
     }
     # check what format we're working on by looking at the extension on the first file
     # if we are in debug mode for the current type of files use Minify's debug mode
     if (!empty($this->_config['debug_minify_js_off']) && pathinfo($min_serveOptions['swift']['files'][0], PATHINFO_EXTENSION) == 'js' || !empty($this->_config['debug_minify_css_off']) && pathinfo($min_serveOptions['swift']['files'][0], PATHINFO_EXTENSION) == 'css') {
         $min_serveOptions['debug'] = true;
     }
     Minify::serve('Swift', $min_serveOptions);
 }
示例#9
0
function minify($files)
{
    global $CFG;
    $cachedir = $CFG->cachedir . '/js';
    // make sure the cache dir exist
    if (!file_exists($cachedir)) {
        @mkdir($cachedir, $CFG->directorypermissions, true);
    }
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    Minify::setCache($cachedir, true);
    $options = array('maxAge' => 60 * 60 * 24 * 20, 'files' => $files);
    Minify::serve('Files', $options);
    die;
}
示例#10
0
 public static function serve()
 {
     // try to disable output_compression (may not have an effect)
     ini_set('zlib.output_compression', '0');
     Minify::setCache(OX_PATH . '/var/cache', true);
     if (isset($_GET['g'])) {
         // serve!
         $options = array();
         $options['minApp']['groupsOnly'] = true;
         $options['rewriteCssUris'] = false;
         $options['minApp']['groups'] = self::prepareGroups();
         Minify::serve('MinApp', $options);
     } else {
         header("Location: /");
         exit;
     }
 }
示例#11
0
 public function action_index()
 {
     $group = $this->request->param('group');
     if (!empty($group)) {
         $_GET['g'] = $group;
     }
     $config = Kohana::$config->load('minify');
     Minify::$uploaderHoursBehind = $config['uploaderHoursBehind'];
     Minify::setCache(isset($config['cachePath']) ? $config['cachePath'] : '', $config['cacheFileLocking']);
     if ($config['documentRoot']) {
         $_SERVER['DOCUMENT_ROOT'] = $config['documentRoot'];
         Minify::$isDocRootSet = TRUE;
     }
     $serve_options = $config['serveOptions'];
     $serve_options['minifierOptions']['text/css']['symlinks'] = $config['symlinks'];
     foreach ($config['symlinks'] as $uri => $target) {
         $serve_options['minApp']['allowDirs'][] = $target;
     }
     if ($config['allowDebugFlag']) {
         $serve_options['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
     }
     if ($config['errorLogger']) {
         if (TRUE === $config['errorLogger']) {
             Minify_Logger::setLogger(FirePHP::getInstance(true));
         } else {
             Minify_Logger::setLogger($config['errorLogger']);
         }
     }
     // Check for URI versioning
     if (preg_match('/&\\d/', Arr::get($_SERVER, 'QUERY_STRING'))) {
         $serve_options['maxAge'] = 31536000;
     }
     if (isset($_GET['g'])) {
         // well need groups config
         $serve_options['minApp']['groups'] = $config['groupsConfig'];
     }
     if (isset($_GET['f']) or isset($_GET['g'])) {
         $response = Minify::serve(new Minify_Controller_MinApp(), array('quiet' => TRUE) + $serve_options);
         $this->response->headers($response['headers'])->status($response['statusCode'])->body($response['content']);
     }
 }
示例#12
0
 public function action_index()
 {
     extract(Kohana::$config->load('minify')->as_array(), EXTR_SKIP);
     if ($this->request->param('group')) {
         $_GET['g'] = $this->request->param('group');
     }
     Minify::$uploaderHoursBehind = $uploaderHoursBehind;
     Minify::setCache(isset($cachePath) ? $cachePath : '', $cacheFileLocking);
     if ($documentRoot) {
         $_SERVER['DOCUMENT_ROOT'] = $documentRoot;
         Minify::$isDocRootSet = TRUE;
     }
     $serveOptions['minifierOptions']['text/css']['symlinks'] = $symlinks;
     $serveOptions['minApp']['allowDirs'] += array_values($symlinks);
     if ($allowDebugFlag) {
         $serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
     }
     if ($errorLogger) {
         if (TRUE === $errorLogger) {
             $errorLogger = FirePHP::getInstance(TRUE);
         }
         Minify_Logger::setLogger($errorLogger);
     }
     // Check for URI versioning
     if (preg_match('/&\\d/', $_SERVER['QUERY_STRING'])) {
         $serveOptions['maxAge'] = 31536000;
     }
     if (isset($_GET['g'])) {
         // Well need groups config
         $serveOptions['minApp']['groups'] = $groupsConfig;
     }
     if (isset($_GET['f']) or isset($_GET['g'])) {
         set_time_limit(0);
         // Serve!
         $response = Minify::serve(new Minify_Controller_MinApp(), array('quiet' => TRUE) + $serveOptions);
         $this->response->headers($response['headers'])->body($response['content'])->status($response['statusCode']);
     }
 }
示例#13
0
function minify($files)
{
    global $CFG;
    $cachedir = $CFG->cachedir . '/js';
    // make sure the cache dir exist
    if (!file_exists($cachedir)) {
        @mkdir($cachedir, $CFG->directorypermissions, true);
    }
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    Minify::setCache($cachedir, true);
    $options = array('maxAge' => 60 * 60 * 24 * 20, 'files' => $files);
    try {
        Minify::serve('Files', $options);
        die;
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error = str_replace("\r", ' ', $error);
        $error = str_replace("\n", ' ', $error);
    }
    // minification failed - try to inform the developer and include the non-minified version
    $js = <<<EOD
try {console.log('Error: Minimisation of javascript failed!');} catch (e) {}

// Error: {$error}
// Problem detected during javascript minimisation, please review the following code
// =================================================================================


EOD;
    echo $js;
    foreach ($files as $jsfile) {
        echo file_get_contents($jsfile) . "\n";
    }
}
示例#14
0
 * Front controller for default Minify implementation
 * 
 * DO NOT EDIT! Configure this utility via config.php and groupsConfig.php
 * 
 * @package Minify
 */
define('MINIFY_MIN_DIR', dirname(__FILE__));
// load config
require MINIFY_MIN_DIR . '/config.php';
if (isset($_GET['test'])) {
    include MINIFY_MIN_DIR . '/config-test.php';
}
require "{$min_libPath}/Minify/Loader.php";
Minify_Loader::register();
Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
Minify::setCache(isset($min_cachePath) ? $min_cachePath : '', $min_cacheFileLocking);
if ($min_documentRoot) {
    $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot;
    Minify::$isDocRootSet = true;
}
$min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
// auto-add targets to allowDirs
foreach ($min_symlinks as $uri => $target) {
    $min_serveOptions['minApp']['allowDirs'][] = $target;
}
if ($min_allowDebugFlag) {
    $min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
}
if ($min_errorLogger) {
    if (true === $min_errorLogger) {
        $min_errorLogger = FirePHP::getInstance(true);
示例#15
0
function minify($files) {
    if (empty($files)) {
        return '';
    }

    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot(); // IIS may need help
    }
    // disable all caching, we do it in moodle
    Minify::setCache(null, false);

    $options = array(
        'bubbleCssImports' => false,
        // Don't gzip content we just want text for storage
        'encodeOutput' => false,
        // Maximum age to cache, not used but required
        'maxAge' => 1800,
        // The files to minify
        'files' => $files,
        // Turn orr URI rewriting
        'rewriteCssUris' => false,
        // This returns the CSS rather than echoing it for display
        'quiet' => true
    );

    $error = 'unknown';
    try {
        $result = Minify::serve('Files', $options);
        if ($result['success']) {
            return $result['content'];
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error = str_replace("\r", ' ', $error);
        $error = str_replace("\n", ' ', $error);
    }

    // minification failed - try to inform the theme developer and include the non-minified version
    $js = <<<EOD
try {console.log('Error: Minimisation of theme javascript failed!');} catch (e) {}

// Error: $error
// Problem detected during javascript minimisation, please review the following code
// =================================================================================


EOD;
    foreach ($files as $jsfile) {
        $js .= file_get_contents($jsfile)."\n";
    }
    return $js;
}
示例#16
0
文件: csslib.php 项目: numbas/moodle
/**
 * Uses the minify library to compress CSS.
 *
 * This is used if $CFG->enablecssoptimiser has been turned off. This was
 * the original CSS optimisation library.
 * It removes whitespace and shrinks things but does no apparent optimisation.
 * Note the minify library is still being used for JavaScript.
 *
 * @param array $files An array of files to minify
 * @return string The minified CSS
 */
function css_minify_css($files)
{
    global $CFG;
    if (empty($files)) {
        return '';
    }
    set_include_path($CFG->libdir . '/minify/lib' . PATH_SEPARATOR . get_include_path());
    require_once 'Minify.php';
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    // disable all caching, we do it in moodle
    Minify::setCache(null, false);
    $options = array('bubbleCssImports' => false, 'encodeOutput' => false, 'maxAge' => 60 * 60 * 24 * 20, 'files' => $files, 'rewriteCssUris' => false, 'quiet' => true);
    $error = 'unknown';
    try {
        $result = Minify::serve('Files', $options);
        if ($result['success']) {
            return $result['content'];
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error = str_replace("\r", ' ', $error);
        $error = str_replace("\n", ' ', $error);
    }
    // minification failed - try to inform the theme developer and include the non-minified version
    $css = <<<EOD
/* Error: {$error} */
/* Problem detected during theme CSS minimisation, please review the following code */
/* ================================================================================ */


EOD;
    foreach ($files as $cssfile) {
        $css .= file_get_contents($cssfile) . "\n";
    }
    return $css;
}
示例#17
0
文件: serve.php 项目: cretzu89/EPESI
        $this_file_dir_pattern = '/' . preg_quote(dirname(__FILE__), '/') . '/i';
        foreach ($arr as $k => $v) {
            if (preg_match($filenamePattern, $v) && file_exists($v) && preg_match($this_file_dir_pattern, realpath($v))) {
                $arr2[] = $v;
            }
        }
        ini_set('include_path', 'libs/minify' . PATH_SEPARATOR . '.' . PATH_SEPARATOR . 'libs' . PATH_SEPARATOR . ini_get('include_path'));
        require 'Minify.php';
        define('_VALID_ACCESS', 1);
        require_once 'include/data_dir.php';
        require_once 'include/config.php';
        $cache_dir = DATA_DIR . '/cache/minify';
        if (!file_exists($cache_dir)) {
            mkdir($cache_dir, 0777, true);
        }
        Minify::setCache($cache_dir);
        $opts = array('files' => $arr2, 'maxAge' => 86400 * 365, 'rewriteCssUris' => false);
        if (!MINIFY_ENCODE) {
            $opts['encodeOutput'] = false;
            $opts['encodeMethod'] = '';
        }
        if (!MINIFY_SOURCES) {
            $opts['minifiers'] = array(Minify::TYPE_CSS => '', Minify::TYPE_HTML => '', Minify::TYPE_JS => '');
        }
        // The Files controller can serve an array of files, but here we just
        // need one.
        Minify::serve('Files', $opts);
        exit;
    }
}
header("HTTP/1.0 404 Not Found");
示例#18
0
文件: styles.php 项目: hatone/moodle
function minify($files)
{
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    // disable all caching, we do it in moodle
    Minify::setCache(null, false);
    $options = array('bubbleCssImports' => false, 'encodeOutput' => false, 'maxAge' => 60 * 60 * 24 * 20, 'files' => $files, 'rewriteCssUris' => false, 'quiet' => true);
    $result = Minify::serve('Files', $options);
    return $result['content'];
}
示例#19
0
function minify($files)
{
    global $CFG;
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    Minify::setCache('', true);
    $options = array('bubbleCssImports' => false, 'encodeOutput' => false, 'maxAge' => 1800, 'files' => $files, 'rewriteCssUris' => false, 'quiet' => true);
    $result = Minify::serve('Files', $options);
    return $result['content'];
}
 /**
  * Merges and minimizes given scripts or css and returns raw content
  *
  * @param array $files
  *
  * @return mixed|bool
  */
 public function Minify($files = array())
 {
     if (empty($files)) {
         return false;
     }
     $_GET['f'] = implode(',', $files);
     $min_libPath = MODX_MANAGER_PATH . 'min/lib';
     @set_include_path($min_libPath . PATH_SEPARATOR . get_include_path());
     if (!class_exists('Minify')) {
         require_once MODX_MANAGER_PATH . 'min/lib/Minify.php';
     }
     if (!class_exists('Minify_Controller_MinApp')) {
         require_once MODX_MANAGER_PATH . 'min/lib/Minify/Controller/MinApp.php';
     }
     $min_serveController = new Minify_Controller_MinApp();
     /* attempt to prevent suhosin issues */
     @ini_set('suhosin.get.max_value_length', 4096);
     $min_serveOptions = array('quiet' => true, 'encodeMethod' => '');
     if (!file_exists(MODX_CORE_PATH . 'cache/minify')) {
         mkdir(MODX_CORE_PATH . 'cache/minify');
     }
     Minify::setCache(MODX_CORE_PATH . 'cache/minify');
     if ($minify = Minify::serve($min_serveController, $min_serveOptions)) {
         if ($minify['success']) {
             return $minify['content'];
         }
     }
     // Fall back to plain files if Minify fails
     $content = array();
     foreach ($files as $file) {
         if (strpos($file, MODX_BASE_PATH) === false) {
             $file = MODX_BASE_PATH . ltrim($file, '/');
             $content[] = file_get_contents($file);
         }
     }
     $content = implode("\n", $content);
     return $content;
 }
 public function action_template_header()
 {
     //Cache::expire( self::$cache_name . '_js' );
     //Cache::expire( self::$cache_name . '_css' );
     // try to disable output_compression (may not have an effect)
     ini_set('zlib.output_compression', '0');
     $modified_js = Stack::get_sorted_stack('template_header_javascript');
     foreach ($modified_js as $key => $value) {
         Stack::remove('template_header_javascript', $key);
     }
     Stack::add('template_header_javascript', Site::get_url('user') . '/files/minified.js', 'Minified');
     $modified_css = Stack::get_sorted_stack('template_stylesheet');
     $css = array();
     foreach ($modified_css as $key => $value) {
         $css[] = $value[0];
         Stack::remove('template_stylesheet', $key);
     }
     Stack::add('template_stylesheet', array(Site::get_url('user') . "/files/minified.css", 'screen'), 'style');
     /*
      * If we have the files or the cache havent expired don't create new files.
      */
     if (!file_exists(site::get_dir('user') . '/files/minified.css') || !file_exists(site::get_dir('user') . '/files/minified.js') || (!Cache::has(self::$cache_name . '_js') || !Cache::has(self::$cache_name . '_css'))) {
         /* Taken from min/index.php */
         define('MINIFY_MIN_DIR', dirname(__FILE__) . '/min/');
         // load config
         require MINIFY_MIN_DIR . '/config.php';
         // setup include path
         set_include_path($min_libPath . PATH_SEPARATOR . get_include_path());
         require 'Minify.php';
         Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
         Minify::setCache(isset($min_cachePath) ? $min_cachePath : '', $min_cacheFileLocking);
         if ($min_documentRoot) {
             $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot;
         } elseif (0 === stripos(PHP_OS, 'win')) {
             Minify::setDocRoot();
             // IIS may need help
         }
         $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
         // Using jsmin+ 1.3
         $min_serveOptions['minifiers']['application/x-javascript'] = array('JSMinPlus', 'minify');
         /* Javascript */
         if (!Cache::has(self::$cache_name . '_js') || !file_exists(site::get_dir('user') . '/files/minified.js')) {
             $js_stack = array();
             foreach ($modified_js as $js) {
                 $js_stack[] = Site::get_path('base') . str_replace(Site::get_url('habari') . '/', '', $js);
             }
             $options = array('files' => $js_stack, 'encodeOutput' => false, 'quiet' => true);
             $result = Minify::serve('Files', $options);
             file_put_contents(site::get_dir('user') . '/files/minified.js', $result['content']);
             Cache::set(self::$cache_name . '_js', 'true', Options::get('minification__expire'));
         }
         /* CSS */
         if (!Cache::has(self::$cache_name . '_css') || !file_exists(site::get_dir('user') . '/files/minified.css')) {
             $css_stack = array();
             foreach ($css as $file) {
                 $css_stack[] = Site::get_path('base') . str_replace(Site::get_url('habari') . '/', '', $file);
             }
             $options = array('files' => $css_stack, 'encodeOutput' => false, 'quiet' => true);
             // handle request
             $result = Minify::serve('Files', $options);
             file_put_contents(site::get_dir('user') . '/files/minified.css', $result['content']);
             Cache::set(self::$cache_name . '_css', 'true', Options::get('minification__expire'));
         }
     }
 }
示例#22
0
 /**
  * Runs minify
  *
  * @return void
  */
 function process()
 {
     require_once W3TC_LIB_W3_DIR . '/Request.php';
     /**
      * Check for rewrite test request
      */
     $rewrite_test = W3_Request::get_boolean('w3tc_rewrite_test');
     if ($rewrite_test) {
         echo 'OK';
         exit;
     }
     $file = W3_Request::get_string('file');
     if (!$file) {
         $this->error('File param is missing', false);
         return;
     }
     $hash = '';
     $matches = null;
     if (preg_match('~^([a-f0-9]+)\\.[a-f0-9]+\\.(css|js)$~', $file, $matches)) {
         list(, $hash, $type) = $matches;
     } elseif (preg_match('~^([a-f0-9]+)\\/(.+)\\.(include(\\-(footer|body))?(-nb)?)\\.[a-f0-9]+\\.(css|js)$~', $file, $matches)) {
         list(, $theme, $template, $location, , , , $type) = $matches;
     } else {
         $this->error(sprintf('Bad file param format: "%s"', $file), false);
         return;
     }
     require_once W3TC_LIB_MINIFY_DIR . '/Minify.php';
     require_once W3TC_LIB_MINIFY_DIR . '/HTTP/Encoder.php';
     /**
      * Fix DOCUMENT_ROOT
      */
     $_SERVER['DOCUMENT_ROOT'] = w3_get_document_root();
     /**
      * Set cache engine
      */
     Minify::setCache($this->_get_cache());
     /**
      * Set cache ID
      */
     $cache_id = $this->get_cache_id($file);
     Minify::setCacheId($cache_id);
     /**
      * Set logger
      */
     require_once W3TC_LIB_MINIFY_DIR . '/Minify/Logger.php';
     Minify_Logger::setLogger(array(&$this, 'error'));
     /**
      * Set options
      */
     $browsercache = $this->_config->get_boolean('browsercache.enabled');
     $serve_options = array_merge($this->_config->get_array('minify.options'), array('debug' => $this->_config->get_boolean('minify.debug'), 'maxAge' => $this->_config->get_integer('browsercache.cssjs.lifetime'), 'encodeOutput' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.compression'), 'bubbleCssImports' => $this->_config->get_string('minify.css.imports') == 'bubble', 'processCssImports' => $this->_config->get_string('minify.css.imports') == 'process', 'cacheHeaders' => array('use_etag' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.etag'), 'expires_enabled' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.expires'), 'cacheheaders_enabled' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.cache.control'), 'cacheheaders' => $this->_config->get_string('browsercache.cssjs.cache.policy'))));
     /**
      * Set sources
      */
     if ($hash) {
         $_GET['f'] = $this->get_files($hash, $type);
     } else {
         $_GET['g'] = $location;
         $serve_options['minApp']['groups'] = $this->get_groups($theme, $template, $type);
     }
     /**
      * Set minifier
      */
     $w3_minifier =& w3_instance('W3_Minifier');
     if ($type == 'js') {
         $minifier_type = 'application/x-javascript';
         switch (true) {
             case ($hash || $location == 'include' || $location == 'include-nb') && $this->_config->get_boolean('minify.js.combine.header'):
             case ($location == 'include-body' || $location == 'include-body-nb') && $this->_config->get_boolean('minify.js.combine.body'):
             case ($location == 'include-footer' || $location == 'include-footer-nb') && $this->_config->get_boolean('minify.js.combine.footer'):
                 $engine = 'combinejs';
                 break;
             default:
                 $engine = $this->_config->get_string('minify.js.engine');
                 if (!$w3_minifier->exists($engine) || !$w3_minifier->available($engine)) {
                     $engine = 'js';
                 }
                 break;
         }
     } elseif ($type == 'css') {
         $minifier_type = 'text/css';
         if (($hash || $location == 'include') && $this->_config->get_boolean('minify.css.combine')) {
             $engine = 'combinecss';
         } else {
             $engine = $this->_config->get_string('minify.css.engine');
             if (!$w3_minifier->exists($engine) || !$w3_minifier->available($engine)) {
                 $engine = 'css';
             }
         }
     }
     /**
      * Initialize minifier
      */
     $w3_minifier->init($engine);
     $serve_options['minifiers'][$minifier_type] = $w3_minifier->get_minifier($engine);
     $serve_options['minifierOptions'][$minifier_type] = $w3_minifier->get_options($engine);
     /**
      * Send X-Powered-By header
      */
     if ($browsercache && $this->_config->get_boolean('browsercache.cssjs.w3tc')) {
         @header('X-Powered-By: ' . W3TC_POWERED_BY);
     }
     /**
      * Minify!
      */
     try {
         Minify::serve('MinApp', $serve_options);
     } catch (Exception $exception) {
         $this->error($exception->getMessage());
     }
 }
示例#23
0
function test_Minify()
{
    global $thisDir;
    $minifyTestPath = dirname(__FILE__) . '/_test_files/minify';
    $thisFileActive = __FILE__ === realpath($_SERVER['SCRIPT_FILENAME']);
    $tomorrow = $_SERVER['REQUEST_TIME'] + 86400;
    $lastModified = $_SERVER['REQUEST_TIME'] - 86400;
    // Test 304 response
    // simulate conditional headers
    $_SERVER['HTTP_IF_NONE_MATCH'] = "\"{$lastModified}pub\"";
    $_SERVER['HTTP_IF_MODIFIED_SINCE'] = gmdate('D, d M Y H:i:s \\G\\M\\T', $lastModified);
    $expected = array('success' => true, 'statusCode' => 304, 'content' => '', 'headers' => array('Expires' => gmdate('D, d M Y H:i:s \\G\\M\\T', $_SERVER['REQUEST_TIME'] + 1800), 'Vary' => 'Accept-Encoding', 'Last-Modified' => gmdate('D, d M Y H:i:s \\G\\M\\T', $lastModified), 'ETag' => "\"pub{$lastModified}\"", 'Cache-Control' => 'max-age=1800, public', '_responseCode' => 'HTTP/1.0 304 Not Modified'));
    $output = Minify::serve('Files', array('files' => $thisDir . '/_test_files/css/styles.css', 'quiet' => true, 'lastModifiedTime' => $lastModified, 'encodeOutput' => false));
    $passed = assertTrue($expected === $output, 'Minify : 304 response');
    if ($thisFileActive) {
        echo "\nOutput: " . var_export($output, 1) . "\n\n";
        if (!$passed) {
            echo "\n\n\n\n---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    assertTrue(!class_exists('Minify_CSS', false) && !class_exists('Minify_Cache', false), 'Minify : cache, and minifier classes aren\'t loaded for 304s');
    // Test minifying JS and serving with Expires header
    $content = preg_replace('/\\r\\n?/', "\n", file_get_contents($minifyTestPath . '/minified.js'));
    $lastModified = max(filemtime($minifyTestPath . '/email.js'), filemtime($minifyTestPath . '/QueryString.js'));
    $expected = array('success' => true, 'statusCode' => 200, 'content' => $content, 'headers' => array('Expires' => gmdate('D, d M Y H:i:s \\G\\M\\T', $tomorrow), 'Vary' => 'Accept-Encoding', 'Last-Modified' => gmdate('D, d M Y H:i:s \\G\\M\\T', $lastModified), 'ETag' => "\"pub{$lastModified}\"", 'Cache-Control' => 'max-age=86400, public', 'Content-Length' => strlen($content), 'Content-Type' => 'application/x-javascript; charset=utf-8'));
    $output = Minify::serve('Files', array('files' => array($minifyTestPath . '/email.js', $minifyTestPath . '/QueryString.js'), 'quiet' => true, 'maxAge' => 86400, 'encodeOutput' => false));
    $passed = assertTrue($expected === $output, 'Minify : JS and Expires');
    if ($thisFileActive) {
        echo "\nOutput: " . var_export($output, 1) . "\n\n";
        if (!$passed) {
            echo "\n\n\n\n---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    // test for Issue 73
    Minify::setCache(null);
    $expected = ";function h(){}";
    $output = Minify::serve('Files', array('files' => array($minifyTestPath . '/issue73_1.js', $minifyTestPath . '/issue73_2.js'), 'quiet' => true, 'encodeOutput' => false));
    $output = $output['content'];
    $passed = assertTrue($expected === $output, 'Minify : Issue 73');
    if ($thisFileActive) {
        if (!$passed) {
            echo "\n---Output  : " . var_export($output, 1) . "\n";
            echo "---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    // test for Issue 89
    $expected = file_get_contents($minifyTestPath . '/issue89_out.min.css');
    $output = Minify::serve('Files', array('files' => array($minifyTestPath . '/issue89_1.css', $minifyTestPath . '/issue89_2.css'), 'quiet' => true, 'encodeOutput' => false, 'bubbleCssImports' => true));
    $output = $output['content'];
    $passed = assertTrue($expected === $output, 'Minify : Issue 89 : bubbleCssImports');
    if ($thisFileActive) {
        if (!$passed) {
            echo "\n---Output  : " . var_export($output, 1) . "\n";
            echo "---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    $output = Minify::serve('Files', array('files' => array($minifyTestPath . '/issue89_1.css', $minifyTestPath . '/issue89_2.css'), 'quiet' => true, 'encodeOutput' => false));
    $output = $output['content'];
    $passed = assertTrue(0 === strpos($output, Minify::$importWarning), 'Minify : Issue 89 : detect invalid imports');
    if ($thisFileActive) {
        if (!$passed) {
            echo "\n---Output  : " . var_export($output, 1) . "\n";
            echo "---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    $output = Minify::serve('Files', array('files' => array($minifyTestPath . '/issue89_1.css'), 'quiet' => true, 'encodeOutput' => false));
    $output = $output['content'];
    $passed = assertTrue(false === strpos($output, Minify::$importWarning), 'Minify : Issue 89 : don\'t warn about valid imports');
    if ($thisFileActive) {
        if (!$passed) {
            echo "\n---Output  : " . var_export($output, 1) . "\n";
            echo "---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
    // Test minifying CSS and responding with Etag/Last-Modified
    Minify::setCache(null);
    // don't allow conditional headers
    unset($_SERVER['HTTP_IF_NONE_MATCH'], $_SERVER['HTTP_IF_MODIFIED_SINCE']);
    $expectedContent = file_get_contents($minifyTestPath . '/minified.css');
    $expected = array('success' => true, 'statusCode' => 200, 'content' => $expectedContent, 'headers' => array('Vary' => 'Accept-Encoding', 'Last-Modified' => gmdate('D, d M Y H:i:s \\G\\M\\T', $lastModified), 'ETag' => "\"pub{$lastModified}\"", 'Cache-Control' => 'max-age=0, public', 'Content-Length' => strlen($expectedContent), 'Content-Type' => 'text/css; charset=utf-8'));
    $output = Minify::serve('Files', array('files' => array($thisDir . '/_test_files/css/styles.css', $thisDir . '/_test_files/css/comments.css'), 'quiet' => true, 'lastModifiedTime' => $lastModified, 'encodeOutput' => false, 'maxAge' => false));
    $passed = assertTrue($expected === $output, 'Minify : CSS and Etag/Last-Modified');
    if ($thisFileActive) {
        echo "\nOutput: " . var_export($output, 1) . "\n\n";
        if (!$passed) {
            echo "\n\n\n\n---Expected: " . var_export($expected, 1) . "\n\n";
        }
    }
}
示例#24
0
文件: m.php 项目: rajarshc/Rooja
    $rootdir = preg_replace('!' . $dir[0] . '$!', '', BP);
    $min_symlinks = array('//' => $rootdir);
}
// Prepends include_path. You could alternately do this via .htaccess or php.ini
set_include_path(BP . DS . 'lib' . DS . 'minify' . DS . 'lib' . PS . get_include_path());
// Set $minifyCachePath to a PHP-writeable path to enable server-side caching
$minifyCachePath = BP . DS . 'var' . DS . 'minifycache';
// The Files controller only "knows" CSS, and JS files.
$serveExtensions = array('css', 'js');
// Serve
if (isset($_GET['f'])) {
    $filenames = explode(",", $_GET['f']);
    $filenamePattern = '/[^\'"\\/\\\\]+\\.(?:' . implode('|', $serveExtensions) . ')$/';
    require 'Minify.php';
    if ($minifyCachePath) {
        Minify::setCache($minifyCachePath);
    }
    if ($min_documentRoot) {
        $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot;
    } elseif (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    //on some apache installs this is needed
    if (array_key_exists('SUBDOMAIN_DOCUMENT_ROOT', $_SERVER)) {
        $_SERVER['DOCUMENT_ROOT'] = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT'];
    }
    //check if requested files exists and add to minify request
    $servefiles = array();
    foreach ($filenames as $filename) {
        if (preg_match($filenamePattern, $filename) && file_exists(BP . $filename)) {
示例#25
0
                            msg += 'The option "zlib.output_compression" is disabled in your PHP configuration '
                                + 'so this behavior is likely due to a server option.';
                        $(document.body).prepend(msg + '<\/p>');
                    } else if (ocStatus == '1')
                        $(document.body).prepend('<\p class=topNote><\strong>Note:</\strong> The option '
                            + '"zlib.output_compression" is enabled in your PHP configuration, but has been '
                            + 'successfully disabled via ini_set(). If you experience mangled output you '
                            + 'may want to consider disabling this option in your PHP configuration.<\/p>'
                        );
                });
            });
        });
    </script>
    <script type="text/javascript">
        // workaround required to test when /min isn't child of web root
        var src = location.pathname.replace(/\/[^\/]*$/, '/_index.js').substr(1);
        document.write('<\script type="text/javascript" src="../?f=' + src + '"><\/script>');
    </script>

<?php 
$serveOpts = array('content' => ob_get_contents(), 'id' => __FILE__, 'lastModifiedTime' => max(filemtime(__FILE__), filemtime(dirname(__FILE__) . '/../config.php')), 'minifyAll' => true, 'encodeOutput' => $encodeOutput);
ob_end_clean();
set_include_path(dirname(__FILE__) . '/../lib' . PATH_SEPARATOR . get_include_path());
require 'Minify.php';
if (0 === stripos(PHP_OS, 'win')) {
    Minify::setDocRoot();
    // we may be on IIS
}
Minify::setCache(isset($min_cachePath) ? $min_cachePath : null);
Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
Minify::serve('Page', $serveOpts);
示例#26
0
/**
 * Uses the minify library to compress CSS.
 *
 * This is used if $CFG->enablecssoptimiser has been turned off. This was
 * the original CSS optimisation library.
 * It removes whitespace and shrinks things but does no apparent optimisation.
 * Note the minify library is still being used for JavaScript.
 *
 * @param array $files An array of files to minify
 * @return string The minified CSS
 */
function css_minify_css($files)
{
    global $CFG;
    if (empty($files)) {
        return '';
    }
    // We do not really want any 304 here!
    // There does not seem to be any better way to prevent them here.
    unset($_SERVER['HTTP_IF_NONE_MATCH']);
    unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
    set_include_path($CFG->libdir . '/minify/lib' . PATH_SEPARATOR . get_include_path());
    require_once 'Minify.php';
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot();
        // IIS may need help
    }
    // disable all caching, we do it in moodle
    Minify::setCache(null, false);
    $options = array('minifiers' => array(Minify::TYPE_JS => array('JSMinPlus', 'minify')), 'bubbleCssImports' => false, 'encodeOutput' => false, 'maxAge' => 60 * 60 * 24 * 20, 'files' => $files, 'rewriteCssUris' => false, 'quiet' => true);
    $error = 'unknown';
    try {
        $result = Minify::serve('Files', $options);
        if ($result['success'] and $result['statusCode'] == 200) {
            return $result['content'];
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error = str_replace("\r", ' ', $error);
        $error = str_replace("\n", ' ', $error);
    }
    // minification failed - try to inform the theme developer and include the non-minified version
    $css = <<<EOD
/* Error: {$error} */
/* Problem detected during theme CSS minimisation, please review the following code */
/* ================================================================================ */


EOD;
    foreach ($files as $cssfile) {
        $css .= file_get_contents($cssfile) . "\n";
    }
    return $css;
}
示例#27
0
 public function enableFilesCache()
 {
     Minify::setCache(new Minify_Cache_File());
 }
 /**
  * Serves friendly minify url with minified contents
  *
  * This actually does a remote get from Minify's dir with appropriate `?f`
  * query variable built from persistently stored detected enqueued files.
  * All minified contents as well as headers should be preserved.
  *
  * Serving friendly minify urls like this cause a lot of overheads, but is
  * safer to use than server rewrite rules.
  *
  * @uses wp_remote_get()
  * @return void
  */
 public function serve($query)
 {
     $group_handle = isset($_GET['min_group']) ? $this->_sanitize_request($_GET['min_group']) : '';
     $type = isset($_GET['min_type']) && in_array($_GET['min_type'], array('js', 'css')) ? $_GET['min_type'] : '';
     $bid = isset($_GET['blog']) ? (int) $_GET['blog'] : 0;
     if (empty($group_handle) || empty($type) || empty($bid)) {
         // if missing any important data, do not proceed
         return;
     }
     global $blog_id;
     if ($bid != $blog_id) {
         // if not on the correct blog, do not proceed
         return;
     }
     $group = $this->_detector->get_group($group_handle);
     if (false == $group) {
         // this should not happen, but just in case it does
         echo sprintf(__('Minify group %s not found.', $this->_domain), $group_handle);
         exit;
     }
     // load Minify class based on default or custom Minify directory
     $min_dir = $this->_main->get_min_dir();
     if (empty($min_dir) || !file_exists($min_dir . 'config.php')) {
         // if Minify directory is not valid or Minify library is not found
         // we can not continue
         _e('Invalid Minify directory, please check Minify settings.', $this->_domain);
         exit;
     }
     // prepare input for Minify to handle
     $_GET['f'] = $group['string'];
     if ($this->_options['enable_debug'] == 'yes') {
         // add debug flag if needed
         $_GET['debug'] = 1;
     } else {
         // minified contents are often served compressed so it's best to turn off
         // error reporting to avoid content encoding error, unless debug is
         // enabled. This is useful when Minify doesn't catch all the notices
         // (for example when the cache directory is not writable).
         error_reporting(0);
     }
     // load Minify classes
     define('MINIFY_MIN_DIR', $min_dir);
     require_once MINIFY_MIN_DIR . '/config.php';
     require_once $min_libPath . '/Minify/Loader.php';
     Minify_Loader::register();
     // set some optional for the Minify application based on current settings
     Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
     // set cache file name (id) and cache path if needed
     Minify::setCacheId('minify-b' . $blog_id . '-' . $group_handle . '.' . $type);
     Minify::setCache(isset($min_cachePath) ? $min_cachePath : '', $min_cacheFileLocking);
     if ($min_documentRoot) {
         $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot;
         Minify::$isDocRootSet = true;
     }
     // set serve options for each file type if needed
     $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
     foreach ($min_symlinks as $uri => $target) {
         $min_serveOptions['minApp']['allowDirs'][] = $target;
     }
     if ($min_allowDebugFlag) {
         // allow debugging Minify application
         $min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
     }
     if ($min_errorLogger) {
         // log Minify error if allowed
         if (true === $min_errorLogger) {
             $min_errorLogger = FirePHP::getInstance(true);
         }
         Minify_Logger::setLogger($min_errorLogger);
     }
     // serve minified contents, on the fly or from cache
     $min_serveController = new Minify_Controller_MinApp();
     Minify::serve($min_serveController, $min_serveOptions);
     // for a proper response headers
     exit;
 }
示例#29
0
 /**
  * Runs minify
  *
  * @param string|null $file
  *
  * @return void
  */
 function process($file = NULL)
 {
     w3_require_once(W3TC_LIB_W3_DIR . '/Request.php');
     /**
      * Check for rewrite test request
      */
     $rewrite_test = W3_Request::get_boolean('w3tc_rewrite_test');
     if ($rewrite_test) {
         echo 'OK';
         exit;
     }
     $rewrite_test = W3_Request::get_string('test_file');
     if ($rewrite_test) {
         $cache = $this->_get_cache();
         header('Content-type: text/css');
         if ($cache->store(basename($rewrite_test), 'content ok')) {
             if (function_exists('gzencode') && $this->_config->get_boolean('browsercache.enabled') && $this->_config->get_boolean('browsercache.cssjs.compression')) {
                 if (!$cache->store(basename($rewrite_test) . '.gzip', gzencode('content ok'))) {
                     echo 'error storing';
                     exit;
                 }
             }
             if ($this->_config->get_string('minify.engine') != 'file') {
                 if ($cache->fetch(basename($rewrite_test)) == 'content ok') {
                     echo 'content ok';
                 } else {
                     echo 'error storing';
                 }
             } else {
                 echo 'retry';
             }
         } else {
             echo 'error storing';
         }
         exit;
     }
     if (is_null($file)) {
         $file = W3_Request::get_string('file');
     }
     if (!$file) {
         $this->error('File param is missing', false);
         return;
     }
     // remove blog_id
     $levels = '';
     if (defined('W3TC_BLOG_LEVELS')) {
         for ($n = 0; $n < W3TC_BLOG_LEVELS; $n++) {
             $levels .= '[0-9]+\\/';
         }
     }
     if (preg_match('~^(' . $levels . '[0-9]+)\\/(.+)$~', $file, $matches)) {
         $file = $matches[2];
     }
     // parse file
     $hash = '';
     $matches = null;
     $location = '';
     $type = '';
     if (preg_match('~^' . MINIFY_AUTO_FILENAME_REGEX . '$~', $file, $matches)) {
         list(, $hash, $type) = $matches;
     } elseif (preg_match('~^' . MINIFY_MANUAL_FILENAME_REGEX . '$~', $file, $matches)) {
         list(, $theme, $template, $location, , , $type) = $matches;
     } else {
         $this->error(sprintf('Bad file param format: "%s"', $file), false);
         return;
     }
     w3_require_once(W3TC_LIB_MINIFY_DIR . '/Minify.php');
     w3_require_once(W3TC_LIB_MINIFY_DIR . '/HTTP/Encoder.php');
     /**
      * Fix DOCUMENT_ROOT
      */
     $_SERVER['DOCUMENT_ROOT'] = w3_get_document_root();
     /**
      * Set cache engine
      */
     Minify::setCache($this->_get_cache());
     /**
      * Set cache ID
      */
     $cache_id = $this->get_cache_id($file);
     Minify::setCacheId($cache_id);
     /**
      * Set logger
      */
     w3_require_once(W3TC_LIB_MINIFY_DIR . '/Minify/Logger.php');
     Minify_Logger::setLogger(array(&$this, 'error'));
     /**
      * Set options
      */
     $browsercache = $this->_config->get_boolean('browsercache.enabled');
     $serve_options = array_merge($this->_config->get_array('minify.options'), array('debug' => $this->_config->get_boolean('minify.debug'), 'maxAge' => $this->_config->get_integer('browsercache.cssjs.lifetime'), 'encodeOutput' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.compression'), 'bubbleCssImports' => $this->_config->get_string('minify.css.imports') == 'bubble', 'processCssImports' => $this->_config->get_string('minify.css.imports') == 'process', 'cacheHeaders' => array('use_etag' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.etag'), 'expires_enabled' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.expires'), 'cacheheaders_enabled' => $browsercache && $this->_config->get_boolean('browsercache.cssjs.cache.control'), 'cacheheaders' => $this->_config->get_string('browsercache.cssjs.cache.policy'))));
     /**
      * Set sources
      */
     if ($hash) {
         $_GET['f'] = $this->get_custom_files($hash, $type);
     } else {
         $_GET['g'] = $location;
         $serve_options['minApp']['groups'] = $this->get_groups($theme, $template, $type);
     }
     /**
      * Set minifier
      */
     $w3_minifier = w3_instance('W3_Minifier');
     if ($type == 'js') {
         $minifier_type = 'application/x-javascript';
         switch (true) {
             case ($hash || $location == 'include') && $this->_config->get_boolean('minify.js.combine.header'):
             case $location == 'include-body' && $this->_config->get_boolean('minify.js.combine.body'):
             case $location == 'include-footer' && $this->_config->get_boolean('minify.js.combine.footer'):
                 $engine = 'combinejs';
                 break;
             default:
                 $engine = $this->_config->get_string('minify.js.engine');
                 if (!$w3_minifier->exists($engine) || !$w3_minifier->available($engine)) {
                     $engine = 'js';
                 }
                 break;
         }
     } elseif ($type == 'css') {
         $minifier_type = 'text/css';
         if (($hash || $location == 'include') && $this->_config->get_boolean('minify.css.combine')) {
             $engine = 'combinecss';
         } else {
             $engine = $this->_config->get_string('minify.css.engine');
             if (!$w3_minifier->exists($engine) || !$w3_minifier->available($engine)) {
                 $engine = 'css';
             }
         }
     }
     /**
      * Initialize minifier
      */
     $w3_minifier->init($engine);
     $serve_options['minifiers'][$minifier_type] = $w3_minifier->get_minifier($engine);
     $serve_options['minifierOptions'][$minifier_type] = $w3_minifier->get_options($engine);
     /**
      * Send X-Powered-By header
      */
     if ($browsercache && $this->_config->get_boolean('browsercache.cssjs.w3tc')) {
         @header('X-Powered-By: ' . W3TC_POWERED_BY);
     }
     /**
      * Minify!
      */
     try {
         Minify::serve('MinApp', $serve_options);
     } catch (Exception $exception) {
         $this->error($exception->getMessage());
     }
     if (!$this->_error_occurred && $this->_config_admin->get_boolean('notes.minify_error')) {
         $error_file = $this->_config_admin->get_string('minify.error.file');
         if ($error_file == $file) {
             $this->_config_admin->set('notes.minify_error', false);
             $this->_config_admin->save();
         }
     }
 }
示例#30
0
function minify($files) {
    if (0 === stripos(PHP_OS, 'win')) {
        Minify::setDocRoot(); // IIS may need help
    }
    // disable all caching, we do it in moodle
    Minify::setCache(null, false);

    $options = array(
        'bubbleCssImports' => false,
        // Don't gzip content we just want text for storage
        'encodeOutput' => false,
        // Maximum age to cache, not used but required
        'maxAge' => 1800,
        // The files to minify
        'files' => $files,
        // Turn orr URI rewriting
        'rewriteCssUris' => false,
        // This returns the CSS rather than echoing it for display
        'quiet' => true
    );

    $result = Minify::serve('Files', $options);
    return $result['content'];
}