1
0
mirror of https://github.com/mrclay/minify.git synced 2025-09-07 04:30:45 +02:00

45 Commits

Author SHA1 Message Date
Elan Ruusamäe
2c83b82bfa update changelog 2017-06-08 20:49:34 +03:00
Elan Ruusamäe
32150b84b6 Merge pull request #600 from Quetzacoalt91/2.x
Cast value as int for PHP 7.1
2017-06-08 20:42:07 +03:00
Thomas N
48a34d6900 Cast value to normalize as int for PHP 7.1 2017-05-31 16:20:51 +01:00
Steve Clay
a36e201ab2 Simplify docs for CSSmin on Minify 2.x 2017-04-25 11:30:12 -04:00
Steve Clay
fefc85d481 Revert "Parse LastModified date without requiring global timezone"
This reverts commit 176fb1084f.
2017-04-03 15:58:28 -04:00
Steve Clay
21cc3e7224 Merge pull request #570 from mrclay/default_tz
Parse LastModified date without requiring global timezone
2017-03-13 11:07:16 -04:00
Steve Clay
176fb1084f Parse LastModified date without requiring global timezone
Fixes #568
2017-02-07 15:33:31 -05:00
Steve Clay
234b9459ca Merge pull request #564 from mrclay/empty_url_2x
URI rewriter passes through empty URLs
2017-01-18 21:08:30 -05:00
Steve Clay
8333f333be URI rewriter passes through empty URLs
Fixes #561
2017-01-18 21:05:07 -05:00
Steve Clay
2d2e06f438 Add temp location to server-info.php 2016-10-02 05:37:07 -04:00
Steve Clay
140673f5b6 Deleted references to WordPress 2016-09-04 10:23:51 -04:00
Steve Clay
49bd730e1a Merge pull request #537 from mrclay/sync_jsmin
Sync JSMin with mrclay/jsmin-php
2016-06-28 14:51:40 -04:00
Steve Clay
850e81c416 Merge pull request #540 from Dargmuesli/2.x
Prevent false mod_rewrite error
2016-06-24 23:39:40 -04:00
Jonas Thelemann
b37d837ff9 Prevent false mod_rewrite error
If Google's Closure Compiler API is enabled, rewriteTest.js is served as
"1;" instead of "1". Therefore the "Note: Your webserver does not seem
to support mod_rewrite (used in /min/.htaccess). Your Minify URIs will
contain '?', which may reduce the benefit of proxy cache servers." is
wrong. This is a simple workaround.
2016-06-25 01:19:44 +02:00
Steve Clay
42b18c1e2a Sync JSMin with mrclay/jsmin-php 2016-06-08 19:00:35 -04:00
Evgeny Mazovetskiy
6a2995f932 list allowDirs in exception to simplify debugging 2016-05-12 10:43:31 -04:00
Steve Clay
b38ed79042 Merge pull request #524 from mrclay/mrclay-mrclay-patch-1
Use $min_libPath in examples and move it within config.php
2016-05-12 10:28:59 -04:00
Steve Clay
bb6e4d5f2e Merge pull request #519 from mrclay/clip_path_517
No longer alters inline SVG id URLs
2016-04-18 21:13:51 -04:00
Steve Clay
28197576c6 Use $min_libPath in examples and move it within config.php
Fixes #522
2016-04-18 21:12:12 -04:00
Steve Clay
cff094781b No longer alters inline SVG id URLs
Fixes #517
2016-03-16 18:32:47 -04:00
Elan Ruusamäe
0eb2cfe78d Update README.md
fixes from googlecode migration
2016-03-13 14:55:23 +02:00
Steve Clay
2d3c417a51 Update README.md
Add news
2016-03-11 23:08:29 -05:00
Steve Clay
f4cb31135d Merge pull request #516 from mrclay/23_deprecations
Begin prep for 2.3 release
2016-03-08 06:49:57 -05:00
Steve Clay
afbcadf33c Begin prep for 2.3 release 2016-03-07 16:50:01 -05:00
Steve Clay
1c3c370dd4 Adds server-info.php 2015-09-26 23:27:29 -04:00
Steve Clay
9eaef368e0 Update FirePHP 2015-09-26 23:16:42 -04:00
Steve Clay
5b6b891cc3 Update UriRewriting.wiki.md 2015-09-26 16:03:05 -04:00
Steve Clay
d71b11ec98 Update CommonProblems.wiki.md 2015-09-22 13:16:36 -04:00
Steve Clay
44e35e69c3 Update README.md 2015-09-22 13:12:46 -04:00
Steve Clay
c24af9fe02 Update README.md 2015-09-22 13:09:41 -04:00
Steve Clay
69019960c9 Update README.md 2015-09-22 13:06:25 -04:00
Steve Clay
0dea940e5f README changes 2015-09-04 17:46:03 -04:00
Steve Clay
f1ef53e84e Add wiki docs and point to some of them (lots of work left here) 2015-09-04 17:38:45 -04:00
Kaue Santoja
d233b65d3d Adds config option to concatenate files only 2015-09-03 14:26:35 -04:00
Elan Ruusamäe
cabd595a5a Merge pull request #142 from KTOmega/readme
Make README into Markdown
2015-04-20 14:49:55 +03:00
Kevin Tran
f9b728918a Make README into Markdown 2015-04-19 23:44:22 -07:00
Kevin Tran
73a085b6c1 Rename README.txt to README.md 2015-04-19 23:41:18 -07:00
Steve Clay
3c11ba8232 Merge pull request #128 from fisharebest/gitattributes
Exclude build/development tools from releases using .gitattributes
2014-10-30 18:58:02 -04:00
Greg Roach
ecbb5ae376 Exclude build/development tools from releases using .gitattributes 2014-10-24 09:29:20 +01:00
Elan Ruusamäe
bd9a450694 update cssmin to v2.4.8-4. fixes #123 2014-09-25 14:40:53 +03:00
Elan Ruusamäe
bceffd5afb remove duplicate $keys assignment 2014-09-21 14:31:30 +03:00
acidvertigo
153e08b5a0 Code clean 2014-09-20 14:21:31 +03:00
Elan Ruusamäe
ce109925aa remove two DOS EOL 2014-09-20 10:34:23 +03:00
Elan Ruusamäe
a0c5ecb514 Merge pull request #102 from greensolid-technologies/master
Add support for Wincache
2014-09-19 16:43:51 +03:00
Matthias Fax
6b469640a7 Add Wincache
Updated comments

Check for Wincache existence in constructor

Normalized markup

Add Wincache test

Tie Wincache test to test index
2014-06-12 15:14:47 +02:00
52 changed files with 3414 additions and 1423 deletions

5
.gitattributes vendored Normal file
View File

@@ -0,0 +1,5 @@
/.editorconfig export-ignore
/.gitignore export-ignore
/.gitattributes export-ignore
/min_extras export-ignore
/min_unit_tests export-ignore

9
.gitignore vendored
View File

@@ -1,7 +1,8 @@
# /
/test
/docs
.idea/
.DS_Store
vendor
/.idea/
/composer.lock
.DS_Store
/vendor
/.php_cs.cache

View File

@@ -1,9 +1,30 @@
Minify Release History
(master)
* Builder styled with Bootstrap (thanks to help from acidvertigo)
Version 2.3.2 (2017-06-09)
* PHP 7.1 compatibility fix. #600
Version 2.2.0
Version 2.3.1 (2017-04-03)
* No longer alters inline SVG id URLs. #517, #519
* Use $min_libPath in examples and move it within config.php. #522, #524
* Prevent false mod_rewrite error. #540
* Sync JSMin with mrclay/jsmin-php. #537
* URI rewriter passes through empty URLs. #561, #564
Version 2.3.0 (2016-03-11)
* Adds `$min_concatOnly` option to just concatenate files
* Deprecates use of Minify_Loader
* Deprecates use of Minify_Logger
* Deprecates use of JSMinPlus
* Deprecates use of FirePHP
* Deprecates use of DooDigestAuth
Version 2.2.1 (2014-10-30)
* Builder styled with Bootstrap (thanks to help from acidvertigo)
* Update CSSmin to v.2.4.8
* Added WinCache
* URLs with spaces properly rewritten
Version 2.2.0 (2014-03-12)
* Fix handling of RegEx in certain situations in JSMin
* Thanks to Vovan-VE for reporting this
* Update composer.json with support info
@@ -25,11 +46,11 @@ Version 2.2.0
* Allow far-future expiration and file versioning with the "v" querystirng parameter in addition to existing method
* Lots of general code tidy ups
Version 2.1.7
Version 2.1.7 (2013-07-23)
* Fixes arbitrary file inclusion vulnerability on some systems
* Thanks to Matt Mecham for reporting this
Version 2.1.6
Version 2.1.6 (2013-07-19)
* JSMin fixes
* Prevents some Closure Compiler API failures
* Uses autoloading for all class loading
@@ -41,7 +62,7 @@ Version 2.1.6
* CLI script more portable
* Adds composer.json
Version 2.1.5
Version 2.1.5 (2012-03-10)
* Removed XSS vulnerability
* Disabled builder bby default
* command line tools to minify and rewrite URIs in CSS
@@ -50,7 +71,7 @@ Version 2.1.5
* Closure Compiler uses cURL when allow_url_fopen is off
* Missing file notices when using groups
Version 2.1.4
Version 2.1.4 (2010-07-10)
* Option to minify JS with Closure Compiler API w/ JSMin failover
* Cookie/bookmarklet-based debug mode. No HTML editing!
* Allows 1 file to be missing w/o complete failure
@@ -66,7 +87,7 @@ Version 2.1.4
* Removed annoying maxFiles limit
* mbstring.func_overload usage is safer
Version 2.1.3
Version 2.1.3 (2009-06-30)
* HTTP fixes
* ETag generation now valid (different when gzipped)
* Vary header always sent when Accept-Encoding is sniffed
@@ -78,7 +99,7 @@ Version 2.1.3
* Allow setting contentType in Minify_Source objects
* No more 5.3 deprecation warnings: split() removed
Version 2.1.2
Version 2.1.2 (2009-03-04)
* Javascript fixes
* Debug mode no longer confused by "*/*" in strings/RegExps (jQuery)
* quote characters inside RegExp literals no longer cause exception
@@ -90,14 +111,14 @@ Version 2.1.2
* Builder app doesn't fail on systems without gzdeflate()
* APC caching class included
Version 2.1.1
Version 2.1.1 (2008-10-19)
* Bug fix release
* Detection and workarounds for zlib.output_compression and non-PHP encoding modules
* Zlib not required (mod_rewrite, et.al., can still be used for encoding)
* HTML : More IE conditional comments preserved
* Minify_groupUri() utility fixed
Version 2.1.0
Version 2.1.0 (2008-09-18)
* "min" default application for quick deployment
* Minify URI Builder app & bookmarklet for quickly creating minify URIs
* Relative URIs in CSS file are fixed automatically by default
@@ -105,7 +126,7 @@ Version 2.1.0
* Better IIS support
* Improved minifier classes:
* JS: preserves IE conditional comments
* CSS: smaller output, preserves more hacks and valid CSS syntax,
* CSS: smaller output, preserves more hacks and valid CSS syntax,
shorter line lengths, other bug fixes
* HTML: smaller output, shorter line lengths, other bug fixes
* Default Cache-Control: max-age of 30 minutes
@@ -122,15 +143,15 @@ Version 2.0.1 (2008-05-31)
* E_STRICT compliance (Cache_Lite_File).
Version 2.0.0 (2008-05-22)
* Complete code overhaul. Minify is now a PEAR-style class and toolkit
* Complete code overhaul. Minify is now a PEAR-style class and toolkit
for building customized minifying file servers.
* Content-Encoding: deflate/gzip/compress, based on request headers
* Expanded CSS and HTML minifiers with test cases
* Easily plug-in 3rd-party minifiers (like Packer)
* Plug-able front end controller allows changing the way files are chosen
* Compression & encoding modules lazy-loaded as needed (304 responses use
* Compression & encoding modules lazy-loaded as needed (304 responses use
use minimal code)
* Separate utility classes for HTTP encoding and cache control
* Separate utility classes for HTTP encoding and cache control
Version 1.0.1 (2007-05-05)
* Fixed various problems resolving pathnames when hosted on an NFS mount.

View File

@@ -176,6 +176,11 @@ file. To enable this, set $min_allowDebugFlag to true in config.php and append
Known issue: files with comment-like strings/regexps can cause problems in this mode.
BYPASSING MINIFICATION
See the $min_concatOnly option in config.php.
QUESTIONS?
http://groups.google.com/group/minify

75
README.md Normal file
View File

@@ -0,0 +1,75 @@
Welcome to Minify!
==================
Minify is an HTTP server for JS and CSS assets. It compresses and combines files
and serves it with appropriate headers, allowing conditional GET or long-Expires.
| *Before* | ![7 requests](http://mrclay.org/wp-content/uploads/2008/09/fiddler_before.png) |
|----------|-----------------------------------------------------------------|
| *After* | ![2 requests](http://mrclay.org/wp-content/uploads/2008/09/fiddler_after.png) |
The stats above are from a [brief walkthrough](http://mrclay.org/index.php/2008/09/19/minify-21-on-mrclayorg/) which shows how easy it is to set up Minify on an existing site. It eliminated 5 HTTP requests and reduced JS/CSS bandwidth by 70%.
Relative URLs in CSS files are rewritten to compensate for being served from a different directory.
News
----
Version [2.3.0](https://github.com/mrclay/minify/releases/tag/2.3.0) was released, mainly to deprecate some classes that will be removed in 3.0.
Installation
------------
Place the `/min/` directory as a child of your DOCUMENT_ROOT
directory: i.e. you will have: `/home/example/www/min`
You can see verify that it is working by visiting these two URLs:
- http://example.org/min/?f=min/quick-test.js
- http://example.org/min/?f=min/quick-test.css
If your server supports mod_rewrite, this URL should also work:
- http://example.org/min/f=min/quick-test.js
Configuration & Usage
---------------------
See the MIN.txt file and the [user guide](https://github.com/mrclay/minify/blob/master/docs/UserGuide.wiki.md)
Minify also comes with a [URI Builder application](https://github.com/mrclay/minify/blob/master/docs/BuilderApp.wiki.md) that can help you write URLs
for use with Minify or configure groups of files.
See the [cookbook](https://github.com/mrclay/minify/blob/master/docs/CookBook.wiki.md) for more advanced options for minification.
More [docs are available](https://github.com/mrclay/minify/tree/master/docs).
Support
-------
[Google Group](http://groups.google.com/group/minify)
Unit Testing
------------
1. Place the /min_unit_tests/ directory as a child of your DOCUMENT_ROOT
directory: i.e. you will have: /home/example/www/min_unit_tests
2. To run unit tests, access: http://example.org/min_unit_tests/test_all.php
(If you wish, the other test_*.php files can be run to test individual
components with more verbose output.)
3. Remove /min_unit_tests/ from your DOCUMENT_ROOT when you are done.
Warnings
--------
* Minify is designed for efficiency, but, for very high traffic sites, it will probably serve files slower than your HTTPd due to the CGI overhead of PHP. See the [FAQ](https://github.com/mrclay/minify/blob/master/docs/FAQ.wiki.md#how-fast-is-it) and [CookBook](https://github.com/mrclay/minify/blob/master/docs/CookBook.wiki.md) for more info.
* If you combine a lot of CSS, watch out for [IE's 4096 selectors-per-file limit](http://stackoverflow.com/a/9906889/3779), affects IE 6 through 9.
* Minify *should* work fine with files encoded in UTF-8 or other 8-bit encodings like ISO 8859/Windows-1252. By default Minify appends ";charset=utf-8" to the Content-Type headers it sends.
Acknowledgments
---------------
Minify was inspired by [jscsscomp](http://code.google.com/p/jscsscomp/) by Maxim Martynyuk and by the article [Supercharged JavaScript](http://www.hunlock.com/blogs/Supercharged_Javascript) by Patrick Hunlock.
The [JSMin library](http://www.crockford.com/javascript/jsmin.html) used for JavaScript minification was originally written by Douglas Crockford and was [ported to PHP](https://github.com/mrclay/jsmin-php) by Ryan Grove specifically for use in Minify.

View File

@@ -1,68 +0,0 @@
WELCOME TO MINIFY!
Minify is an HTTP content server. It compresses sources of content
(usually files), combines the result and serves it with appropriate
HTTP headers. These headers can allow clients to perform conditional
GETs (serving content only when clients do not have a valid cache)
and tell clients to cache the file for a period of time.
More info: http://code.google.com/p/minify/
WORDPRESS USER?
These WP plugins integrate Minify into WordPress's style and script hooks to
get you set up faster.
http://wordpress.org/extend/plugins/bwp-minify/
http://wordpress.org/extend/plugins/w3-total-cache/
INSTALLATION
Place the /min/ directory as a child of your DOCUMENT_ROOT
directory: i.e. you will have: /home/example/www/min
You can see verify that it is working by visiting these two URLs:
http://example.org/min/?f=min/quick-test.js
http://example.org/min/?f=min/quick-test.css
If your server supports mod_rewrite, this URL should also work:
http://example.org/min/f=min/quick-test.js
CONFIGURATION & USAGE
See the MIN.txt file and http://code.google.com/p/minify/wiki/UserGuide
Minify also comes with a URI Builder application that can help you write URLs
for use with Minify or configure groups of files. See here for details:
http://code.google.com/p/minify/wiki/BuilderApp
The cookbook also provides some more advanced options for minification:
http://code.google.com/p/minify/wiki/CookBook
UPGRADING
See UPGRADING.txt for instructions.
UNIT TESTING:
1. Place the /min_unit_tests/ directory as a child of your DOCUMENT_ROOT
directory: i.e. you will have: /home/example/www/min_unit_tests
2. To run unit tests, access: http://example.org/min_unit_tests/test_all.php
(If you wish, the other test_*.php files can be run to test individual
components with more verbose output.)
3. Remove /min_unit_tests/ from your DOCUMENT_ROOT when you are done.
FILE ENCODINGS
Minify *should* work fine with files encoded in UTF-8 or other 8-bit
encodings like ISO 8859/Windows-1252. By default Minify appends
";charset=utf-8" to the Content-Type headers it sends.
Leading UTF-8 BOMs are stripped from all sources to prevent
duplication in output files, and files are converted to Unix newlines.

View File

@@ -16,11 +16,17 @@
"issues": "http://code.google.com/p/minify/issues/list",
"wiki": "http://code.google.com/p/minify/w/list"
},
"autoload": {
"classmap": ["min/lib/"]
},
"require": {
"php": ">=5.2.1",
"ext-pcre": "*"
},
"autoload": {
"classmap": ["min/lib/"]
"require-dev": {
"tubalmartin/cssmin": "~2.4.8"
},
"suggest": {
"tubalmartin/cssmin": "Support minify with CSSMin (YUI PHP port)"
}
}

View File

@@ -0,0 +1,29 @@
If you test sites in a subdirectory (e.g. `http://localhost/testSite/`) rather than a virtualhost, then you'll need to adjust the way you use Minify to rewrite CSS correctly.
1. Place the following in `min/config.php`:
```
// Set the document root to be the path of the "site root"
$min_documentRoot = substr(__FILE__, 0, -15);
// Set $sitePrefix to the path of the site from the webserver's real docroot
list($sitePrefix) = explode('/min/index.php', $_SERVER['SCRIPT_NAME'], 2);
// Prepend $sitePrefix to the rewritten URIs in CSS files
$min_symlinks['//' . ltrim($sitePrefix, '/')] = $min_documentRoot;
```
2. In the HTML, make your Minify URIs document-relative (e.g. `min/f=js/file.js` and `../min/f=js/file.js`), not root-relative.
Now the `min` application should operate correctly from a subdirectory and will serve files relative to your "site" root rather than the document root. E.g.
| **environment** | production | testing |
|:----------------|:-----------|:--------|
| **server document root** | `/home/mysite_com/www` | `/var/www` |
| **`$min_documentRoot` ("site root")** | `/home/mysite_com/www` | `/var/www/testSite` |
| **`$sitePrefix`** | (empty) | `/testSite` |
| **Minify URL** | `http://mysite.com/min/f=js/file1.js` | `http://localhost/testSite/min/f=js/file1.js` |
| **file served** | `/home/mysite_com/www/js/file1.js` | `/var/www/testSite/js/file1.js` |
Caveats:
* This configuration may break the Builder application (located at `/min/builder/`) used to create Minify URIs, but you can still [create them by hand](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/README.txt#18).
* Make sure you don't reset `$min_symlinks` to a different value lower in your config file.

9
docs/BuilderApp.wiki.md Normal file
View File

@@ -0,0 +1,9 @@
Minify ships with "Builder", a simple Javascript app for constructing URIs to use with Minify. ([screenshots of the 2.1.0 version](http://www.mrclay.org/index.php/2008/09/19/minify-21-on-mrclayorg/))
It also does some run-time checks of your PHP and Minify configuration to look for problematic settings like [auto-encoding](http://code.google.com/p/minify/wiki/CommonProblems#Output_is_distorted/random_chars).
After installation, this is found at **`http://example.com/min/builder/`**
You must enable it by editing `min/config.php` and setting `$min_enableBuilder = true;`
After use, you should disable it by resetting `$min_enableBuilder = false;`

129
docs/CommonProblems.wiki.md Normal file
View File

@@ -0,0 +1,129 @@
If this page doesn't help, please post a question on our [Google group](http://groups.google.com/group/minify).
## URIs are re-written incorrectly in CSS output
See UriRewriting.
## Files aren't cached in IE6
**Use Minify 2.1.4+**.
For Minify 2.1.3 and below:
1. Open `/min/lib/HTTP/Encoder.php`
1. On line [62](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/HTTP/Encoder.php#62), change `false` to `true`.
## Builder Fails / 400 Errors
**Use Minify 2.1.4+**, and you can see the cause of 400 responses using FirePHP (See [Debugging](Debugging.md)).
## PHP/Apache crashes
[PCRE (which provides regular expressions) commonly crashes PHP](https://www.google.com/search?q=pcre+php+crash) and this is nearly impossible to solve in PHP code. Things to try:
* Raise Apache's [ThreadStackSize](http://stackoverflow.com/a/7597506/3779)
* In [php.ini](http://php.net/manual/en/pcre.configuration.php) raise `pcre.backtrack_limit` and `pcre.recursion_limit` to 1000000. These will allow processing longer strings, but also require a larger stack size.
* Try [this CSSmin configuration](http://code.google.com/p/minify/wiki/CookBook#CSSmin_PHP_port)
## Dealing with Javascript errors
Short answer: **use Minify 2.1.4+, use a pre-compressed version of your file, and rename it `*.min.js` or `*-min.js`**. By default Minify won't try to minify these files (but will still gzip them). The [Compressor Rater](http://compressorrater.thruhere.net/) is handy for compressing files individually.
If the error is in your code, enable [debug mode](Debugging.md) while debugging your code in Firebug or your favorite browser's Javascript debugger. This will insert comments to allow you to keep track of the individual source locations in the combined file.
If you have Java on your web host, you can use the [wrapper for YUI Compressor](http://code.google.com/p/minify/source/browse/min/lib/Minify/YUICompressor.php) instead of JSMin. [This thread](http://groups.google.com/group/minify/browse_thread/thread/f12f25f27e1256fe) shows how a user has done this.
## Javascript isn't being minified
If the filename ends with **`-min.js`** or **`.min.js`**, Minify will assume the file is already compressed and just combine it with any other files.
### Scriptaculous
Scriptaculous 1.8.2 (and probably all 1.x) has an [autoloader script](http://github.com/madrobby/scriptaculous/blob/4b49fd8884920d4ee760b0194431f4f433f878df/src/scriptaculous.js#L54) that requires files to be in a particular place on disk. To serve Scriptaculous modules with Minify, just serve `prototype.js` and the individual support files (e.g. `dragdrop.js`, `effects.js`) and the library should work fine. E.g.:
```
<script src="/min/f=scriptaculous/lib/prototype.js" type="text/javascript"></script>
<script src="/min/b=scriptaculous/src&amp;f=effects.js,dragdrop.js" type="text/javascript"></script>
<script type="text/javascript">
/* DragDrop and Effects modules can be used here. */
</script>
```
## Server cache files won't update
If you upload files using [Coda or Transmit](http://groups.google.com/group/coda-users/browse_thread/thread/572d2dc315ec02e7/) or from a Windows PC to a non-Windows server, your new files may end up with the wrong `mtime` (timestamp) on the server, confusing the cache system.
Setting the [$min\_uploaderHoursBehind option](https://github.com/mrclay/minify/blob/master/min/config.php#L171) in `config.php` can compensate for this.
WinSCP has a [Daylight Saving Time option](http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time) that can prevent this issue.
This can also occur if your files are changed, and the `mtime` is set in the past (e.g. via a `git checkout` operation). If so you'll have to `touch` the changed files or use some other method to make the `mtime` current.
## Can't see changes in browser
Generally changes aren't seen because a) the browser is refusing to send a new request, or b) the server doesn't recognize that your source files have been modified after the server cache was created.
First, place the Minify URL directly in the address bar and refresh.
If a change is not seen, verify that the server cache file is being updated.
## Disable Caching
If you'd like to temporarily disable the cache without using [debug mode](Debugging.md), place these settings at the end of `config.php`:
```
// disable server caching
$min_cachePath = null;
// prevent client caching
$min_serveOptions['maxAge'] = 0;
$min_serveOptions['lastModifiedTime'] = $_SERVER['REQUEST_TIME'];
```
**Don't do this on a production server!** Minify will have to combine, minify, and gzencode on every request.
## Character Encodings
_Please_ use UTF-8. The string processing may work on encodings like Windows-1251 but will certainly fail on radically different ones like UTF-16.
If you consistently use a different encoding, in `config.php` set `$min_serveOptions['contentTypeCharset']` to this encoding to send it in the Content-Type header.
Otherwise, set it to `false` to remove it altogether. You can still, in CSS, use the [@charset](http://www.w3.org/TR/CSS2/syndata.html#x50) directive to tell the browser the encoding, but (a) it must appear first and (b) shouldn't appear later in the output (and Minify won't enforce this).
Moral? To minimize problems, use UTF-8 and remove any `@charset` directives from your CSS.
## @imports can appear in invalid locations in combined CSS files
If you combine CSS files, @import declarations can appear after CSS rules, invalidating the stylesheet. As of version 2.1.2, if Minify detects this, it will prepend a warning to the output CSS file. To resolve this, you can either move your @import statements within your files, or enable the option 'bubbleCssImports'.
## Debug mode can cause a Javascript error
This issue was resolved in version 2.1.2.
Debug mode adds line numbers in comments. Unfortunately, in versions <= 2.1.1, if the source file had a string or regex containing (what looks like) a C-style comment token, the algorithm was confused and the injected comments caused a syntax error.
## Minification can cause a Javascript error
This issue was resolved in version 2.1.2.
In rare instances the [JSMin](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/JSMin.php#14) algorithm in versions <= 2.1.1 could be confused by regexes in certain contexts and throw an exception. The workaround was to simply wrap the expression in parenthesis. E.g.
```
// in 2.1.1 and previous
return /'/; // JSMin throws error
return (/'/); // no error
```
## Output is distorted/random chars
What you're seeing is a mismatch between the content encoding the browser expects and what it receives.
The usual problem is that a global PHP or web server configuration is causing the output of PHP scripts to be automatically gzipped. Since Minify already outputs gzipped content, the browser receives "double encoded" content which it interprets as noise. The Builder app in 2.1.4 sometimes can tell you which component is causing the auto-encoding.
## Can't specify more than 10 files via URL
Use Minify 2.1.4+. Before there was a setting to adjust the maximum allowed.
## Directory Listing Denied
This may also appear as "Virtual Directory does not allow contents to be listed". Minify requires that the URI `/min/` (a request for a directory listing) result in the execution of `/min/index.php`. On Apache, you would make sure `index.php` is listed in the [DirectoryIndex directive](http://httpd.apache.org/docs/2.0/mod/mod_dir.html#directoryindex). IIS calls this the [Default Document](http://www.iis.net/ConfigReference/system.webServer/defaultDocument).
## See Also
* [Debugging](Debugging.md)

View File

@@ -0,0 +1,14 @@
# PHP5 Component Classes
| **Class** | **Functionality** |
|:----------|:------------------|
| [Minify](http://code.google.com/p/minify/source/browse/min/lib/Minify.php) | Combine, process, and serve pieces of content (usually CSS/JS files). Almost all behavior is configurable including request handling (via [controllers](http://code.google.com/p/minify/source/browse/min/lib/Minify/Controller/)), HTTP headers & encoding, caching ([file/APC/memcached](http://code.google.com/p/minify/source/browse/min/lib/Minify/Cache/)), and compression functions (by default, the classes below) |
| [JSMin](http://code.google.com/p/minify/source/browse/min/lib/JSMin.php) | A port of [jsmin.c](http://www.crockford.com/javascript/jsmin.html), extended to preserve some multi-line comments and IE conditional comments (since these occasionally have their [uses](http://dean.edwards.name/weblog/2007/03/sniff/)). |
| [Minify\_CSS](http://code.google.com/p/minify/source/browse/min/lib/Minify/CSS.php) | Uses the two classes below to minify CSS and optionally rewrite URIs. |
| [Minify\_CSS\_Compressor](http://code.google.com/p/minify/source/browse/min/lib/Minify/CSS/Compressor.php) | Agressively minifies CSS. Includes a thorough [test suite](http://code.google.com/p/minify/source/browse/min_unit_tests/_test_files/css/) to make sure most common [hacks](http://code.google.com/p/minify/source/browse/min_unit_tests/_test_files/css/hacks.css) and [unusual syntaxes](http://code.google.com/p/minify/source/browse/min_unit_tests/_test_files/css/unusual_strings.css) are preserved. |
| [Minify\_CSS\_UriRewriter](http://code.google.com/p/minify/source/browse/min/lib/Minify/CSS/UriRewriter.php) | In CSS files, rewrites file-relative URIs as root-relative. With [test suite](http://code.google.com/p/minify/source/browse/min_unit_tests/_test_files/css_uriRewriter/) |
| [Minify\_HTML](http://code.google.com/p/minify/source/browse/min/lib/Minify/HTML.php) | Agressively minifies (X)HTML markup. Preserves TEXTAREA/PRE contents, can invoke minifiers on STYLE and SCRIPT blocks, and wraps content in CDATA blocks in XHTML when necessary. Includes [test suite](http://code.google.com/p/minify/source/browse/min_unit_tests/_test_files/html/). |
| [Minify\_YUICompressor](http://code.google.com/p/minify/source/browse/min/lib/Minify/YUICompressor.php) | (Experimental) PHP wrapper for invoking the Java-based [YUI Compressor](http://developer.yahoo.com/yui/compressor/) |
| [Minify\_ImportProcessor](http://code.google.com/p/minify/source/browse/min/lib/Minify/ImportProcessor.php) | Linearize a CSS/JS file by including content specified by CSS import declarations. In CSS files, relative URIs are fixed. This has a test suite but should be considered "experimental". |
| [HTTP\_Encoder](http://code.google.com/p/minify/source/browse/min/lib/HTTP/Encoder.php) | Applies HTTP encoding to content. Can serve content with conditional encoding based on Accept-Encoding headers (parsed according to [HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html)) and known browser bugs. |
| [HTTP\_ConditionalGet](http://code.google.com/p/minify/source/browse/min/lib/HTTP/ConditionalGet.php) | Implements HTTP conditional GETs via a simple, flexible API. |

139
docs/CookBook.wiki.md Normal file
View File

@@ -0,0 +1,139 @@
Unless mentioned, all the following snippets go in `min/config.php`.
## Faster Cache Performance
By default, Minify uses [Minify\_Cache\_File](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Cache/File.php). It uses `readfile`/`fpassthru` to improve performance over most file-based systems, but it's still file IO. I haven't done comparative benchmarks on all three, but APC/Memcache _should_ be faster. In all cases, Minify cache ids begin with `"minify_"`.
### APC
```
require "$min_libPath/Minify/Cache/APC.php";
$min_cachePath = new Minify_Cache_APC();
```
### Memcache
You must create and connect your Memcache object then pass it to `Minify_Cache_Memcache`'s constructor.
```
require "$min_libPath/Minify/Cache/Memcache.php";
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$min_cachePath = new Minify_Cache_Memcache($memcache);
```
### Zend Platform
Patrick van Dissel has contributed a [cache adapter for Zend Platform](http://code.google.com/p/minify/issues/detail?id=167).
## Closure Compiler API Wrapper
An [experimental wrapper for Google's closure compiler API](https://github.com/mrclay/minify/blob/master/min/lib/Minify/JS/ClosureCompiler.php) is available for compressing Javascript. If the API fails for any reason, JSMin is used as the default backup minifier.
```
$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');
```
## YUICompressor
If your host can execute Java, you can use Minify's YUI Compressor wrapper. You'll need the latest [yuicompressor-x.x.x.jar](http://yuilibrary.com/downloads/#yuicompressor) and a temp directory. Place the .jar in `min/lib`, then:
```
function yuiJs($js) {
Minify_YUICompressor::$jarFile = __DIR__ . '/lib/yuicompressor-x.x.x.jar';
Minify_YUICompressor::$tempDir = '/tmp';
return Minify_YUICompressor::minifyJs($js);
}
$min_serveOptions['minifiers']['application/x-javascript'] = 'yuiJs';
```
To use YUIC for CSS with fixed URIs:
```
function yuiCss($css, $options) {
Minify_YUICompressor::$jarFile = __DIR__ . '/lib/yuicompressor-x.x.x.jar';
Minify_YUICompressor::$tempDir = '/tmp';
$css = Minify_YUICompressor::minifyCss($css);
$css = Minify_CSS_UriRewriter::rewrite(
$css
,$options['currentDir']
,isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT']
,isset($options['symlinks']) ? $options['symlinks'] : array()
);
return $css;
}
$min_serveOptions['minifiers']['text/css'] = 'yuiCss';
```
### CSSmin PHP port
Minify has added Túbal Martín's [PHP port](https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port/blob/master/cssmin.php) of the YUI Compressor's CSSmin. While it is not completely integrated yet, you may try it out:
```
$min_serveOptions['minifiers']['text/css'] = array('Minify_CSSmin', 'minify');
```
## JSMin+
Tino Zijdel's [JSMin+](http://crisp.tweakblogs.net/blog/6861/jsmin%2B-version-14.html) has resulted in memory usage problems for many users and will be removed from the Minify codebase in 3.0. If you wish to use it, you should download it outside the Minify directory and link to it:
```
require '/path/to/jsminplus.php';
$min_serveOptions['minifiers']['application/x-javascript'] = array('JSMinPlus', 'minify');
```
## Server-specific Options
You may need to have different options depending on what server you're on. You can do this just how you'd expect:
```
if ($_SERVER['SERVER_NAME'] == 'myTestingWorkstation') {
// testing
$min_allowDebugFlag = true;
$min_errorLogger = true;
$min_enableBuilder = true;
$min_cachePath = 'c:\\WINDOWS\\Temp';
$min_serveOptions['maxAge'] = 0; // see changes immediately
} else {
// production
$min_allowDebugFlag = false;
$min_errorLogger = false;
$min_enableBuilder = false;
$min_cachePath = '/tmp';
$min_serveOptions['maxAge'] = 86400;
}
```
## Site in a Subdirectory
If you test/develop sites in a subdirectory (e.g. `http://localhost/siteA/`), see AlternateFileLayouts.
## Group-specific Options
In "group" requests, `$_GET['g']` holds the group key, so you can code based on it:
```
if (isset($_GET['g'])) {
switch ($_GET['g']) {
case 'js' : $min_serveOptions['maxAge'] = 86400 * 7;
break;
case 'css': $min_serveOptions['contentTypeCharset'] = 'iso-8859-1';
break;
}
}
```
## File/Source-specific Options
See CustomSource.
## Processing Output After Minification
If `$min_serveOptions['postprocessor']` is set to a callback, Minify will pass the minified content to this function with type as the second argument. This allows you to apply changes to your minified content without making your own custom minifier. E.g.:
```
function postProcess($content, $type) {
if ($type === Minify::TYPE_CSS) {
require_once 'CssColorReplacer.php';
return CssColorReplacer::process($content);
}
return $content;
}
$min_serveOptions['postprocessor'] = 'postProcess';
```
This function is only called once immediately after minification and its output is stored in the cache.

153
docs/CustomServer.wiki.md Normal file
View File

@@ -0,0 +1,153 @@
Please see the UserGuide if you're just getting started with Minify. This guide is for more advanced users who wish to implement an HTTP server in PHP using the [Minify](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify.php) class.
The basic steps are:
1. Set up the include\_path
1. Set up caching
1. Choose a Minify controller
1. Set up service and controller options
1. Handle the request
## Set up the include\_path
```
set_include_path('/path/to/min/lib' . PATH_SEPARATOR . get_include_path());
```
## Set up caching
Minify ships with [cache classes](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Cache/) for files, APC, and memcache. Choose one, instantiate it, and pass it to Minify:
```
require 'Minify.php';
require 'Minify/Cache/File.php';
Minify::setCache(new Minify_Cache_File()); // files in directory chosen by Solar_Dir
```
## Choose a Minify controller
Minify uses controller classes to analyze HTTP requests and determine which sources will make up the response. (The content isn't always returned; if the browser's cache is valid, Minify can return a 304 header instead).
The [Files](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/Files.php#9) controller doesn't care about the HTTP request. It just specifies a given array of sources (file paths or [source objects](CustomSource.md)).
The [Groups](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/Groups.php) controller uses `$_SERVER['PATH_INFO']` to choose from an array of source lists. There's an example at the end of this page.
The Files controller is simple, so we'll use it here.
## Set up service and controller options
A single array is used for configuration, and is passed to the `Minify::serve` method. `serve` passes it to the controller, which picks off the keys it needs and returns it to `serve` for Minify's own built-in [options](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify.php#88). This architecture allows the controller to set defaults for `serve`.
The Files controller only needs one key: `files`: the array of sources to be combined and served.
The only `serve` option we'll set is `maxAge` (the default is a measly 1800 seconds).
```
$options = array(
// options for the controller
'files' => array('//js/file1.js', '//js/file2.js', $src),
// options for Minify::serve
'maxAge' => 86400
);
```
(In the above $src is a [Minify\_Source object](CustomSource.md), which allows you to serve non-file content, and/or apply settings to individual sources.)
## Handle the request
```
Minify::serve('Files', $options);
```
That's it...
Minify's default application (sometimes referred to as "min") is implemented this way, in the file [min/index.php](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/index.php). Most of its request handling is encapsulated in its own [MinApp](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/MinApp.php#15) controller.
# The Request Cycle
In handling a request, `Minify::serve` does a number of operations:
1. creates a controller object, unless you pass it a readymade object (let's call this `$ctrl`).
1. calls `$ctrl->setupSources($options)`, which analyzes the request and sets `$ctrl->sources` accordingly to an array of Minify\_Source objects.
1. calls `$ctrl->analyzeSources($options)`, which set `$options` keys for `contentType` and `lastModifiedTime`, based on the sources.
1. calls `$ctrl->mixInDefaultOptions($options)`, to mix the controller's default options with the user's.
1. determines if the browser accepts gzip
1. validates the browser cache (optionally responding with a 304)
1. validates the server cache. If it needs refreshing, `Minify::_combineMinify` is called, which...
* calls `$source->getContent` on each source
* the content is combined before or after minification (depending on individual source options)
1. sets up headers to be sent
1. either returns the headers and content in an array (if `quiet` is set), or sends it to the browser.
# Using the Groups controller
```
$options = array(
'groups' => array(
'js' => array('//js/file1.js', '//js/file2.js'),
'css' => array('//css/file1.css', '//css/file2.css'),
),
);
Minify::serve('Groups', $options);
```
With the above, if you request `http://example.org/myServer.php/css`, Apache will set `$_SERVER['PATH_INFO'] = '/css'` and the sources in `$options['groups']['css']` will be served.
<a href='Hidden comment: Move somewhere else
== Sending far future Expires headers ==
By default Minify enables [http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers conditional GETs] for client-side caching, but in this model the browser has to continuously check back with the server to revalidate its cache. A better method is to send [http://developer.yahoo.com/performance/rules.html#expires far future Expires headers] and change the URL when the file changes. As long as you generate your HTML with PHP, Minify makes it easy to do this.
1. Move the "groups" configuration array into a separate file "_groupsConfig.php":
```
<?php
// configures both Minify::serve() and Minify_Build
return array(
"js1" => array("//js/yourFile1.js", "//js/yourFile2.js")
,"js2" => array("//js/yourFile1.js", "//js/yourFile3.js")
,"jQuery" => array("//js/jquery-1.2.6.js")
,"css" => array("//css/layout.css", "//css/fonts.css")
);
```
2. Adjust "min.php" to use this file:
```
Minify::serve("Groups", array(
"groups" => (require "_groupsConfig.php")
));
```
3. In your HTML-generating script, create Minify_Build objects for each minify URI you"re going to use, and, to each, apply the uri() method:
```
require "Minify/Build.php";
$_gc = (require "_groupsConfig.php");
$js1Build = new Minify_Build($_gc["js1"]);
$cssBuild = new Minify_Build($_gc["css"]);
echo "<link rel="stylesheet" type="text/css" href="" . $cssBuild->uri("/min.php/css") . "" />";
/* ... */
echo "<script type="text/javascript" src="" . $js1Build->uri("/min.php/js1") . ""></script>";
```
5. Open the (X)HTML page in your browser. The Javascript and CSS should "work".
6. View source. The minify URIs should look like: "/min.php/js1?##########" (a unix timestamp)
7. Now that our URI"s are synched with source file changes, we can safely send Expires headers. In "min.php":
```
Minify::serve("Groups", array(
"groups" => (require "_groupsConfig.php")
,"maxAge" => 31536000 // 1 yr
// in 2.0 was "setExpires" => $_SERVER["REQUEST_TIME"] + 31536000
));
```
Now "min.php" will serve files with Expires headers, causing the browser to always retrieve them from cache (until the expiration date).
When you make a change to any of your source Javascript/CSS files, your HTML file will have a different querystring appended to the minify URIs, causing the browser to download it as a new URL, and Minify will automatically rebuild its cache files on the server.
'></a>

138
docs/CustomSource.wiki.md Normal file
View File

@@ -0,0 +1,138 @@
In `groupsConfig.php`, usually you specify source file paths using strings like `/path/to/file.js` or `//js/file1.js` (Minify expands this to `"{$_SERVER['DOCUMENT_ROOT']}/js/file1.js"` ).
Instead of a string, you may substitute a "source object" (an instance of class [Minify\_Source](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Source.php)). This allows you to customize how minification is applied, and/or pull content from a non-file location (e.g. a URL).
### Example: filepath
In the `$spec` array, set the key `filepath` to produce a source based on a file path:
```
$src1 = new Minify_Source(array(
'filepath' => '//js/file1.js',
));
$src2 = new Minify_Source(array(
'filepath' => '//js/file2.js',
));
return array(
'js' => array($src1, $src2)
);
```
Note the above is functionally identical to:
```
return array(
'js' => array('//js/file1.js', '//js/file2.js')
);
```
### Example: Specify a different minifier or none at all
To change minifier, set `minifier` to a [callback](http://php.net/manual/en/language.pseudo-types.php)`*` or the empty string (for none):
**`*`Prepare for `groupsConfig.php` to be executed more than once.** (This is likely if you're using the functions in `/min/utils.php`.) In practice this just means making sure functions are conditionally defined if they don't already exist, etc.
```
if (! function_exists('myMin')) {
function myMin($js) {
require_once '/path/to/jsminplus.php';
return JSMinPlus::minify($js);
}
}
$src1 = new Minify_Source(array(
'filepath' => '//js/file1.js',
'minifier' => 'myMin',
));
$src2 = new Minify_Source(array(
'filepath' => '//js/file2.js',
'minifier' => '', // don't compress
));
```
In the above, `myMin()` is only called when rebuilding the cache. This way `JSMinPlus.php` is only loaded when needed.
**`*`Do _not_ use [create\_function](http://php.net/manual/en/function.create-function.php) or anonymous functions for the minifier.** The internal names of these function tend to vary, causing Minify to create lots of [duplicate cache files](http://code.google.com/p/minify/issues/detail?id=138) (and perform poorly).
## Non-File Sources
You're not limited to flat js/css files, but without `filepath`, the `$spec` array must contain these keys:
* **`id `** a unique string id for this source. (e.g. `'my source'`)
* **`getContentFunc `** a [callback](http://php.net/manual/en/language.pseudo-types.php) that returns the content. The function is only called when the cache is rebuilt.
* **`contentType `** `Minify::TYPE_JS` or `Minify::TYPE_CSS`
* **`lastModified `** a timestamp indicating when the content last changed. (If you can't determine this quickly, you can "fake" it using a step function, causing the cache to be periodically rebuilt.)
### Example: Content from a URL
Here we want to fetch javascript from a URL. We don't know when it will change, so we use a stepping expression to re-fetch it every midnight:
```
if (! function_exists('src1_fetch')) {
function src1_fetch() {
return file_get_contents('http://example.org/javascript.php');
}
}
$src1 = new Minify_Source(array(
'id' => 'source1',
'getContentFunc' => 'src1_fetch',
'contentType' => Minify::TYPE_JS,
'lastModified' => ($_SERVER['REQUEST_TIME'] - $_SERVER['REQUEST_TIME'] % 86400),
));
```
If you know that the URL content only depends on a few local files, you can use the maximum of their `mtime`s as the `lastModified` key:
```
...
$src1 = new Minify_Source(array(
'id' => 'source1',
'getContentFunc' => 'src1_fetch',
'contentType' => Minify::TYPE_JS,
'lastModified' => max(
filemtime('/path/to/javascript.php')
,filemtime('/path/to/javascript_input.css')
),
));
```
## Performance Considerations
Be aware that all the code you put in groupsConfig.php will be evaluated upon every request like `/min/g=...`, so make it as light as possible.
If you wish to keep groupsConfig.php "clean", you can alternately create a separate PHP script that manually sets up sources, caching, options, and calls Minify::serve().
```
<?php // myServer.php
/**
* This script implements a Minify server for a single set of sources.
* If you don't want '.php' in the URL, use mod_rewrite...
*/
// setup Minify
set_include_path('path/to/min/lib' . PATH_SEPARATOR . get_include_path());
require 'Minify.php';
require 'Minify/Cache/File.php';
Minify::setCache(new Minify_Cache_File()); // guesses a temp directory
function src1_fetch() {
return file_get_contents('http://example.org/javascript.php');
}
// setup sources
$sources = array();
$sources[] = new Minify_Source(array(
'id' => 'source1'
,'getContentFunc' => 'src1_fetch'
,'contentType' => Minify::TYPE_JS
,'lastModified' => max(
filemtime('/path/to/javascript.php')
,filemtime('/path/to/javascript_input.js')
)
));
$sources[] = '//file2.js';
$sources[] = '//file3.js';
// setup serve options
$options = array(
'files' => $sources,
'maxAge' => 86400,
);
// handle request
Minify::serve('Files', $options);
```

80
docs/Debugging.wiki.md Normal file
View File

@@ -0,0 +1,80 @@
# Server Errors
| **Code** | **Most likely cause** |
|:---------|:----------------------|
| 400 | Controller failed to return valid set of sources to serve |
| 500 | Minifier threw exception (e.g. JSMin choked on syntax) |
You can find details by enabling FirePHP logging:
1. Install/enable [FirePHP](https://addons.mozilla.org/en-US/firefox/addon/6149).
1. Open Firebug's console
1. Set `$min_errorLogger = true;` in min/config.php
1. Reload the Minify URL
Hopefully you'll see the error appear:
```
Minify: Something bad happened!
```
# Javascript/CSS Problems
When Javascript errors occur, or URIs in CSS files are incorrectly rewritten, enable "debug mode" to ease debugging combined files:
1. Set `$min_allowDebugFlag = 'true'` in min/config.php
1. Append `&debug` to the Minify URI. E.g. `/min/?f=script1.js,script2.js&debug` (or use the bookmarklet provided by /min/builder/)
In "debug mode":
* comments are inserted into the output showing you line numbers in the original file(s)
* no minification is performed
* In CSS, URI rewriting _is_ performed
* In CSS, a leading comment shows how URIs were rewritten.
Example: a combination of two Javascript files in debug mode
```
/* firstFile.js */
/* 1 */ (function () {
/* 2 */ if (window.foo) {
...
/* 11 */ })();
;
/* secondFile.js */
/* 1 */ var Foo = window.Foo || {};
/* 2 */
...
```
Example: Top of CSS output in debug mode
```
docRoot : M:\home\foo\www
currentDir : M:\home\foo\www\css
file-relative URI : typography.css
path prepended : M:\home\foo\www\css\typography.css
docroot stripped : \css\typography.css
traversals removed : /css/typography.css
file-relative URI : ../images/bg.jpg
path prepended : M:\home\foo\www\css\..\images\bg.jpg
docroot stripped : \css\..\images\bg.jpg
traversals removed : /images/bg.jpg
```
### Tips for handling Javascript errors
* Use the latest version (2.1.4 beta as of Dec 2010)
* Try [debug mode](#Javascript/CSS_Problems.md) to make the combined file more readable (and error locations findable)
* Find out if other browsers have the same error
* For pre-minified files, make the filenames end in `.min.js` or `-min.js`, which will prevent Minify from altering them
* Test your scripts in [JSLint](http://www.jslint.com/).
## See Also
* CommonProblems

79
docs/FAQ.wiki.md Normal file
View File

@@ -0,0 +1,79 @@
## Why do the CSS & HTML minifiers add so many line breaks?
TL;DR: Ignore them. They don't add to the output size and if you absolutely want all content on one line you will have to use another tool.
It's [rumored](https://github.com/yui/yuicompressor/blob/master/doc/README#L43) that some source control tools and old browsers don't like very long lines. Compressed files with shorter lines are also easier to diff.
Since both Minify classes are regex-based, it would be very difficult/error-prone to count characters then try to re-establish context to add line breaks. Instead, both classes trade 1 space for 1 line break (`\n`) wherever possible, adding breaks but without adding bytes.
If you can think of another safe & efficient way to limit lines in these two tools without adding bytes, please submit a patch, but this is not something anyone should be worrying about.
## Minify doesn't compress as much as product XYZ. Why not?
Out of the box, Minify uses algorithms available in PHP, which frankly aren't as solid as competing products, but I consider them _good enough_. At this point I don't have time to work on further tweaking, so if you must have _perfect_ minification you can explore the CookBook to plug in other minifiers. If you'd like to propose specific tweaks in the algorithm (and don't have a patch), please propose these in the Google Group, not the issue tracker.
## How fast is it?
With Minify you will ideally serve _fewer_ requests, but Minify can be slower than your HTTPd serving flat files. If you have a high-traffic site with hundreds of simultaneous requests from new users, you should probably:
* Use the [APC/Memcache adapters](CookBook.md).
* Revision your Minify URIs (so far-off Expires headers will be sent). One way to do this is using [predefined groups](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/README.txt#69) and the [Minify\_groupUri()](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/utils.php#13) utility function.
* Place your HTTPd behind a [reverse proxy](http://www.squid-cache.org/Intro/why.dyn) to cache the Minify URLs.
* Benchmark Minify on your development server before rolling out to production.
### Will it get faster?
Ideally, but a couple [other goals](ProjectGoals.md) come first. For Apache users we're designing a feature to enable [minified and pre-encoded files to be served directly from the HTTPd](http://mrclay.org/index.php/2008/05/25/apache-http-encoding-negotiation-notes/). Requests will not execute PHP at all and be blazingly fast (for varying definitions of "blazingly").
## How does it compare with other services?
Yahoo's [Combo Handler](http://yuiblog.com/blog/2008/07/16/combohandler/) and Google's [AJAX Libraries API](http://code.google.com/apis/ajaxlibs/) both serve content from their heavy-duty [CDN](http://en.wikipedia.org/wiki/Content_Delivery_Network)s and _potentially_ increase the chance that your visitor will already have a file in her browser cache. Neither service serves custom content that you provide. You may wish to use these services to serve popular libraries and Minify to serve your code.
## Is this where I get support for...
If you get a link to this page in response to a request for help, please make sure that you're using the software downloaded from [this project](http://code.google.com/p/minify/) (or [on github](https://github.com/mrclay/minify)), and have followed the [directions](UserGuide.md).
There are many projects with "minify" in the title/description but don't have anything to do with this project, or which many only use a few [components](ComponentClasses.md) from this project.
Although you may be able to get support for usage of the components, the [Google Group](http://groups.google.com/group/minify) members/project owners may not be able to offer any helpful advice with unrelated projects.
## Does it support gzip compression?
Yes. Based on the browser's Accept-Encoding header, Minify will serve content encoded with deflate or gzip.
## Does it work with PHP opcode caches like APC and eAccelerator?
Of course, and you can also use [APC for content caching](CookBook.md).
## Can it minify remote files/the output of dynamic scripts?
[Yes](http://code.google.com/p/minify/wiki/CustomSource#Non-File_Sources), but it's not a straightforward setup, and probably best avoided.
## Is there a minifier for HTML?
Yes, but only in the form of a PHP class: [Minify\_HTML](http://code.google.com/p/minify/source/browse/min/lib/Minify/HTML.php).
It also can accept callbacks to minify embedded STYLE and SCRIPT elements.
Since Minify\_HTML is not fast, there's no _easy way_ to integrate it into dynamic pages, and you'll have to search the archives for ideas of how to use it. One opportunity would be when storing HTML (assuming writes are infrequent); e.g., in a DB keep one copy for editing and one minified for serving.
Minify is not suited for _serving_ HTML pages on a site, though it can be done for small numbers of static pages. Look the the [Page controller](http://code.google.com/p/minify/source/browse/min/lib/Minify/Controller/Page.php).
## How does it ensure that the client can't request files it shouldn't have access to?
In 2.1, by default, Minify allows files to be specified using the URI, or using pre-configured sets of files. With URI-specified files, Minify is [very careful](Security.md) to serve only JS/CSS files that are already public on your server, but if you hide public directories--with .htaccess, e.g.--Minify can't know that. Obvious Tip: don't put sensitive info in JS/CSS files inside DOC\_ROOT :)
An included option can disable URI-specified files so Minify will serve only the pre-configured file sets.
## Is it used in production by any large-scale websites?
I'd love to know. 2.1.1 had 54K downloads and I know the library is powering several [plugins](http://mrclay.org/index.php/2009/01/10/minify-getting-out-there/) these days, at least 3 for WordPress.
## Can I use it with my commercial website or product?
Yes. Minify is distributed under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php), which means that you're free to use, modify, and redistribute Minify or derivative works thereof, even for commercial purposes, as long as you comply with a few simple requirements. See the [LICENSE.txt](http://code.google.com/p/minify/source/browse/LICENSE.txt) file for details.
## How can I tell if my server cache is working?
The easiest way is to place a Minify URL directly in your browser's address bar and refresh (F5), which should override the client-side caching that Minify specifies and force Minify to send you a complete response. With cache working, this response should take 100ms or so. Without cache, multiple seconds. (You can get accurate response times using an HTTP inspector like Firebug.)
If you have file access to the server you can check your cache path directly for filenames beginning with "minify

14
docs/MinApp.wiki.md Normal file
View File

@@ -0,0 +1,14 @@
"Min" is the application included in Minify that handles requests to `http://example.com/min/` and responds with compressed/combined content.
When the documentation refers to "Minify" it usually means this application, but sometimes refers to the ComponentClasses.
User-configurable files:
* `/min/config.php`: general configuration
* `/min/groupsConfig.php`: configuration of pre-defined groups of files
Other files of interest:
* `/min/.htaccess`: rewrites URLs for the front controller
* `/min/index.php`: front controller
* `/min/lib/Minify/Controller/MinApp.php`: determines which files are combined based on `$_GET`, sets some default options

View File

@@ -0,0 +1,19 @@
# Unit Testing
0. If you haven't already, install Minify using the UserGuide.
1. Copy the "min\_unit\_tests" directory directly into your DOCUMENT\_ROOT.
2. Browse to http://example.com/min_unit_tests/test_all.php
You should see a list of "PASS"es. You can run the individual test PHP files in http://example.com/min_unit_tests/ for more verbose output.
## Common Problems
### !WARN: environment : Local HTTP request failed. Testing cannot continue.
[test\_environment.php](http://code.google.com/p/minify/source/browse/min_unit_tests/test_environment.php) makes a few local HTTP requests to sniff for `zlib.output_compression` and other auto-encoding behavior, which may break Minify's output. This warning will appear if `allow_url_fopen` is disabled in php.ini, but **does not** necessarily mean there is a problem.
If Minify seems to work fine, ignore the warning. If Minify produces garbled output, enable `allow_url_fopen` in php.ini and re-run the tests. The tests may be able to tell you if PHP or your server is automatically encoding output.
Unless you need it in other scripts, disable `allow_url_fopen` once the issue is resolved. Minify does not need it.

73
docs/UriRewriting.wiki.md Normal file
View File

@@ -0,0 +1,73 @@
## Default operation
Minify uses an algorithm to rewrite relative URIs in CSS output to root-relative URIs so that each link points to the same location it did in its original file.
Say your style sheet `http://example.org/theme/fashion/style.css` contains:
```
body { background: url(bg.jpg); }
```
When Minify serves this content (from `http://example.org/min/f=theme/fashion/style.css` or `http://example.org/min/g=css`) it re-writes the URI so the image is correctly linked:
```
body{background:url(/theme/fashion/bg.jpg)}
```
You can see the steps used to rewrite your URIs by enabling [debug mode](Debugging.md).
## Disable Rewriting
You can disable the automatic rewriting by setting this in min/config.php:
```
$min_serveOptions['rewriteCssUris'] = false;
```
## Manual Rewriting
You can manually rewrite relative URIs in CSS in a couple ways. The simplest is to prepend a string to each relative URI:
```
$min_serveOptions['rewriteCssUris'] = false;
$min_serveOptions['minifierOptions']['text/css']['prependRelativePath'] = '/css/';
```
Or you can run the minified output through a custom [post-processor](CookBook#Processing_Output_After_Minification.md) function.
## Document Root Confusion
Out-of-the-box, Minify gets confused when `min` is placed in a subdirectory of the real document root. There's now a [simple workaround](AlternateFileLayouts.md) for this, making `min` more portable.
## Aliases / Symlinks / Virtual Directories
Whether you use [aliases](http://httpd.apache.org/docs/2.2/mod/mod_alias.html), [symlinks](http://en.wikipedia.org/wiki/Symbolic_link), or [virtual directories](http://msdn.microsoft.com/en-us/library/zwk103ab.aspx), if you make content outside of the DOC\_ROOT available at public URLs, Minify may need manual configuration of the `$min_symlinks` option to rewrite some URIs correctly. Consider this scenario, where `http://example.org/static/style.css` will serve `/etc/static_content/style.css`:
| document root | `/var/www` |
|:------------------|:--------------------------------------------|
| Apache mod\_alias | `Alias /static /etc/static_content` |
| ...or symlink | `ln -s /etc/static_content /var/www/static` |
In `/min/config.php` you'll need the following:
```
// map URL path to file path
$min_symlinks = array(
'//static' => '/etc/static_content'
);
```
This lets Minify know during the rewriting process that an internal file path starting with `/etc/static_content` should be rewritten as a public URI beginning with `/static`.
If your alias target directory is outside of DOC\_ROOT, you'll also need to explicitly allow Minify to serve files from it:
```
$min_serveOptions['minApp']['allowDirs'] = array(
'//', // allow from the normal DOC_ROOT
'/etc/static_content' // allow from our alias target
);
```
### What's my document root?
You can enable the script `min/server-info.php` and open http://example.org/min/server-info.php to find useful `$_SERVER` values. People in the [Google Group](https://groups.google.com/forum/#!forum/minify) might need these to help you.
## It's still not working
1. Make sure you have the [latest version](http://code.google.com/p/minify/downloads/list).
1. Enable [debug mode](Debugging.md), which will show you the URI transformation process.
1. Check that `$_SERVER['DOCUMENT_ROOT']` is a real directory path. If not, URI rewriting will fail. If you cannot fix this in httpd.conf, etc., use the [configuration option](http://code.google.com/p/minify/source/browse/min/config.php?r=292#47).
1. Paste your [debug mode](Debugging.md) comment block into a new post on the [minify mailing list](http://groups.google.com/group/minify).

48
docs/UserGuide.wiki.md Normal file
View File

@@ -0,0 +1,48 @@
If this page doesn't help, please post a question on our [Google group](http://groups.google.com/group/minify).
# Installing Minify for the first time
1. Clone the [minify git repository](https://github.com/mrclay/minify).
1. The distribution contains a folder "min". Copy this into your DOCUMENT\_ROOT so it is a **direct child** of DOCUMENT\_ROOT (e.g. `http://example.com/min/`). Document roots are usually named `htdocs`, `public_html`, or `www`.
1. Test it can serve content: http://example.com/min/?f=min/quick-test.js and http://example.com/min/?f=min/quick-test.css
1. If you want to use the BuilderApp, you must enable it in `min/config.php`.
Note: The BuilderApp will not function properly in subdirectories, but it's not necessary for Minify's functionality.
Done!
(Optional) See TestingMinify if you'd like to run unit tests.
### Hosting on Lighttpd
Minify comes with Apache mod\_rewrite rules, but this does the same for Lighttpd:
```
url.rewrite-once = ( "^/min/([a-z]=.*)" => "/min/index.php?$1" )
```
# Usage
Enable the BuilderApp via your [config file](https://github.com/mrclay/minify/blob/master/min/config.php#L10). The default password is "admin", but even if no password is used there's very little server information disclosed.
Browse to http://example.com/min/
The Minify URI Builder will help you create URIs you can use to minify existing files on your site. You can see screenshots and get a feel for this process from this [walkthrough on mrclay.org](http://mrclay.org/index.php/2008/09/19/minify-21-on-mrclayorg/)
More info here: https://github.com/mrclay/minify/blob/master/MIN.txt
You may want to disable the BuilderApp when not in use.
# Configuration
[min/config.php](https://github.com/mrclay/minify/blob/master/min/config.php) holds general config options.
[min/groupsConfig.php](https://github.com/mrclay/minify/blob/master/min/groupsConfig.php) holds preset groups of files to minify. (The builder application can help with this).
CookBook shows how to customize settings between production/development environments, and between groups.
CustomSource shows how to set some file/source-specific options, or serve content from a PHP script or URL.
# Problems?
See [CommonProblems](https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md) and [Debugging](https://github.com/mrclay/minify/blob/master/docs/Debugging.wiki.md). You might also try [TestingMinify](https://github.com/mrclay/minify/blob/master/docs/TestingMinify.wiki.md) (running `test_environment.php` in particular).

92
docs/old/History.wiki.md Normal file
View File

@@ -0,0 +1,92 @@
## Version 2.1.5 (2012-03-10)
* Removed XSS vulnerability
* Disabled builder by default
* command line tools to minify and rewrite URIs in CSS
* upgrade (optional) JSMin+ library
* more efficient JS minification when using CC/YUIC
* Closure Compiler uses cURL when allow\_url\_fopen is off
* Missing file notices when using groups
## Version 2.1.4b (2010-07-10)
* Option to minify JS with Closure Compiler API w/ JSMin failover
* Cookie/bookmarklet-based debug mode. No HTML editing!
* Allows 1 file to be missing w/o complete failure
* Combine multiple groups and files in single URI
* More useful HTML helpers for writing versioned URIs
* More detailed error logging, including minifier exceptions
* Builder offers more helpful messages/PHP environment warnings
* Bypass minification based on filename pattern. e.g. foo.min.js / foo-min.css
* JSMin won't choke on common Closure compiler syntaxes (`i+ ++j`)
* Better caching in IE6
* Cache ids are influenced by group/file names
* Debug mode for Javascript doesn't break on common XPath strings (Prototype 1.6)
* Removed annoying maxFiles limit
* mbstring.func\_overload usage is safer
## Version 2.1.3 (2009-06-30)
* CSS fixes
* A few URI rewriting bugs fixed
* comment/whitespace removal no longer breaks some values
* IE6 [pseudo-element selector bug](http://www.crankygeek.com/ie6pebug/) no longer triggered
* HTTP fixes
* Proper Expires handling in webkit (dropped "must-revalidate", which triggered a [webkit bug](http://mrclay.org/index.php/2009/02/24/safari-4-beta-cache-controlmust-revalidate-bug/))
* ETag generation now valid ([must be unique when gzipped](https://issues.apache.org/bugzilla/show_bug.cgi?id=39727))
* Vary header always sent when Accept-Encoding is sniffed
* Dropped deflate encoding, since browser and proxy support [could be buggy](http://stackoverflow.com/questions/883841/).
* File cache now works w/o setting `$min_cachePath`
* No more 5.3 deprecation warnings: `split()` removed
* API: Can set contentType Minify\_Source objects (fixes an annoying [caveat](http://groups.google.com/group/minify/msg/8446d32ee99a4961))
* [Resolved Issue list](http://code.google.com/p/minify/issues/list?can=1&q=label%3ARelease-2.1.2%20status%3AVerified)
## Version 2.1.2 (2009-03-04)
* Javascript fixes
* Debug mode no longer confused by `*/*` in strings/RegExps (jQuery)
* quote characters inside RegExp literals no longer cause exception
* files ending in single-line comments no longer cause code loss
* CSS: data: URLs no longer mangled
* Optional error logging to Firefox's FirePHP extension
* Unit tests to check for common DOCUMENT\_ROOT problems
* DOCUMENT\_ROOT no longer overwritten on IIS servers
* Builder app doesn't fail on systems without gzdeflate()
* APC caching class included
## Version 2.1.1 (2008-10-19)
* Bug fix release
* Detection and workarounds for zlib.output\_compression and non-PHP encoding modules
* Zlib not required (mod\_rewrite, et.al., can still be used for encoding)
* HTML : More IE conditional comments preserved
* Minify\_groupUri() utility fixed
## Version 2.1.0 (2008-09-18)
* "min" default application for quick deployment
* Minify URI Builder app & bookmarklet for quickly creating minify URIs
* Relative URIs in CSS file are fixed automatically by default
* "debug" mode for revealing original line #s in combined files
* Better IIS support
* Improved minifier classes:
* JS: preserves IE conditional comments
* CSS: smaller output, preserves more hacks and valid CSS syntax, shorter line lengths, other bug fixes
* HTML: smaller output, shorter line lengths, other bug fixes
* Default Cache-Control: max-age of 30 minutes
* Conditional GETs supported even when max-age sent
* Experimental memcache cache class (default is files)
* Minify\_Cache\_File has flock()s (by default)
* Workaround for Windows mtime reporting bug
## Version 2.0.0 (2008-05-22)
* Complete code overhaul. Minify is now a PEAR-style class and toolkit for building customized minifying file servers.
* Content-Encoding: deflate/gzip/compress, based on request headers
* Expanded CSS and HTML minifiers with test cases
* Easily plug-in 3rd-party minifiers (like Packer)
* Plug-able front end controller allows changing the way files are chosen
* Compression & encoding modules lazy-loaded as needed (304 responses use minimal code)
* Separate utility classes for HTTP encoding and cache control
## Version 1.0.1 (2007-05-05)
* Fixed various problems resolving pathnames when hosted on an NFS mount.
* Fixed 'undefined constant' notice.
* Replaced old JSMin library with a much faster custom implementation.
## Version 1.0.0 (2007-05-02)
* First release.

View File

@@ -0,0 +1,31 @@
### Browsers, trust your cache
In all responses a `Cache-Control` header is sent, telling the browser it doesn't need to "check in" with the server for some period of time. The ideal request is the one that never leaves the browser!
### Convert a request to source objects
When the browser makes a request like `/min/g=css`, Apache rewrites this to `/min/index.php?g=css`, which calls Minify's front controller.
A separate controller then uses the querystring to establish a "sources" array, specifying exactly which objects (usually files) are to be included in the final output.
### Try browser cache
Minify finds the latest modification time of all the source objects (`filemtime` for files, so if you use a tool that doesn't update this, you might need to `touch` your modified files).
If the browser has sent an `If-Modified-Since` header, and it's valid (the given date is older than the most recent source), then a 304 header is returned, execution stops, and the browser uses its cache copy.
### Try server cache
Minify generates a unique cache ID for the particular set of sources and their options. This is used to maintain a cache (file usually) of the final output.
If the cache is "valid" (younger than the most recently modified source), then its content is sent along with a `Last-Modified` header with the most recent source's modification time, and execution stops.
### Minification has to be done
If any source is younger than the cache, the cache must be rebuilt from the minification process (slow, but infrequently done):
Minify processes each source with a "minifier" function (determined by the content type of the sources and source-specific options), combines them to a single string, saves this to the cache object, then serves it with the `Last-Modified` header as sbove.
#### Content encoding
Minify actually stores a gzipped version of each output in a second cache object. If the browser supports it, Minify streams the pre-compressed content straight from cache (disk usually) to the browser.

View File

@@ -0,0 +1,63 @@
# HTTP Caching in Minify
## Conditional GET
Minify sends all files with Last-Modified and ETag headers. If the browser requests a file again it will send along If-Modified-Since and If-None-Match headers. Minify checks these headers and, if the browser has the latest version, sends back only a slim "304 Not Modified" response (no content), telling the browser to use its cached file.
## Expires Header
Minify also sends Expires and Cache-Control: max-age headers, indicating that the file should be considered valid for a period of time. In future page views the browser will not re-request the file (unless the user refreshes), and instead will use the cached version.
By default, Minify sends an Expires header for 1800 seconds (30 minutes) into the future (configurable via `$min_serveOptions['maxAge']`). This means your file changes may not be seen by users immediately after you make them. If your changes must be seen immediately, you should reduce max-age to 0, but note you will not get as much benefit, as browsers will still have to send requests **every time**.
## Far-off Expires
When pre-set groups are used and a number is appended to the minify URI (e.g. `/min/g=css&456`), then Minify sends an Expires date of 1 year in the future. This is great for caching, but places responsibility on your HTML pages. They _must_ change the number whenever a JS/CSS source file is updated, or the browser will not know to re-request the file. If you're generating your page with PHP, the [Minify\_groupUri](http://code.google.com/p/minify/source/browse/min/utils.php?r=222#11) utility function can make this easier to manage.
# Using `HTTP_ConditionalGet` in other projects
Minify uses the PHP class [HTTP\_ConditionalGet](http://code.google.com/p/minify/source/browse/lib/HTTP/ConditionalGet.php) to implement the conditional GET model. To use this in your own project you'll need the last modification time of your content (for a file, use [filemtime()](http://www.php.net/filemtime)), or a short hash digest of the content (something that changes when the content changes). You'll also want to consider if the content can be stored in public caches, or should only be stored in the user's browser.
## When the last modification time is known
In this example we implement conditional GET for a mostly-static PHP script. The browser needs to redownload the content only when the file is updated.
```
// top of file
$cg = new HTTP_ConditionalGet(array(
'isPublic' => true,
'lastModifiedTime' => filemtime(__FILE__)
));
$cg->sendHeaders();
if ($cg->cacheIsValid) { // 304 already sent
exit();
}
// rest of script
```
For the first request the browser's cache won't be valid, so the full script will execute, sending the full content. On the next, the cache will be valid and the sendHeaders() method will have already set the 304 header, so the script can be halted.
There's also a shortcut static method for this:
```
HTTP_ConditionalGet::check(filemtime(__FILE__), true); // exits if client has cache
// rest of script
```
## When last modification time isn't known
Let's say you have an HTML page in a database, but no modification time. To reduce DB requests, you cache this content in a file/memory, but you'd also like to reduce bandwidth. In this case, what you can do is also cache a hash of the page along with the content. Now you can do this:
```
$cache = getCache();
$cg = new HTTP_ConditionalGet(array(
'isPublic' => true,
'contentHash' => $cache['hash']
));
$cg->sendHeaders();
if ($cg->cacheIsValid) { // 304 already sent
exit();
}
echo $cache['page'];
```
Although Last-Modified cannot be set, ETag will serve the same purposes in most browsers, allowing the conditional GET.

View File

@@ -0,0 +1,13 @@
## 1. Be easy to implement
A PHP user should be able to quickly start serving JS/CSS much more optimally.
## 2. Be extensible/versatile
The user should be able to work Minify into an environment without modifying Minify's source. Right now this should be easy on the controller side, but the Minify class is static, which is fast, but may hinder extensibility.
## 3. Be fast as possible
With the release of 2.0.2 Minify will be much faster, outperforming even Apache's mod\_deflate (which apparently doesn't cache the encoded content like mod\_gzip does).
Since testing has shown that [pre-encoding files and using type-maps on Apache is blazingly fast](http://mrclay.org/index.php/2008/06/03/pre-encoding-vs-mod_deflate/), Minify should work towards maintaining builds of pre-encoded files and letting Apache serve them. It's not clear if there's something similar to type-maps on lighttpd, but it's worth looking into.

15
docs/old/Security.wiki.md Normal file
View File

@@ -0,0 +1,15 @@
This was quickly converted from an e-mail, please consider it "temporary".
## Each file specified by `$_GET['f']` must:
* Have the [same extension, either "css" or "js"](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/Minify/Controller/MinApp.php#66),
* Exist, and...
* Have a [realpath() within a whitelist of subdirectories](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/Minify/Controller/Base.php#122).
The default whitelist contains only DOCUMENT\_ROOT, but can be [specified](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/config.php#57).
Then, a few more steps just to be paranoid:
* If a base was given by `$_GET['b']`, [it can't have ".."](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/Minify/Controller/MinApp.php#84).
* `$_GET['f']` [must not contain "//", "\", or "./"](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/Minify/Controller/MinApp.php#64).
* There can be [no duplicates](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/Minify/Controller/MinApp.php#77) and only a [limited number of files](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/config.php#73) can be specified.

View File

@@ -0,0 +1,35 @@
# Minify 2
[Minify 2.0.0](http://code.google.com/p/minify/source/browse/tags/release_2.0.0/) was released May 22, 2008 and represents an architectural redesign of Minify's code and its usage. 2.0 is built as a library of classes allowing users to easily build customized minified-file servers; or add minification, HTTP encoding, or [conditional GET](http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers) to existing projects.
The release includes 3 [example sites](http://code.google.com/p/minify/source/browse/tags/release_2.0.0/web/examples) to demostrate usage and [unit tests](http://code.google.com/p/minify/source/browse/tags/release_2.0.0/web/test/) you can run on your system.
## Documentation
Each PHP file is documented, but, for now, the [README file](http://code.google.com/p/minify/source/browse/tags/release_2.0.0/README) is the best reference for getting started with the library. This [blog post](http://mrclay.org/index.php/2008/03/27/minifying-javascript-and-css-on-mrclayorg/) may also give you some ideas.
The best place for questions is the [minify Google group](http://groups.google.com/group/minify).
### Included HTTP Classes
The two HTTP utility classes, [HTTP\_ConditionalGet](http://code.google.com/p/minify/source/browse/lib/HTTP/ConditionalGet.php) and [HTTP\_Encoder](http://code.google.com/p/minify/source/browse/lib/HTTP/Encoder.php), are already fairly well-tested and include a set of test pages to see how they work. On the [Florida Automated Weather Network](http://fawn.ifas.ufl.edu/) site, these are used especially in scripts that serve data to our Flash components.
Here's an example of using both to conditionally serve a text file gzipped:
```
$cg = new HTTP_ConditionalGet(array(
'lastModifiedTime' => filemtime($filepath)
,'isPublic' => true
));
$cg->sendHeaders();
if ($cg->cacheIsValid) {
// client cache was valid, no content needed
exit();
}
require 'HTTP/Encoder.php';
$he = new HTTP_Encoder(array(
'content' => file_get_contents($filepath)
,'type' => 'text/plain'
));
$he->encode();
$he->sendAll();
```

View File

@@ -12,7 +12,7 @@ var MUB = {
$.ajax({
url : '../f=' + testUri + '&' + (new Date()).getTime(),
success : function (data) {
if (data === '1') {
if (data === '1' || data === '1;') {
MUB._minRoot = '/min/';
$('span.minRoot').html('/min/');
} else

View File

@@ -1,4 +1,4 @@
<?php
<?php
/**
* AJAX checks for zlib.output_compression
*
@@ -11,7 +11,7 @@ $_oc = ini_get('zlib.output_compression');
require dirname(__FILE__) . '/../config.php';
if (! $min_enableBuilder) {
header('Location: /');
exit();
exit;
}
if (isset($_GET['hello'])) {
@@ -26,8 +26,8 @@ if (isset($_GET['hello'])) {
'content' => 'World!'
,'method' => 'deflate'
));
$he->encode();
$he->sendAll();
$he->encode();
$he->sendAll();
} else {
// echo status "0" or "1"

View File

@@ -1,5 +1,5 @@
<?php
exit();
exit;
/* currently unused.
// capture PHP's default setting (may get overridden in config
@@ -8,7 +8,7 @@ $_oc = ini_get('zlib.output_compression');
// allow access only if builder is enabled
require dirname(__FILE__) . '/../config.php';
if (! $min_enableBuilder) {
exit();
exit;
}
if (isset($_GET['oc'])) {

View File

@@ -12,6 +12,13 @@
*/
$min_enableBuilder = false;
/**
* Concatenate but do not minify the files. This can be used for testing.
*/
$min_concatOnly = false;
/**
* If non-empty, the Builder will be protected with HTTP Digest auth.
* The username is "admin".
@@ -52,11 +59,20 @@ $min_allowDebugFlag = false;
//$min_cachePath = 'c:\\WINDOWS\\Temp';
//$min_cachePath = '/tmp';
//$min_cachePath = preg_replace('/^\\d+;/', '', session_save_path());
/**
* Path to Minify's lib folder. If you happen to move it, change
* this accordingly.
*/
$min_libPath = dirname(__FILE__) . '/lib';
/**
* To use APC/Memcache/ZendPlatform for cache storage, require the class and
* set $min_cachePath to an instance. Example below:
*/
//require dirname(__FILE__) . '/lib/Minify/Cache/APC.php';
//require "$min_libPath/Minify/Cache/APC.php";
//$min_cachePath = new Minify_Cache_APC();
@@ -179,12 +195,5 @@ $min_symlinks = array();
$min_uploaderHoursBehind = 0;
/**
* Path to Minify's lib folder. If you happen to move it, change
* this accordingly.
*/
$min_libPath = dirname(__FILE__) . '/lib';
// try to disable output_compression (may not have an effect)
ini_set('zlib.output_compression', '0');

View File

@@ -52,6 +52,10 @@ if ($min_allowDebugFlag) {
$min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']);
}
if (!empty($min_concatOnly)) {
$min_serveOptions['concatOnly'] = true;
}
if ($min_errorLogger) {
if (true === $min_errorLogger) {
$min_errorLogger = FirePHP::getInstance(true);
@@ -74,13 +78,15 @@ if (isset($_GET['g'])) {
if (isset($_GET['f']) || isset($_GET['g'])) {
if (! isset($min_serveController)) {
$min_serveController = new Minify_Controller_MinApp();
}
}
Minify::serve($min_serveController, $min_serveOptions);
} elseif ($min_enableBuilder) {
header('Location: builder/');
exit();
exit;
} else {
header("Location: /");
exit();
header('Location: /');
exit;
}

View File

@@ -1,7 +1,7 @@
<?php
/*!
* cssmin.php 2.4.8-2
* cssmin.php v2.4.8-4
* Author: Tubal Martin - http://tubalmartin.me/
* Repo: https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port
*
@@ -107,7 +107,7 @@ class CSSmin
$l = strlen($css);
// if the number of characters is 25000 or less, do not chunk
// if the number of characters is 5000 or less, do not chunk
if ($l <= $css_chunk_length) {
$css_chunks[] = $css;
} else {
@@ -291,7 +291,7 @@ class CSSmin
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
$css = preg_replace_callback('/(?:^|\})(?:(?:[^\{\:])+\:)+(?:[^\{]*\{)/', array($this, 'replace_colon'), $css);
$css = preg_replace_callback('/(?:^|\})[^\{]*\s+\:/', array($this, 'replace_colon'), $css);
// Remove spaces before the things that should not have spaces before them.
$css = preg_replace('/\s+([\!\{\}\;\:\>\+\(\)\]\~\=,])/', '$1', $css);
@@ -336,11 +336,13 @@ class CSSmin
// to avoid issues on Symbian S60 3.x browsers.
$css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css);
// Replace 0 length units 0(px,em,%) with 0.
$css = preg_replace('/(^|[^0-9])(?:0?\.)?0(?:em|ex|ch|rem|vw|vh|vm|vmin|cm|mm|in|px|pt|pc|%|deg|g?rad|m?s|k?hz)/iS', '${1}0', $css);
// Replace 0 <length> and 0 <percentage> values with 0.
// <length> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/length
// <percentage> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/percentage
$css = preg_replace('/([^\\\\]\:|\s)0(?:em|ex|ch|rem|vw|vh|vm|vmin|cm|mm|in|px|pt|pc|%)/iS', '${1}0', $css);
// 0% step in a keyframe? restore the % unit
$css = preg_replace_callback('/(@[a-z\-]*?keyframes[^\{]*?\{)(.*?\}\s*\})/iS', array($this, 'replace_keyframe_zero'), $css);
$css = preg_replace_callback('/(@[a-z\-]*?keyframes[^\{]+\{)(.*?)(\}\})/iS', array($this, 'replace_keyframe_zero'), $css);
// Replace 0 0; or 0 0 0; or 0 0 0 0; with 0.
$css = preg_replace('/\:0(?: 0){1,3}(;|\}| \!)/', ':0$1', $css);
@@ -596,7 +598,7 @@ class CSSmin
private function replace_keyframe_zero($matches)
{
return $matches[1] . preg_replace('/0\s*,/', '0%,', preg_replace('/\s*0\s*\{/', '0%{', $matches[2]));
return $matches[1] . preg_replace('/0(\{|,[^\)\{]+\{)/', '0%$1', $matches[2]) . $matches[3];
}
private function rgb_to_hex($matches)
@@ -764,12 +766,12 @@ class CSSmin
{
if (is_string($size)) {
switch (substr($size, -1)) {
case 'M': case 'm': return $size * 1048576;
case 'K': case 'k': return $size * 1024;
case 'G': case 'g': return $size * 1073741824;
case 'M': case 'm': return (int) $size * 1048576;
case 'K': case 'k': return (int) $size * 1024;
case 'G': case 'g': return (int) $size * 1073741824;
}
}
return (int) $size;
}
}
}

View File

@@ -23,6 +23,8 @@
* @version $Id: DooDigestAuth.php 1000 2009-07-7 18:27:22
* @package doo.auth
* @since 1.0
*
* @deprecated 2.3 This will be removed in Minify 3.0
*/
class DooDigestAuth{

File diff suppressed because it is too large Load Diff

View File

@@ -108,6 +108,11 @@ class JSMin {
$mbIntEnc = mb_internal_encoding();
mb_internal_encoding('8bit');
}
if (isset($this->input[0]) && $this->input[0] === "\xef") {
$this->input = substr($this->input, 3);
}
$this->input = str_replace("\r\n", "\n", $this->input);
$this->inputLength = strlen($this->input);
@@ -271,37 +276,39 @@ class JSMin {
protected function isRegexpLiteral()
{
if (false !== strpos("(,=:[!&|?+-~*{;", $this->a)) {
// we obviously aren't dividing
// we can't divide after these tokens
return true;
}
// we have to check for a preceding keyword, and we don't need to pattern
// match over the whole output.
$recentOutput = substr($this->output, -10);
// check if return/typeof directly precede a pattern without a space
foreach (array('return', 'typeof') as $keyword) {
if ($this->a !== substr($keyword, -1)) {
// certainly wasn't keyword
continue;
}
if (preg_match("~(^|[\\s\\S])" . substr($keyword, 0, -1) . "$~", $recentOutput, $m)) {
if ($m[1] === '' || !$this->isAlphaNum($m[1])) {
return true;
}
// check if first non-ws token is "/" (see starts-regex.js)
$length = strlen($this->output);
if ($this->a === ' ' || $this->a === "\n") {
if ($length < 2) { // weird edge case
return true;
}
}
// check all keywords
if ($this->a === ' ' || $this->a === "\n") {
if (preg_match('~(^|[\\s\\S])(?:case|else|in|return|typeof)$~', $recentOutput, $m)) {
if ($m[1] === '' || !$this->isAlphaNum($m[1])) {
return true;
}
}
// if the "/" follows a keyword, it must be a regexp, otherwise it's best to assume division
$subject = $this->output . trim($this->a);
if (!preg_match('/(?:case|else|in|return|typeof)$/', $subject, $m)) {
// not a keyword
return false;
}
return false;
// can't be sure it's a keyword yet (see not-regexp.js)
$charBeforeKeyword = substr($subject, 0 - strlen($m[0]) - 1, 1);
if ($this->isAlphaNum($charBeforeKeyword)) {
// this is really an identifier ending in a keyword, e.g. "xreturn"
return false;
}
// it's a regexp. Remove unneeded whitespace after keyword
if ($this->a === ' ' || $this->a === "\n") {
$this->a = '';
}
return true;
}
/**

View File

@@ -170,7 +170,9 @@ define('KEYWORD_VOID', 'void');
define('KEYWORD_WHILE', 'while');
define('KEYWORD_WITH', 'with');
/**
* @deprecated 2.3 This will be removed in Minify 3.0
*/
class JSMinPlus
{
private $parser;
@@ -197,6 +199,8 @@ class JSMinPlus
public static function minify($js, $filename='')
{
trigger_error(__CLASS__ . ' is deprecated. This will be removed in Minify 3.0', E_USER_DEPRECATED);
static $instance;
// this is a singleton

View File

@@ -124,6 +124,9 @@ class Minify {
* '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
@@ -251,11 +254,21 @@ class Minify {
$headers = $cg->getHeaders();
unset($cg);
}
if (self::$_options['contentType'] === self::TYPE_CSS
&& self::$_options['rewriteCssUris']) {
foreach($controller->sources as $key => $source) {
if ($source->filepath
if (self::$_options['concatOnly']) {
foreach ($controller->sources as $key => $source) {
if (self::$_options['contentType'] === self::TYPE_JS) {
$source->minifier = "";
} elseif (self::$_options['contentType'] === self::TYPE_CSS) {
$source->minifier = array('Minify_CSS', 'minify');
$source->minifyOptions['compress'] = false;
}
}
}
if (self::$_options['contentType'] === self::TYPE_CSS && self::$_options['rewriteCssUris']) {
foreach ($controller->sources as $key => $source) {
if ($source->filepath
&& !isset($source->minifyOptions['currentDir'])
&& !isset($source->minifyOptions['prependRelativePath'])
) {
@@ -435,7 +448,7 @@ class Minify {
header('Content-Type: text/html; charset=utf-8');
echo "<h1>$h1</h1>";
echo "<p>Please see <a href='$url'>$url</a>.</p>";
exit();
exit;
}
/**
@@ -493,7 +506,7 @@ class Minify {
// get next source
$source = null;
if ($i < $l) {
$source = self::$_controller->sources[$i];
$source = self::$_controller->sources[$i];
/* @var Minify_Source $source */
$sourceContent = $source->getContent();

View File

@@ -66,16 +66,20 @@ class Minify_CSS_UriRewriter {
self::$debugText .= "\n";
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
// rewrite
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
,array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/'
,array(self::$className, '_processUriCB'), $css);
$css = self::_unOwlify($css);
return $css;
}
/**
* In CSS content, prepend a path to relative URIs
*
@@ -90,6 +94,8 @@ class Minify_CSS_UriRewriter {
self::$_prependPath = $path;
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
// append
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
@@ -97,6 +103,8 @@ class Minify_CSS_UriRewriter {
$css = preg_replace_callback('/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/'
,array(self::$className, '_processUriCB'), $css);
$css = self::_unOwlify($css);
self::$_prependPath = null;
return $css;
}
@@ -282,6 +290,11 @@ class Minify_CSS_UriRewriter {
? $m[1]
: substr($m[1], 1, strlen($m[1]) - 2);
}
if ($uri === '') {
return $m[0];
}
// if not root/scheme relative and not starts with scheme
if (!preg_match('~^(/|[a-z]+\:)~', $uri)) {
// URI is file-relative: rewrite depending on options
@@ -304,4 +317,30 @@ class Minify_CSS_UriRewriter {
? "@import {$quoteChar}{$uri}{$quoteChar}"
: "url({$quoteChar}{$uri}{$quoteChar})";
}
/**
* Mungs some inline SVG URL declarations so they won't be touched
*
* @link https://github.com/mrclay/minify/issues/517
* @see _unOwlify
*
* @param string $css
* @return string
*/
private static function _owlifySvgPaths($css) {
return preg_replace('~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)url(\(\s*#\w+\s*\))~', '$1owl$2', $css);
}
/**
* Undo work of _owlify
*
* @see _owlifySvgPaths
*
* @param string $css
* @return string
*/
private static function _unOwlify($css) {
return preg_replace('~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)owl~', '$1url', $css);
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* Class Minify_Cache_Wincache
* @package Minify
*/
/**
* WinCache-based cache class for Minify
*
* <code>
* Minify::setCache(new Minify_Cache_WinCache());
* </code>
*
* @package Minify
* @author Matthias Fax
**/
class Minify_Cache_WinCache
{
/**
* Create a Minify_Cache_Wincache object, to be passed to
* Minify::setCache().
*
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*/
public function __construct($expire = 0)
{
if (!function_exists('wincache_ucache_info')) {
throw new Exception("WinCache for PHP is not installed to be able to use Minify_Cache_WinCache!");
}
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return wincache_ucache_set($id, "{$_SERVER['REQUEST_TIME']}|{$data}", $this->_exp);
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
if (!$this->_fetch($id)) {
return false;
}
return (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) ? mb_strlen($this->_data, '8bit') : strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id) ? $this->_data : '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id) ? $this->_data : '';
}
private $_exp = NULL;
// cache of most recently fetched id
private $_lm = NULL;
private $_data = NULL;
private $_id = NULL;
/**
* Fetch data and timestamp from WinCache, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$suc = false;
$ret = wincache_ucache_get($id, $suc);
if (!$suc) {
$this->_id = NULL;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}

View File

@@ -51,6 +51,7 @@ abstract class Minify_Controller_Base {
,'bubbleCssImports' => false
,'quiet' => false // serve() will send headers and output
,'debug' => false
,'concatOnly' => false
// if you override these, the response codes MUST be directly after
// the first space.
@@ -125,7 +126,9 @@ abstract class Minify_Controller_Base {
return true;
}
}
throw new Exception("File '$file' is outside \$allowDirs. If the path is"
$allowDirs = implode(';', array_values($allowDirs));
throw new Exception("File '$file' is outside \$allowDirs ($allowDirs). If the path is"
. " resolved via an alias/symlink, look into the \$min_symlinks option."
. " E.g. \$min_symlinks['/" . dirname($uri) . "'] = '" . dirname($file) . "';");
}
@@ -145,9 +148,7 @@ abstract class Minify_Controller_Base {
/**
* instances of Minify_Source, which provide content and any individual minification needs.
*
* @var array
*
* @see Minify_Source
* @var Minify_Source[]
*/
public $sources = array();

View File

@@ -49,7 +49,6 @@ class Minify_Controller_MinApp extends Minify_Controller_Base {
$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");

View File

@@ -9,6 +9,8 @@
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*
* @deprecated 2.3 This will be removed in Minify 3.0
*/
class Minify_Loader {
public function loadClass($class)
@@ -20,6 +22,9 @@ class Minify_Loader {
}
}
/**
* @deprecated 2.3 This will be removed in Minify 3.0
*/
static public function register()
{
$inst = new self();

View File

@@ -10,7 +10,7 @@
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*
* @todo lose this singleton! pass log object in Minify::serve and distribute to others
* @deprecated 2.3 This will be removed in Minify 3.0
*/
class Minify_Logger {

28
min/server-info.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
/**
* Reports server info useful in configuring the options $min_documentRoot, $min_symlinks,
* and $min_serveOptions['minApp']['allowDirs'].
*
* Change to true to expose this info.
*/
$enabled = false;
///////////////////////
if (!$enabled) {
die('Set $enabled to true to see server info.');
}
header('Content-Type: text/plain');
$file = __FILE__;
$tmp = sys_get_temp_dir();
echo <<<EOD
__FILE__ : $file
SCRIPT_FILENAME : {$_SERVER['SCRIPT_FILENAME']}
DOCUMENT_ROOT : {$_SERVER['DOCUMENT_ROOT']}
SCRIPT_NAME : {$_SERVER['SCRIPT_NAME']}
REQUEST_URI : {$_SERVER['REQUEST_URI']}
Cache directory : $tmp
EOD;

View File

@@ -44,7 +44,7 @@ if (isset($_POST['method']) && $_POST['method'] === 'Minify and serve') {
} catch (Exception $e) {
echo h($e->getMessage());
}
exit();
exit;
}
$tpl = array();

View File

@@ -8,10 +8,16 @@
@import url("/css/foo.css"); /* abs, should not alter */
@import url(/css2/foo.css); /* abs, should not alter */
@import url(foo:bar); /* scheme, should not alter */
@import url(); /* empty, should not alter */
foo {clip-path:url(#c1)} /* inline clip path, should not alter */
foo {clip-path:url(/_test_files/css_uriRewriter/foo.svg#c1)}
foo {mask: url(#c1)} /* should not alter */
foo {-webkit-mask: url(#c1)} /* should not alter */
foo {background:url('/_test_files/css_uriRewriter/bar/foo.png')}
foo {background:url('http://foo.com/css/foo.css');} /* scheme, should not alter */
foo {background:url("//foo.com/css/foo.css");} /* protocol relative, should not alter */
foo {background:url(foo:bar);} /* scheme, should not alter */
foo {background:url("/_test_files/css_uriRewriter/foo bar.jpg");}
foo {background:url("");} /* empty, should not alter */
@import url('/_test_files/css_uriRewriter/foo bar.css');
@import "/_test_files/css_uriRewriter/foo bar.css";

View File

@@ -8,10 +8,16 @@
@import url("/css/foo.css"); /* abs, should not alter */
@import url(/css2/foo.css); /* abs, should not alter */
@import url(foo:bar); /* scheme, should not alter */
@import url(); /* empty, should not alter */
foo {clip-path:url(#c1)} /* inline clip path, should not alter */
foo {clip-path:url(http://cnd.com/A/B/foo.svg#c1)}
foo {mask: url(#c1)} /* should not alter */
foo {-webkit-mask: url(#c1)} /* should not alter */
foo {background:url('http://cnd.com/A/B/bar/foo.png')}
foo {background:url('http://foo.com/css/foo.css');} /* scheme, should not alter */
foo {background:url("//foo.com/css/foo.css");} /* protocol relative, should not alter */
foo {background:url(foo:bar);} /* scheme, should not alter */
foo {background:url("http://cnd.com/A/B/foo bar.jpg");}
foo {background:url("");} /* empty, should not alter */
@import url('http://cnd.com/A/B/foo bar.css');
@import "http://cnd.com/A/B/foo bar.css";

View File

@@ -8,10 +8,16 @@
@import url("/css/foo.css"); /* abs, should not alter */
@import url(/css2/foo.css); /* abs, should not alter */
@import url(foo:bar); /* scheme, should not alter */
@import url(); /* empty, should not alter */
foo {clip-path:url(#c1)} /* inline clip path, should not alter */
foo {clip-path:url(//cnd.com/A/B/foo.svg#c1)}
foo {mask: url(#c1)} /* should not alter */
foo {-webkit-mask: url(#c1)} /* should not alter */
foo {background:url('//cnd.com/A/B/bar/foo.png')}
foo {background:url('http://foo.com/css/foo.css');} /* scheme, should not alter */
foo {background:url("//foo.com/css/foo.css");} /* protocol relative, should not alter */
foo {background:url(foo:bar);} /* scheme, should not alter */
foo {background:url("//cnd.com/A/B/foo bar.jpg");}
foo {background:url("");} /* empty, should not alter */
@import url('//cnd.com/A/B/foo bar.css');
@import "//cnd.com/A/B/foo bar.css";

View File

@@ -8,10 +8,16 @@
@import url("/css/foo.css"); /* abs, should not alter */
@import url(/css2/foo.css); /* abs, should not alter */
@import url(foo:bar); /* scheme, should not alter */
@import url(); /* empty, should not alter */
foo {clip-path:url(#c1)} /* inline clip path, should not alter */
foo {clip-path:url(foo.svg#c1)}
foo {mask: url( #c1 )} /* should not alter */
foo {-webkit-mask: url( #c1 )} /* should not alter */
foo {background:url('bar/foo.png')}
foo {background:url('http://foo.com/css/foo.css');} /* scheme, should not alter */
foo {background:url("//foo.com/css/foo.css");} /* protocol relative, should not alter */
foo {background:url(foo:bar);} /* scheme, should not alter */
foo {background:url("foo bar.jpg");}
foo {background:url("");} /* empty, should not alter */
@import url('foo bar.css');
@import "foo bar.css";

View File

@@ -1,3 +1,2 @@
function testIssue74(){return /'/;}
!function(s){return /^[£$€?.]/.test(s);}();typeof
/ ' /;x=/ [/] /;1/foo;(2)/foo;function(){return/foo/};function(){return typeof/foo/};
function testIssue74(){return/'/;}
!function(s){return/^[£$€?.]/.test(s);}();typeof/ ' /;x=/ [/] /;1/foo;(2)/foo;function(){return/foo/};function(){return typeof/foo/};

View File

@@ -0,0 +1,31 @@
<?php
require_once '_inc.php';
function test_Minify_Cache_WinCache()
{
$prefix = 'Minify_Cache_WinCache : ';
if (! function_exists('wincache_ucache_info')) {
return;
}
$data = str_repeat(md5(time()) . 'í', 100); // 3400 bytes in UTF-8
$id = 'Minify_test_cache';
$cache = new Minify_Cache_WinCache();
assertTrue(true === $cache->store($id, $data), $prefix . 'store');
assertTrue(countBytes($data) === $cache->getSize($id), $prefix . 'getSize');
assertTrue(true === $cache->isValid($id, $_SERVER['REQUEST_TIME'] - 10), $prefix . 'isValid');
ob_start();
$cache->display($id);
$displayed = ob_get_contents();
ob_end_clean();
assertTrue($data === $displayed, $prefix . 'display');
assertTrue($data === $cache->fetch($id), $prefix . 'fetch');
}
test_Minify_Cache_WinCache();

View File

@@ -6,6 +6,7 @@ require 'test_Minify_HTML_Helper.php';
require 'test_Minify_Cache_APC.php';
require 'test_Minify_Cache_File.php';
require 'test_Minify_Cache_Memcache.php';
require 'test_Minify_Cache_WinCache.php';
require 'test_Minify_Cache_ZendPlatform.php';
require 'test_Minify_CSS.php';
require 'test_Minify_CSS_UriRewriter.php';