1
0
mirror of https://github.com/mrclay/minify.git synced 2025-08-13 17:44:00 +02:00

resolveFilePath() now supports absolute local URLs (e.g. 'http://example.com/foo/bar.js')

This commit is contained in:
Ryan Grove
2007-05-02 00:45:17 +00:00
parent 7dffc6c0bd
commit 419fc72417

View File

@@ -1,6 +1,6 @@
<?php <?php
/** /**
* minify.php - On the fly JavaScript/CSS minifier. * Minify - Combines, minifies, and caches JavaScript and CSS files on demand.
* *
* This library was inspired by jscsscomp by Maxim Martynyuk <flashkot@mail.ru> * This library was inspired by jscsscomp by Maxim Martynyuk <flashkot@mail.ru>
* and by the article "Supercharged JavaScript" by Patrick Hunlock * and by the article "Supercharged JavaScript" by Patrick Hunlock
@@ -12,12 +12,12 @@
* *
* Requires PHP 5.2.1+. * Requires PHP 5.2.1+.
* *
* See http://wonko.com/software/minify/ for news and updates. * @package Minify
*
* @author Ryan Grove <ryan@wonko.com> * @author Ryan Grove <ryan@wonko.com>
* @copyright Copyright (c) 2007 Ryan Grove. All rights reserved. * @copyright 2007 Ryan Grove. All rights reserved.
* @license http://opensource.org/licenses/bsd-license.php New BSD License * @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version 1.0.0 (?) * @version 1.0.0 (2007-05-01)
* @link http://code.google.com/p/minify/
*/ */
if (!defined('MINIFY_BASE_DIR')) { if (!defined('MINIFY_BASE_DIR')) {
@@ -43,16 +43,33 @@ if (!defined('MINIFY_MAX_FILES')) {
define('MINIFY_MAX_FILES', 16); define('MINIFY_MAX_FILES', 16);
} }
/**
* Minify is a library for combining, minifying, and caching JavaScript and CSS
* files on demand before sending them to a web browser.
*
* @package Minify
* @author Ryan Grove <ryan@wonko.com>
* @copyright 2007 Ryan Grove. All rights reserved.
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version 1.0.0 (2007-05-01)
* @link http://code.google.com/p/minify/
*/
class Minify { class Minify {
const TYPE_CSS = 'text/css'; const TYPE_CSS = 'text/css';
const TYPE_JS = 'text/javascript'; const TYPE_JS = 'text/javascript';
private $files = array(); protected $files = array();
private $type = TYPE_JS; protected $type = TYPE_JS;
private $useCache = true; protected $useCache = true;
// -- Public Static Methods -------------------------------------------------- // -- Public Static Methods --------------------------------------------------
/**
* Combines, minifies, and outputs the requested files.
*
* Inspects the $_GET array for a 'files' entry containing a comma-separated
* list and uses this as the set of files to be combined and minified.
*/
public static function handleRequest() { public static function handleRequest() {
// 404 if no files were requested. // 404 if no files were requested.
if (!isset($_GET['files'])) { if (!isset($_GET['files'])) {
@@ -89,14 +106,30 @@ class Minify {
} }
} }
/**
* Minifies the specified string and returns it.
*
* @param string $string JavaScript or CSS string to minify
* @param string $type content type of the string (either Minify::TYPE_CSS or
* Minify::TYPE_JS)
* @return string minified string
*/
public static function minify($string, $type = self::TYPE_JS) { public static function minify($string, $type = self::TYPE_JS) {
return $type === self::TYPE_JS ? self::jsMinify($string) : return $type === self::TYPE_JS ? self::minifyJS($string) :
self::cssMinify($string); self::minifyCSS($string);
} }
// -- Private Static Methods ------------------------------------------------- // -- Protected Static Methods -----------------------------------------------
private static function cssMinify($string) { /**
* Minifies the specified CSS string and returns it.
*
* @param string $string CSS string
* @return string minified string
* @see minify()
* @see minifyJS()
*/
protected static function minifyCSS($string) {
// Compress whitespace. // Compress whitespace.
$string = preg_replace('/\s+/', ' ', $string); $string = preg_replace('/\s+/', ' ', $string);
@@ -106,7 +139,15 @@ class Minify {
return trim($string); return trim($string);
} }
private static function jsMinify($string) { /**
* Minifies the specified JavaScript string and returns it.
*
* @param string $string JavaScript string
* @return string minified string
* @see minify()
* @see minifyCSS()
*/
protected static function minifyJS($string) {
define('JSMIN_AS_LIB', true); define('JSMIN_AS_LIB', true);
require_once dirname(__FILE__).'/lib/JSMin_lib.php'; require_once dirname(__FILE__).'/lib/JSMin_lib.php';
@@ -116,6 +157,16 @@ class Minify {
} }
// -- Public Instance Methods ------------------------------------------------ // -- Public Instance Methods ------------------------------------------------
/**
* Instantiates a new Minify object. A filename can be in the form of a
* relative path or a URL that resolves to the same site that hosts Minify.
*
* @param array|string $files filename or array of filenames to be minified
* @param string $type content type of the specified files (either
* Minify::TYPE_CSS or Minify::TYPE_JS)
* @param bool $useCache whether or not to use the disk-based cache
*/
public function __construct($files = array(), $type = self::TYPE_JS, public function __construct($files = array(), $type = self::TYPE_JS,
$useCache = true) { $useCache = true) {
@@ -134,9 +185,12 @@ class Minify {
/** /**
* Adds the specified filename or array of filenames to the list of files to * Adds the specified filename or array of filenames to the list of files to
* be minified. * be minified. A filename can be in the form of a relative path or a URL
* that resolves to the same site that hosts Minify.
* *
* @param array|string $files filename or array of filenames * @param array|string $files filename or array of filenames
* @see getFiles()
* @see removeFile()
*/ */
public function addFile($files) { public function addFile($files) {
$files = @array_map(array($this, 'resolveFilePath'), (array) $files); $files = @array_map(array($this, 'resolveFilePath'), (array) $files);
@@ -144,15 +198,18 @@ class Minify {
} }
/** /**
* Checks the ETag value and/or If-Modified-Since timestamp sent by the * Attempts to serve the combined, minified files from the cache if possible.
* browser and exits with an HTTP "304 Not Modified" response if the
* requested files haven't changed since they were last sent to the client.
* *
* If the browser hasn't cached the content, checks to see if we've cached it * This method first checks the ETag value and If-Modified-Since timestamp
* on the server and, if so, sends the cached content and exits. * sent by the browser and exits with an HTTP "304 Not Modified" response if
* the requested files haven't changed since they were last sent to the
* client.
* *
* If neither the client nor the server has the content in its cache, * If the browser hasn't cached the content, we check to see if it's been
* execution will continue. * cached on the server and, if so, we send the cached content and exit.
*
* If neither the client nor the server has the content in its cache, we don't
* do anything.
*/ */
public function cache() { public function cache() {
$hash = $this->getHash(); $hash = $this->getHash();
@@ -206,6 +263,9 @@ class Minify {
* Combines and returns the contents of all files that have been added with * Combines and returns the contents of all files that have been added with
* addFile() or via this class's constructor. * addFile() or via this class's constructor.
* *
* If Minify->useCache is true, the results will be saved to the on-disk
* cache.
*
* @param bool $minify minify the combined contents before returning them * @param bool $minify minify the combined contents before returning them
* @return string combined file contents * @return string combined file contents
*/ */
@@ -233,6 +293,8 @@ class Minify {
* addFile() or via this class's constructor. * addFile() or via this class's constructor.
* *
* @return array array of absolute pathnames * @return array array of absolute pathnames
* @see addFile()
* @see removeFile()
*/ */
public function getFiles() { public function getFiles() {
return $this->files; return $this->files;
@@ -251,23 +313,44 @@ class Minify {
* to be minified. * to be minified.
* *
* @param array|string $files filename or array of filenames * @param array|string $files filename or array of filenames
* @see addFile()
* @see getFiles()
*/ */
public function removeFile($files) { public function removeFile($files) {
$files = @array_map(array($this, 'resolveFilePath'), (array) $files); $files = @array_map(array($this, 'resolveFilePath'), (array) $files);
$this->files = array_diff($this->files, $files); $this->files = array_diff($this->files, $files);
} }
// -- Private Instance Methods ----------------------------------------------- // -- Protected Instance Methods ---------------------------------------------
/** /**
* Returns the canonicalized absolute pathname to the specified file. * Returns the canonicalized absolute pathname to the specified file or local
* URL.
* *
* @param string $file relative file path * @param string $file relative file path
* @return string canonicalized absolute pathname * @return string canonicalized absolute pathname
*/ */
private function resolveFilePath($file) { protected function resolveFilePath($file) {
// Is this a URL?
if (preg_match('/^https?:\/\//i', $file)) {
if (!$parsedUrl = parse_url($file)) {
throw new MinifyInvalidUrlException("Invalid URL: $file");
}
// Does the server name match the local server name?
if (!isset($parsedUrl['host']) ||
$parsedUrl['host'] != $_SERVER['SERVER_NAME']) {
throw new MinifyInvalidUrlException('Non-local URL not supported: '.
$file);
}
// Get the file's absolute path.
$filepath = realpath(MINIFY_BASE_DIR.$parsedUrl['path']);
}
else {
// Get the file's absolute path. // Get the file's absolute path.
$filepath = realpath(MINIFY_BASE_DIR.'/'.$file); $filepath = realpath(MINIFY_BASE_DIR.'/'.$file);
}
// Ensure that the file exists, that the path is under the base directory, // Ensure that the file exists, that the path is under the base directory,
// that the file's extension is either '.css' or '.js', and that the file is // that the file's extension is either '.css' or '.js', and that the file is
@@ -292,6 +375,7 @@ class Minify {
class MinifyException extends Exception {} class MinifyException extends Exception {}
class MinifyFileNotFoundException extends MinifyException {} class MinifyFileNotFoundException extends MinifyException {}
class MinifyInvalidArgumentException extends MinifyException {} class MinifyInvalidArgumentException extends MinifyException {}
class MinifyInvalidUrlException extends MinifyException {}
// -- Global Scope ------------------------------------------------------------- // -- Global Scope -------------------------------------------------------------
if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) {