/** * @see Minify_Controller_Base::loadMinifier() */ public function loadMinifier($minifierCallback) { if ($this->_loadCssJsMinifiers) { // Minify will not call for these so we must manually load // them when Minify/HTML.php is called for. } parent::loadMinifier($minifierCallback); // load Minify/HTML.php }
/** * @see Minify_Controller_Base::loadMinifier() */ public function loadMinifier($minifierCallback) { if ($this->_loadCssJsMinifiers) { // Minify will not call for these so we must manually load // them when Minify/HTML.php is called for. require_once W3TC_LIB_MINIFY_DIR . '/Minify/CSS.php'; require_once W3TC_LIB_MINIFY_DIR . '/JSMin.php'; } parent::loadMinifier($minifierCallback); // load Minify/HTML.php }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * @return array Minify options * */ public function setupSources($options) { // PHP insecure by default: realpath() and other FS functions can't handle null bytes. if (isset($_GET['files'])) { $_GET['files'] = str_replace("", '', (string) $_GET['files']); } self::_setupDefines(); if (MINIFY_USE_CACHE) { $cacheDir = defined('MINIFY_CACHE_DIR') ? MINIFY_CACHE_DIR : ''; Minify::setCache($cacheDir); } $options['badRequestHeader'] = 'HTTP/1.0 404 Not Found'; $options['contentTypeCharset'] = MINIFY_ENCODING; // The following restrictions are to limit the URLs that minify will // respond to. Ideally there should be only one way to reference a file. if (!isset($_GET['files']) || !preg_match('/^[^,]+\\.(css|js)(,[^,]+\\.\\1)*$/', $_GET['files'], $m) || strpos($_GET['files'], '//') !== false || strpos($_GET['files'], '\\') !== false || preg_match('/(?:^|[^\\.])\\.\\//', $_GET['files'])) { return $options; } $extension = $m[1]; $files = explode(',', $_GET['files']); if (count($files) > MINIFY_MAX_FILES) { return $options; } // strings for prepending to relative/absolute paths $prependRelPaths = dirname($_SERVER['SCRIPT_FILENAME']) . DIRECTORY_SEPARATOR; $prependAbsPaths = $_SERVER['DOCUMENT_ROOT']; $sources = array(); $goodFiles = array(); $hasBadSource = false; $allowDirs = isset($options['allowDirs']) ? $options['allowDirs'] : MINIFY_BASE_DIR; foreach ($files as $file) { // prepend appropriate string for abs/rel paths $file = ($file[0] === '/' ? $prependAbsPaths : $prependRelPaths) . $file; // make sure a real file! $file = realpath($file); // don't allow unsafe or duplicate files if (parent::_fileIsSafe($file, $allowDirs) && !in_array($file, $goodFiles)) { $goodFiles[] = $file; $srcOptions = array('filepath' => $file); $this->sources[] = new Minify_Source($srcOptions); } else { $hasBadSource = true; break; } } if ($hasBadSource) { $this->sources = array(); } if (!MINIFY_REWRITE_CSS_URLS) { $options['rewriteCssUris'] = false; } return $options; }
/** * Combines sources and minifies the result. * * @return string */ protected static function _combineMinify() { $type = self::$_options['contentType']; // ease readability // when combining scripts, make sure all statements separated and // trailing single line comment is terminated $implodeSeparator = $type === self::TYPE_JS ? "\n;" : ''; // allow the user to pass a particular array of options to each // minifier (designated by type). source objects may still override // these $defaultOptions = isset(self::$_options['minifierOptions'][$type]) ? self::$_options['minifierOptions'][$type] : array(); // if minifier not set, default is no minification. source objects // may still override this $defaultMinifier = isset(self::$_options['minifiers'][$type]) ? self::$_options['minifiers'][$type] : false; // process groups of sources with identical minifiers/options $content = array(); $i = 0; $l = count(self::$_controller->sources); $groupToProcessTogether = array(); $lastMinifier = null; $lastOptions = null; do { // get next source $source = null; if ($i < $l) { $source = self::$_controller->sources[$i]; /* @var Minify_Source $source */ $sourceContent = $source->getContent(); // allow the source to override our minifier and options $minifier = null !== $source->minifier ? $source->minifier : $defaultMinifier; $options = null !== $source->minifyOptions ? array_merge($defaultOptions, $source->minifyOptions) : $defaultOptions; } // do we need to process our group right now? if ($i > 0 && (!$source || $type === self::TYPE_CSS || $minifier !== $lastMinifier || $options !== $lastOptions)) { // minify previous sources with last settings $imploded = implode($implodeSeparator, $groupToProcessTogether); $groupToProcessTogether = array(); if ($lastMinifier) { self::$_controller->loadMinifier($lastMinifier); try { $content[] = call_user_func($lastMinifier, $imploded, $lastOptions); } catch (Exception $e) { throw new Exception("Exception in minifier: " . $e->getMessage()); } } else { $content[] = $imploded; } } // add content to the group if ($source) { $groupToProcessTogether[] = $sourceContent; $lastMinifier = $minifier; $lastOptions = $options; } $i++; } while ($source); $content = implode($implodeSeparator, $content); if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) { $content = self::_handleCssImports($content); } // do any post-processing (esp. for editing build URIs) if (self::$_options['postprocessorRequire']) { require_once self::$_options['postprocessorRequire']; } if (self::$_options['postprocessor']) { $content = call_user_func(self::$_options['postprocessor'], $content, $type); } return $content; }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * @return array Minify options * */ public function setupSources($options) { // filter controller options $cOptions = array_merge(array('allowDirs' => '//', 'groupsOnly' => false, 'groups' => array(), 'maxFiles' => 100), isset($options['minApp']) ? $options['minApp'] : array()); unset($options['minApp']); $sources = array(); if (isset($_GET['g'])) { // try groups if (!isset($cOptions['groups'][$_GET['g']])) { $this->log("A group configuration for \"{$_GET['g']}\" was not set"); return $options; } $files = $cOptions['groups'][$_GET['g']]; // if $files is a single object, casting will break it if (is_object($files)) { $files = array($files); } elseif (!is_array($files)) { $files = (array) $files; } foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } if (0 === strpos($file, '//')) { $file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1); } $realPath = realpath($file); if (is_file($realPath)) { $sources[] = new Minify_Source(array('filepath' => $realPath)); } else { $this->log("The path \"{$realPath}\" could not be found (or was not a file)"); continue; } } } elseif (!$cOptions['groupsOnly'] && isset($_GET['f'])) { $config = w3_instance('W3_Config'); $external = $config->get_array('minify.cache.files'); $files = $_GET['f']; $temp_files = array(); $external_files = 0; foreach ($files as $file) { if (!is_string($file)) { $url = $file->minifyOptions['prependRelativePath']; $verified = false; foreach ($external as $ext) { if (preg_match('#' . w3_get_url_regexp($ext) . '#', $url) && !$verified) { $verified = true; } } if (!$verified) { $this->log("GET['f'] param part invalid, not in accepted external files list: \"{$url}\""); return $options; } $external_files++; } else { $temp_files[] = $file; } } if ($temp_files) { $imploded = implode(',', $temp_files); if (!preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $imploded) || strpos($imploded, '//') !== false || strpos($imploded, '\\') !== false || preg_match('/(?:^|[^\\.])\\.\\//', $imploded)) { $this->log("GET['f'] param part invalid: \"{$imploded}\""); return $options; } } if (count($files) > $cOptions['maxFiles'] || count($files) - $external_files != count(array_unique($temp_files))) { $this->log("Too many or duplicate files specified: \"" . implode(', ', $temp_files) . "\""); return $options; } if (!empty($_GET['b'])) { // check for validity if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b']) && false === strpos($_GET['b'], '..') && $_GET['b'] !== '.') { // valid base $base = "/{$_GET['b']}/"; } else { $this->log("GET['b'] param invalid: \"{$_GET['b']}\""); return $options; } } else { $base = '/'; } $allowDirs = array(); foreach ((array) $cOptions['allowDirs'] as $allowDir) { $allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir)); } foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } $path = $_SERVER['DOCUMENT_ROOT'] . $base . $file; $file = realpath($path); if (false === $file) { $this->log("Path \"{$path}\" failed realpath()"); return $options; } elseif (!parent::_fileIsSafe($file, $allowDirs)) { $this->log("Path \"{$path}\" failed Minify_Controller_Base::_fileIsSafe()"); return $options; } else { $sources[] = new Minify_Source(array('filepath' => $file)); } } } if ($sources) { $this->sources = $sources; } else { $this->log("No sources to serve"); } return $options; }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * @return array Minify options * */ public function setupSources($options) { // filter controller options $cOptions = array_merge(array('allowDirs' => '//', 'groupsOnly' => false, 'groups' => array(), 'noMinPattern' => '@[-\\.]min\\.(?:js|css)$@i'), isset($options['minApp']) ? $options['minApp'] : array()); unset($options['minApp']); $sources = array(); $this->selectionId = ''; $firstMissingResource = null; if (isset($_GET['g'])) { // add group(s) $this->selectionId .= 'g=' . $_GET['g']; $keys = explode(',', $_GET['g']); if ($keys != array_unique($keys)) { $this->log("Duplicate group key found."); return $options; } $keys = explode(',', $_GET['g']); foreach ($keys as $key) { if (!isset($cOptions['groups'][$key])) { $this->log("A group configuration for \"{$key}\" was not found"); return $options; } $files = $cOptions['groups'][$key]; // if $files is a single object, casting will break it if (is_object($files)) { $files = array($files); } elseif (!is_array($files)) { $files = (array) $files; } foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } if (0 === strpos($file, '//')) { $file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1); } $realpath = realpath($file); if ($realpath && is_file($realpath)) { $sources[] = $this->_getFileSource($realpath, $cOptions); } else { $this->log("The path \"{$file}\" (realpath \"{$realpath}\") could not be found (or was not a file)"); if (null === $firstMissingResource) { $firstMissingResource = basename($file); continue; } else { $secondMissingResource = basename($file); $this->log("More than one file was missing: '{$firstMissingResource}', '{$secondMissingResource}'"); return $options; } } } if ($sources) { try { $this->checkType($sources[0]); } catch (Exception $e) { $this->log($e->getMessage()); return $options; } } } } if (!$cOptions['groupsOnly'] && isset($_GET['f'])) { // try user files // The following restrictions are to limit the URLs that minify will // respond to. if (!preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $_GET['f'], $m) || strpos($_GET['f'], '//') !== false || strpos($_GET['f'], '\\') !== false) { $this->log("GET param 'f' was invalid"); return $options; } $ext = ".{$m[1]}"; try { $this->checkType($m[1]); } catch (Exception $e) { $this->log($e->getMessage()); return $options; } $files = explode(',', $_GET['f']); if ($files != array_unique($files)) { $this->log("Duplicate files were specified"); return $options; } if (isset($_GET['b'])) { // check for validity if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b']) && false === strpos($_GET['b'], '..') && $_GET['b'] !== '.') { // valid base $base = "/{$_GET['b']}/"; } else { $this->log("GET param 'b' was invalid"); return $options; } } else { $base = '/'; } $allowDirs = array(); foreach ((array) $cOptions['allowDirs'] as $allowDir) { $allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir)); } $basenames = array(); // just for cache id foreach ($files as $file) { $uri = $base . $file; $path = $_SERVER['DOCUMENT_ROOT'] . $uri; $realpath = realpath($path); if (false === $realpath || !is_file($realpath)) { $this->log("The path \"{$path}\" (realpath \"{$realpath}\") could not be found (or was not a file)"); if (null === $firstMissingResource) { $firstMissingResource = $uri; continue; } else { $secondMissingResource = $uri; $this->log("More than one file was missing: '{$firstMissingResource}', '{$secondMissingResource}`'"); return $options; } } try { parent::checkNotHidden($realpath); parent::checkAllowDirs($realpath, $allowDirs, $uri); } catch (Exception $e) { $this->log($e->getMessage()); return $options; } $sources[] = $this->_getFileSource($realpath, $cOptions); $basenames[] = basename($realpath, $ext); } if ($this->selectionId) { $this->selectionId .= '_f='; } $this->selectionId .= implode(',', $basenames) . $ext; } if ($sources) { if (null !== $firstMissingResource) { array_unshift($sources, new Minify_Source(array('id' => 'missingFile', 'lastModified' => 0, 'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n", 'minifier' => ''))); } $this->sources = $sources; } else { $this->log("No sources to serve"); } return $options; }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * @return array Minify options * */ public function setupSources($options) { // filter controller options $cOptions = array_merge(array('allowDirs' => '//', 'groupsOnly' => false, 'groups' => array(), 'maxFiles' => 10), isset($options['minApp']) ? $options['minApp'] : array()); unset($options['minApp']); $sources = array(); if (isset($_GET['g'])) { // try groups if (!isset($cOptions['groups'][$_GET['g']])) { $this->log("A group configuration for \"{$_GET['g']}\" was not set"); return $options; } $files = $cOptions['groups'][$_GET['g']]; // if $files is a single object, casting will break it if (is_object($files)) { $files = array($files); } elseif (!is_array($files)) { $files = (array) $files; } foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } if (0 === strpos($file, '//')) { $file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1); } $realPath = realpath($file); if (is_file($realPath)) { $sources[] = new Minify_Source(array('filepath' => $realPath)); } else { $this->log("The path \"{$realPath}\" could not be found (or was not a file)"); continue; } } } elseif (!$cOptions['groupsOnly'] && isset($_GET['f'])) { // try user files // The following restrictions are to limit the URLs that minify will // respond to. Ideally there should be only one way to reference a file. if (!preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $_GET['f']) || strpos($_GET['f'], '//') !== false || strpos($_GET['f'], '\\') !== false || preg_match('/(?:^|[^\\.])\\.\\//', $_GET['f'])) { $this->log("GET['f'] param invalid: \"{$_GET['f']}\""); return $options; } $files = explode(',', $_GET['f']); if (count($files) > $cOptions['maxFiles'] || $files != array_unique($files)) { $this->log("Too many or duplicate files specified: \"" . implode(', ', $files) . "\""); return $options; } if (!empty($_GET['b'])) { // check for validity if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b']) && false === strpos($_GET['b'], '..') && $_GET['b'] !== '.') { // valid base $base = "/{$_GET['b']}/"; } else { $this->log("GET['b'] param invalid: \"{$_GET['b']}\""); return $options; } } else { $base = '/'; } $allowDirs = array(); foreach ((array) $cOptions['allowDirs'] as $allowDir) { $allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir)); } foreach ($files as $file) { $path = $_SERVER['DOCUMENT_ROOT'] . $base . $file; $file = realpath($path); if (false === $file) { $this->log("Path \"{$path}\" failed realpath()"); return $options; } elseif (!parent::_fileIsSafe($file, $allowDirs)) { $this->log("Path \"{$path}\" failed Minify_Controller_Base::_fileIsSafe()"); return $options; } else { $sources[] = new Minify_Source(array('filepath' => $file)); } } } if ($sources) { $this->sources = $sources; } else { $this->log("No sources to serve"); } return $options; }
/** * @param Minify_Env $env Environment * @param Minify_Source_Factory $sourceFactory Source factory. If you need to serve files from any path, this * component must have its "checkAllowDirs" option set to false. */ public function __construct(Minify_Env $env, Minify_Source_Factory $sourceFactory) { parent::__construct($env, $sourceFactory); }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * * @return array Minify options */ public function setupSources($options) { // PHP insecure by default: realpath() and other FS functions can't handle null bytes. foreach (array('g', 'b', 'f') as $key) { if (isset($_GET[$key])) { $_GET[$key] = str_replace("", '', (string) $_GET[$key]); } } // filter controller options $cOptions = array_merge(array('allowDirs' => '//', 'groupsOnly' => false, 'groups' => array(), 'noMinPattern' => '@[-\\.]min\\.(?:js|css)$@i'), isset($options['minApp']) ? $options['minApp'] : array()); unset($options['minApp']); $sources = array(); $this->selectionId = ''; $firstMissingResource = null; if (isset($_GET['g'])) { // add group(s) $this->selectionId .= 'g=' . $_GET['g']; $keys = explode(',', $_GET['g']); if ($keys != array_unique($keys)) { $this->log("Duplicate group key found."); return $options; } $keys = explode(',', $_GET['g']); foreach ($keys as $key) { if (!isset($cOptions['groups'][$key])) { $this->log("A group configuration for \"{$key}\" was not found"); return $options; } $files = $cOptions['groups'][$key]; // if $files is a single object, casting will break it if (is_object($files)) { $files = array($files); } elseif (!is_array($files)) { $files = (array) $files; } foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } if (0 === strpos($file, '//')) { $file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1); } $realpath = \W3TC\Util_Environment::realpath($file); if ($realpath && is_file($realpath)) { $sources[] = $this->_getFileSource($realpath, $cOptions); } else { $this->log("The path \"{$file}\" (realpath \"{$realpath}\") could not be found (or was not a file)"); if (null === $firstMissingResource) { $firstMissingResource = basename($file); continue; } else { $secondMissingResource = basename($file); $this->log("More than one file was missing: '{$firstMissingResource}', '{$secondMissingResource}'"); return $options; } } } if ($sources) { try { $this->checkType($sources[0]); } catch (Exception $e) { $this->log($e->getMessage()); return $options; } } } } if (!$cOptions['groupsOnly'] && isset($_GET['f_array'])) { $files = $_GET['f_array']; $ext = $_GET['ext']; if (!empty($_GET['b'])) { // check for validity if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b']) && false === strpos($_GET['b'], '..') && $_GET['b'] !== '.') { // valid base $base = "/{$_GET['b']}/"; } else { $this->log("GET param 'b' invalid (see MinApp.php line 84)"); return $options; } } else { $base = '/'; } $allowDirs = array(); foreach ((array) $cOptions['allowDirs'] as $allowDir) { $allowDirs[] = \W3TC\Util_Environment::realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir)); } $basenames = array(); // just for cache id foreach ($files as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } $uri = $base . $file; $path = $_SERVER['DOCUMENT_ROOT'] . $uri; $realpath = \W3TC\Util_Environment::realpath($path); if (false === $realpath || !is_file($realpath)) { $this->log("The path \"{$path}\" (realpath \"{$realpath}\") could not be found (or was not a file)"); if (null === $firstMissingResource) { $firstMissingResource = $uri; continue; } else { $secondMissingResource = $uri; $this->log("More than one file was missing: '{$firstMissingResource}', '{$secondMissingResource}`'"); return $options; } } try { parent::checkNotHidden($realpath); parent::checkAllowDirs($realpath, $allowDirs, $uri); } catch (Exception $e) { $this->log($e->getMessage()); return $options; } $sources[] = $this->_getFileSource($realpath, $cOptions); $basenames[] = basename($realpath, $ext); } if ($this->selectionId) { $this->selectionId .= '_f='; } $this->selectionId .= implode(',', $basenames) . $ext; } if ($sources) { if (null !== $firstMissingResource) { array_unshift($sources, new Minify_Source(array('id' => 'missingFile', 'lastModified' => 0, 'content' => "/* Minify: at least one missing file. See " . Minify0_Minify::URL_DEBUG . " */\n", 'minifier' => ''))); } $this->sources = $sources; } else { $this->log("No sources to serve"); } return $options; }
/** * Serve a request for a minified file. * * Here are the available options and defaults: * * 'isPublic' : send "public" instead of "private" in Cache-Control * headers, allowing shared caches to cache the output. (default true) * * 'quiet' : set to true to have serve() return an array rather than sending * any headers/output (default false) * * 'encodeOutput' : set to false to disable content encoding, and not send * the Vary header (default true) * * 'encodeMethod' : generally you should let this be determined by * HTTP_Encoder (leave null), but you can force a particular encoding * to be returned, by setting this to 'gzip' or '' (no encoding) * * 'encodeLevel' : level of encoding compression (0 to 9, default 9) * * 'contentTypeCharset' : appended to the Content-Type header sent. Set to a falsey * value to remove. (default 'utf-8') * * 'maxAge' : set this to the number of seconds the client should use its cache * before revalidating with the server. This sets Cache-Control: max-age and the * Expires header. Unlike the old 'setExpires' setting, this setting will NOT * prevent conditional GETs. Note this has nothing to do with server-side caching. * * 'rewriteCssUris' : If true, serve() will automatically set the 'currentDir' * minifier option to enable URI rewriting in CSS files (default true) * * 'bubbleCssImports' : If true, all @import declarations in combined CSS * files will be move to the top. Note this may alter effective CSS values * due to a change in order. (default false) * * 'debug' : set to true to minify all sources with the 'Lines' controller, which * eases the debugging of combined files. This also prevents 304 responses. * @see Minify_Lines::minify() * * 'concatOnly' : set to true to disable minification and simply concatenate the files. * For JS, no minifier will be used. For CSS, only URI rewriting is still performed. * * 'minifiers' : to override Minify's default choice of minifier function for * a particular content-type, specify your callback under the key of the * content-type: * <code> * // call customCssMinifier($css) for all CSS minification * $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier'; * * // don't minify Javascript at all * $options['minifiers'][Minify::TYPE_JS] = ''; * </code> * * 'minifierOptions' : to send options to the minifier function, specify your options * under the key of the content-type. E.g. To send the CSS minifier an option: * <code> * // give CSS minifier array('optionName' => 'optionValue') as 2nd argument * $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue'; * </code> * * 'contentType' : (optional) this is only needed if your file extension is not * js/css/html. The given content-type will be sent regardless of source file * extension, so this should not be used in a Groups config with other * Javascript/CSS files. * * 'importWarning' : serve() will check CSS files for @import declarations that * appear too late in the combined stylesheet. If found, serve() will prepend * the output with this warning. To disable this, set this option to empty string. * * Any controller options are documented in that controller's createConfiguration() method. * * @param Minify_ControllerInterface $controller instance of subclass of Minify_Controller_Base * * @param array $options controller/serve options * * @return null|array if the 'quiet' option is set to true, an array * with keys "success" (bool), "statusCode" (int), "content" (string), and * "headers" (array). * * @throws Exception */ public function serve(Minify_ControllerInterface $controller, $options = array()) { $options = array_merge($this->getDefaultOptions(), $options); $config = $controller->createConfiguration($options); $this->sources = $config->getSources(); $this->selectionId = $config->getSelectionId(); $this->options = $this->analyzeSources($config->getOptions()); // check request validity if (!$this->sources) { // invalid request! if (!$this->options['quiet']) { $this->errorExit($this->options['badRequestHeader'], self::URL_DEBUG); } else { list(, $statusCode) = explode(' ', $this->options['badRequestHeader']); return array('success' => false, 'statusCode' => (int) $statusCode, 'content' => '', 'headers' => array()); } } $this->controller = $controller; if ($this->options['debug']) { $this->setupDebug(); $this->options['maxAge'] = 0; } // determine encoding if ($this->options['encodeOutput']) { $sendVary = true; if ($this->options['encodeMethod'] !== null) { // controller specifically requested this $contentEncoding = $this->options['encodeMethod']; } else { // sniff request header // depending on what the client accepts, $contentEncoding may be // 'x-gzip' while our internal encodeMethod is 'gzip'. Calling // getAcceptedEncoding(false, false) leaves out compress and deflate as options. list($this->options['encodeMethod'], $contentEncoding) = HTTP_Encoder::getAcceptedEncoding(false, false); $sendVary = !HTTP_Encoder::isBuggyIe(); } } else { $this->options['encodeMethod'] = ''; // identity (no encoding) } // check client cache $cgOptions = array('lastModifiedTime' => $this->options['lastModifiedTime'], 'isPublic' => $this->options['isPublic'], 'encoding' => $this->options['encodeMethod']); if ($this->options['maxAge'] > 0) { $cgOptions['maxAge'] = $this->options['maxAge']; } elseif ($this->options['debug']) { $cgOptions['invalidate'] = true; } $cg = new HTTP_ConditionalGet($cgOptions); if ($cg->cacheIsValid) { // client's cache is valid if (!$this->options['quiet']) { $cg->sendHeaders(); return; } else { return array('success' => true, 'statusCode' => 304, 'content' => '', 'headers' => $cg->getHeaders()); } } else { // client will need output $headers = $cg->getHeaders(); unset($cg); } if ($this->options['contentType'] === self::TYPE_CSS && $this->options['rewriteCssUris']) { $this->setupUriRewrites(); } if ($this->options['concatOnly']) { $this->options['minifiers'][self::TYPE_JS] = false; foreach ($this->sources as $key => $source) { if ($this->options['contentType'] === self::TYPE_JS) { $source->setMinifier(""); } elseif ($this->options['contentType'] === self::TYPE_CSS) { $source->setMinifier(array('Minify_CSSmin', 'minify')); $sourceOpts = $source->getMinifierOptions(); $sourceOpts['compress'] = false; $source->setMinifierOptions($sourceOpts); } } } // check server cache if (!$this->options['debug']) { // using cache // the goal is to use only the cache methods to sniff the length and // output the content, as they do not require ever loading the file into // memory. $cacheId = $this->_getCacheId(); $fullCacheId = $this->options['encodeMethod'] ? $cacheId . '.gz' : $cacheId; // check cache for valid entry $cacheIsReady = $this->cache->isValid($fullCacheId, $this->options['lastModifiedTime']); if ($cacheIsReady) { $cacheContentLength = $this->cache->getSize($fullCacheId); } else { // generate & cache content try { $content = $this->combineMinify(); } catch (Exception $e) { $this->controller->log($e->getMessage()); if (!$this->options['quiet']) { $this->errorExit($this->options['errorHeader'], self::URL_DEBUG); } throw $e; } $this->cache->store($cacheId, $content); if (function_exists('gzencode') && $this->options['encodeMethod']) { $this->cache->store($cacheId . '.gz', gzencode($content, $this->options['encodeLevel'])); } } } else { // no cache $cacheIsReady = false; try { $content = $this->combineMinify(); } catch (Exception $e) { $this->controller->log($e->getMessage()); if (!$this->options['quiet']) { $this->errorExit($this->options['errorHeader'], self::URL_DEBUG); } throw $e; } } if (!$cacheIsReady && $this->options['encodeMethod']) { // still need to encode $content = gzencode($content, $this->options['encodeLevel']); } // add headers if ($cacheIsReady) { $headers['Content-Length'] = $cacheContentLength; } else { if (function_exists('mb_strlen') && (int) ini_get('mbstring.func_overload') & 2) { $headers['Content-Length'] = mb_strlen($content, '8bit'); } else { $headers['Content-Length'] = strlen($content); } } $headers['Content-Type'] = $this->options['contentType']; if ($this->options['contentTypeCharset']) { $headers['Content-Type'] .= '; charset=' . $this->options['contentTypeCharset']; } if ($this->options['encodeMethod'] !== '') { $headers['Content-Encoding'] = $contentEncoding; } if ($this->options['encodeOutput'] && $sendVary) { $headers['Vary'] = 'Accept-Encoding'; } if (!$this->options['quiet']) { // output headers & content foreach ($headers as $name => $val) { header($name . ': ' . $val); } if ($cacheIsReady) { $this->cache->display($fullCacheId); } else { echo $content; } } else { return array('success' => true, 'statusCode' => 200, 'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content, 'headers' => $headers); } }
/** * Set up groups of files as sources * * @param array $options controller and Minify options * @return array Minify options * */ public function setupSources($options) { // filter controller options $cOptions = array_merge(array('allowDirs' => '//', 'groupsOnly' => false, 'groups' => array(), 'maxFiles' => 10), isset($options['minApp']) ? $options['minApp'] : array()); unset($options['minApp']); $sources = array(); if (isset($_GET['g'])) { // try groups if (!isset($cOptions['groups'][$_GET['g']])) { return $options; } foreach ((array) $cOptions['groups'][$_GET['g']] as $file) { if ($file instanceof Minify_Source) { $sources[] = $file; continue; } if (0 === strpos($file, '//')) { $file = $_SERVER['DOCUMENT_ROOT'] . substr($file, 1); } $file = realpath($file); if (is_file($file)) { $sources[] = new Minify_Source(array('filepath' => $file)); } else { // file doesn't exist return $options; } } } elseif (!$cOptions['groupsOnly'] && isset($_GET['f'])) { // try user files // The following restrictions are to limit the URLs that minify will // respond to. Ideally there should be only one way to reference a file. if (!preg_match('/^[^,]+\\.(css|js)(?:,[^,]+\\.\\1)*$/', $_GET['f']) || strpos($_GET['f'], '//') !== false || strpos($_GET['f'], '\\') !== false || preg_match('/(?:^|[^\\.])\\.\\//', $_GET['f'])) { return $options; } $files = explode(',', $_GET['f']); if (count($files) > $cOptions['maxFiles'] || $files != array_unique($files)) { // too many or duplicate files return $options; } if (isset($_GET['b'])) { // check for validity if (preg_match('@^[^/]+(?:/[^/]+)*$@', $_GET['b']) && false === strpos($_GET['b'], '..') && $_GET['b'] !== '.') { // valid base $base = "/{$_GET['b']}/"; } else { return $options; } } else { $base = '/'; } $allowDirs = array(); foreach ((array) $cOptions['allowDirs'] as $allowDir) { $allowDirs[] = realpath(str_replace('//', $_SERVER['DOCUMENT_ROOT'] . '/', $allowDir)); } foreach ($files as $file) { $file = realpath($_SERVER['DOCUMENT_ROOT'] . $base . $file); // don't allow unsafe or duplicate files if (parent::_fileIsSafe($file, $allowDirs)) { $sources[] = new Minify_Source(array('filepath' => $file)); } else { // unsafe file return $options; } } } if ($sources) { $this->sources = $sources; } return $options; }