Minify.php 24 KB

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