8 * Minify - Combines, minifies, and caches JavaScript and CSS files on demand.
10 * See README for usage instructions (for now).
12 * This library was inspired by {@link mailto:flashkot@mail.ru jscsscomp by Maxim Martynyuk}
13 * and by the article {@link http://www.hunlock.com/blogs/Supercharged_Javascript "Supercharged JavaScript" by Patrick Hunlock}.
16 * Tested on PHP 5.1.6.
19 * @author Ryan Grove <ryan@wonko.com>
20 * @author Stephen Clay <steve@mrclay.org>
21 * @copyright 2008 Ryan Grove, Stephen Clay. All rights reserved.
22 * @license http://opensource.org/licenses/bsd-license.php New BSD License
23 * @link http://code.google.com/p/minify/
27 const VERSION = '2.1.7';
28 const TYPE_CSS = 'text/css';
29 const TYPE_HTML = 'text/html';
30 // there is some debate over the ideal JS Content-Type, but this is the
31 // Apache default and what Yahoo! uses..
32 const TYPE_JS = 'application/x-javascript';
33 const URL_DEBUG = 'http://code.google.com/p/minify/wiki/Debugging';
36 * How many hours behind are the file modification times of uploaded files?
38 * If you upload files from Windows to a non-Windows server, Windows may report
39 * incorrect mtimes for the files. Immediately after modifying and uploading a
40 * file, use the touch command to update the mtime on the server. If the mtime
41 * jumps ahead by a number of hours, set this variable to that number. If the mtime
42 * moves back, this should not be needed.
44 * @var int $uploaderHoursBehind
46 public static $uploaderHoursBehind = 0;
49 * If this string is not empty AND the serve() option 'bubbleCssImports' is
50 * NOT set, then serve() will check CSS files for @import declarations that
51 * appear too late in the combined stylesheet. If found, serve() will prepend
52 * the output with this warning.
54 * @var string $importWarning
56 public static $importWarning = "/* See http://code.google.com/p/minify/wiki/CommonProblems#@imports_can_appear_in_invalid_locations_in_combined_CSS_files */\n";
59 * Has the DOCUMENT_ROOT been set in user code?
63 public static $isDocRootSet = false;
66 * Specify a cache object (with identical interface as Minify_Cache_File) or
67 * a path to use with Minify_Cache_File.
69 * If not called, Minify will not use a cache and, for each 200 response, will
70 * need to recombine files, minify and encode the output.
72 * @param mixed $cache object with identical interface as Minify_Cache_File or
73 * a directory path, or null to disable caching. (default = '')
75 * @param bool $fileLocking (default = true) This only applies if the first
76 * parameter is a string.
80 public static function setCache($cache = '', $fileLocking = true)
82 if (is_string($cache)) {
83 self::$_cache = new Minify_Cache_File($cache, $fileLocking);
85 self::$_cache = $cache;
90 * Serve a request for a minified file.
92 * Here are the available options and defaults in the base controller:
94 * 'isPublic' : send "public" instead of "private" in Cache-Control
95 * headers, allowing shared caches to cache the output. (default true)
97 * 'quiet' : set to true to have serve() return an array rather than sending
98 * any headers/output (default false)
100 * 'encodeOutput' : set to false to disable content encoding, and not send
101 * the Vary header (default true)
103 * 'encodeMethod' : generally you should let this be determined by
104 * HTTP_Encoder (leave null), but you can force a particular encoding
105 * to be returned, by setting this to 'gzip' or '' (no encoding)
107 * 'encodeLevel' : level of encoding compression (0 to 9, default 9)
109 * 'contentTypeCharset' : appended to the Content-Type header sent. Set to a falsey
110 * value to remove. (default 'utf-8')
112 * 'maxAge' : set this to the number of seconds the client should use its cache
113 * before revalidating with the server. This sets Cache-Control: max-age and the
114 * Expires header. Unlike the old 'setExpires' setting, this setting will NOT
115 * prevent conditional GETs. Note this has nothing to do with server-side caching.
117 * 'rewriteCssUris' : If true, serve() will automatically set the 'currentDir'
118 * minifier option to enable URI rewriting in CSS files (default true)
120 * 'bubbleCssImports' : If true, all @import declarations in combined CSS
121 * files will be move to the top. Note this may alter effective CSS values
122 * due to a change in order. (default false)
124 * 'debug' : set to true to minify all sources with the 'Lines' controller, which
125 * eases the debugging of combined files. This also prevents 304 responses.
126 * @see Minify_Lines::minify()
128 * 'minifiers' : to override Minify's default choice of minifier function for
129 * a particular content-type, specify your callback under the key of the
132 * // call customCssMinifier($css) for all CSS minification
133 * $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier';
135 * // don't minify Javascript at all
136 * $options['minifiers'][Minify::TYPE_JS] = '';
139 * 'minifierOptions' : to send options to the minifier function, specify your options
140 * under the key of the content-type. E.g. To send the CSS minifier an option:
142 * // give CSS minifier array('optionName' => 'optionValue') as 2nd argument
143 * $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue';
146 * 'contentType' : (optional) this is only needed if your file extension is not
147 * js/css/html. The given content-type will be sent regardless of source file
148 * extension, so this should not be used in a Groups config with other
149 * Javascript/CSS files.
151 * Any controller options are documented in that controller's setupSources() method.
153 * @param mixed $controller instance of subclass of Minify_Controller_Base or string
154 * name of controller. E.g. 'Files'
156 * @param array $options controller/serve options
158 * @return null|array if the 'quiet' option is set to true, an array
159 * with keys "success" (bool), "statusCode" (int), "content" (string), and
164 public static function serve($controller, $options = array())
166 if (! self::$isDocRootSet && 0 === stripos(PHP_OS, 'win')) {
170 if (is_string($controller)) {
171 // make $controller into object
172 $class = 'Minify_Controller_' . $controller;
173 $controller = new $class();
174 /* @var Minify_Controller_Base $controller */
177 // set up controller sources and mix remaining options with
178 // controller defaults
179 $options = $controller->setupSources($options);
180 $options = $controller->analyzeSources($options);
181 self::$_options = $controller->mixInDefaultOptions($options);
183 // check request validity
184 if (! $controller->sources) {
186 if (! self::$_options['quiet']) {
187 self::_errorExit(self::$_options['badRequestHeader'], self::URL_DEBUG);
189 list(,$statusCode) = explode(' ', self::$_options['badRequestHeader']);
192 ,'statusCode' => (int)$statusCode
194 ,'headers' => array()
199 self::$_controller = $controller;
201 if (self::$_options['debug']) {
202 self::_setupDebug($controller->sources);
203 self::$_options['maxAge'] = 0;
206 // determine encoding
207 if (self::$_options['encodeOutput']) {
209 if (self::$_options['encodeMethod'] !== null) {
210 // controller specifically requested this
211 $contentEncoding = self::$_options['encodeMethod'];
213 // sniff request header
214 // depending on what the client accepts, $contentEncoding may be
215 // 'x-gzip' while our internal encodeMethod is 'gzip'. Calling
216 // getAcceptedEncoding(false, false) leaves out compress and deflate as options.
217 list(self::$_options['encodeMethod'], $contentEncoding) = HTTP_Encoder::getAcceptedEncoding(false, false);
218 $sendVary = ! HTTP_Encoder::isBuggyIe();
221 self::$_options['encodeMethod'] = ''; // identity (no encoding)
224 // check client cache
226 'lastModifiedTime' => self::$_options['lastModifiedTime']
227 ,'isPublic' => self::$_options['isPublic']
228 ,'encoding' => self::$_options['encodeMethod']
230 if (self::$_options['maxAge'] > 0) {
231 $cgOptions['maxAge'] = self::$_options['maxAge'];
232 } elseif (self::$_options['debug']) {
233 $cgOptions['invalidate'] = true;
235 $cg = new HTTP_ConditionalGet($cgOptions);
236 if ($cg->cacheIsValid) {
237 // client's cache is valid
238 if (! self::$_options['quiet']) {
246 ,'headers' => $cg->getHeaders()
250 // client will need output
251 $headers = $cg->getHeaders();
255 if (self::$_options['contentType'] === self::TYPE_CSS
256 && self::$_options['rewriteCssUris']) {
257 foreach($controller->sources as $key => $source) {
258 if ($source->filepath
259 && !isset($source->minifyOptions['currentDir'])
260 && !isset($source->minifyOptions['prependRelativePath'])
262 $source->minifyOptions['currentDir'] = dirname($source->filepath);
267 // check server cache
268 if (null !== self::$_cache && ! self::$_options['debug']) {
270 // the goal is to use only the cache methods to sniff the length and
271 // output the content, as they do not require ever loading the file into
273 $cacheId = self::_getCacheId();
274 $fullCacheId = (self::$_options['encodeMethod'])
277 // check cache for valid entry
278 $cacheIsReady = self::$_cache->isValid($fullCacheId, self::$_options['lastModifiedTime']);
280 $cacheContentLength = self::$_cache->getSize($fullCacheId);
282 // generate & cache content
284 $content = self::_combineMinify();
285 } catch (Exception $e) {
286 self::$_controller->log($e->getMessage());
287 if (! self::$_options['quiet']) {
288 self::_errorExit(self::$_options['errorHeader'], self::URL_DEBUG);
292 self::$_cache->store($cacheId, $content);
293 if (function_exists('gzencode') && self::$_options['encodeMethod']) {
294 self::$_cache->store($cacheId . '.gz', gzencode($content, self::$_options['encodeLevel']));
299 $cacheIsReady = false;
301 $content = self::_combineMinify();
302 } catch (Exception $e) {
303 self::$_controller->log($e->getMessage());
304 if (! self::$_options['quiet']) {
305 self::_errorExit(self::$_options['errorHeader'], self::URL_DEBUG);
310 if (! $cacheIsReady && self::$_options['encodeMethod']) {
311 // still need to encode
312 $content = gzencode($content, self::$_options['encodeLevel']);
316 $headers['Content-Length'] = $cacheIsReady
317 ? $cacheContentLength
318 : ((function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
319 ? mb_strlen($content, '8bit')
322 $headers['Content-Type'] = self::$_options['contentTypeCharset']
323 ? self::$_options['contentType'] . '; charset=' . self::$_options['contentTypeCharset']
324 : self::$_options['contentType'];
325 if (self::$_options['encodeMethod'] !== '') {
326 $headers['Content-Encoding'] = $contentEncoding;
328 if (self::$_options['encodeOutput'] && $sendVary) {
329 $headers['Vary'] = 'Accept-Encoding';
332 if (! self::$_options['quiet']) {
333 // output headers & content
334 foreach ($headers as $name => $val) {
335 header($name . ': ' . $val);
338 self::$_cache->display($fullCacheId);
346 ,'content' => $cacheIsReady
347 ? self::$_cache->fetch($fullCacheId)
349 ,'headers' => $headers
355 * Return combined minified content for a set of sources
357 * No internal caching will be used and the content will not be HTTP encoded.
359 * @param array $sources array of filepaths and/or Minify_Source objects
361 * @param array $options (optional) array of options for serve. By default
362 * these are already set: quiet = true, encodeMethod = '', lastModifiedTime = 0.
366 public static function combine($sources, $options = array())
368 $cache = self::$_cache;
369 self::$_cache = null;
370 $options = array_merge(array(
371 'files' => (array)$sources
373 ,'encodeMethod' => ''
374 ,'lastModifiedTime' => 0
376 $out = self::serve('Files', $options);
377 self::$_cache = $cache;
378 return $out['content'];
382 * Set $_SERVER['DOCUMENT_ROOT']. On IIS, the value is created from SCRIPT_FILENAME and SCRIPT_NAME.
384 * @param string $docRoot value to use for DOCUMENT_ROOT
386 public static function setDocRoot($docRoot = '')
388 self::$isDocRootSet = true;
390 $_SERVER['DOCUMENT_ROOT'] = $docRoot;
391 } elseif (isset($_SERVER['SERVER_SOFTWARE'])
392 && 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
393 $_SERVER['DOCUMENT_ROOT'] = substr(
394 $_SERVER['SCRIPT_FILENAME']
396 ,strlen($_SERVER['SCRIPT_FILENAME']) - strlen($_SERVER['SCRIPT_NAME']));
397 $_SERVER['DOCUMENT_ROOT'] = rtrim($_SERVER['DOCUMENT_ROOT'], '\\');
402 * Any Minify_Cache_* object or null (i.e. no server cache is used)
404 * @var Minify_Cache_File
406 private static $_cache = null;
409 * Active controller for current request
411 * @var Minify_Controller_Base
413 protected static $_controller = null;
416 * Options for current request
420 protected static $_options = null;
423 * @param string $header
427 protected static function _errorExit($header, $url)
429 $url = htmlspecialchars($url, ENT_QUOTES);
430 list(,$h1) = explode(' ', $header, 2);
431 $h1 = htmlspecialchars($h1);
432 // FastCGI environments require 3rd arg to header() to be set
433 list(, $code) = explode(' ', $header, 3);
434 header($header, true, $code);
435 header('Content-Type: text/html; charset=utf-8');
437 echo "<p>Please see <a href='$url'>$url</a>.</p>";
442 * Set up sources to use Minify_Lines
444 * @param Minify_Source[] $sources Minify_Source instances
446 protected static function _setupDebug($sources)
448 foreach ($sources as $source) {
449 $source->minifier = array('Minify_Lines', 'minify');
450 $id = $source->getId();
451 $source->minifyOptions = array(
452 'id' => (is_file($id) ? basename($id) : $id)
458 * Combines sources and minifies the result.
464 protected static function _combineMinify()
466 $type = self::$_options['contentType']; // ease readability
468 // when combining scripts, make sure all statements separated and
469 // trailing single line comment is terminated
470 $implodeSeparator = ($type === self::TYPE_JS)
473 // allow the user to pass a particular array of options to each
474 // minifier (designated by type). source objects may still override
476 $defaultOptions = isset(self::$_options['minifierOptions'][$type])
477 ? self::$_options['minifierOptions'][$type]
479 // if minifier not set, default is no minification. source objects
480 // may still override this
481 $defaultMinifier = isset(self::$_options['minifiers'][$type])
482 ? self::$_options['minifiers'][$type]
485 // process groups of sources with identical minifiers/options
488 $l = count(self::$_controller->sources);
489 $groupToProcessTogether = array();
490 $lastMinifier = null;
496 $source = self::$_controller->sources[$i];
497 /* @var Minify_Source $source */
498 $sourceContent = $source->getContent();
500 // allow the source to override our minifier and options
501 $minifier = (null !== $source->minifier)
504 $options = (null !== $source->minifyOptions)
505 ? array_merge($defaultOptions, $source->minifyOptions)
508 // do we need to process our group right now?
509 if ($i > 0 // yes, we have at least the first group populated
511 ! $source // yes, we ran out of sources
512 || $type === self::TYPE_CSS // yes, to process CSS individually (avoiding PCRE bugs/limits)
513 || $minifier !== $lastMinifier // yes, minifier changed
514 || $options !== $lastOptions) // yes, options changed
517 // minify previous sources with last settings
518 $imploded = implode($implodeSeparator, $groupToProcessTogether);
519 $groupToProcessTogether = array();
522 $content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
523 } catch (Exception $e) {
524 throw new Exception("Exception in minifier: " . $e->getMessage());
527 $content[] = $imploded;
530 // add content to the group
532 $groupToProcessTogether[] = $sourceContent;
533 $lastMinifier = $minifier;
534 $lastOptions = $options;
539 $content = implode($implodeSeparator, $content);
541 if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
542 $content = self::_handleCssImports($content);
545 // do any post-processing (esp. for editing build URIs)
546 if (self::$_options['postprocessorRequire']) {
547 require_once self::$_options['postprocessorRequire'];
549 if (self::$_options['postprocessor']) {
550 $content = call_user_func(self::$_options['postprocessor'], $content, $type);
556 * Make a unique cache id for for this request.
558 * Any settings that could affect output are taken into consideration
560 * @param string $prefix
564 protected static function _getCacheId($prefix = 'minify')
566 $name = preg_replace('/[^a-zA-Z0-9\\.=_,]/', '', self::$_controller->selectionId);
567 $name = preg_replace('/\\.+/', '.', $name);
568 $name = substr($name, 0, 200 - 34 - strlen($prefix));
569 $md5 = md5(serialize(array(
570 Minify_Source::getDigest(self::$_controller->sources)
571 ,self::$_options['minifiers']
572 ,self::$_options['minifierOptions']
573 ,self::$_options['postprocessor']
574 ,self::$_options['bubbleCssImports']
577 return "{$prefix}_{$name}_{$md5}";
581 * Bubble CSS @imports to the top or prepend a warning if an import is detected not at the top.
587 protected static function _handleCssImports($css)
589 if (self::$_options['bubbleCssImports']) {
590 // bubble CSS imports
591 preg_match_all('/@import.*?;/', $css, $imports);
592 $css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
593 } else if ('' !== self::$importWarning) {
594 // remove comments so we don't mistake { in a comment as a block
595 $noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
596 $lastImportPos = strrpos($noCommentCss, '@import');
597 $firstBlockPos = strpos($noCommentCss, '{');
598 if (false !== $lastImportPos
599 && false !== $firstBlockPos
600 && $firstBlockPos < $lastImportPos
602 // { appears before @import : prepend warning
603 $css = self::$importWarning . $css;