1
0
mirror of https://github.com/mrclay/minify.git synced 2025-01-17 21:28:14 +01:00

WIP: Huge overhaul. min app works!

This commit is contained in:
Steve Clay 2014-09-23 11:09:09 -04:00
parent c75f97f3bc
commit 6d9fe1531e
18 changed files with 693 additions and 674 deletions

View File

@ -220,22 +220,33 @@ by Minify. E.g. <code>@import "<span class=minRoot>/min/?</span>g=css2";</code><
<?php
$content = ob_get_clean();
// setup Minify
Minify::setCache(
isset($min_cachePath) ? $min_cachePath : ''
,$min_cacheFileLocking
);
Minify::$uploaderHoursBehind = $min_uploaderHoursBehind;
if (empty($min_cachePath)) {
$cache = new Minify_Cache_File('', $min_cacheFileLocking);
} elseif (is_object($min_cachePath)) {
$cache = $min_cachePath;
} else {
$cache = new Minify_Cache_File($min_cachePath, $min_cacheFileLocking);
}
Minify::serve('Page', array(
'content' => $content
,'id' => __FILE__
,'lastModifiedTime' => max(
// regenerate cache if any of these change
filemtime(__FILE__)
,filemtime(dirname(__FILE__) . '/../config.php')
,filemtime(dirname(__FILE__) . '/../lib/Minify.php')
)
,'minifyAll' => true
,'encodeOutput' => $encodeOutput
$env = new Minify_Env();
$sourceFactory = new Minify_Source_Factory($env, array(
'uploaderHoursBehind' => $min_uploaderHoursBehind,
));
$controller = new Minify_Controller_Page($env, $sourceFactory);
$server = new Minify($cache);
$server->serve($controller, array(
'content' => $content,
'id' => __FILE__,
'lastModifiedTime' => max(
// regenerate cache if any of these change
filemtime(__FILE__),
filemtime(dirname(__FILE__) . '/../config.php'),
filemtime(dirname(__FILE__) . '/../lib/Minify.php')
),
'minifyAll' => true,
'encodeOutput' => $encodeOutput,
));

View File

@ -12,6 +12,8 @@
**/
return array(
// 'js' => array('//js/file1.js', '//js/file2.js'),
// 'css' => array('//css/file1.css', '//css/file2.css'),
// 'testJs' => array('//minify/min/quick-test.js'),
// 'testCss' => array('//minify/min/quick-test.css'),
// 'js' => array('//js/file1.js', '//js/file2.js'),
// 'css' => array('//css/file1.css', '//css/file2.css'),
);

View File

@ -13,7 +13,7 @@ define('MINIFY_MIN_DIR', dirname(__FILE__));
$min_configPaths = array(
'base' => MINIFY_MIN_DIR . '/config.php',
'test' => MINIFY_MIN_DIR . '/config-test.php',
'groups' => MINIFY_MIN_DIR . '/groupsConfig.php'
'groups' => MINIFY_MIN_DIR . '/groupsConfig.php',
);
// check for custom config paths
@ -53,8 +53,9 @@ if (!isset($min_cachePath)) {
$cache = new Minify_Cache_File($min_cachePath, $min_cacheFileLocking);
}
$server = new Minify($env, $cache);
$server = new Minify($cache);
$min_serveOptions['minifierOptions']['text/css']['docRoot'] = $env->getDocRoot();
$min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks;
// auto-add targets to allowDirs
foreach ($min_symlinks as $uri => $target) {
@ -62,7 +63,7 @@ foreach ($min_symlinks as $uri => $target) {
}
if ($min_allowDebugFlag) {
$min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
$min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($env);
}
if ($min_errorLogger) {
@ -73,44 +74,37 @@ if ($min_errorLogger) {
}
// check for URI versioning
if (preg_match('/&\\d/', $_SERVER['QUERY_STRING']) || isset($_GET['v'])) {
if (null !== $env->get('v') || preg_match('/&\\d/', $env->server('QUERY_STRING'))) {
$min_serveOptions['maxAge'] = 31536000;
}
// need groups config?
if (isset($_GET['g'])) {
if (null !== $env->get('g')) {
// well need groups config
$min_serveOptions['minApp']['groups'] = (require $min_configPaths['groups']);
}
// serve or redirect
if (isset($_GET['f']) || isset($_GET['g'])) {
if ($env->get('f') || null !== $env->get('g')) {
// serving!
if (! isset($min_serveController)) {
$sourceFactoryOptions = array(
'noMinPattern' => '@[-\\.]min\\.(?:js|css)$@i', // matched against basename
'uploaderHoursBehind' => 0,
'fileChecker' => array($this, 'checkIsFile'),
'resolveDocRoot' => true,
'checkAllowDirs' => true,
'allowDirs' => array($env->getDocRoot()),
);
$sourceFactoryOptions = array();
if (isset($min_serveOptions['minApp']['noMinPattern'])) {
$sourceFactoryOptions['noMinPattern'] = $min_serveOptions['minApp']['noMinPattern'];
}
$sourceFactory = new Minify_Source_Factory($env, $sourceFactoryOptions);
$min_serveController = new Minify_Controller_MinApp();
$min_serveController = new Minify_Controller_MinApp($env, $sourceFactory);
}
$server->serve($min_serveController, $min_serveOptions);
} elseif ($min_enableBuilder) {
header('Location: builder/');
exit;
} else {
header('Location: /');
exit;
}
// not serving
if ($min_enableBuilder) {
header('Location: builder/');
exit;
}
header('Location: /');
exit;

View File

@ -32,35 +32,95 @@ class Minify {
const TYPE_JS = 'application/x-javascript';
const URL_DEBUG = 'http://code.google.com/p/minify/wiki/Debugging';
public function __construct(Minify_Env $env, Minify_CacheInterface $cache) {
$this->env = $env;
/**
* Any Minify_Cache_* object or null (i.e. no server cache is used)
*
* @var Minify_CacheInterface
*/
private $cache = null;
/**
* Active controller for current request
*
* @var Minify_Controller_Base
*/
protected $controller = null;
/**
* @var Minify_SourceInterface[]
*/
protected $sources;
/**
* @var string
*/
protected $selectionId;
/**
* Options for current request
*
* @var array
*/
protected $options = null;
/**
* @param Minify_CacheInterface $cache
*/
public function __construct(Minify_CacheInterface $cache) {
$this->cache = $cache;
}
/**
* If this string is not empty AND the serve() option 'bubbleCssImports' is
* NOT set, then serve() will check CSS files for @import declarations that
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning.
* Get default Minify options.
*
* @var string $importWarning
* @return array options for Minify
*/
public $importWarning = "/* See http://code.google.com/p/minify/wiki/CommonProblems#@imports_can_appear_in_invalid_locations_in_combined_CSS_files */\n";
/**
* Replace the cache object
*
* @param Minify_CacheInterface $cache object
*/
public function setCache(Minify_CacheInterface $cache)
public function getDefaultOptions()
{
$this->cache = $cache;
return array(
'isPublic' => true,
'encodeOutput' => function_exists('gzdeflate'),
'encodeMethod' => null, // determine later
'encodeLevel' => 9,
'minifiers' => array(
Minify::TYPE_JS => array('JSMin', 'minify'),
Minify::TYPE_CSS => array('Minify_CSS', 'minify'),
Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
),
'minifierOptions' => array(), // no minifier options
'contentTypeCharset' => 'utf-8',
'maxAge' => 1800, // 30 minutes
'rewriteCssUris' => true,
'bubbleCssImports' => false,
'quiet' => false, // serve() will send headers and output
'debug' => false,
// if you override these, the response codes MUST be directly after
// the first space.
'badRequestHeader' => 'HTTP/1.0 400 Bad Request',
'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
// callback function to see/modify content of all sources
'postprocessor' => null,
// file to require to load preprocessor
'postprocessorRequire' => null,
/**
* If this string is not empty AND the serve() option 'bubbleCssImports' is
* NOT set, then serve() will check CSS files for @import declarations that
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning.
*/
'importWarning' => "/* See http://code.google.com/p/minify/wiki/CommonProblems#@imports_can_appear_in_invalid_locations_in_combined_CSS_files */\n"
);
}
/**
* Serve a request for a minified file.
*
* Here are the available options and defaults in the base controller:
* Here are the available options and defaults:
*
* 'isPublic' : send "public" instead of "private" in Cache-Control
* headers, allowing shared caches to cache the output. (default true)
@ -118,13 +178,16 @@ class Minify {
* js/css/html. The given content-type will be sent regardless of source file
* extension, so this should not be used in a Groups config with other
* Javascript/CSS files.
*
* 'importWarning' : serve() will check CSS files for @import declarations that
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning. To disable this, set this option to empty string.
*
* Any controller options are documented in that controller's setupSources() method.
* Any controller options are documented in that controller's createConfiguration() method.
*
* @param mixed $controller instance of subclass of Minify_Controller_Base or string
* name of controller. E.g. 'Files'
* @param Minify_ControllerInterface $controller instance of subclass of Minify_Controller_Base
*
* @param array $options controller/serve options
* @param array $options controller/serve options
*
* @return null|array if the 'quiet' option is set to true, an array
* with keys "success" (bool), "statusCode" (int), "content" (string), and
@ -132,33 +195,28 @@ class Minify {
*
* @throws Exception
*/
public function serve($controller, $options = array())
public function serve(Minify_ControllerInterface $controller, $options = array())
{
if (is_string($controller)) {
// make $controller into object
$class = 'Minify_Controller_' . $controller;
$controller = new $class();
/* @var Minify_Controller_Base $controller */
}
// set up controller sources and mix remaining options with
// controller defaults
$options = $controller->setupSources($options);
$options = $controller->analyzeSources($options);
$this->options = $controller->mixInDefaultOptions($options);
$options = array_merge($this->getDefaultOptions(), $options);
$config = $controller->createConfiguration($options);
$this->sources = $config->getSources();
$this->selectionId = $config->getSelectionId();
$this->options = $this->analyzeSources($config->getOptions());
// check request validity
if (! $controller->sources) {
if (!$this->sources) {
// invalid request!
if (! $this->options['quiet']) {
$this->errorExit($this->options['badRequestHeader'], self::URL_DEBUG);
} else {
list(,$statusCode) = explode(' ', $this->options['badRequestHeader']);
return array(
'success' => false
,'statusCode' => (int)$statusCode
,'content' => ''
,'headers' => array()
'success' => false,
'statusCode' => (int)$statusCode,
'content' => '',
'headers' => array(),
);
}
}
@ -166,7 +224,7 @@ class Minify {
$this->controller = $controller;
if ($this->options['debug']) {
$this->setupDebug($controller->sources);
$this->setupDebug();
$this->options['maxAge'] = 0;
}
@ -190,15 +248,17 @@ class Minify {
// check client cache
$cgOptions = array(
'lastModifiedTime' => $this->options['lastModifiedTime']
,'isPublic' => $this->options['isPublic']
,'encoding' => $this->options['encodeMethod']
'lastModifiedTime' => $this->options['lastModifiedTime'],
'isPublic' => $this->options['isPublic'],
'encoding' => $this->options['encodeMethod'],
);
if ($this->options['maxAge'] > 0) {
$cgOptions['maxAge'] = $this->options['maxAge'];
} elseif ($this->options['debug']) {
$cgOptions['invalidate'] = true;
}
$cg = new HTTP_ConditionalGet($cgOptions);
if ($cg->cacheIsValid) {
// client's cache is valid
@ -207,10 +267,10 @@ class Minify {
return;
} else {
return array(
'success' => true
,'statusCode' => 304
,'content' => ''
,'headers' => $cg->getHeaders()
'success' => true,
'statusCode' => 304,
'content' => '',
'headers' => $cg->getHeaders(),
);
}
} else {
@ -219,11 +279,8 @@ class Minify {
unset($cg);
}
if ($this->options['contentType'] === self::TYPE_CSS
&& $this->options['rewriteCssUris']) {
foreach($controller->sources as $key => $source) {
$source->setupUriRewrites();
}
if ($this->options['contentType'] === self::TYPE_CSS && $this->options['rewriteCssUris']) {
$this->setupUriRewrites();
}
// check server cache
@ -233,9 +290,8 @@ class Minify {
// output the content, as they do not require ever loading the file into
// memory.
$cacheId = $this->_getCacheId();
$fullCacheId = ($this->options['encodeMethod'])
? $cacheId . '.gz'
: $cacheId;
$fullCacheId = ($this->options['encodeMethod']) ? $cacheId . '.gz' : $cacheId;
// check cache for valid entry
$cacheIsReady = $this->cache->isValid($fullCacheId, $this->options['lastModifiedTime']);
if ($cacheIsReady) {
@ -275,15 +331,21 @@ class Minify {
}
// add headers
$headers['Content-Length'] = $cacheIsReady
? $cacheContentLength
: ((function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($content, '8bit')
: strlen($content)
);
$headers['Content-Type'] = $this->options['contentTypeCharset']
? $this->options['contentType'] . '; charset=' . $this->options['contentTypeCharset']
: $this->options['contentType'];
if ($cacheIsReady) {
$headers['Content-Length'] = $cacheContentLength;
} else {
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
$headers['Content-Length'] = mb_strlen($content, '8bit');
} else {
$headers['Content-Length'] = strlen($content);
}
}
$headers['Content-Type'] = $this->options['contentType'];
if ($this->options['contentTypeCharset']) {
$headers['Content-Type'] .= '; charset=' . $this->options['contentTypeCharset'];
}
if ($this->options['encodeMethod'] !== '') {
$headers['Content-Encoding'] = $contentEncoding;
}
@ -303,12 +365,10 @@ class Minify {
}
} else {
return array(
'success' => true
,'statusCode' => 200
,'content' => $cacheIsReady
? $this->cache->fetch($fullCacheId)
: $content
,'headers' => $headers
'success' => true,
'statusCode' => 200,
'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
'headers' => $headers,
);
}
}
@ -327,45 +387,26 @@ class Minify {
*/
public function combine($sources, $options = array())
{
throw new BadMethodCallException(__METHOD__ . ' needs to be rewritten/replaced');
$cache = $this->cache;
$this->cache = null;
$this->cache = new Minify_Cache_Null();
$options = array_merge(array(
'files' => (array)$sources
,'quiet' => true
,'encodeMethod' => ''
,'lastModifiedTime' => 0
'files' => (array)$sources,
'quiet' => true,
'encodeMethod' => '',
'lastModifiedTime' => 0,
), $options);
$out = $this->serve('Files', $options);
$sourceFactory = new Minify_Source_Factory($this->env);
$controller = new Minify_Controller_Files($this->env, $sourceFactory);
$out = $this->serve($controller, $options);
$this->cache = $cache;
return $out['content'];
}
/**
* @var Minify_Env
*/
protected $env;
/**
* Any Minify_Cache_* object or null (i.e. no server cache is used)
*
* @var Minify_CacheInterface
*/
private $cache = null;
/**
* Active controller for current request
*
* @var Minify_Controller_Base
*/
protected $controller = null;
/**
* Options for current request
*
* @var array
*/
protected $options = null;
/**
* @param string $header
*
@ -386,17 +427,34 @@ class Minify {
}
/**
* Set up sources to use Minify_Lines
*
* @param Minify_SourceInterface[] $sources
* Setup CSS sources for URI rewriting
*/
protected function setupDebug($sources)
protected function setupUriRewrites()
{
foreach ($sources as $source) {
foreach($this->sources as $key => $source) {
$file = $source->getFilePath();
$minifyOptions = $source->getMinifierOptions();
if ($file
&& !isset($minifyOptions['currentDir'])
&& !isset($minifyOptions['prependRelativePath'])
) {
$minifyOptions['currentDir'] = dirname($file);
$source->setMinifierOptions($minifyOptions);
}
}
}
/**
* Set up sources to use Minify_Lines
*/
protected function setupDebug()
{
foreach ($this->sources as $source) {
$source->setMinifier(array('Minify_Lines', 'minify'));
$id = $source->getId();
$source->setMinifierOptions(array(
'id' => (is_file($id) ? basename($id) : $id)
'id' => (is_file($id) ? basename($id) : $id),
));
}
}
@ -414,25 +472,29 @@ class Minify {
// when combining scripts, make sure all statements separated and
// trailing single line comment is terminated
$implodeSeparator = ($type === self::TYPE_JS)
? "\n;"
: '';
$implodeSeparator = ($type === self::TYPE_JS) ? "\n;" : '';
// allow the user to pass a particular array of options to each
// minifier (designated by type). source objects may still override
// these
$defaultOptions = isset($this->options['minifierOptions'][$type])
? $this->options['minifierOptions'][$type]
: array();
if (isset($this->options['minifierOptions'][$type])) {
$defaultOptions = $this->options['minifierOptions'][$type];
} else {
$defaultOptions = array();
}
// if minifier not set, default is no minification. source objects
// may still override this
$defaultMinifier = isset($this->options['minifiers'][$type])
? $this->options['minifiers'][$type]
: false;
if (isset($this->options['minifiers'][$type])) {
$defaultMinifier = $this->options['minifiers'][$type];
} else {
$defaultMinifier = false;
}
// process groups of sources with identical minifiers/options
$content = array();
$i = 0;
$l = count($this->controller->sources);
$l = count($this->sources);
$groupToProcessTogether = array();
$lastMinifier = null;
$lastOptions = null;
@ -440,7 +502,7 @@ class Minify {
// get next source
$source = null;
if ($i < $l) {
$source = $this->controller->sources[$i];
$source = $this->sources[$i];
/* @var Minify_Source $source */
$sourceContent = $source->getContent();
@ -509,16 +571,16 @@ class Minify {
*/
protected function _getCacheId($prefix = 'minify')
{
$name = preg_replace('/[^a-zA-Z0-9\\.=_,]/', '', $this->controller->selectionId);
$name = preg_replace('/[^a-zA-Z0-9\\.=_,]/', '', $this->selectionId);
$name = preg_replace('/\\.+/', '.', $name);
$name = substr($name, 0, 100 - 34 - strlen($prefix));
$md5 = md5(serialize(array(
Minify_SourceSet::getDigest($this->controller->sources)
,$this->options['minifiers']
,$this->options['minifierOptions']
,$this->options['postprocessor']
,$this->options['bubbleCssImports']
,self::VERSION
Minify_SourceSet::getDigest($this->sources),
$this->options['minifiers'],
$this->options['minifierOptions'],
$this->options['postprocessor'],
$this->options['bubbleCssImports'],
Minify::VERSION,
)));
return "{$prefix}_{$name}_{$md5}";
}
@ -536,19 +598,68 @@ class Minify {
// bubble CSS imports
preg_match_all('/@import.*?;/', $css, $imports);
$css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
} else if ('' !== $this->importWarning) {
// remove comments so we don't mistake { in a comment as a block
$noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
$lastImportPos = strrpos($noCommentCss, '@import');
$firstBlockPos = strpos($noCommentCss, '{');
if (false !== $lastImportPos
&& false !== $firstBlockPos
&& $firstBlockPos < $lastImportPos
) {
// { appears before @import : prepend warning
$css = $this->importWarning . $css;
}
return $css;
}
if ('' === $this->options['importWarning']) {
return $css;
}
// remove comments so we don't mistake { in a comment as a block
$noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
$lastImportPos = strrpos($noCommentCss, '@import');
$firstBlockPos = strpos($noCommentCss, '{');
if (false !== $lastImportPos
&& false !== $firstBlockPos
&& $firstBlockPos < $lastImportPos
) {
// { appears before @import : prepend warning
$css = $this->options['importWarning'] . $css;
}
return $css;
}
/**
* Analyze sources (if there are any) and set $options 'contentType'
* and 'lastModifiedTime' if they already aren't.
*
* @param array $options options for Minify
*
* @return array options for Minify
*/
protected function analyzeSources($options = array())
{
if (!$this->sources) {
return $options;
}
$type = null;
foreach ($this->sources as $source) {
if ($type === null) {
$type = $source->getContentType();
} elseif ($source->getContentType() !== $type) {
// TODO better logging
Minify_Logger::log('ContentType mismatch');
$this->sources = array();
return $options;
}
}
if (null === $type) {
$type = 'text/plain';
}
$options['contentType'] = $type;
// last modified is needed for caching, even if setExpires is set
if (!isset($options['lastModifiedTime'])) {
$max = 0;
foreach ($this->sources as $source) {
$max = max($source->getLastModified(), $max);
}
$options['lastModifiedTime'] = $max;
}
return $options;
}
}

View File

@ -7,209 +7,47 @@
/**
* Base class for Minify controller
*
* The controller class validates a request and uses it to create sources
* for minification and set options like contentType. It's also responsible
* for loading minifier code upon request.
* The controller class validates a request and uses it to create a configuration for Minify::serve().
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
abstract class Minify_Controller_Base {
abstract class Minify_Controller_Base implements Minify_ControllerInterface {
/**
* Setup controller sources and set an needed options for Minify::source
*
* You must override this method in your subclass controller to set
* $this->sources. If the request is NOT valid, make sure $this->sources
* is left an empty array. Then strip any controller-specific options from
* $options and return it. To serve files, $this->sources must be an array of
* Minify_Source objects.
* @var Minify_Env
*/
protected $env;
/**
* @var Minify_Source_Factory
*/
protected $sourceFactory;
/**
* @var string
*/
protected $type;
/**
* @param Minify_Env $env
* @param Minify_Source_Factory $sourceFactory
*/
public function __construct(Minify_Env $env, Minify_Source_Factory $sourceFactory)
{
$this->env = $env;
$this->sourceFactory = $sourceFactory;
}
/**
* Create controller sources and options for Minify::serve()
*
* @param array $options controller and Minify options
*
* @return array $options Minify::serve options
* @return Minify_ServeConfiguration
*/
abstract public function setupSources($options);
abstract public function createConfiguration(array $options);
/**
* Get default Minify options for this controller.
*
* Override in subclass to change defaults
*
* @return array options for Minify
*/
public function getDefaultMinifyOptions()
{
return array(
'isPublic' => true
,'encodeOutput' => function_exists('gzdeflate')
,'encodeMethod' => null // determine later
,'encodeLevel' => 9
,'minifierOptions' => array() // no minifier options
,'contentTypeCharset' => 'utf-8'
,'maxAge' => 1800 // 30 minutes
,'rewriteCssUris' => true
,'bubbleCssImports' => false
,'quiet' => false // serve() will send headers and output
,'debug' => false
// if you override these, the response codes MUST be directly after
// the first space.
,'badRequestHeader' => 'HTTP/1.0 400 Bad Request'
,'errorHeader' => 'HTTP/1.0 500 Internal Server Error'
// callback function to see/modify content of all sources
,'postprocessor' => null
// file to require to load preprocessor
,'postprocessorRequire' => null
);
}
/**
* Get default minifiers for this controller.
*
* Override in subclass to change defaults
*
* @return array minifier callbacks for common types
*/
public function getDefaultMinifers()
{
$ret[Minify::TYPE_JS] = array('JSMin', 'minify');
$ret[Minify::TYPE_CSS] = array('Minify_CSS', 'minify');
$ret[Minify::TYPE_HTML] = array('Minify_HTML', 'minify');
return $ret;
}
/**
* Is a user-given file within an allowable directory, existing,
* and having an extension js/css/html/txt ?
*
* This is a convenience function for controllers that have to accept
* user-given paths
*
* @param string $file full file path (already processed by realpath())
*
* @param array $safeDirs directories where files are safe to serve. Files can also
* be in subdirectories of these directories.
*
* @return bool file is safe
*
* @deprecated use checkAllowDirs, checkNotHidden instead
*/
public static function _fileIsSafe($file, $safeDirs)
{
$pathOk = false;
foreach ((array)$safeDirs as $safeDir) {
if (strpos($file, $safeDir) === 0) {
$pathOk = true;
break;
}
}
$base = basename($file);
if (! $pathOk || ! is_file($file) || $base[0] === '.') {
return false;
}
list($revExt) = explode('.', strrev($base));
return in_array(strrev($revExt), array('js', 'css', 'html', 'txt'));
}
/**
* @param string $file
* @param array $allowDirs
* @param string $uri
* @return bool
* @throws Exception
*/
public static function checkAllowDirs($file, $allowDirs, $uri)
{
foreach ((array)$allowDirs as $allowDir) {
if (strpos($file, $allowDir) === 0) {
return true;
}
}
throw new Exception("File '$file' is outside \$allowDirs. If the path is"
. " resolved via an alias/symlink, look into the \$min_symlinks option."
. " E.g. \$min_symlinks['/" . dirname($uri) . "'] = '" . dirname($file) . "';");
}
/**
* @param string $file
* @throws Exception
*/
public static function checkNotHidden($file)
{
$b = basename($file);
if (0 === strpos($b, '.')) {
throw new Exception("Filename '$b' starts with period (may be hidden)");
}
}
/**
* instances of Minify_Source, which provide content and any individual minification needs.
*
* @var Minify_SourceInterface[]
*/
public $sources = array();
/**
* Short name to place inside cache id
*
* The setupSources() method may choose to set this, making it easier to
* recognize a particular set of sources/settings in the cache folder. It
* will be filtered and truncated to make the final cache id <= 250 bytes.
*
* @var string
*/
public $selectionId = '';
/**
* Mix in default controller options with user-given options
*
* @param array $options user options
*
* @return array mixed options
*/
public final function mixInDefaultOptions($options)
{
$ret = array_merge(
$this->getDefaultMinifyOptions(), $options
);
if (! isset($options['minifiers'])) {
$options['minifiers'] = array();
}
$ret['minifiers'] = array_merge(
$this->getDefaultMinifers(), $options['minifiers']
);
return $ret;
}
/**
* Analyze sources (if there are any) and set $options 'contentType'
* and 'lastModifiedTime' if they already aren't.
*
* @param array $options options for Minify
*
* @return array options for Minify
*/
public final function analyzeSources($options = array())
{
if ($this->sources) {
if (! isset($options['contentType'])) {
$options['contentType'] = Minify_SourceSet::getContentType($this->sources);
}
// last modified is needed for caching, even if setExpires is set
if (! isset($options['lastModifiedTime'])) {
$max = 0;
/** @var Minify_Source $source */
foreach ($this->sources as $source) {
$max = max($source->getLastModified(), $max);
}
$options['lastModifiedTime'] = $max;
}
}
return $options;
}
/**
* Send message to the Minify logger
*

View File

@ -36,7 +36,7 @@ class Minify_Controller_Files extends Minify_Controller_Base {
*
* 'files': (required) array of complete file paths, or a single path
*/
public function setupSources($options) {
public function createConfiguration($options) {
// strip controller options
$files = $options['files'];

View File

@ -38,7 +38,7 @@ class Minify_Controller_Groups extends Minify_Controller_Base {
*
* @return array Minify options
*/
public function setupSources($options) {
public function createConfiguration($options) {
// strip controller options
$groups = $options['groups'];
unset($options['groups']);

View File

@ -11,7 +11,7 @@
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_MinApp extends Minify_Controller_Base {
/**
* Set up groups of files as sources
*
@ -19,43 +19,44 @@ class Minify_Controller_MinApp extends Minify_Controller_Base {
*
* @return array Minify options
*/
public function setupSources($options) {
public function createConfiguration(array $options) {
// PHP insecure by default: realpath() and other FS functions can't handle null bytes.
$get = $this->env->get();
foreach (array('g', 'b', 'f') as $key) {
if (isset($_GET[$key])) {
$_GET[$key] = str_replace("\x00", '', (string)$_GET[$key]);
if (isset($get[$key])) {
$get[$key] = str_replace("\x00", '', (string)$get[$key]);
}
}
// filter controller options
$cOptions = array_merge(
$localOptions = array_merge(
array(
'allowDirs' => '//'
,'groupsOnly' => false
,'groups' => array()
,'noMinPattern' => '@[-\\.]min\\.(?:js|css)$@i' // matched against basename
'groupsOnly' => false,
'groups' => array(),
)
,(isset($options['minApp']) ? $options['minApp'] : array())
);
unset($options['minApp']);
$sources = array();
$this->selectionId = '';
$selectionId = '';
$firstMissingResource = null;
if (isset($_GET['g'])) {
if (isset($get['g'])) {
// add group(s)
$this->selectionId .= 'g=' . $_GET['g'];
$keys = explode(',', $_GET['g']);
$selectionId .= 'g=' . $get['g'];
$keys = explode(',', $get['g']);
if ($keys != array_unique($keys)) {
$this->log("Duplicate group key found.");
return $options;
return new Minify_ServeConfiguration($options);
}
$keys = explode(',', $_GET['g']);
$keys = explode(',', $get['g']);
foreach ($keys as $key) {
if (! isset($cOptions['groups'][$key])) {
if (! isset($localOptions['groups'][$key])) {
$this->log("A group configuration for \"{$key}\" was not found");
return $options;
return new Minify_ServeConfiguration($options);
}
$files = $cOptions['groups'][$key];
$files = $localOptions['groups'][$key];
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
@ -63,150 +64,111 @@ class Minify_Controller_MinApp extends Minify_Controller_Base {
$files = (array)$files;
}
foreach ($files as $file) {
if ($file instanceof Minify_Source) {
if ($file instanceof Minify_SourceInterface) {
$sources[] = $file;
continue;
}
if (0 === strpos($file, '//')) {
$file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1);
}
$realpath = realpath($file);
if ($realpath && is_file($realpath)) {
$sources[] = $this->_getFileSource($realpath, $cOptions);
} else {
$this->log("The path \"{$file}\" (realpath \"{$realpath}\") could not be found (or was not a file)");
try {
$source = $this->sourceFactory->makeSource(array(
'filepath' => $file,
));
$sources[] = $source;
} catch (Minify_Source_FactoryException $e) {
$this->log($e->getMessage());
if (null === $firstMissingResource) {
$firstMissingResource = basename($file);
continue;
} else {
$secondMissingResource = basename($file);
$this->log("More than one file was missing: '$firstMissingResource', '$secondMissingResource'");
return $options;
return new Minify_ServeConfiguration($options);
}
}
}
if ($sources) {
try {
$this->checkType($sources[0]);
} catch (Exception $e) {
$this->log($e->getMessage());
return $options;
}
}
}
}
if (! $cOptions['groupsOnly'] && isset($_GET['f'])) {
if (! $localOptions['groupsOnly'] && isset($get['f'])) {
// try user files
// The following restrictions are to limit the URLs that minify will
// respond to.
if (// verify at least one file, files are single comma separated,
// and are all same extension
! preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $_GET['f'], $m)
! preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $get['f'], $m)
// no "//"
|| strpos($_GET['f'], '//') !== false
|| strpos($get['f'], '//') !== false
// no "\"
|| strpos($_GET['f'], '\\') !== false
|| strpos($get['f'], '\\') !== false
) {
$this->log("GET param 'f' was invalid");
return $options;
return new Minify_ServeConfiguration($options);
}
$ext = ".{$m[1]}";
try {
$this->checkType($m[1]);
} catch (Exception $e) {
$this->log($e->getMessage());
return $options;
}
$files = explode(',', $_GET['f']);
$files = explode(',', $get['f']);
if ($files != array_unique($files)) {
$this->log("Duplicate files were specified");
return $options;
return new Minify_ServeConfiguration($options);
}
if (isset($_GET['b'])) {
if (isset($get['b'])) {
// check for validity
if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b'])
&& false === strpos($_GET['b'], '..')
&& $_GET['b'] !== '.') {
if (preg_match('@^[^/]+(?:/[^/]+)*$@', $get['b'])
&& false === strpos($get['b'], '..')
&& $get['b'] !== '.') {
// valid base
$base = "/{$_GET['b']}/";
$base = "/{$get['b']}/";
} else {
$this->log("GET param 'b' was invalid");
return $options;
return new Minify_ServeConfiguration($options);
}
} else {
$base = '/';
}
$allowDirs = array();
foreach ((array)$cOptions['allowDirs'] as $allowDir) {
$allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir));
}
$basenames = array(); // just for cache id
foreach ($files as $file) {
$uri = $base . $file;
$path = $_SERVER['DOCUMENT_ROOT'] . $uri;
$realpath = realpath($path);
if (false === $realpath || ! is_file($realpath)) {
$this->log("The path \"{$path}\" (realpath \"{$realpath}\") could not be found (or was not a file)");
$path = $this->env->getDocRoot() . $uri;
try {
$source = $this->sourceFactory->makeSource(array(
'filepath' => $path,
));
$sources[] = $source;
$basenames[] = basename($path, $ext);
} catch (Minify_Source_FactoryException $e) {
$this->log($e->getMessage());
if (null === $firstMissingResource) {
$firstMissingResource = $uri;
continue;
} else {
$secondMissingResource = $uri;
$this->log("More than one file was missing: '$firstMissingResource', '$secondMissingResource`'");
return $options;
return new Minify_ServeConfiguration($options);
}
}
try {
parent::checkNotHidden($realpath);
parent::checkAllowDirs($realpath, $allowDirs, $uri);
} catch (Exception $e) {
$this->log($e->getMessage());
return $options;
}
$sources[] = $this->_getFileSource($realpath, $cOptions);
$basenames[] = basename($realpath, $ext);
}
if ($this->selectionId) {
$this->selectionId .= '_f=';
if ($selectionId) {
$selectionId .= '_f=';
}
$this->selectionId .= implode(',', $basenames) . $ext;
$selectionId .= implode(',', $basenames) . $ext;
}
if ($sources) {
if (null !== $firstMissingResource) {
array_unshift($sources, new Minify_Source(array(
'id' => 'missingFile'
// should not cause cache invalidation
,'lastModified' => 0
// due to caching, filename is unreliable.
,'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n"
,'minifier' => ''
)));
}
$this->sources = $sources;
} else {
$this->log("No sources to serve");
}
return $options;
}
/**
* @param string $file
*
* @param array $cOptions
*
* @return Minify_Source
*/
protected function _getFileSource($file, $cOptions)
{
$spec['filepath'] = $file;
if ($cOptions['noMinPattern'] && preg_match($cOptions['noMinPattern'], basename($file))) {
if (preg_match('~\.css$~i', $file)) {
$spec['minifyOptions']['compress'] = false;
} else {
$spec['minifier'] = '';
}
if (!$sources) {
$this->log("No sources to serve");
return new Minify_ServeConfiguration($options);
}
return new Minify_Source($spec);
if (null !== $firstMissingResource) {
array_unshift($sources, new Minify_Source(array(
'id' => 'missingFile'
// should not cause cache invalidation
,'lastModified' => 0
// due to caching, filename is unreliable.
,'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n"
,'minifier' => ''
)));
}
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
protected $_type = null;

View File

@ -29,11 +29,9 @@ class Minify_Controller_Page extends Minify_Controller_Base {
* is recommended to allow both server and client-side caching.
*
* 'minifyAll': should all CSS and Javascript blocks be individually
* minified? (default false)
*
* @todo Add 'file' option to read HTML file.
* minified? (default false)
*/
public function setupSources($options) {
public function createConfiguration(array $options) {
if (isset($options['file'])) {
$sourceSpec = array(
'filepath' => $options['file']
@ -49,7 +47,7 @@ class Minify_Controller_Page extends Minify_Controller_Base {
unset($options['content'], $options['id']);
}
// something like "builder,index.php" or "directory,file.html"
$this->selectionId = strtr(substr($f, 1 + strlen(dirname(dirname($f)))), '/\\', ',,');
$selectionId = strtr(substr($f, 1 + strlen(dirname(dirname($f)))), '/\\', ',,');
if (isset($options['minifyAll'])) {
// this will be the 2nd argument passed to Minify_HTML::minify()
@ -59,10 +57,11 @@ class Minify_Controller_Page extends Minify_Controller_Base {
);
unset($options['minifyAll']);
}
$this->sources[] = new Minify_Source($sourceSpec);
$options['contentType'] = Minify::TYPE_HTML;
return $options;
$sourceSpec['contentType'] = Minify::TYPE_HTML;
$sources[] = new Minify_Source($sourceSpec);
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}

View File

@ -23,7 +23,7 @@ class Minify_Controller_Version1 extends Minify_Controller_Base {
* @return array Minify options
*
*/
public function setupSources($options) {
public function createConfiguration($options) {
// PHP insecure by default: realpath() and other FS functions can't handle null bytes.
if (isset($_GET['files'])) {
$_GET['files'] = str_replace("\x00", '', (string)$_GET['files']);

View File

@ -0,0 +1,13 @@
<?php
interface Minify_ControllerInterface {
/**
* Create controller sources and options for Minify::serve()
*
* @param array $options controller and Minify options
*
* @return Minify_ServeConfiguration
*/
public function createConfiguration(array $options);
}

View File

@ -7,16 +7,17 @@
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_DebugDetector {
public static function shouldDebugRequest($cookie, $get, $requestUri)
public static function shouldDebugRequest(Minify_Env $env)
{
if (isset($get['debug'])) {
if ($env->get('debug')) {
return true;
}
if (! empty($cookie['minifyDebug'])) {
foreach (preg_split('/\\s+/', $cookie['minifyDebug']) as $debugUri) {
$cookieValue = $env->cookie('minifyDebug');
if ($cookieValue) {
foreach (preg_split('/\\s+/', $cookieValue) as $debugUri) {
$pattern = '@' . preg_quote($debugUri, '@') . '@i';
$pattern = str_replace(array('\\*', '\\?'), array('.*', '.'), $pattern);
if (preg_match($pattern, $requestUri)) {
if (preg_match($pattern, $env->getRequestUri())) {
return true;
}
}

View File

@ -2,19 +2,6 @@
class Minify_Env {
/**
* How many hours behind are the file modification times of uploaded files?
*
* If you upload files from Windows to a non-Windows server, Windows may report
* incorrect mtimes for the files. Immediately after modifying and uploading a
* file, use the touch command to update the mtime on the server. If the mtime
* jumps ahead by a number of hours, set this variable to that number. If the mtime
* moves back, this should not be needed.
*
* @var int $uploaderHoursBehind
*/
protected $uploaderHoursBehind = 0;
/**
* @return null
*/
@ -47,22 +34,31 @@ class Minify_Env {
$this->cookie = $options['cookie'];
}
public function server($key)
public function server($key = null)
{
if (null === $key) {
return $this->server;
}
return isset($this->server[$key])
? $this->server[$key]
: null;
}
public function cookie($key)
public function cookie($key = null)
{
if (null === $key) {
return $this->cookie;
}
return isset($this->cookie[$key])
? $this->cookie[$key]
: null;
}
public function get($key)
public function get($key = null)
{
if (null === $key) {
return $this->get;
}
return isset($this->get[$key])
? $this->get[$key]
: null;
@ -80,16 +76,15 @@ class Minify_Env {
*/
protected function computeDocRoot(array $server)
{
if (isset($server['SERVER_SOFTWARE'])
&& 0 === strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
$docRoot = substr(
$server['SCRIPT_FILENAME']
,0
,strlen($server['SCRIPT_FILENAME']) - strlen($server['SCRIPT_NAME']));
$docRoot = rtrim($docRoot, '\\');
} else {
if (empty($server['SERVER_SOFTWARE'])
|| 0 !== strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
throw new InvalidArgumentException('DOCUMENT_ROOT is not provided and could not be computed');
}
return $docRoot;
$docRoot = substr(
$server['SCRIPT_FILENAME']
,0
,strlen($server['SCRIPT_FILENAME']) - strlen($server['SCRIPT_NAME'])
);
return rtrim($docRoot, '\\');
}
}

View File

@ -0,0 +1,70 @@
<?php
/**
* Class Minify_ServeConfiguration
* @package Minify
*/
/**
* A configuration for Minify::serve() determined by a controller
*
* @package Minify
*/
class Minify_ServeConfiguration {
/**
* @var Minify_SourceInterface[]
*/
protected $sources;
/**
* @var array
*/
protected $options;
/**
* @var string
*/
protected $selectionId = '';
/**
* @param array $options
* @param Minify_SourceInterface[] $sources
* @param string $selectionId
*/
function __construct(array $options, array $sources = array(), $selectionId = '')
{
$this->options = $options;
$this->sources = $sources;
$this->selectionId = $selectionId;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @return Minify_SourceInterface[]
*/
public function getSources()
{
return $this->sources;
}
/**
* Short name to place inside cache id
*
* The setupSources() method may choose to set this, making it easier to
* recognize a particular set of sources/settings in the cache folder. It
* will be filtered and truncated to make the final cache id <= 250 bytes.
*
* @return string
*/
public function getSelectionId()
{
return $this->selectionId;
}
}

View File

@ -15,6 +15,101 @@
*/
class Minify_Source implements Minify_SourceInterface {
/**
* @var int time of last modification
*/
protected $lastModified = null;
/**
* @var callback minifier function specifically for this source.
*/
protected $minifier = null;
/**
* @var array minification options specific to this source.
*/
protected $minifyOptions = array();
/**
* @var string full path of file
*/
protected $filepath = null;
/**
* @var string HTTP Content Type (Minify requires one of the constants Minify::TYPE_*)
*/
protected $contentType = null;
/**
* @var string
*/
protected $content = null;
/**
* @var callable
*/
protected $getContentFunc = null;
/**
* @var string
*/
protected $id = null;
/**
* Create a Minify_Source
*
* In the $spec array(), you can either provide a 'filepath' to an existing
* file (existence will not be checked!) or give 'id' (unique string for
* the content), 'content' (the string content) and 'lastModified'
* (unixtime of last update).
*
* @param array $spec options
*/
public function __construct($spec)
{
if (isset($spec['filepath'])) {
$ext = pathinfo($spec['filepath'], PATHINFO_EXTENSION);
switch ($ext) {
case 'js' : $this->contentType = Minify::TYPE_JS;
break;
case 'css' : $this->contentType = Minify::TYPE_CSS;
break;
case 'htm' : // fallthrough
case 'html' : $this->contentType = Minify::TYPE_HTML;
break;
}
$this->filepath = $spec['filepath'];
$this->id = $spec['filepath'];
// TODO ideally not touch disk in constructor
$this->lastModified = filemtime($spec['filepath']);
if (!empty($spec['uploaderHoursBehind'])) {
// offset for Windows uploaders with out of sync clocks
$this->lastModified += round($spec['uploaderHoursBehind'] * 3600);
}
} elseif (isset($spec['id'])) {
$this->id = 'id::' . $spec['id'];
if (isset($spec['content'])) {
$this->content = $spec['content'];
} else {
$this->getContentFunc = $spec['getContentFunc'];
}
$this->lastModified = isset($spec['lastModified'])
? $spec['lastModified']
: time();
}
if (isset($spec['contentType'])) {
$this->contentType = $spec['contentType'];
}
if (isset($spec['minifier'])) {
$this->minifier = $spec['minifier'];
}
if (isset($spec['minifyOptions'])) {
$this->minifyOptions = $spec['minifyOptions'];
}
}
/**
* {@inheritdoc}
*/
@ -63,81 +158,22 @@ class Minify_Source implements Minify_SourceInterface {
return $this->contentType;
}
/**
* Create a Minify_Source
*
* In the $spec array(), you can either provide a 'filepath' to an existing
* file (existence will not be checked!) or give 'id' (unique string for
* the content), 'content' (the string content) and 'lastModified'
* (unixtime of last update).
*
* As a shortcut, the controller will replace "//" at the beginning
* of a filepath with $_SERVER['DOCUMENT_ROOT'] . '/'.
*
* @param array $spec options
*/
public function __construct($spec)
{
if (isset($spec['filepath'])) {
if (0 === strpos($spec['filepath'], '//')) {
$spec['filepath'] = $_SERVER['DOCUMENT_ROOT'] . substr($spec['filepath'], 1);
}
$segments = explode('.', $spec['filepath']);
$ext = strtolower(array_pop($segments));
switch ($ext) {
case 'js' : $this->contentType = 'application/x-javascript';
break;
case 'css' : $this->contentType = 'text/css';
break;
case 'htm' : // fallthrough
case 'html' : $this->contentType = 'text/html';
break;
}
$this->filepath = $spec['filepath'];
$this->_id = $spec['filepath'];
$this->lastModified = filemtime($spec['filepath']);
if (!empty($spec['uploaderHoursBehind'])) {
// offset for Windows uploaders with out of sync clocks
$this->lastModified += round($spec['uploaderHoursBehind'] * 3600);
}
} elseif (isset($spec['id'])) {
$this->_id = 'id::' . $spec['id'];
if (isset($spec['content'])) {
$this->_content = $spec['content'];
} else {
$this->_getContentFunc = $spec['getContentFunc'];
}
$this->lastModified = isset($spec['lastModified'])
? $spec['lastModified']
: time();
}
if (isset($spec['contentType'])) {
$this->contentType = $spec['contentType'];
}
if (isset($spec['minifier'])) {
$this->minifier = $spec['minifier'];
}
if (isset($spec['minifyOptions'])) {
$this->minifyOptions = $spec['minifyOptions'];
}
}
/**
* {@inheritdoc}
*/
public function getContent()
{
$content = (null !== $this->filepath)
? file_get_contents($this->filepath)
: ((null !== $this->_content)
? $this->_content
: call_user_func($this->_getContentFunc, $this->_id)
);
if (null === $this->filepath) {
if (null === $this->content) {
$content = call_user_func($this->getContentFunc, $this->id);
} else {
$content = $this->content;
}
} else {
$content = file_get_contents($this->filepath);
}
// remove UTF-8 BOM if present
return ("\xEF\xBB\xBF" === substr($content, 0, 3))
? substr($content, 3)
: $content;
return ("\xEF\xBB\xBF" === substr($content, 0, 3)) ? substr($content, 3) : $content;
}
/**
@ -145,7 +181,15 @@ class Minify_Source implements Minify_SourceInterface {
*/
public function getId()
{
return $this->_id;
return $this->id;
}
/**
* {@inheritdoc}
*/
public function getFilePath()
{
return $this->filepath;
}
/**
@ -159,44 +203,4 @@ class Minify_Source implements Minify_SourceInterface {
$this->minifyOptions['currentDir'] = dirname($this->filepath);
}
}
/**
* @var int time of last modification
*/
protected $lastModified = null;
/**
* @var callback minifier function specifically for this source.
*/
protected $minifier = null;
/**
* @var array minification options specific to this source.
*/
protected $minifyOptions = array();
/**
* @var string full path of file
*/
protected $filepath = null;
/**
* @var string HTTP Content Type (Minify requires one of the constants Minify::TYPE_*)
*/
protected $contentType = null;
/**
* @var string
*/
protected $_content = null;
/**
* @var callable
*/
protected $_getContentFunc = null;
/**
* @var string
*/
protected $_id = null;
}

View File

@ -2,25 +2,70 @@
class Minify_Source_Factory {
/**
* @var array
*/
protected $options;
/**
* @var callable[]
*/
protected $handlers = array();
/**
* @var Minify_Env
*/
protected $env;
/**
* @param Minify_Env $env
* @param array $options
*
* noMinPattern : Pattern matched against basename of the filepath (if present). If the pattern
* matches, Minify will try to avoid re-compressing the resource.
*
* fileChecker : Callable responsible for verifying the existence of the file.
*
* resolveDocRoot : If true, a leading "//" will be replaced with the document root.
*
* checkAllowDirs : If true, the filepath will be verified to be within one of the directories
* specified by allowDirs.
*
* allowDirs : Directory paths in which sources can be served.
*
* uploaderHoursBehind : How many hours behind are the file modification times of uploaded files?
* If you upload files from Windows to a non-Windows server, Windows may report
* incorrect mtimes for the files. Immediately after modifying and uploading a
* file, use the touch command to update the mtime on the server. If the mtime
* jumps ahead by a number of hours, set this variable to that number. If the mtime
* moves back, this should not be needed.
*
*/
public function __construct(Minify_Env $env, array $options = array())
{
$this->env = $env;
$this->options = array_merge(array(
'noMinPattern' => '@[-\\.]min\\.(?:js|css)$@i', // matched against basename
'uploaderHoursBehind' => 0,
'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
'fileChecker' => array($this, 'checkIsFile'),
'resolveDocRoot' => true,
'checkAllowDirs' => true,
'allowDirs' => array($env->getDocRoot()),
'allowDirs' => array('//'),
'uploaderHoursBehind' => 0,
), $options);
// resolve // in allowDirs
$docRoot = $env->getDocRoot();
foreach ($this->options['allowDirs'] as $i => $dir) {
$this->options['allowDirs'][$i] = $docRoot . substr($dir, 1);
}
if ($this->options['fileChecker'] && !is_callable($this->options['fileChecker'])) {
throw new InvalidArgumentException("fileChecker option is not callable");
}
$this->setHandler('~\.(js|css)$~i', function ($spec) {
return new Minify_Source($spec);
});
}
/**
@ -77,10 +122,8 @@ class Minify_Source_Factory {
return new Minify_Source($spec);
}
if ($this->options['resolveDocRoot']) {
if (0 === strpos($spec['filepath'], '//')) {
$spec['filepath'] = $this->env->getDocRoot() . substr($spec['filepath'], 1);
}
if ($this->options['resolveDocRoot'] && 0 === strpos($spec['filepath'], '//')) {
$spec['filepath'] = $this->env->getDocRoot() . substr($spec['filepath'], 1);
}
if (!empty($this->options['fileChecker'])) {
@ -114,17 +157,13 @@ class Minify_Source_Factory {
foreach ($this->handlers as $basenamePattern => $handler) {
if (preg_match($basenamePattern, $basename)) {
$source = $handler($spec);
$source = call_user_func($handler, $spec);
break;
}
}
if (!$source) {
if (in_array(pathinfo($spec['filepath'], PATHINFO_EXTENSION), array('css', 'js'))) {
$source = new Minify_Source($spec);
} else {
throw new Minify_Source_FactoryException("Handler not found for file: {$spec['filepath']}");
}
throw new Minify_Source_FactoryException("Handler not found for file: $basename");
}
return $source;

View File

@ -73,9 +73,9 @@ interface Minify_SourceInterface {
public function getId();
/**
* Setup the current source for URI rewrites
* Get the path of the file that this source is based on (may be null)
*
* @return void
* @return string|null
*/
public function setupUriRewrites();
public function getFilePath();
}

View File

@ -26,24 +26,4 @@ class Minify_SourceSet {
}
return md5(serialize($info));
}
/**
* Get content type from a group of sources
*
* This is called if the user doesn't pass in a 'contentType' options
*
* @param Minify_SourceInterface[] $sources Minify_Source instances
*
* @return string content type. e.g. 'text/css'
*/
public static function getContentType($sources)
{
foreach ($sources as $source) {
$contentType = $source->getContentType();
if ($contentType) {
return $contentType;
}
}
return 'text/plain';
}
}