Minify.php 23 KB

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