10 require_once 'Minify/Source.php';
13 * Minify - Combines, minifies, and caches JavaScript and CSS files on demand.
15 * See README for usage instructions (for now).
17 * This library was inspired by {@link mailto:flashkot@mail.ru jscsscomp by Maxim Martynyuk}
18 * and by the article {@link http://www.hunlock.com/blogs/Supercharged_Javascript "Supercharged JavaScript" by Patrick Hunlock}.
21 * Tested on PHP 5.1.6.
24 * @author Ryan Grove <ryan@wonko.com>
25 * @author Stephen Clay <steve@mrclay.org>
26 * @copyright 2008 Ryan Grove, Stephen Clay. All rights reserved.
27 * @license http://opensource.org/licenses/bsd-license.php New BSD License
28 * @link http://code.google.com/p/minify/
32 const VERSION = '2.1.3';
33 const TYPE_CSS = 'text/css';
34 const TYPE_HTML = 'text/html';
35 // there is some debate over the ideal JS Content-Type, but this is the
36 // Apache default and what Yahoo! uses..
37 const TYPE_JS = 'application/x-javascript';
40 * How many hours behind are the file modification times of uploaded files?
42 * If you upload files from Windows to a non-Windows server, Windows may report
43 * incorrect mtimes for the files. Immediately after modifying and uploading a
44 * file, use the touch command to update the mtime on the server. If the mtime
45 * jumps ahead by a number of hours, set this variable to that number. If the mtime
46 * moves back, this should not be needed.
48 * @var int $uploaderHoursBehind
50 public static $uploaderHoursBehind = 0;
53 * If this string is not empty AND the serve() option 'bubbleCssImports' is
54 * NOT set, then serve() will check CSS files for @import declarations that
55 * appear too late in the combined stylesheet. If found, serve() will prepend
56 * the output with this warning.
58 * @var string $importWarning
60 public static $importWarning = "/* See http://code.google.com/p/minify/wiki/CommonProblems#@imports_can_appear_in_invalid_locations_in_combined_CSS_files */\n";
63 * Specify a cache object (with identical interface as Minify_Cache_File) or
64 * a path to use with Minify_Cache_File.
66 * If not called, Minify will not use a cache and, for each 200 response, will
67 * need to recombine files, minify and encode the output.
69 * @param mixed $cache object with identical interface as Minify_Cache_File or
70 * a directory path, or null to disable caching. (default = '')
72 * @param bool $fileLocking (default = true) This only applies if the first
73 * parameter is a string.
77 public static function setCache($cache = '', $fileLocking = true)
79 if (is_string($cache)) {
80 require_once 'Minify/Cache/File.php';
81 self::$_cache = new Minify_Cache_File($cache, $fileLocking);
83 self::$_cache = $cache;
88 * Serve a request for a minified file.
90 * Here are the available options and defaults in the base controller:
92 * 'isPublic' : send "public" instead of "private" in Cache-Control
93 * headers, allowing shared caches to cache the output. (default true)
95 * 'quiet' : set to true to have serve() return an array rather than sending
96 * any headers/output (default false)
98 * 'encodeOutput' : set to false to disable content encoding, and not send
99 * the Vary header (default true)
101 * 'encodeMethod' : generally you should let this be determined by
102 * HTTP_Encoder (leave null), but you can force a particular encoding
103 * to be returned, by setting this to 'gzip' or '' (no encoding)
105 * 'encodeLevel' : level of encoding compression (0 to 9, default 9)
107 * 'contentTypeCharset' : appended to the Content-Type header sent. Set to a falsey
108 * value to remove. (default 'utf-8')
110 * 'maxAge' : set this to the number of seconds the client should use its cache
111 * before revalidating with the server. This sets Cache-Control: max-age and the
112 * Expires header. Unlike the old 'setExpires' setting, this setting will NOT
113 * prevent conditional GETs. Note this has nothing to do with server-side caching.
115 * 'rewriteCssUris' : If true, serve() will automatically set the 'currentDir'
116 * minifier option to enable URI rewriting in CSS files (default true)
118 * 'bubbleCssImports' : If true, all @import declarations in combined CSS
119 * files will be move to the top. Note this may alter effective CSS values
120 * due to a change in order. (default false)
122 * 'debug' : set to true to minify all sources with the 'Lines' controller, which
123 * eases the debugging of combined files. This also prevents 304 responses.
124 * @see Minify_Lines::minify()
126 * 'minifiers' : to override Minify's default choice of minifier function for
127 * a particular content-type, specify your callback under the key of the
130 * // call customCssMinifier($css) for all CSS minification
131 * $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier';
133 * // don't minify Javascript at all
134 * $options['minifiers'][Minify::TYPE_JS] = '';
137 * 'minifierOptions' : to send options to the minifier function, specify your options
138 * under the key of the content-type. E.g. To send the CSS minifier an option:
140 * // give CSS minifier array('optionName' => 'optionValue') as 2nd argument
141 * $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue';
144 * 'contentType' : (optional) this is only needed if your file extension is not
145 * js/css/html. The given content-type will be sent regardless of source file
146 * extension, so this should not be used in a Groups config with other
147 * Javascript/CSS files.
149 * Any controller options are documented in that controller's setupSources() method.
151 * @param mixed instance of subclass of Minify_Controller_Base or string name of
152 * controller. E.g. 'Files'
154 * @param array $options controller/serve options
156 * @return mixed null, or, if the 'quiet' option is set to true, an array
157 * with keys "success" (bool), "statusCode" (int), "content" (string), and
160 public static function serve($controller, $options = array())
162 if (is_string($controller)) {
163 // make $controller into object
164 $class = 'Minify_Controller_' . $controller;
165 if (! class_exists($class, false)) {
166 require_once "Minify/Controller/"
167 . str_replace('_', '/', $controller) . ".php";
169 $controller = new $class();
172 // set up controller sources and mix remaining options with
173 // controller defaults
174 $options = $controller->setupSources($options);
175 $options = $controller->analyzeSources($options);
176 self::$_options = $controller->mixInDefaultOptions($options);
178 // check request validity
179 if (! $controller->sources) {
181 if (! self::$_options['quiet']) {
182 header(self::$_options['badRequestHeader']);
183 echo self::$_options['badRequestHeader'];
186 list(,$statusCode) = explode(' ', self::$_options['badRequestHeader']);
189 ,'statusCode' => (int)$statusCode
191 ,'headers' => array()
196 self::$_controller = $controller;
198 if (self::$_options['debug']) {
199 self::_setupDebug($controller->sources);
200 self::$_options['maxAge'] = 0;
203 // determine encoding
204 if (self::$_options['encodeOutput']) {
205 if (self::$_options['encodeMethod'] !== null) {
206 // controller specifically requested this
207 $contentEncoding = self::$_options['encodeMethod'];
209 // sniff request header
210 require_once 'HTTP/Encoder.php';
211 // depending on what the client accepts, $contentEncoding may be
212 // 'x-gzip' while our internal encodeMethod is 'gzip'. Calling
213 // getAcceptedEncoding(false, false) leaves out compress and deflate as options.
214 list(self::$_options['encodeMethod'], $contentEncoding) = HTTP_Encoder::getAcceptedEncoding(false, false);
217 self::$_options['encodeMethod'] = ''; // identity (no encoding)
220 // check client cache
221 require_once 'HTTP/ConditionalGet.php';
223 'lastModifiedTime' => self::$_options['lastModifiedTime']
224 ,'isPublic' => self::$_options['isPublic']
225 ,'encoding' => self::$_options['encodeMethod']
227 if (self::$_options['maxAge'] > 0) {
228 $cgOptions['maxAge'] = self::$_options['maxAge'];
230 $cg = new HTTP_ConditionalGet($cgOptions);
231 if ($cg->cacheIsValid) {
232 // client's cache is valid
233 if (! self::$_options['quiet']) {
241 ,'headers' => $cg->getHeaders()
245 // client will need output
246 $headers = $cg->getHeaders();
250 if (self::$_options['contentType'] === self::TYPE_CSS
251 && self::$_options['rewriteCssUris']) {
252 reset($controller->sources);
253 while (list($key, $source) = each($controller->sources)) {
254 if ($source->filepath
255 && !isset($source->minifyOptions['currentDir'])
256 && !isset($source->minifyOptions['prependRelativePath'])
258 $source->minifyOptions['currentDir'] = dirname($source->filepath);
263 // check server cache
264 if (null !== self::$_cache) {
266 // the goal is to use only the cache methods to sniff the length and
267 // output the content, as they do not require ever loading the file into
269 $cacheId = 'minify_' . self::_getCacheId();
270 $fullCacheId = (self::$_options['encodeMethod'])
273 // check cache for valid entry
274 $cacheIsReady = self::$_cache->isValid($fullCacheId, self::$_options['lastModifiedTime']);
276 $cacheContentLength = self::$_cache->getSize($fullCacheId);
278 // generate & cache content
279 $content = self::_combineMinify();
280 self::$_cache->store($cacheId, $content);
281 if (function_exists('gzencode')) {
282 self::$_cache->store($cacheId . '.gz', gzencode($content, self::$_options['encodeLevel']));
287 $cacheIsReady = false;
288 $content = self::_combineMinify();
290 if (! $cacheIsReady && self::$_options['encodeMethod']) {
291 // still need to encode
292 $content = gzencode($content, self::$_options['encodeLevel']);
296 $headers['Content-Length'] = $cacheIsReady
297 ? $cacheContentLength
299 $headers['Content-Type'] = self::$_options['contentTypeCharset']
300 ? self::$_options['contentType'] . '; charset=' . self::$_options['contentTypeCharset']
301 : self::$_options['contentType'];
302 if (self::$_options['encodeMethod'] !== '') {
303 $headers['Content-Encoding'] = $contentEncoding;
305 if (self::$_options['encodeOutput']) {
306 $headers['Vary'] = 'Accept-Encoding';
309 if (! self::$_options['quiet']) {
310 // output headers & content
311 foreach ($headers as $name => $val) {
312 header($name . ': ' . $val);
315 self::$_cache->display($fullCacheId);
323 ,'content' => $cacheIsReady
324 ? self::$_cache->fetch($fullCacheId)
326 ,'headers' => $headers
332 * Return combined minified content for a set of sources
334 * No internal caching will be used and the content will not be HTTP encoded.
336 * @param array $sources array of filepaths and/or Minify_Source objects
338 * @param array $options (optional) array of options for serve. By default
339 * these are already set: quiet = true, encodeMethod = '', lastModifiedTime = 0.
343 public static function combine($sources, $options = array())
345 $cache = self::$_cache;
346 self::$_cache = null;
347 $options = array_merge(array(
348 'files' => (array)$sources
350 ,'encodeMethod' => ''
351 ,'lastModifiedTime' => 0
353 $out = self::serve('Files', $options);
354 self::$_cache = $cache;
355 return $out['content'];
359 * On IIS, create $_SERVER['DOCUMENT_ROOT']
361 * @param bool $unsetPathInfo (default false) if true, $_SERVER['PATH_INFO']
362 * will be unset (it is inconsistent with Apache's setting)
366 public static function setDocRoot($unsetPathInfo = false)
368 if (isset($_SERVER['SERVER_SOFTWARE'])
369 && 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/')
371 $_SERVER['DOCUMENT_ROOT'] = rtrim(substr(
372 $_SERVER['PATH_TRANSLATED']
374 ,strlen($_SERVER['PATH_TRANSLATED']) - strlen($_SERVER['SCRIPT_NAME'])
376 if ($unsetPathInfo) {
377 unset($_SERVER['PATH_INFO']);
379 require_once 'Minify/Logger.php';
380 Minify_Logger::log("setDocRoot() set DOCUMENT_ROOT to \"{$_SERVER['DOCUMENT_ROOT']}\"");
385 * @var mixed Minify_Cache_* object or null (i.e. no server cache is used)
387 private static $_cache = null;
390 * @var Minify_Controller active controller for current request
392 protected static $_controller = null;
395 * @var array options for current request
397 protected static $_options = null;
400 * Set up sources to use Minify_Lines
402 * @param array $sources Minify_Source instances
406 protected static function _setupDebug($sources)
408 foreach ($sources as $source) {
409 $source->minifier = array('Minify_Lines', 'minify');
410 $id = $source->getId();
411 $source->minifyOptions = array(
412 'id' => (is_file($id) ? basename($id) : $id)
418 * Combines sources and minifies the result.
422 protected static function _combineMinify()
424 $type = self::$_options['contentType']; // ease readability
426 // when combining scripts, make sure all statements separated and
427 // trailing single line comment is terminated
428 $implodeSeparator = ($type === self::TYPE_JS)
431 // allow the user to pass a particular array of options to each
432 // minifier (designated by type). source objects may still override
434 $defaultOptions = isset(self::$_options['minifierOptions'][$type])
435 ? self::$_options['minifierOptions'][$type]
437 // if minifier not set, default is no minification. source objects
438 // may still override this
439 $defaultMinifier = isset(self::$_options['minifiers'][$type])
440 ? self::$_options['minifiers'][$type]
443 if (Minify_Source::haveNoMinifyPrefs(self::$_controller->sources)) {
444 // all source have same options/minifier, better performance
445 // to combine, then minify once
446 foreach (self::$_controller->sources as $source) {
447 $pieces[] = $source->getContent();
449 $content = implode($implodeSeparator, $pieces);
450 if ($defaultMinifier) {
451 self::$_controller->loadMinifier($defaultMinifier);
452 $content = call_user_func($defaultMinifier, $content, $defaultOptions);
455 // minify each source with its own options and minifier, then combine
456 foreach (self::$_controller->sources as $source) {
457 // allow the source to override our minifier and options
458 $minifier = (null !== $source->minifier)
461 $options = (null !== $source->minifyOptions)
462 ? array_merge($defaultOptions, $source->minifyOptions)
465 self::$_controller->loadMinifier($minifier);
466 // get source content and minify it
467 $pieces[] = call_user_func($minifier, $source->getContent(), $options);
469 $pieces[] = $source->getContent();
472 $content = implode($implodeSeparator, $pieces);
475 if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
476 $content = self::_handleCssImports($content);
479 // do any post-processing (esp. for editing build URIs)
480 if (self::$_options['postprocessorRequire']) {
481 require_once self::$_options['postprocessorRequire'];
483 if (self::$_options['postprocessor']) {
484 $content = call_user_func(self::$_options['postprocessor'], $content, $type);
490 * Make a unique cache id for for this request.
492 * Any settings that could affect output are taken into consideration
496 protected static function _getCacheId()
498 return md5(serialize(array(
499 Minify_Source::getDigest(self::$_controller->sources)
500 ,self::$_options['minifiers']
501 ,self::$_options['minifierOptions']
502 ,self::$_options['postprocessor']
503 ,self::$_options['bubbleCssImports']
508 * Bubble CSS @imports to the top or prepend a warning if an
509 * @import is detected not at the top.
511 protected static function _handleCssImports($css)
513 if (self::$_options['bubbleCssImports']) {
514 // bubble CSS imports
515 preg_match_all('/@import.*?;/', $css, $imports);
\r
516 $css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
517 } else if ('' !== self::$importWarning) {
518 // remove comments so we don't mistake { in a comment as a block
519 $noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
520 $lastImportPos = strrpos($noCommentCss, '@import');
521 $firstBlockPos = strpos($noCommentCss, '{');
522 if (false !== $lastImportPos
523 && false !== $firstBlockPos
524 && $firstBlockPos < $lastImportPos
526 // { appears before @import : prepend warning
527 $css = self::$importWarning . $css;