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