Minify.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. * 'minifiers' : to override Minify's default choice of minifier function for
  122. * a particular content-type, specify your callback under the key of the
  123. * content-type:
  124. * <code>
  125. * // call customCssMinifier($css) for all CSS minification
  126. * $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier';
  127. *
  128. * // don't minify Javascript at all
  129. * $options['minifiers'][Minify::TYPE_JS] = '';
  130. * </code>
  131. *
  132. * 'minifierOptions' : to send options to the minifier function, specify your options
  133. * under the key of the content-type. E.g. To send the CSS minifier an option:
  134. * <code>
  135. * // give CSS minifier array('optionName' => 'optionValue') as 2nd argument
  136. * $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue';
  137. * </code>
  138. *
  139. * 'contentType' : (optional) this is only needed if your file extension is not
  140. * js/css/html. The given content-type will be sent regardless of source file
  141. * extension, so this should not be used in a Groups config with other
  142. * Javascript/CSS files.
  143. *
  144. * Any controller options are documented in that controller's setupSources() method.
  145. *
  146. * @param mixed $controller instance of subclass of Minify_Controller_Base or string
  147. * name of controller. E.g. 'Files'
  148. *
  149. * @param array $options controller/serve options
  150. *
  151. * @return null|array if the 'quiet' option is set to true, an array
  152. * with keys "success" (bool), "statusCode" (int), "content" (string), and
  153. * "headers" (array).
  154. *
  155. * @throws Exception
  156. */
  157. public static function serve($controller, $options = array())
  158. {
  159. if (! self::$isDocRootSet && 0 === stripos(PHP_OS, 'win')) {
  160. self::setDocRoot();
  161. }
  162. if (is_string($controller)) {
  163. // make $controller into object
  164. $class = 'Minify_Controller_' . $controller;
  165. $controller = new $class();
  166. /* @var Minify_Controller_Base $controller */
  167. }
  168. // set up controller sources and mix remaining options with
  169. // controller defaults
  170. $options = $controller->setupSources($options);
  171. $options = $controller->analyzeSources($options);
  172. self::$_options = $controller->mixInDefaultOptions($options);
  173. // check request validity
  174. if (! $controller->sources) {
  175. // invalid request!
  176. if (! self::$_options['quiet']) {
  177. self::_errorExit(self::$_options['badRequestHeader'], self::URL_DEBUG);
  178. } else {
  179. list(,$statusCode) = explode(' ', self::$_options['badRequestHeader']);
  180. return array(
  181. 'success' => false
  182. ,'statusCode' => (int)$statusCode
  183. ,'content' => ''
  184. ,'headers' => array()
  185. );
  186. }
  187. }
  188. self::$_controller = $controller;
  189. if (self::$_options['debug']) {
  190. self::_setupDebug($controller->sources);
  191. self::$_options['maxAge'] = 0;
  192. }
  193. // determine encoding
  194. if (self::$_options['encodeOutput']) {
  195. $sendVary = true;
  196. if (self::$_options['encodeMethod'] !== null) {
  197. // controller specifically requested this
  198. $contentEncoding = self::$_options['encodeMethod'];
  199. } else {
  200. // sniff request header
  201. // depending on what the client accepts, $contentEncoding may be
  202. // 'x-gzip' while our internal encodeMethod is 'gzip'. Calling
  203. // getAcceptedEncoding(false, false) leaves out compress and deflate as options.
  204. list(self::$_options['encodeMethod'], $contentEncoding) = HTTP_Encoder::getAcceptedEncoding(false, false);
  205. $sendVary = ! HTTP_Encoder::isBuggyIe();
  206. }
  207. } else {
  208. self::$_options['encodeMethod'] = ''; // identity (no encoding)
  209. }
  210. // check client cache
  211. $cgOptions = array(
  212. 'lastModifiedTime' => self::$_options['lastModifiedTime']
  213. ,'isPublic' => self::$_options['isPublic']
  214. ,'encoding' => self::$_options['encodeMethod']
  215. );
  216. if (self::$_options['maxAge'] > 0) {
  217. $cgOptions['maxAge'] = self::$_options['maxAge'];
  218. } elseif (self::$_options['debug']) {
  219. $cgOptions['invalidate'] = true;
  220. }
  221. $cg = new HTTP_ConditionalGet($cgOptions);
  222. if ($cg->cacheIsValid) {
  223. // client's cache is valid
  224. if (! self::$_options['quiet']) {
  225. $cg->sendHeaders();
  226. return;
  227. } else {
  228. return array(
  229. 'success' => true
  230. ,'statusCode' => 304
  231. ,'content' => ''
  232. ,'headers' => $cg->getHeaders()
  233. );
  234. }
  235. } else {
  236. // client will need output
  237. $headers = $cg->getHeaders();
  238. unset($cg);
  239. }
  240. if (self::$_options['contentType'] === self::TYPE_CSS
  241. && self::$_options['rewriteCssUris']) {
  242. foreach($controller->sources as $key => $source) {
  243. if ($source->filepath
  244. && !isset($source->minifyOptions['currentDir'])
  245. && !isset($source->minifyOptions['prependRelativePath'])
  246. ) {
  247. $source->minifyOptions['currentDir'] = dirname($source->filepath);
  248. }
  249. }
  250. }
  251. // check server cache
  252. if (null !== self::$_cache && ! self::$_options['debug']) {
  253. // using cache
  254. // the goal is to use only the cache methods to sniff the length and
  255. // output the content, as they do not require ever loading the file into
  256. // memory.
  257. $cacheId = self::_getCacheId();
  258. $fullCacheId = (self::$_options['encodeMethod'])
  259. ? $cacheId . '.gz'
  260. : $cacheId;
  261. // check cache for valid entry
  262. $cacheIsReady = self::$_cache->isValid($fullCacheId, self::$_options['lastModifiedTime']);
  263. if ($cacheIsReady) {
  264. $cacheContentLength = self::$_cache->getSize($fullCacheId);
  265. } else {
  266. // generate & cache content
  267. try {
  268. $content = self::_combineMinify();
  269. } catch (Exception $e) {
  270. self::$_controller->log($e->getMessage());
  271. if (! self::$_options['quiet']) {
  272. self::_errorExit(self::$_options['errorHeader'], self::URL_DEBUG);
  273. }
  274. throw $e;
  275. }
  276. self::$_cache->store($cacheId, $content);
  277. if (function_exists('gzencode') && self::$_options['encodeMethod']) {
  278. self::$_cache->store($cacheId . '.gz', gzencode($content, self::$_options['encodeLevel']));
  279. }
  280. }
  281. } else {
  282. // no cache
  283. $cacheIsReady = false;
  284. try {
  285. $content = self::_combineMinify();
  286. } catch (Exception $e) {
  287. self::$_controller->log($e->getMessage());
  288. if (! self::$_options['quiet']) {
  289. self::_errorExit(self::$_options['errorHeader'], self::URL_DEBUG);
  290. }
  291. throw $e;
  292. }
  293. }
  294. if (! $cacheIsReady && self::$_options['encodeMethod']) {
  295. // still need to encode
  296. $content = gzencode($content, self::$_options['encodeLevel']);
  297. }
  298. // add headers
  299. $headers['Content-Length'] = $cacheIsReady
  300. ? $cacheContentLength
  301. : ((function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
  302. ? mb_strlen($content, '8bit')
  303. : strlen($content)
  304. );
  305. $headers['Content-Type'] = self::$_options['contentTypeCharset']
  306. ? self::$_options['contentType'] . '; charset=' . self::$_options['contentTypeCharset']
  307. : self::$_options['contentType'];
  308. if (self::$_options['encodeMethod'] !== '') {
  309. $headers['Content-Encoding'] = $contentEncoding;
  310. }
  311. if (self::$_options['encodeOutput'] && $sendVary) {
  312. $headers['Vary'] = 'Accept-Encoding';
  313. }
  314. if (! self::$_options['quiet']) {
  315. // output headers & content
  316. foreach ($headers as $name => $val) {
  317. header($name . ': ' . $val);
  318. }
  319. if ($cacheIsReady) {
  320. self::$_cache->display($fullCacheId);
  321. } else {
  322. echo $content;
  323. }
  324. } else {
  325. return array(
  326. 'success' => true
  327. ,'statusCode' => 200
  328. ,'content' => $cacheIsReady
  329. ? self::$_cache->fetch($fullCacheId)
  330. : $content
  331. ,'headers' => $headers
  332. );
  333. }
  334. }
  335. /**
  336. * Return combined minified content for a set of sources
  337. *
  338. * No internal caching will be used and the content will not be HTTP encoded.
  339. *
  340. * @param array $sources array of filepaths and/or Minify_Source objects
  341. *
  342. * @param array $options (optional) array of options for serve. By default
  343. * these are already set: quiet = true, encodeMethod = '', lastModifiedTime = 0.
  344. *
  345. * @return string
  346. */
  347. public static function combine($sources, $options = array())
  348. {
  349. $cache = self::$_cache;
  350. self::$_cache = null;
  351. $options = array_merge(array(
  352. 'files' => (array)$sources
  353. ,'quiet' => true
  354. ,'encodeMethod' => ''
  355. ,'lastModifiedTime' => 0
  356. ), $options);
  357. $out = self::serve('Files', $options);
  358. self::$_cache = $cache;
  359. return $out['content'];
  360. }
  361. /**
  362. * Set $_SERVER['DOCUMENT_ROOT']. On IIS, the value is created from SCRIPT_FILENAME and SCRIPT_NAME.
  363. *
  364. * @param string $docRoot value to use for DOCUMENT_ROOT
  365. */
  366. public static function setDocRoot($docRoot = '')
  367. {
  368. self::$isDocRootSet = true;
  369. if ($docRoot) {
  370. $_SERVER['DOCUMENT_ROOT'] = $docRoot;
  371. } elseif (isset($_SERVER['SERVER_SOFTWARE'])
  372. && 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
  373. $_SERVER['DOCUMENT_ROOT'] = substr(
  374. $_SERVER['SCRIPT_FILENAME']
  375. ,0
  376. ,strlen($_SERVER['SCRIPT_FILENAME']) - strlen($_SERVER['SCRIPT_NAME']));
  377. $_SERVER['DOCUMENT_ROOT'] = rtrim($_SERVER['DOCUMENT_ROOT'], '\\');
  378. }
  379. }
  380. /**
  381. * Any Minify_Cache_* object or null (i.e. no server cache is used)
  382. *
  383. * @var Minify_Cache_File
  384. */
  385. private static $_cache = null;
  386. /**
  387. * Active controller for current request
  388. *
  389. * @var Minify_Controller_Base
  390. */
  391. protected static $_controller = null;
  392. /**
  393. * Options for current request
  394. *
  395. * @var array
  396. */
  397. protected static $_options = null;
  398. /**
  399. * @param string $header
  400. *
  401. * @param string $url
  402. */
  403. protected static function _errorExit($header, $url)
  404. {
  405. $url = htmlspecialchars($url, ENT_QUOTES);
  406. list(,$h1) = explode(' ', $header, 2);
  407. $h1 = htmlspecialchars($h1);
  408. // FastCGI environments require 3rd arg to header() to be set
  409. list(, $code) = explode(' ', $header, 3);
  410. header($header, true, $code);
  411. header('Content-Type: text/html; charset=utf-8');
  412. echo "<h1>$h1</h1>";
  413. echo "<p>Please see <a href='$url'>$url</a>.</p>";
  414. exit;
  415. }
  416. /**
  417. * Set up sources to use Minify_Lines
  418. *
  419. * @param Minify_Source[] $sources Minify_Source instances
  420. */
  421. protected static function _setupDebug($sources)
  422. {
  423. foreach ($sources as $source) {
  424. $source->minifier = array('Minify_Lines', 'minify');
  425. $id = $source->getId();
  426. $source->minifyOptions = array(
  427. 'id' => (is_file($id) ? basename($id) : $id)
  428. );
  429. }
  430. }
  431. /**
  432. * Combines sources and minifies the result.
  433. *
  434. * @return string
  435. *
  436. * @throws Exception
  437. */
  438. protected static function _combineMinify()
  439. {
  440. $type = self::$_options['contentType']; // ease readability
  441. // when combining scripts, make sure all statements separated and
  442. // trailing single line comment is terminated
  443. $implodeSeparator = ($type === self::TYPE_JS)
  444. ? "\n;"
  445. : '';
  446. // allow the user to pass a particular array of options to each
  447. // minifier (designated by type). source objects may still override
  448. // these
  449. $defaultOptions = isset(self::$_options['minifierOptions'][$type])
  450. ? self::$_options['minifierOptions'][$type]
  451. : array();
  452. // if minifier not set, default is no minification. source objects
  453. // may still override this
  454. $defaultMinifier = isset(self::$_options['minifiers'][$type])
  455. ? self::$_options['minifiers'][$type]
  456. : false;
  457. // process groups of sources with identical minifiers/options
  458. $content = array();
  459. $i = 0;
  460. $l = count(self::$_controller->sources);
  461. $groupToProcessTogether = array();
  462. $lastMinifier = null;
  463. $lastOptions = null;
  464. do {
  465. // get next source
  466. $source = null;
  467. if ($i < $l) {
  468. $source = self::$_controller->sources[$i];
  469. /* @var Minify_Source $source */
  470. $sourceContent = $source->getContent();
  471. // allow the source to override our minifier and options
  472. $minifier = (null !== $source->minifier)
  473. ? $source->minifier
  474. : $defaultMinifier;
  475. $options = (null !== $source->minifyOptions)
  476. ? array_merge($defaultOptions, $source->minifyOptions)
  477. : $defaultOptions;
  478. }
  479. // do we need to process our group right now?
  480. if ($i > 0 // yes, we have at least the first group populated
  481. && (
  482. ! $source // yes, we ran out of sources
  483. || $type === self::TYPE_CSS // yes, to process CSS individually (avoiding PCRE bugs/limits)
  484. || $minifier !== $lastMinifier // yes, minifier changed
  485. || $options !== $lastOptions) // yes, options changed
  486. )
  487. {
  488. // minify previous sources with last settings
  489. $imploded = implode($implodeSeparator, $groupToProcessTogether);
  490. $groupToProcessTogether = array();
  491. if ($lastMinifier) {
  492. try {
  493. $content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
  494. } catch (Exception $e) {
  495. throw new Exception("Exception in minifier: " . $e->getMessage());
  496. }
  497. } else {
  498. $content[] = $imploded;
  499. }
  500. }
  501. // add content to the group
  502. if ($source) {
  503. $groupToProcessTogether[] = $sourceContent;
  504. $lastMinifier = $minifier;
  505. $lastOptions = $options;
  506. }
  507. $i++;
  508. } while ($source);
  509. $content = implode($implodeSeparator, $content);
  510. if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
  511. $content = self::_handleCssImports($content);
  512. }
  513. // do any post-processing (esp. for editing build URIs)
  514. if (self::$_options['postprocessorRequire']) {
  515. require_once self::$_options['postprocessorRequire'];
  516. }
  517. if (self::$_options['postprocessor']) {
  518. $content = call_user_func(self::$_options['postprocessor'], $content, $type);
  519. }
  520. return $content;
  521. }
  522. /**
  523. * Make a unique cache id for for this request.
  524. *
  525. * Any settings that could affect output are taken into consideration
  526. *
  527. * @param string $prefix
  528. *
  529. * @return string
  530. */
  531. protected static function _getCacheId($prefix = 'minify')
  532. {
  533. $name = preg_replace('/[^a-zA-Z0-9\\.=_,]/', '', self::$_controller->selectionId);
  534. $name = preg_replace('/\\.+/', '.', $name);
  535. $name = substr($name, 0, 100 - 34 - strlen($prefix));
  536. $md5 = md5(serialize(array(
  537. Minify_Source::getDigest(self::$_controller->sources)
  538. ,self::$_options['minifiers']
  539. ,self::$_options['minifierOptions']
  540. ,self::$_options['postprocessor']
  541. ,self::$_options['bubbleCssImports']
  542. ,self::VERSION
  543. )));
  544. return "{$prefix}_{$name}_{$md5}";
  545. }
  546. /**
  547. * Bubble CSS @imports to the top or prepend a warning if an import is detected not at the top.
  548. *
  549. * @param string $css
  550. *
  551. * @return string
  552. */
  553. protected static function _handleCssImports($css)
  554. {
  555. if (self::$_options['bubbleCssImports']) {
  556. // bubble CSS imports
  557. preg_match_all('/@import.*?;/', $css, $imports);
  558. $css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
  559. } else if ('' !== self::$importWarning) {
  560. // remove comments so we don't mistake { in a comment as a block
  561. $noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
  562. $lastImportPos = strrpos($noCommentCss, '@import');
  563. $firstBlockPos = strpos($noCommentCss, '{');
  564. if (false !== $lastImportPos
  565. && false !== $firstBlockPos
  566. && $firstBlockPos < $lastImportPos
  567. ) {
  568. // { appears before @import : prepend warning
  569. $css = self::$importWarning . $css;
  570. }
  571. }
  572. return $css;
  573. }
  574. }