MODX Revolution PHP Cross Reference Content Management Systems

Source: /manager/min/lib/Minify.php - 581 lines - 22646 bytes - Summary - Text - Print

Description: Class Minify

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

title

Description

title

Description

title

Description

title

title

Body