Minify.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. /**
  3. * Class Minify
  4. * @package Minify
  5. */
  6. /**
  7. * Minify_Source
  8. */
  9. require_once 'Minify/Source.php';
  10. /**
  11. * Minify - Combines, minifies, and caches JavaScript and CSS files on demand.
  12. *
  13. * See README for usage instructions (for now).
  14. *
  15. * This library was inspired by {@link mailto:flashkot@mail.ru jscsscomp by Maxim Martynyuk}
  16. * and by the article {@link http://www.hunlock.com/blogs/Supercharged_Javascript "Supercharged JavaScript" by Patrick Hunlock}.
  17. *
  18. * Requires PHP 5.1.0.
  19. * Tested on PHP 5.1.6.
  20. *
  21. * @package Minify
  22. * @author Ryan Grove <ryan@wonko.com>
  23. * @author Stephen Clay <steve@mrclay.org>
  24. * @copyright 2008 Ryan Grove, Stephen Clay. All rights reserved.
  25. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  26. * @link http://code.google.com/p/minify/
  27. */
  28. class Minify {
  29. const VERSION = '2.1.3';
  30. const TYPE_CSS = 'text/css';
  31. const TYPE_HTML = 'text/html';
  32. // there is some debate over the ideal JS Content-Type, but this is the
  33. // Apache default and what Yahoo! uses..
  34. const TYPE_JS = 'application/x-javascript';
  35. /**
  36. * How many hours behind are the file modification times of uploaded files?
  37. *
  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.
  43. *
  44. * @var int $uploaderHoursBehind
  45. */
  46. public static $uploaderHoursBehind = 0;
  47. /**
  48. * If this string is not empty AND the serve() option 'bubbleCssImports' is
  49. * NOT set, then serve() will check CSS files for @import declarations that
  50. * appear too late in the combined stylesheet. If found, serve() will prepend
  51. * the output with this warning.
  52. *
  53. * @var string $importWarning
  54. */
  55. public static $importWarning = "/* See http://code.google.com/p/minify/wiki/CommonProblems#@imports_can_appear_in_invalid_locations_in_combined_CSS_files */\n";
  56. /**
  57. * Specify a cache object (with identical interface as Minify_Cache_File) or
  58. * a path to use with Minify_Cache_File.
  59. *
  60. * If not called, Minify will not use a cache and, for each 200 response, will
  61. * need to recombine files, minify and encode the output.
  62. *
  63. * @param mixed $cache object with identical interface as Minify_Cache_File or
  64. * a directory path, or null to disable caching. (default = '')
  65. *
  66. * @param bool $fileLocking (default = true) This only applies if the first
  67. * parameter is a string.
  68. *
  69. * @return null
  70. */
  71. public static function setCache($cache = '', $fileLocking = true)
  72. {
  73. if (is_string($cache)) {
  74. require_once 'Minify/Cache/File.php';
  75. self::$_cache = new Minify_Cache_File($cache, $fileLocking);
  76. } else {
  77. self::$_cache = $cache;
  78. }
  79. }
  80. /**
  81. * Serve a request for a minified file.
  82. *
  83. * Here are the available options and defaults in the base controller:
  84. *
  85. * 'isPublic' : send "public" instead of "private" in Cache-Control
  86. * headers, allowing shared caches to cache the output. (default true)
  87. *
  88. * 'quiet' : set to true to have serve() return an array rather than sending
  89. * any headers/output (default false)
  90. *
  91. * 'encodeOutput' : set to false to disable content encoding, and not send
  92. * the Vary header (default true)
  93. *
  94. * 'encodeMethod' : generally you should let this be determined by
  95. * HTTP_Encoder (leave null), but you can force a particular encoding
  96. * to be returned, by setting this to 'gzip' or '' (no encoding)
  97. *
  98. * 'encodeLevel' : level of encoding compression (0 to 9, default 9)
  99. *
  100. * 'contentTypeCharset' : appended to the Content-Type header sent. Set to a falsey
  101. * value to remove. (default 'utf-8')
  102. *
  103. * 'maxAge' : set this to the number of seconds the client should use its cache
  104. * before revalidating with the server. This sets Cache-Control: max-age and the
  105. * Expires header. Unlike the old 'setExpires' setting, this setting will NOT
  106. * prevent conditional GETs. Note this has nothing to do with server-side caching.
  107. *
  108. * 'rewriteCssUris' : If true, serve() will automatically set the 'currentDir'
  109. * minifier option to enable URI rewriting in CSS files (default true)
  110. *
  111. * 'bubbleCssImports' : If true, all @import declarations in combined CSS
  112. * files will be move to the top. Note this may alter effective CSS values
  113. * due to a change in order. (default false)
  114. *
  115. * 'debug' : set to true to minify all sources with the 'Lines' controller, which
  116. * eases the debugging of combined files. This also prevents 304 responses.
  117. * @see Minify_Lines::minify()
  118. *
  119. * 'minifiers' : to override Minify's default choice of minifier function for
  120. * a particular content-type, specify your callback under the key of the
  121. * content-type:
  122. * <code>
  123. * // call customCssMinifier($css) for all CSS minification
  124. * $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier';
  125. *
  126. * // don't minify Javascript at all
  127. * $options['minifiers'][Minify::TYPE_JS] = '';
  128. * </code>
  129. *
  130. * 'minifierOptions' : to send options to the minifier function, specify your options
  131. * under the key of the content-type. E.g. To send the CSS minifier an option:
  132. * <code>
  133. * // give CSS minifier array('optionName' => 'optionValue') as 2nd argument
  134. * $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue';
  135. * </code>
  136. *
  137. * 'contentType' : (optional) this is only needed if your file extension is not
  138. * js/css/html. The given content-type will be sent regardless of source file
  139. * extension, so this should not be used in a Groups config with other
  140. * Javascript/CSS files.
  141. *
  142. * Any controller options are documented in that controller's setupSources() method.
  143. *
  144. * @param mixed instance of subclass of Minify_Controller_Base or string name of
  145. * controller. E.g. 'Files'
  146. *
  147. * @param array $options controller/serve options
  148. *
  149. * @return mixed null, or, if the 'quiet' option is set to true, an array
  150. * with keys "success" (bool), "statusCode" (int), "content" (string), and
  151. * "headers" (array).
  152. */
  153. public static function serve($controller, $options = array())
  154. {
  155. if (is_string($controller)) {
  156. // make $controller into object
  157. $class = 'Minify_Controller_' . $controller;
  158. if (! class_exists($class, false)) {
  159. require_once "Minify/Controller/"
  160. . str_replace('_', '/', $controller) . ".php";
  161. }
  162. $controller = new $class();
  163. }
  164. // set up controller sources and mix remaining options with
  165. // controller defaults
  166. $options = $controller->setupSources($options);
  167. $options = $controller->analyzeSources($options);
  168. self::$_options = $controller->mixInDefaultOptions($options);
  169. // check request validity
  170. if (! $controller->sources) {
  171. // invalid request!
  172. if (! self::$_options['quiet']) {
  173. header(self::$_options['badRequestHeader']);
  174. echo self::$_options['badRequestHeader'];
  175. return;
  176. } else {
  177. list(,$statusCode) = explode(' ', self::$_options['badRequestHeader']);
  178. return array(
  179. 'success' => false
  180. ,'statusCode' => (int)$statusCode
  181. ,'content' => ''
  182. ,'headers' => array()
  183. );
  184. }
  185. }
  186. self::$_controller = $controller;
  187. if (self::$_options['debug']) {
  188. self::_setupDebug($controller->sources);
  189. self::$_options['maxAge'] = 0;
  190. }
  191. // determine encoding
  192. if (self::$_options['encodeOutput']) {
  193. if (self::$_options['encodeMethod'] !== null) {
  194. // controller specifically requested this
  195. $contentEncoding = self::$_options['encodeMethod'];
  196. } else {
  197. // sniff request header
  198. require_once 'HTTP/Encoder.php';
  199. // depending on what the client accepts, $contentEncoding may be
  200. // 'x-gzip' while our internal encodeMethod is 'gzip'. Calling
  201. // getAcceptedEncoding(false, false) leaves out compress and deflate as options.
  202. list(self::$_options['encodeMethod'], $contentEncoding) = HTTP_Encoder::getAcceptedEncoding(false, false);
  203. }
  204. } else {
  205. self::$_options['encodeMethod'] = ''; // identity (no encoding)
  206. }
  207. // check client cache
  208. require_once 'HTTP/ConditionalGet.php';
  209. $cgOptions = array(
  210. 'lastModifiedTime' => self::$_options['lastModifiedTime']
  211. ,'isPublic' => self::$_options['isPublic']
  212. ,'encoding' => self::$_options['encodeMethod']
  213. );
  214. if (self::$_options['maxAge'] > 0) {
  215. $cgOptions['maxAge'] = self::$_options['maxAge'];
  216. }
  217. $cg = new HTTP_ConditionalGet($cgOptions);
  218. if ($cg->cacheIsValid) {
  219. // client's cache is valid
  220. if (! self::$_options['quiet']) {
  221. $cg->sendHeaders();
  222. return;
  223. } else {
  224. return array(
  225. 'success' => true
  226. ,'statusCode' => 304
  227. ,'content' => ''
  228. ,'headers' => $cg->getHeaders()
  229. );
  230. }
  231. } else {
  232. // client will need output
  233. $headers = $cg->getHeaders();
  234. unset($cg);
  235. }
  236. if (self::$_options['contentType'] === self::TYPE_CSS
  237. && self::$_options['rewriteCssUris']) {
  238. reset($controller->sources);
  239. while (list($key, $source) = each($controller->sources)) {
  240. if ($source->filepath
  241. && !isset($source->minifyOptions['currentDir'])
  242. && !isset($source->minifyOptions['prependRelativePath'])
  243. ) {
  244. $source->minifyOptions['currentDir'] = dirname($source->filepath);
  245. }
  246. }
  247. }
  248. // check server cache
  249. if (null !== self::$_cache) {
  250. // using cache
  251. // the goal is to use only the cache methods to sniff the length and
  252. // output the content, as they do not require ever loading the file into
  253. // memory.
  254. $cacheId = 'minify_' . self::_getCacheId();
  255. $fullCacheId = (self::$_options['encodeMethod'])
  256. ? $cacheId . '.gz'
  257. : $cacheId;
  258. // check cache for valid entry
  259. $cacheIsReady = self::$_cache->isValid($fullCacheId, self::$_options['lastModifiedTime']);
  260. if ($cacheIsReady) {
  261. $cacheContentLength = self::$_cache->getSize($fullCacheId);
  262. } else {
  263. // generate & cache content
  264. $content = self::_combineMinify();
  265. self::$_cache->store($cacheId, $content);
  266. if (function_exists('gzencode')) {
  267. self::$_cache->store($cacheId . '.gz', gzencode($content, self::$_options['encodeLevel']));
  268. }
  269. }
  270. } else {
  271. // no cache
  272. $cacheIsReady = false;
  273. $content = self::_combineMinify();
  274. }
  275. if (! $cacheIsReady && self::$_options['encodeMethod']) {
  276. // still need to encode
  277. $content = gzencode($content, self::$_options['encodeLevel']);
  278. }
  279. // add headers
  280. $headers['Content-Length'] = $cacheIsReady
  281. ? $cacheContentLength
  282. : strlen($content);
  283. $headers['Content-Type'] = self::$_options['contentTypeCharset']
  284. ? self::$_options['contentType'] . '; charset=' . self::$_options['contentTypeCharset']
  285. : self::$_options['contentType'];
  286. if (self::$_options['encodeMethod'] !== '') {
  287. $headers['Content-Encoding'] = $contentEncoding;
  288. }
  289. if (self::$_options['encodeOutput']) {
  290. $headers['Vary'] = 'Accept-Encoding';
  291. }
  292. if (! self::$_options['quiet']) {
  293. // output headers & content
  294. foreach ($headers as $name => $val) {
  295. header($name . ': ' . $val);
  296. }
  297. if ($cacheIsReady) {
  298. self::$_cache->display($fullCacheId);
  299. } else {
  300. echo $content;
  301. }
  302. } else {
  303. return array(
  304. 'success' => true
  305. ,'statusCode' => 200
  306. ,'content' => $cacheIsReady
  307. ? self::$_cache->fetch($fullCacheId)
  308. : $content
  309. ,'headers' => $headers
  310. );
  311. }
  312. }
  313. /**
  314. * Return combined minified content for a set of sources
  315. *
  316. * No internal caching will be used and the content will not be HTTP encoded.
  317. *
  318. * @param array $sources array of filepaths and/or Minify_Source objects
  319. *
  320. * @param array $options (optional) array of options for serve. By default
  321. * these are already set: quiet = true, encodeMethod = '', lastModifiedTime = 0.
  322. *
  323. * @return string
  324. */
  325. public static function combine($sources, $options = array())
  326. {
  327. $cache = self::$_cache;
  328. self::$_cache = null;
  329. $options = array_merge(array(
  330. 'files' => (array)$sources
  331. ,'quiet' => true
  332. ,'encodeMethod' => ''
  333. ,'lastModifiedTime' => 0
  334. ), $options);
  335. $out = self::serve('Files', $options);
  336. self::$_cache = $cache;
  337. return $out['content'];
  338. }
  339. /**
  340. * On IIS, create $_SERVER['DOCUMENT_ROOT']
  341. *
  342. * @param bool $unsetPathInfo (default false) if true, $_SERVER['PATH_INFO']
  343. * will be unset (it is inconsistent with Apache's setting)
  344. *
  345. * @return null
  346. */
  347. public static function setDocRoot($unsetPathInfo = false)
  348. {
  349. if (isset($_SERVER['SERVER_SOFTWARE'])
  350. && 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/')
  351. ) {
  352. $_SERVER['DOCUMENT_ROOT'] = rtrim(substr(
  353. $_SERVER['PATH_TRANSLATED']
  354. ,0
  355. ,strlen($_SERVER['PATH_TRANSLATED']) - strlen($_SERVER['SCRIPT_NAME'])
  356. ), '\\');
  357. if ($unsetPathInfo) {
  358. unset($_SERVER['PATH_INFO']);
  359. }
  360. require_once 'Minify/Logger.php';
  361. Minify_Logger::log("setDocRoot() set DOCUMENT_ROOT to \"{$_SERVER['DOCUMENT_ROOT']}\"");
  362. }
  363. }
  364. /**
  365. * @var mixed Minify_Cache_* object or null (i.e. no server cache is used)
  366. */
  367. private static $_cache = null;
  368. /**
  369. * @var Minify_Controller active controller for current request
  370. */
  371. protected static $_controller = null;
  372. /**
  373. * @var array options for current request
  374. */
  375. protected static $_options = null;
  376. /**
  377. * Set up sources to use Minify_Lines
  378. *
  379. * @param array $sources Minify_Source instances
  380. *
  381. * @return null
  382. */
  383. protected static function _setupDebug($sources)
  384. {
  385. foreach ($sources as $source) {
  386. $source->minifier = array('Minify_Lines', 'minify');
  387. $id = $source->getId();
  388. $source->minifyOptions = array(
  389. 'id' => (is_file($id) ? basename($id) : $id)
  390. );
  391. }
  392. }
  393. /**
  394. * Combines sources and minifies the result.
  395. *
  396. * @return string
  397. */
  398. protected static function _combineMinify()
  399. {
  400. $type = self::$_options['contentType']; // ease readability
  401. // when combining scripts, make sure all statements separated and
  402. // trailing single line comment is terminated
  403. $implodeSeparator = ($type === self::TYPE_JS)
  404. ? "\n;"
  405. : '';
  406. // allow the user to pass a particular array of options to each
  407. // minifier (designated by type). source objects may still override
  408. // these
  409. $defaultOptions = isset(self::$_options['minifierOptions'][$type])
  410. ? self::$_options['minifierOptions'][$type]
  411. : array();
  412. // if minifier not set, default is no minification. source objects
  413. // may still override this
  414. $defaultMinifier = isset(self::$_options['minifiers'][$type])
  415. ? self::$_options['minifiers'][$type]
  416. : false;
  417. if (Minify_Source::haveNoMinifyPrefs(self::$_controller->sources)) {
  418. // all source have same options/minifier, better performance
  419. // to combine, then minify once
  420. foreach (self::$_controller->sources as $source) {
  421. $pieces[] = $source->getContent();
  422. }
  423. $content = implode($implodeSeparator, $pieces);
  424. if ($defaultMinifier) {
  425. self::$_controller->loadMinifier($defaultMinifier);
  426. $content = call_user_func($defaultMinifier, $content, $defaultOptions);
  427. }
  428. } else {
  429. // minify each source with its own options and minifier, then combine
  430. foreach (self::$_controller->sources as $source) {
  431. // allow the source to override our minifier and options
  432. $minifier = (null !== $source->minifier)
  433. ? $source->minifier
  434. : $defaultMinifier;
  435. $options = (null !== $source->minifyOptions)
  436. ? array_merge($defaultOptions, $source->minifyOptions)
  437. : $defaultOptions;
  438. if ($minifier) {
  439. self::$_controller->loadMinifier($minifier);
  440. // get source content and minify it
  441. $pieces[] = call_user_func($minifier, $source->getContent(), $options);
  442. } else {
  443. $pieces[] = $source->getContent();
  444. }
  445. }
  446. $content = implode($implodeSeparator, $pieces);
  447. }
  448. if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
  449. $content = self::_handleCssImports($content);
  450. }
  451. // do any post-processing (esp. for editing build URIs)
  452. if (self::$_options['postprocessorRequire']) {
  453. require_once self::$_options['postprocessorRequire'];
  454. }
  455. if (self::$_options['postprocessor']) {
  456. $content = call_user_func(self::$_options['postprocessor'], $content, $type);
  457. }
  458. return $content;
  459. }
  460. /**
  461. * Make a unique cache id for for this request.
  462. *
  463. * Any settings that could affect output are taken into consideration
  464. *
  465. * @return string
  466. */
  467. protected static function _getCacheId()
  468. {
  469. return md5(serialize(array(
  470. Minify_Source::getDigest(self::$_controller->sources)
  471. ,self::$_options['minifiers']
  472. ,self::$_options['minifierOptions']
  473. ,self::$_options['postprocessor']
  474. ,self::$_options['bubbleCssImports']
  475. )));
  476. }
  477. /**
  478. * Bubble CSS @imports to the top or prepend a warning if an
  479. * @import is detected not at the top.
  480. */
  481. protected static function _handleCssImports($css)
  482. {
  483. if (self::$_options['bubbleCssImports']) {
  484. // bubble CSS imports
  485. preg_match_all('/@import.*?;/', $css, $imports);
  486. $css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
  487. } else if ('' !== self::$importWarning) {
  488. // remove comments so we don't mistake { in a comment as a block
  489. $noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
  490. $lastImportPos = strrpos($noCommentCss, '@import');
  491. $firstBlockPos = strpos($noCommentCss, '{');
  492. if (false !== $lastImportPos
  493. && false !== $firstBlockPos
  494. && $firstBlockPos < $lastImportPos
  495. ) {
  496. // { appears before @import : prepend warning
  497. $css = self::$importWarning . $css;
  498. }
  499. }
  500. return $css;
  501. }
  502. }