initial commit

This commit is contained in:
2024-04-29 13:12:44 +05:45
commit 34887303c5
19300 changed files with 5268802 additions and 0 deletions

View File

@ -0,0 +1,26 @@
Copyright (c) 2008 Ryan Grove <ryan@wonko.com>
Copyright (c) 2008 Steve Clay <steve@mrclay.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of this project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,457 @@
<?php
namespace JSMin;
/**
* JSMin.php - modified PHP implementation of Douglas Crockford's JSMin.
*
* <code>
* $minifiedJs = JSMin::minify($js);
* </code>
*
* This is a modified port of jsmin.c. Improvements:
*
* Does not choke on some regexp literals containing quote characters. E.g. /'/
*
* Spaces are preserved after some add/sub operators, so they are not mistakenly
* converted to post-inc/dec. E.g. a + ++b -> a+ ++b
*
* Preserves multi-line comments that begin with /*!
*
* PHP 5 or higher is required.
*
* Permission is hereby granted to use this version of the library under the
* same terms as jsmin.c, which has the following license:
*
* --
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* The Software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* --
*
* @package JSMin
* @author Ryan Grove <ryan@wonko.com> (PHP port)
* @author Steve Clay <steve@mrclay.org> (modifications + cleanup)
* @author Andrea Giammarchi <http://www.3site.eu> (spaceBeforeRegExp)
* @copyright 2002 Douglas Crockford <douglas@crockford.com> (jsmin.c)
* @copyright 2008 Ryan Grove <ryan@wonko.com> (PHP port)
* @license http://opensource.org/licenses/mit-license.php MIT License
* @link http://code.google.com/p/jsmin-php/
*/
class JSMin {
const ORD_LF = 10;
const ORD_SPACE = 32;
const ACTION_KEEP_A = 1;
const ACTION_DELETE_A = 2;
const ACTION_DELETE_A_B = 3;
protected $a = "\n";
protected $b = '';
protected $input = '';
protected $inputIndex = 0;
protected $inputLength = 0;
protected $lookAhead = null;
protected $output = '';
protected $lastByteOut = '';
protected $keptComment = '';
/**
* Minify Javascript.
*
* @param string $js Javascript to be minified
*
* @return string
*/
public static function minify($js)
{
$jsmin = new JSMin($js);
return $jsmin->min();
}
/**
* @param string $input
*/
public function __construct($input)
{
$this->input = $input;
}
/**
* Perform minification, return result
*
* @return string
*/
public function min()
{
if ($this->output !== '') { // min already run
return $this->output;
}
$mbIntEnc = null;
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
$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);
$this->action(self::ACTION_DELETE_A_B);
while ($this->a !== null) {
// determine next command
$command = self::ACTION_KEEP_A; // default
if ($this->a === ' ') {
if (($this->lastByteOut === '+' || $this->lastByteOut === '-')
&& ($this->b === $this->lastByteOut)) {
// Don't delete this space. If we do, the addition/subtraction
// could be parsed as a post-increment
} elseif (! $this->isAlphaNum($this->b)) {
$command = self::ACTION_DELETE_A;
}
} elseif ($this->a === "\n") {
if ($this->b === ' ') {
$command = self::ACTION_DELETE_A_B;
// in case of mbstring.func_overload & 2, must check for null b,
// otherwise mb_strpos will give WARNING
} elseif ($this->b === null
|| (false === strpos('{[(+-!~', $this->b)
&& ! $this->isAlphaNum($this->b))) {
$command = self::ACTION_DELETE_A;
}
} elseif (! $this->isAlphaNum($this->a)) {
if ($this->b === ' '
|| ($this->b === "\n"
&& (false === strpos('}])+-"\'', $this->a)))) {
$command = self::ACTION_DELETE_A_B;
}
}
$this->action($command);
}
$this->output = trim($this->output);
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return $this->output;
}
/**
* ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
* ACTION_DELETE_A = Copy B to A. Get the next B.
* ACTION_DELETE_A_B = Get the next B.
*
* @param int $command
* @throws UnterminatedRegExpException|UnterminatedStringException
*/
protected function action($command)
{
// make sure we don't compress "a + ++b" to "a+++b", etc.
if ($command === self::ACTION_DELETE_A_B
&& $this->b === ' '
&& ($this->a === '+' || $this->a === '-')) {
// Note: we're at an addition/substraction operator; the inputIndex
// will certainly be a valid index
if ($this->input[$this->inputIndex] === $this->a) {
// This is "+ +" or "- -". Don't delete the space.
$command = self::ACTION_KEEP_A;
}
}
switch ($command) {
case self::ACTION_KEEP_A: // 1
$this->output .= $this->a;
if ($this->keptComment) {
$this->output = rtrim($this->output, "\n");
$this->output .= $this->keptComment;
$this->keptComment = '';
}
$this->lastByteOut = $this->a;
// fallthrough intentional
case self::ACTION_DELETE_A: // 2
$this->a = $this->b;
if ($this->a === "'" || $this->a === '"' || $this->a === '`') { // string/template literal
$delimiter = $this->a;
$str = $this->a; // in case needed for exception
for(;;) {
$this->output .= $this->a;
$this->lastByteOut = $this->a;
$this->a = $this->get();
if ($this->a === $this->b) { // end quote
break;
}
if ($delimiter === '`' && $this->a === "\n") {
// leave the newline
} elseif ($this->isEOF($this->a)) {
$byte = $this->inputIndex - 1;
throw new UnterminatedStringException(
"JSMin: Unterminated String at byte {$byte}: {$str}");
}
$str .= $this->a;
if ($this->a === '\\') {
$this->output .= $this->a;
$this->lastByteOut = $this->a;
$this->a = $this->get();
$str .= $this->a;
}
}
}
// fallthrough intentional
case self::ACTION_DELETE_A_B: // 3
$this->b = $this->next();
if ($this->b === '/' && $this->isRegexpLiteral()) {
$this->output .= $this->a . $this->b;
$pattern = '/'; // keep entire pattern in case we need to report it in the exception
for(;;) {
$this->a = $this->get();
$pattern .= $this->a;
if ($this->a === '[') {
for(;;) {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
if ($this->a === ']') {
break;
}
if ($this->a === '\\') {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
}
if ($this->isEOF($this->a)) {
throw new UnterminatedRegExpException(
"JSMin: Unterminated set in RegExp at byte "
. $this->inputIndex .": {$pattern}");
}
}
}
if ($this->a === '/') { // end pattern
break; // while (true)
} elseif ($this->a === '\\') {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
} elseif ($this->isEOF($this->a)) {
$byte = $this->inputIndex - 1;
throw new UnterminatedRegExpException(
"JSMin: Unterminated RegExp at byte {$byte}: {$pattern}");
}
$this->output .= $this->a;
$this->lastByteOut = $this->a;
}
$this->b = $this->next();
}
// end case ACTION_DELETE_A_B
}
}
/**
* @return bool
*/
protected function isRegexpLiteral()
{
if (false !== strpos("(,=:[!&|?+-~*{;", $this->a)) {
// we can't divide after these tokens
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;
}
}
// 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;
}
// 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;
}
/**
* Return the next character from stdin. Watch out for lookahead. If the character is a control character,
* translate it to a space or linefeed.
*
* @return string
*/
protected function get()
{
$c = $this->lookAhead;
$this->lookAhead = null;
if ($c === null) {
// getc(stdin)
if ($this->inputIndex < $this->inputLength) {
$c = $this->input[$this->inputIndex];
$this->inputIndex += 1;
} else {
$c = null;
}
}
if (ord($c) >= self::ORD_SPACE || $c === "\n" || $c === null) {
return $c;
}
if ($c === "\r") {
return "\n";
}
return ' ';
}
/**
* Does $a indicate end of input?
*
* @param string $a
* @return bool
*/
protected function isEOF($a)
{
return ord($a) <= self::ORD_LF;
}
/**
* Get next char (without getting it). If is ctrl character, translate to a space or newline.
*
* @return string
*/
protected function peek()
{
$this->lookAhead = $this->get();
return $this->lookAhead;
}
/**
* Return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character.
*
* @param string $c
*
* @return bool
*/
protected function isAlphaNum($c)
{
return (preg_match('/^[a-z0-9A-Z_\\$\\\\]$/', $c) || ord($c) > 126);
}
/**
* Consume a single line comment from input (possibly retaining it)
*/
protected function consumeSingleLineComment()
{
$comment = '';
while (true) {
$get = $this->get();
$comment .= $get;
if (ord($get) <= self::ORD_LF) { // end of line reached
// if IE conditional comment
if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
$this->keptComment .= "/{$comment}";
}
return;
}
}
}
/**
* Consume a multiple line comment from input (possibly retaining it)
*
* @throws UnterminatedCommentException
*/
protected function consumeMultipleLineComment()
{
$this->get();
$comment = '';
for(;;) {
$get = $this->get();
if ($get === '*') {
if ($this->peek() === '/') { // end of comment reached
$this->get();
if (0 === strpos($comment, '!')) {
// preserved by YUI Compressor
if (!$this->keptComment) {
// don't prepend a newline if two comments right after one another
$this->keptComment = "\n";
}
$this->keptComment .= "/*!" . substr($comment, 1) . "*/\n";
} else if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
// IE conditional
$this->keptComment .= "/*{$comment}*/";
}
return;
}
} elseif ($get === null) {
throw new UnterminatedCommentException(
"JSMin: Unterminated comment at byte {$this->inputIndex}: /*{$comment}");
}
$comment .= $get;
}
}
/**
* Get the next character, skipping over comments. Some comments may be preserved.
*
* @return string
*/
protected function next()
{
$get = $this->get();
if ($get === '/') {
switch ($this->peek()) {
case '/':
$this->consumeSingleLineComment();
$get = "\n";
break;
case '*':
$this->consumeMultipleLineComment();
$get = ' ';
break;
}
}
return $get;
}
}

View File

@ -0,0 +1,6 @@
<?php
namespace JSMin;
class UnterminatedCommentException extends \Exception {
}

View File

@ -0,0 +1,6 @@
<?php
namespace JSMin;
class UnterminatedRegExpException extends \Exception {
}

View File

@ -0,0 +1,6 @@
<?php
namespace JSMin;
class UnterminatedStringException extends \Exception {
}

View File

@ -0,0 +1,92 @@
<?php
require __DIR__ . '/../vendor/autoload.php';
function h($txt) {
return htmlspecialchars($txt, ENT_QUOTES, 'UTF-8');
}
$tpl = array();
if (isset($_POST['textIn'])) {
$textIn = str_replace("\r\n", "\n", $_POST['textIn']);
$tpl['inBytes'] = strlen($textIn);
$startTime = microtime(true);
try {
$tpl['output'] = \JSMin\JSMin::minify($textIn);
} catch (Exception $e) {
$tpl['exceptionMsg'] = getExceptionMsg($e, $textIn);
$tpl['output'] = $textIn;
sendPage($tpl);
}
$tpl['time'] = microtime(true) - $startTime;
$tpl['outBytes'] = strlen($tpl['output']);
}
sendPage($tpl);
/**
* @param Exception $e
* @param string $input
* @return string HTML
*/
function getExceptionMsg(Exception $e, $input) {
$msg = "<p>" . h($e->getMessage()) . "</p>";
if (0 !== strpos(get_class($e), 'JSMin\\Unterminated')
|| !preg_match('~byte (\d+)~', $e->getMessage(), $m)) {
return $msg;
}
$msg .= "<pre>";
if ($m[1] > 200) {
$msg .= h(substr($input, ($m[1] - 200), 200));
} else {
$msg .= h(substr($input, 0, $m[1]));
}
$highlighted = isset($input[$m[1]]) ? h($input[$m[1]]) : '&#9220;';
if ($highlighted === "\n") {
$highlighted = "&#9166;\n";
}
$msg .= "<span style='background:#c00;color:#fff'>$highlighted</span>";
$msg .= h(substr($input, $m[1] + 1, 200)) . "</span></pre>";
return $msg;
}
/**
* Draw page
*
* @param array $vars
*/
function sendPage($vars) {
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html><head><title>JSMin</title></head>
<?php
if (isset($vars['exceptionMsg'])) {
echo $vars['exceptionMsg'];
}
if (isset($vars['time'])) {
echo "
<table>
<tr><th>Bytes in</th><td>{$vars['inBytes']} (after line endings normalized to <code>\\n</code>)</td></tr>
<tr><th>Bytes out</th><td>{$vars['outBytes']} (reduced " . round(100 - (100 * $vars['outBytes'] / $vars['inBytes'])) . "%)</td></tr>
<tr><th>Time (s)</th><td>" . round($vars['time'], 5) . "</td></tr>
</table>
";
}
?>
<form action="?2" method="post">
<p><label>Content<br><textarea name="textIn" cols="80" rows="35" style="width:99%"><?php
if (isset($vars['output'])) {
echo h($vars['output']);
}
?></textarea></label></p>
<p><input type="submit" name="method" value="JSMin::minify()"></p>
</form><?php
exit;
}

View File

@ -0,0 +1,26 @@
Copyright (c) 2008 Ryan Grove <ryan@wonko.com>
Copyright (c) 2008 Steve Clay <steve@mrclay.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of this project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,25 @@
<?php
/**
* Sets up autoloading and returns the Minify\App
*/
call_user_func(function () {
if (is_dir(__DIR__ . '/../../../vendor')) {
// Used as a composer library
$vendorDir = __DIR__ . '/../../../vendor';
} else {
$vendorDir = __DIR__ . '/vendor';
}
$file = $vendorDir . '/autoload.php';
if (!is_file($file)) {
echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
'php composer.phar install'.PHP_EOL;
exit(1);
}
require $file;
});
return new \Minify\App(__DIR__);

View File

@ -0,0 +1,260 @@
/*!
* Minify URI Builder
*/
var MUB = {
_uid : 0,
_minRoot : '/min/?',
checkRewrite : function () {
var testUri = location.pathname.replace(/\/[^\/]*$/, '/rewriteTest.js').substr(1);
function fail() {
$('#minRewriteFailed')[0].className = 'topNote';
}
$.ajax({
url : '../f=' + testUri + '&' + (new Date()).getTime(),
success : function (data) {
if (data === '1' || data === '1;') {
MUB._minRoot = '/min/';
$('span.minRoot').html('/min/');
} else
fail();
},
error : fail
});
},
/**
* Get markup for new source LI element
*/
newLi : function () {
return '<li id="li' + MUB._uid + '">' + location.protocol + '//' + location.host + '/<input type=text size=20>' +
' <button class="btn btn-danger btn-sm" title="Remove">x</button> <button class="btn btn-default btn-sm" title="Include Earlier">&uarr;</button>' +
' <button class="btn btn-default btn-sm" title="Include Later">&darr;</button> <span></span></li>';
},
/**
* Add new empty source LI and attach handlers to buttons
*/
addLi : function () {
$('#sources').append(MUB.newLi());
var li = $('#li' + MUB._uid)[0];
$('button[title=Remove]', li).click(function () {
$('#results').addClass('hide');
var hadValue = !!$('input', li)[0].value;
$(li).remove();
});
$('button[title$=Earlier]', li).click(function () {
$(li).prev('li').find('input').each(function () {
$('#results').addClass('hide');
// this = previous li input
var tmp = this.value;
this.value = $('input', li).val();
$('input', li).val(tmp);
MUB.updateAllTestLinks();
});
});
$('button[title$=Later]', li).click(function () {
$(li).next('li').find('input').each(function () {
$('#results').addClass('hide');
// this = next li input
var tmp = this.value;
this.value = $('input', li).val();
$('input', li).val(tmp);
MUB.updateAllTestLinks();
});
});
++MUB._uid;
},
/**
* In the context of a source LI element, this will analyze the URI in
* the INPUT and check the URL on the site.
*/
liUpdateTestLink : function () { // call in context of li element
if (! $('input', this)[0].value)
return;
var li = this;
$('span', this).html('');
var url = location.protocol + '//' + location.host + '/' +
$('input', this)[0].value.replace(/^\//, '');
$.ajax({
url : url,
complete : function (xhr, stat) {
if ('success' === stat)
$('span', li).html('<a href="#" class="btn btn-success btn-sm disabled">&#x2713;</a>');
else {
$('span', li).html('<button class="btn btn-warning btn-sm"><b>404! </b> recheck</button>')
.find('button').click(function () {
MUB.liUpdateTestLink.call(li);
});
}
},
dataType : 'text'
});
},
/**
* Check all source URLs
*/
updateAllTestLinks : function () {
$('#sources li').each(MUB.liUpdateTestLink);
},
/**
* In a given array of strings, find the character they all have at
* a particular index
* @param Array arr array of strings
* @param Number pos index to check
* @return mixed a common char or '' if any do not match
*/
getCommonCharAtPos : function (arr, pos) {
var i,
l = arr.length,
c = arr[0].charAt(pos);
if (c === '' || l === 1)
return c;
for (i = 1; i < l; ++i)
if (arr[i].charAt(pos) !== c)
return '';
return c;
},
/**
* Get the shortest URI to minify the set of source files
* @param Array sources URIs
*/
getBestUri : function (sources) {
var pos = 0,
base = '',
c;
while (true) {
c = MUB.getCommonCharAtPos(sources, pos);
if (c === '')
break;
else
base += c;
++pos;
}
base = base.replace(/[^\/]+$/, '');
var uri = MUB._minRoot + 'f=' + sources.join(',');
if (base.charAt(base.length - 1) === '/') {
// we have a base dir!
var basedSources = sources,
i,
l = sources.length;
for (i = 0; i < l; ++i) {
basedSources[i] = sources[i].substr(base.length);
}
base = base.substr(0, base.length - 1);
var bUri = MUB._minRoot + 'b=' + base + '&f=' + basedSources.join(',');
//window.console && console.log([uri, bUri]);
uri = uri.length < bUri.length ? uri : bUri;
}
return uri;
},
/**
* Create the Minify URI for the sources
*/
update : function () {
MUB.updateAllTestLinks();
var sources = [],
ext = false,
fail = false,
markup;
$('#sources input').each(function () {
var m, val;
if (! fail && this.value && (m = this.value.match(/\.(css|js)$/))) {
var thisExt = m[1];
if (ext === false)
ext = thisExt;
else if (thisExt !== ext) {
fail = true;
return alert('extensions must match!');
}
this.value = this.value.replace(/^\//, '');
if (-1 !== $.inArray(this.value, sources)) {
fail = true;
return alert('duplicate file!');
}
sources.push(this.value);
}
});
if (fail || ! sources.length)
return;
$('#groupConfig').val(" 'keyName' => array('//" + sources.join("', '//") + "'),");
var uri = MUB.getBestUri(sources),
uriH = uri.replace(/</, '&lt;').replace(/>/, '&gt;').replace(/&/, '&amp;');
$('#uriA').html(uriH)[0].href = uri;
if (ext === 'js') {
markup = '<script type="text/javascript" src="' + uriH + '"></script>';
} else {
markup = '<link type="text/css" rel="stylesheet" href="' + uriH + '" />';
}
$('#uriHtml').val(markup);
$('#results').removeClass('hide');
},
/**
* Handler for the "Add file +" button
*/
addButtonClick : function () {
$('#results').addClass('hide');
MUB.addLi();
MUB.updateAllTestLinks();
$('#update').removeClass('hide').click(MUB.update);
$('#sources li:last input')[0].focus();
},
/**
* Runs on DOMready
*/
init : function () {
$('#jsDidntLoad').remove();
$('#app').removeClass('hide');
$('#sources').html('');
$('#add button').click(MUB.addButtonClick);
// make easier to copy text out of
$('#uriHtml, #groupConfig, #symlinkOpt').click(function () {
this.select();
}).focus(function () {
this.select();
});
$('a.ext').attr({target:'_blank'});
if (location.hash) {
// make links out of URIs from bookmarklet
$('#getBm').addClass('hide');
var i = 0, found = location.hash.substr(1).split(','), l = found.length;
$('#bmUris').html('<p><strong>Found by bookmarklet:</strong> /</p>');
var $p = $('#bmUris p');
for (; i < l; i++) {
$p.append($('<a href=#></a>').text(found[i])[0]);
if (i < (l - 1)) {
$p.append(', /');
}
}
$('#bmUris a').click(function () {
MUB.addButtonClick();
$('#sources li:last input').val(this.innerHTML);
MUB.liUpdateTestLink.call($('#sources li:last')[0]);
$('#results').addClass('hide');
return false;
}).attr({title:'Add file +'});
} else {
// setup bookmarklet 1
$.ajax({
url : '../?f=' + location.pathname.replace(/\/[^\/]*$/, '/bm.js').substr(1),
success : function (code) {
$('#bm')[0].href = code
.replace('%BUILDER_URL%', location.href)
.replace(/\n/g, ' ');
},
dataType : 'text'
});
if ($.browser.msie) {
$('#getBm p:last').append(' Sorry, not supported in MSIE!');
}
MUB.addButtonClick();
}
// setup bookmarklet 2
$.ajax({
url : '../?f=' + location.pathname.replace(/\/[^\/]*$/, '/bm2.js').substr(1),
success : function (code) {
$('#bm2')[0].href = code.replace(/\n/g, ' ');
},
dataType : 'text'
});
MUB.checkRewrite();
}
};
$(MUB.init);

View File

@ -0,0 +1,38 @@
javascript:(function() {
var d = document
,uris = []
,i = 0
,o
,home = (location + '').split('/').splice(0, 3).join('/') + '/';
function add(uri) {
if (0 !== uri.indexOf(home)) {
return;
}
uri = uri.replace(/\?.*/, '');
uris.push(escape(uri.substr(home.length)));
};
function sheet(ss) {
// we must check the domain with add() before accessing ss.cssRules
// otherwise a security exception will be thrown
if (ss.href && add(ss.href) && ss.cssRules) {
var i = 0, r;
while (r = ss.cssRules[i++])
r.styleSheet && sheet(r.styleSheet);
}
};
while (o = d.getElementsByTagName('script')[i++])
o.src && !(o.type && /vbs/i.test(o.type)) && add(o.src);
i = 0;
while (o = d.styleSheets[i++])
/* http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-DocumentStyle-styleSheets
document.styleSheet is a list property where [0] accesses the 1st element and
[outOfRange] returns null. In IE, styleSheets is a function, and also throws an
exception when you check the out of bounds index. (sigh) */
sheet(o);
if (uris.length)
window.open('%BUILDER_URL%#' + uris.join(','));
else
alert('No js/css files found with URLs within "'
+ home.split('/')[2]
+ '".\n(This tool is limited to URLs with the same domain.)');
})();

View File

@ -0,0 +1,15 @@
javascript:(function(){
var d = document
,c = d.cookie
,m = c.match(/\bminifyDebug=([^; ]+)/)
,v = m ? decodeURIComponent(m[1]) : ''
,p = prompt('Debug Minify URIs on ' + location.hostname + ' which contain:'
+ '\n(empty for none, space = OR, * = any string, ? = any char)', v)
;
if (p === null) return;
p = p.replace(/^\s+|\s+$/, '');
v = (p === '')
? 'minifyDebug=; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/'
: 'minifyDebug=' + encodeURIComponent(p) + '; path=/';
d.cookie = v;
})();

View File

@ -0,0 +1,221 @@
<?php
$app = (require __DIR__ . '/../bootstrap.php');
/* @var \Minify\App $app */
$config = $app->config;
// recommend $min_symlinks setting for Apache UserDir
$symlinkOption = '';
if (0 === strpos($app->env->server("SERVER_SOFTWARE"), 'Apache/')
&& preg_match('@^/\\~(\\w+)/@', $app->env->server('REQUEST_URI'), $m)
) {
$userDir = DIRECTORY_SEPARATOR . $m[1] . DIRECTORY_SEPARATOR;
if (false !== strpos(__FILE__, $userDir)) {
$sm = array();
$sm["//~{$m[1]}"] = dirname(__DIR__);
$array = str_replace('array (', 'array(', var_export($sm, 1));
$symlinkOption = "\$min_symlinks = $array;";
}
}
if (!$config->enableBuilder) {
header('Content-Type: text/plain');
die('This application is not enabled. See https://github.com/mrclay/minify/blob/master/docs/BuilderApp.wiki.md');
}
if ($config->builderPassword && $config->builderPassword !== '') {
$auth = new Intervention\Httpauth\Httpauth(array(
'username' => 'admin',
'password' => $config->builderPassword,
'type' => 'digest',
'realm' => 'Minify Builder',
));
$auth->secure();
}
ob_start();
?>
<!DOCTYPE html>
<title>Minify URI Builder</title>
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style>
body {margin:1em 60px;}
h1, h2, h3 {margin-left:-25px; position:relative;}
h1 {margin-top:0;}
#sources {margin:0; padding:0;}
#sources li {margin:0 0 0 40px}
#sources li input {margin-left:2px}
#add {margin:5px 0 1em 40px}
.hide {display:none}
#uriTable {border-collapse:collapse;}
#uriTable td, #uriTable th {padding-top:10px;}
#uriTable th {padding-right:10px;}
#groupConfig {font-family:monospace;}
b {color:#c00}
.topNote {background: #ff9; display:inline-block; padding:.5em .6em; margin:0 0 1em;}
.topWarning {background:#c00; color:#fff; padding:.5em .6em; margin:0 0 1em;}
.topWarning a {color:#fff;}
#jsDidntLoad {display:none;}
</style>
<body>
<?php if ($symlinkOption): ?>
<div class=topNote><strong>Note:</strong> It looks like you're running Minify in a user
directory. You may need the following option in /min/config.php to have URIs
correctly rewritten in CSS output:
<br><textarea id=symlinkOpt rows=3 cols=80 readonly><?php echo htmlspecialchars($symlinkOption); ?></textarea>
</div>
<?php endif; ?>
<p class=topWarning id=jsDidntLoad><strong>Uh Oh.</strong> Minify was unable to
serve Javascript for this app. To troubleshoot this,
<a href="https://github.com/mrclay/minify/blob/master/docs/Debugging.wiki.md">enable FirePHP debugging</a>
and request the <a id=builderScriptSrc href=#>Minify URL</a> directly. Hopefully the
FirePHP console will report the cause of the error.
</p>
<p id=minRewriteFailed class="hide"><strong>Note:</strong> Your webserver does not seem to
support mod_rewrite (used in /min/.htaccess). Your Minify URIs will contain "?", which
<a href="http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/"
>may reduce the benefit of proxy cache servers</a>.</p>
<h1>Minify URI Builder</h1>
<noscript><p class="topNote">Javascript and a browser supported by jQuery 1.2.6 is required
for this application.</p></noscript>
<div id=app class=hide>
<p>Create a list of Javascript or CSS files (or 1 is fine) you'd like to combine
and click [Update].</p>
<ol id=sources><li></li></ol>
<div id=add><button>Add file +</button></div>
<div id=bmUris></div>
<p><button class="btn btn-primary hide" id=update>Update</button></p>
<div id=results class=hide>
<h2>Minify URI</h2>
<p>Place this URI in your HTML to serve the files above combined, minified, compressed and
with cache headers.</p>
<table id=uriTable>
<tr><th>URI</th><td><a id=uriA class=ext>/min</a> <small>(opens in new window)</small></td></tr>
<tr><th>HTML</th><td><input id=uriHtml type=text size=100 readonly></td></tr>
</table>
<h2>How to serve these files as a group</h2>
<p>For the best performance you can serve these files as a pre-defined group with a URI
like: <code><span class=minRoot>/min/?</span>g=keyName</code></p>
<p>To do this, add a line like this to /min/groupsConfig.php:</p>
<pre><code>return array(
<span style="color:#666">... your existing groups here ...</span>
<input id=groupConfig size=100 type=text readonly>
);</code></pre>
<p><em>Make sure to replace <code>keyName</code> with a unique key for this group.</em></p>
</div>
<div id=getBm>
<h3>Find URIs on a Page</h3>
<p>You can use the bookmarklet below to fetch all CSS &amp; Javascript URIs from a page
on your site. When you active it, this page will open in a new window with a list of
available URIs to add.</p>
<p><a id=bm>Create Minify URIs</a> <small>(right-click, add to bookmarks)</small></p>
</div>
<h3>Combining CSS files that contain <code>@import</code></h3>
<p>If your CSS files contain <code>@import</code> declarations, Minify will not
remove them. Therefore, you will want to remove those that point to files already
in your list, and move any others to the top of the first file in your list
(imports below any styles will be ignored by browsers as invalid).</p>
<p>If you desire, you can use Minify URIs in imports and they will not be touched
by Minify. E.g. <code>@import "<span class=minRoot>/min/?</span>g=css2";</code></p>
<h3>Debug Mode</h3>
<p>When /min/config.php has <code>$min_allowDebugFlag = <strong>true</strong>;</code>
you can get debug output by appending <code>&amp;debug</code> to a Minify URL, or
by sending the cookie <code>minDebug=&lt;match&gt;</code>, where <code>&lt;match&gt;</code>
should be a string in the Minify URIs you'd like to debug. This bookmarklet will allow you to
set this cookie.</p>
<p><a id=bm2>Minify Debug</a> <small>(right-click, add to bookmarks)</small></p>
</div><!-- #app -->
<hr>
<p>Need help? Check the <a href="https://github.com/mrclay/minify/tree/master/docs">wiki</a>,
or post to the <a class=ext href="http://groups.google.com/group/minify">discussion
list</a>.</p>
<p><small>Powered by Minify <?php echo Minify::VERSION; ?></small></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery-1.6.3.min.js"><\/script>')</script>
<script>
(function () {
// workaround required to test when /min isn't child of web root
var src = "../?f=" + location.pathname.replace(/\/[^\/]*$/, '/_index.js').substr(1);
// load script immediately
document.write('<\script src="' + src + '"><\/script>');
$(function () {
$('#builderScriptSrc')[0].href = src;
// give Minify a few seconds to serve _index.js before showing scary red warning
setTimeout(function () {
if (! window.MUB) {
// Minify didn't load
$('#jsDidntLoad').css({display:'block'});
}
}, 3000);
// detection of double output encoding
var msg = '<\p class=topWarning><\strong>Warning:<\/strong> ';
var url = 'ocCheck.php?' + (new Date()).getTime();
$.get(url, function (ocStatus) {
$.get(url + '&hello=1', function (ocHello) {
var expected = [];
for (var i = 0; i < 500; i++) {
expected.push('0123456789');
}
if (ocHello != expected.join('')) {
msg += 'It appears output is being automatically compressed, interfering '
+ ' with Minify\'s own compression. ';
if (ocStatus == '1')
msg += 'The option "zlib.output_compression" is enabled in your PHP configuration. '
+ 'Minify set this to "0", but it had no effect. This option must be disabled '
+ 'in php.ini or .htaccess.';
else
msg += 'The option "zlib.output_compression" is disabled in your PHP configuration '
+ 'so this behavior is likely due to a server option.';
$(document.body).prepend(msg + '<\/p>');
} else
if (ocStatus == '1')
$(document.body).prepend('<\p class=topNote><\strong>Note:</\strong> The option '
+ '"zlib.output_compression" is enabled in your PHP configuration, but has been '
+ 'successfully disabled via ini_set(). If you experience mangled output you '
+ 'may want to consider disabling this option in your PHP configuration.<\/p>'
);
});
});
});
})();
</script>
</body>
<?php
$content = ob_get_clean();
$controller = new Minify_Controller_Page($app->env, $app->sourceFactory);
$minify = $app->minify->serve($controller, array(
'content' => $content,
'id' => __FILE__,
'lastModifiedTime' => max(
// regenerate cache if any of these change
filemtime(__FILE__),
filemtime(__DIR__ . '/../config.php'),
filemtime(__DIR__ . '/../lib/Minify.php')
),
'minifyAll' => true,
));

View File

@ -0,0 +1,36 @@
<?php
/**
* AJAX checks for zlib.output_compression
*
* @package Minify
*/
$app = (require __DIR__ . '/../bootstrap.php');
/* @var \Minify\App $app */
$_oc = ini_get('zlib.output_compression');
// allow access only if builder is enabled
if (!$app->config->enableBuilder) {
header('Location: /');
exit;
}
if ($app->env->get('hello')) {
// echo 'World!'
// try to prevent double encoding (may not have an effect)
ini_set('zlib.output_compression', '0');
HTTP_Encoder::$encodeToIe6 = true; // just in case
$he = new HTTP_Encoder(array(
'content' => str_repeat('0123456789', 500),
'method' => 'deflate',
));
$he->encode();
$he->sendAll();
} else {
// echo status "0" or "1"
header('Content-Type: text/plain');
echo (int)$_oc;
}

View File

@ -0,0 +1,43 @@
<?php
exit;
/* currently unused.
// capture PHP's default setting (may get overridden in config
$_oc = ini_get('zlib.output_compression');
// allow access only if builder is enabled
require __DIR__ . '/../config.php';
if (! $min_enableBuilder) {
exit;
}
if (isset($_GET['oc'])) {
header('Content-Type: text/plain');
echo (int)$_oc;
} elseif (isset($_GET['text']) && in_array($_GET['text'], array('js', 'css', 'fake'))) {
ini_set('zlib.output_compression', '0');
$type = ($_GET['text'] == 'js')
? 'application/x-javascript'
: "text/{$_GET['text']}";
header("Content-Type: {$type}");
echo 'Hello';
} elseif (isset($_GET['docroot'])) {
if (false === realpath($_SERVER['DOCUMENT_ROOT'])) {
echo "<p class=topWarning><strong>realpath(DOCUMENT_ROOT) failed.</strong> You may need "
. "to set \$min_documentRoot manually (hopefully realpath() is not "
. "broken in your environment).</p>";
}
if (0 !== strpos(realpath(__FILE__), realpath($_SERVER['DOCUMENT_ROOT']))) {
echo "<p class=topWarning><strong>DOCUMENT_ROOT doesn't contain this file.</strong> You may "
. " need to set \$min_documentRoot manually</p>";
}
if (isset($_SERVER['SUBDOMAIN_DOCUMENT_ROOT'])) {
echo "<p class=topNote><strong>\$_SERVER['SUBDOMAIN_DOCUMENT_ROOT'] is set.</strong> "
. "You may need to set \$min_documentRoot to this in config.php</p>";
}
}
//*/

View File

@ -0,0 +1,9 @@
<?php
/**
* Additional configuration applied when the variable "test" is added to the querystring.
*
* To test config options, place them in this file and add "&test" to your Minify URL.
* Note that if this is on a public server, anyone can execute your test.
*
* @package Minify
*/

View File

@ -0,0 +1,200 @@
<?php
/**
* Configuration for "min", the default application built with the Minify
* library
*
* @package Minify
*/
/**
* Enable the static serving feature
*/
$min_enableStatic = false;
/**
* Allow use of the Minify URI Builder app. Only set this to true while you need it.
*/
$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".
*/
$min_builderPassword = 'admin';
/**
* Set to true to log messages to FirePHP (Firefox Firebug addon) and PHP's error_log
* Set to false for no error logging (Minify may be slightly faster).
*/
$min_errorLogger = false;
/**
* To allow debug mode output, you must set this option to true.
*
* Once true, you can send the cookie minDebug to request debug mode output. The
* cookie value should match the URIs you'd like to debug. E.g. to debug
* /min/f=file1.js send the cookie minDebug=file1.js
* You can manually enable debugging by appending "&debug" to a URI.
* E.g. /min/?f=script1.js,script2.js&debug
*
* In 'debug' mode, Minify combines files with no minification and adds comments
* to indicate line #s of the original files.
*/
$min_allowDebugFlag = false;
/**
* For best performance, specify your temp directory here. Otherwise Minify
* will have to load extra code to guess. Some examples below:
*/
//$min_cachePath = 'c:\\WINDOWS\\Temp';
//$min_cachePath = '/tmp';
//$min_cachePath = preg_replace('/^\\d+;/', '', session_save_path());
/**
* To use APC/Memcache/ZendPlatform for cache storage, require the class and
* set $min_cachePath to an instance. Example below:
*/
//$min_cachePath = new Minify_Cache_APC();
/**
* Leave an empty string to use PHP's $_SERVER['DOCUMENT_ROOT'].
*
* On some servers, this value may be misconfigured or missing. If so, set this
* to your full document root path with no trailing slash.
* E.g. '/home/accountname/public_html' or 'c:\\xampp\\htdocs'
*
* If /min/ is directly inside your document root, just uncomment the
* second line. The third line might work on some Apache servers.
*/
$min_documentRoot = '';
//$min_documentRoot = dirname(dirname(__DIR__));
//$min_documentRoot = substr(__FILE__, 0, -15);
//$min_documentRoot = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT'];
/**
* Cache file locking. Set to false if filesystem is NFS. On at least one
* NFS system flock-ing attempts stalled PHP for 30 seconds!
*/
$min_cacheFileLocking = true;
/**
* Combining multiple CSS files can place @import declarations after rules, which
* is invalid. Minify will attempt to detect when this happens and place a
* warning comment at the top of the CSS output. To resolve this you can either
* move the @imports within your CSS files, or enable this option, which will
* move all @imports to the top of the output. Note that moving @imports could
* affect CSS values (which is why this option is disabled by default).
*/
$min_serveOptions['bubbleCssImports'] = false;
/**
* Cache-Control: max-age value sent to browser (in seconds). After this period,
* the browser will send another conditional GET. Use a longer period for lower
* traffic but you may want to shorten this before making changes if it's crucial
* those changes are seen immediately.
*
* Note: Despite this setting, if you include a number at the end of the
* querystring, maxAge will be set to one year. E.g. /min/f=hello.css&123456
*/
$min_serveOptions['maxAge'] = 1800;
/**
* To use the CSS compressor that shipped with 2.x, uncomment the following line:
*/
//$min_serveOptions['minifiers'][Minify::TYPE_CSS] = array('Minify_CSS', 'minify');
/**
* To use Google's Closure Compiler API to minify Javascript (falling back to JSMin
* on failure), uncomment the following line:
*/
//$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');
/**
* If you'd like to restrict the "f" option to files within/below
* particular directories below DOCUMENT_ROOT, set this here.
* You will still need to include the directory in the
* f or b GET parameters.
*
* // = shortcut for DOCUMENT_ROOT
*/
//$min_serveOptions['minApp']['allowDirs'] = array('//js', '//css');
/**
* Set to true to disable the "f" GET parameter for specifying files.
* Only the "g" parameter will be considered.
*/
$min_serveOptions['minApp']['groupsOnly'] = false;
/**
* By default, Minify will not minify files with names containing .min or -min
* before the extension. E.g. myFile.min.js will not be processed by JSMin
*
* To minify all files, set this option to null. You could also specify your
* own pattern that is matched against the filename.
*/
//$min_serveOptions['minApp']['noMinPattern'] = '@[-\\.]min\\.(?:js|css)$@i';
/**
* If you minify CSS files stored in symlink-ed directories, the URI rewriting
* algorithm can fail. To prevent this, provide an array of link paths to
* target paths, where the link paths are within the document root.
*
* Because paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*/
$min_symlinks = array();
/**
* If you upload files from Windows to a non-Windows server, Windows may report
* incorrect mtimes for the files. This may cause Minify to keep serving stale
* cache files when source file changes are made too frequently (e.g. more than
* once an hour).
*
* Immediately after modifying and uploading a file, use the touch command to
* update the mtime on the server. If the mtime jumps ahead by a number of hours,
* set this variable to that number. If the mtime moves back, this should not be
* needed.
*
* In the Windows SFTP client WinSCP, there's an option that may fix this
* issue without changing the variable below. Under login > environment,
* select the option "Adjust remote timestamp with DST".
* @link http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time
*/
$min_uploaderHoursBehind = 0;
/**
* Advanced: you can replace some of the PHP classes Minify uses to serve requests.
* To do this, assign a callable to one of the elements of the $min_factories array.
*
* You can see the default implementations (and what gets passed in) in index.php.
*/
//$min_factories['minify'] = ... a callable accepting a Minify\App object
//$min_factories['controller'] = ... a callable accepting a Minify\App object

View File

@ -0,0 +1,11 @@
<?php
// template file for creating your own Minify endpoint
// remove this
die('disabled');
// adjust this path as necessary
require __DIR__ . '/../vendor/autoload.php';
$app = new \Minify\App(__DIR__);
$app->runServer();

View File

@ -0,0 +1,19 @@
<?php
/**
* Groups configuration for default Minify implementation
* @package Minify
*/
/**
* You may wish to use the Minify URI Builder app to suggest
* changes. http://yourdomain/min/builder/
*
* See https://github.com/mrclay/minify/blob/master/docs/CustomServer.wiki.md for other ideas
**/
return array(
// 'testJs' => array('//minify/quick-test.js'),
// 'testCss' => array('//minify/quick-test.css'),
// 'js' => array('//js/file1.js', '//js/file2.js'),
// 'css' => array('//css/file1.css', '//css/file2.css'),
);

View File

@ -0,0 +1,13 @@
<?php
/**
* Sets up MinApp controller and serves files
*
* DO NOT EDIT! Configure this utility via config.php and groupsConfig.php
*
* @package Minify
*/
$app = (require __DIR__ . '/bootstrap.php');
/* @var \Minify\App $app */
$app->runServer();

View File

@ -0,0 +1,376 @@
<?php
/**
* Class HTTP_ConditionalGet
* @package Minify
* @subpackage HTTP
*/
/**
* Implement conditional GET via a timestamp or hash of content
*
* E.g. Content from DB with update time:
* <code>
* list($updateTime, $content) = getDbUpdateAndContent();
* $cg = new HTTP_ConditionalGet(array(
* 'lastModifiedTime' => $updateTime
* ,'isPublic' => true
* ));
* $cg->sendHeaders();
* if ($cg->cacheIsValid) {
* exit();
* }
* echo $content;
* </code>
*
* E.g. Shortcut for the above
* <code>
* HTTP_ConditionalGet::check($updateTime, true); // exits if client has cache
* echo $content;
* </code>
*
* E.g. Content from DB with no update time:
* <code>
* $content = getContentFromDB();
* $cg = new HTTP_ConditionalGet(array(
* 'contentHash' => md5($content)
* ));
* $cg->sendHeaders();
* if ($cg->cacheIsValid) {
* exit();
* }
* echo $content;
* </code>
*
* E.g. Static content with some static includes:
* <code>
* // before content
* $cg = new HTTP_ConditionalGet(array(
* 'lastUpdateTime' => max(
* filemtime(__FILE__)
* ,filemtime('/path/to/header.inc')
* ,filemtime('/path/to/footer.inc')
* )
* ));
* $cg->sendHeaders();
* if ($cg->cacheIsValid) {
* exit();
* }
* </code>
* @package Minify
* @subpackage HTTP
* @author Stephen Clay <steve@mrclay.org>
*/
class HTTP_ConditionalGet
{
/**
* Does the client have a valid copy of the requested resource?
*
* You'll want to check this after instantiating the object. If true, do
* not send content, just call sendHeaders() if you haven't already.
*
* @var bool
*/
public $cacheIsValid = null;
/**
* @param array $spec options
*
* 'isPublic': (bool) if false, the Cache-Control header will contain
* "private", allowing only browser caching. (default false)
*
* 'lastModifiedTime': (int) if given, both ETag AND Last-Modified headers
* will be sent with content. This is recommended.
*
* 'encoding': (string) if set, the header "Vary: Accept-Encoding" will
* always be sent and a truncated version of the encoding will be appended
* to the ETag. E.g. "pub123456;gz". This will also trigger a more lenient
* checking of the client's If-None-Match header, as the encoding portion of
* the ETag will be stripped before comparison.
*
* 'contentHash': (string) if given, only the ETag header can be sent with
* content (only HTTP1.1 clients can conditionally GET). The given string
* should be short with no quote characters and always change when the
* resource changes (recommend md5()). This is not needed/used if
* lastModifiedTime is given.
*
* 'eTag': (string) if given, this will be used as the ETag header rather
* than values based on lastModifiedTime or contentHash. Also the encoding
* string will not be appended to the given value as described above.
*
* 'invalidate': (bool) if true, the client cache will be considered invalid
* without testing. Effectively this disables conditional GET.
* (default false)
*
* 'maxAge': (int) if given, this will set the Cache-Control max-age in
* seconds, and also set the Expires header to the equivalent GMT date.
* After the max-age period has passed, the browser will again send a
* conditional GET to revalidate its cache.
*/
public function __construct($spec)
{
$scope = (isset($spec['isPublic']) && $spec['isPublic'])
? 'public'
: 'private';
$maxAge = 0;
// backwards compatibility (can be removed later)
if (isset($spec['setExpires'])
&& is_numeric($spec['setExpires'])
&& ! isset($spec['maxAge'])) {
$spec['maxAge'] = $spec['setExpires'] - $_SERVER['REQUEST_TIME'];
}
if (isset($spec['maxAge'])) {
$maxAge = $spec['maxAge'];
$this->_headers['Expires'] = self::gmtDate(
$_SERVER['REQUEST_TIME'] + $spec['maxAge']
);
}
$etagAppend = '';
if (isset($spec['encoding'])) {
$this->_stripEtag = true;
if ('' !== $spec['encoding']) {
$this->_headers['Vary'] = 'Accept-Encoding';
if (0 === strpos($spec['encoding'], 'x-')) {
$spec['encoding'] = substr($spec['encoding'], 2);
}
$etagAppend = ';' . substr($spec['encoding'], 0, 2);
}
}
if (isset($spec['lastModifiedTime'])) {
$this->_setLastModified($spec['lastModifiedTime']);
if (isset($spec['eTag'])) { // Use it
$this->_setEtag($spec['eTag'], $scope);
} else { // base both headers on time
$this->_setEtag($spec['lastModifiedTime'] . $etagAppend, $scope);
}
} elseif (isset($spec['eTag'])) { // Use it
$this->_setEtag($spec['eTag'], $scope);
} elseif (isset($spec['contentHash'])) { // Use the hash as the ETag
$this->_setEtag($spec['contentHash'] . $etagAppend, $scope);
}
$privacy = ($scope === 'private')
? ', private'
: '';
$this->_headers['Cache-Control'] = "max-age={$maxAge}{$privacy}";
// invalidate cache if disabled, otherwise check
$this->cacheIsValid = (isset($spec['invalidate']) && $spec['invalidate'])
? false
: $this->_isCacheValid();
}
/**
* Get array of output headers to be sent
*
* In the case of 304 responses, this array will only contain the response
* code header: array('_responseCode' => 'HTTP/1.0 304 Not Modified')
*
* Otherwise something like:
* <code>
* array(
* 'Cache-Control' => 'max-age=0, public'
* ,'ETag' => '"foobar"'
* )
* </code>
*
* @return array
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* Set the Content-Length header in bytes
*
* With most PHP configs, as long as you don't flush() output, this method
* is not needed and PHP will buffer all output and set Content-Length for
* you. Otherwise you'll want to call this to let the client know up front.
*
* @param int $bytes
*
* @return int copy of input $bytes
*/
public function setContentLength($bytes)
{
return $this->_headers['Content-Length'] = $bytes;
}
/**
* Send headers
*
* @see getHeaders()
*
* Note this doesn't "clear" the headers. Calling sendHeaders() will
* call header() again (but probably have not effect) and getHeaders() will
* still return the headers.
*
* @return null
*/
public function sendHeaders()
{
$headers = $this->_headers;
if (array_key_exists('_responseCode', $headers)) {
// FastCGI environments require 3rd arg to header() to be set
list(, $code) = explode(' ', $headers['_responseCode'], 3);
header($headers['_responseCode'], true, $code);
unset($headers['_responseCode']);
}
foreach ($headers as $name => $val) {
header($name . ': ' . $val);
}
}
/**
* Exit if the client's cache is valid for this resource
*
* This is a convenience method for common use of the class
*
* @param int $lastModifiedTime if given, both ETag AND Last-Modified headers
* will be sent with content. This is recommended.
*
* @param bool $isPublic (default false) if true, the Cache-Control header
* will contain "public", allowing proxies to cache the content. Otherwise
* "private" will be sent, allowing only browser caching.
*
* @param array $options (default empty) additional options for constructor
*/
public static function check($lastModifiedTime = null, $isPublic = false, $options = array())
{
if (null !== $lastModifiedTime) {
$options['lastModifiedTime'] = (int)$lastModifiedTime;
}
$options['isPublic'] = (bool)$isPublic;
$cg = new HTTP_ConditionalGet($options);
$cg->sendHeaders();
if ($cg->cacheIsValid) {
exit();
}
}
/**
* Get a GMT formatted date for use in HTTP headers
*
* <code>
* header('Expires: ' . HTTP_ConditionalGet::gmtdate($time));
* </code>
*
* @param int $time unix timestamp
*
* @return string
*/
public static function gmtDate($time)
{
return gmdate('D, d M Y H:i:s \G\M\T', $time);
}
protected $_headers = array();
protected $_lmTime = null;
protected $_etag = null;
protected $_stripEtag = false;
/**
* @param string $hash
*
* @param string $scope
*/
protected function _setEtag($hash, $scope)
{
$this->_etag = '"' . substr($scope, 0, 3) . $hash . '"';
$this->_headers['ETag'] = $this->_etag;
}
/**
* @param int $time
*/
protected function _setLastModified($time)
{
$this->_lmTime = (int)$time;
$this->_headers['Last-Modified'] = self::gmtDate($time);
}
/**
* Determine validity of client cache and queue 304 header if valid
*
* @return bool
*/
protected function _isCacheValid()
{
if (null === $this->_etag) {
// lmTime is copied to ETag, so this condition implies that the
// server sent neither ETag nor Last-Modified, so the client can't
// possibly has a valid cache.
return false;
}
$isValid = ($this->resourceMatchedEtag() || $this->resourceNotModified());
if ($isValid) {
$this->_headers['_responseCode'] = 'HTTP/1.0 304 Not Modified';
}
return $isValid;
}
/**
* @return bool
*/
protected function resourceMatchedEtag()
{
if (!isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
return false;
}
$clientEtagList = PHP_VERSION_ID < 50400 && get_magic_quotes_gpc()
? stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])
: $_SERVER['HTTP_IF_NONE_MATCH'];
$clientEtags = explode(',', $clientEtagList);
$compareTo = $this->normalizeEtag($this->_etag);
foreach ($clientEtags as $clientEtag) {
if ($this->normalizeEtag($clientEtag) === $compareTo) {
// respond with the client's matched ETag, even if it's not what
// we would've sent by default
$this->_headers['ETag'] = trim($clientEtag);
return true;
}
}
return false;
}
/**
* @param string $etag
*
* @return string
*/
protected function normalizeEtag($etag)
{
$etag = trim($etag);
return $this->_stripEtag
? preg_replace('/;\\w\\w"$/', '"', $etag)
: $etag;
}
/**
* @return bool
*/
protected function resourceNotModified()
{
if (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
return false;
}
// strip off IE's extra data (semicolon)
list($ifModifiedSince) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE'], 2);
$date = new DateTime($ifModifiedSince, new DateTimeZone('UTC'));
if ($date->getTimestamp() >= $this->_lmTime) {
// Apache 2.2's behavior. If there was no ETag match, send the
// non-encoded version of the ETag value.
$this->_headers['ETag'] = $this->normalizeEtag($this->_etag);
return true;
}
return false;
}
}

View File

@ -0,0 +1,339 @@
<?php
/**
* Class HTTP_Encoder
* @package Minify
* @subpackage HTTP
*/
/**
* Encode and send gzipped/deflated content
*
* The "Vary: Accept-Encoding" header is sent. If the client allows encoding,
* Content-Encoding and Content-Length are added.
*
* <code>
* // Send a CSS file, compressed if possible
* $he = new HTTP_Encoder(array(
* 'content' => file_get_contents($cssFile)
* ,'type' => 'text/css'
* ));
* $he->encode();
* $he->sendAll();
* </code>
*
* <code>
* // Shortcut to encoding output
* header('Content-Type: text/css'); // needed if not HTML
* HTTP_Encoder::output($css);
* </code>
*
* <code>
* // Just sniff for the accepted encoding
* $encoding = HTTP_Encoder::getAcceptedEncoding();
* </code>
*
* For more control over headers, use getHeaders() and getData() and send your
* own output.
*
* Note: If you don't need header mgmt, use PHP's native gzencode, gzdeflate,
* and gzcompress functions for gzip, deflate, and compress-encoding
* respectively.
*
* @package Minify
* @subpackage HTTP
* @author Stephen Clay <steve@mrclay.org>
*/
class HTTP_Encoder
{
/**
* Should the encoder allow HTTP encoding to IE6?
*
* If you have many IE6 users and the bandwidth savings is worth troubling
* some of them, set this to true.
*
* By default, encoding is only offered to IE7+. When this is true,
* getAcceptedEncoding() will return an encoding for IE6 if its user agent
* string contains "SV1". This has been documented in many places as "safe",
* but there seem to be remaining, intermittent encoding bugs in patched
* IE6 on the wild web.
*
* @var bool
*/
public static $encodeToIe6 = true;
/**
* Default compression level for zlib operations
*
* This level is used if encode() is not given a $compressionLevel
*
* @var int
*/
public static $compressionLevel = 6;
/**
* Get an HTTP Encoder object
*
* @param array $spec options
*
* 'content': (string required) content to be encoded
*
* 'type': (string) if set, the Content-Type header will have this value.
*
* 'method: (string) only set this if you are forcing a particular encoding
* method. If not set, the best method will be chosen by getAcceptedEncoding()
* The available methods are 'gzip', 'deflate', 'compress', and '' (no
* encoding)
*/
public function __construct($spec)
{
$this->_useMbStrlen = (function_exists('mb_strlen')
&& (ini_get('mbstring.func_overload') !== '')
&& ((int)ini_get('mbstring.func_overload') & 2));
$this->_content = $spec['content'];
$this->_headers['Content-Length'] = $this->_useMbStrlen
? (string)mb_strlen($this->_content, '8bit')
: (string)strlen($this->_content);
if (isset($spec['type'])) {
$this->_headers['Content-Type'] = $spec['type'];
}
if (isset($spec['method'])
&& in_array($spec['method'], array('gzip', 'deflate', 'compress', ''))) {
$this->_encodeMethod = array($spec['method'], $spec['method']);
} else {
$this->_encodeMethod = self::getAcceptedEncoding();
}
}
/**
* Get content in current form
*
* Call after encode() for encoded content.
*
* @return string
*/
public function getContent()
{
return $this->_content;
}
/**
* Get array of output headers to be sent
*
* E.g.
* <code>
* array(
* 'Content-Length' => '615'
* ,'Content-Encoding' => 'x-gzip'
* ,'Vary' => 'Accept-Encoding'
* )
* </code>
*
* @return array
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* Send output headers
*
* You must call this before headers are sent and it probably cannot be
* used in conjunction with zlib output buffering / mod_gzip. Errors are
* not handled purposefully.
*
* @see getHeaders()
*/
public function sendHeaders()
{
foreach ($this->_headers as $name => $val) {
header($name . ': ' . $val);
}
}
/**
* Send output headers and content
*
* A shortcut for sendHeaders() and echo getContent()
*
* You must call this before headers are sent and it probably cannot be
* used in conjunction with zlib output buffering / mod_gzip. Errors are
* not handled purposefully.
*/
public function sendAll()
{
$this->sendHeaders();
echo $this->_content;
}
/**
* Determine the client's best encoding method from the HTTP Accept-Encoding
* header.
*
* If no Accept-Encoding header is set, or the browser is IE before v6 SP2,
* this will return ('', ''), the "identity" encoding.
*
* A syntax-aware scan is done of the Accept-Encoding, so the method must
* be non 0. The methods are favored in order of gzip, deflate, then
* compress. Deflate is always smallest and generally faster, but is
* rarely sent by servers, so client support could be buggier.
*
* @param bool $allowCompress allow the older compress encoding
*
* @param bool $allowDeflate allow the more recent deflate encoding
*
* @return array two values, 1st is the actual encoding method, 2nd is the
* alias of that method to use in the Content-Encoding header (some browsers
* call gzip "x-gzip" etc.)
*/
public static function getAcceptedEncoding($allowCompress = true, $allowDeflate = true)
{
// @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
if (! isset($_SERVER['HTTP_ACCEPT_ENCODING'])
|| self::isBuggyIe()) {
return array('', '');
}
$ae = $_SERVER['HTTP_ACCEPT_ENCODING'];
// gzip checks (quick)
if (0 === strpos($ae, 'gzip,') // most browsers
|| 0 === strpos($ae, 'deflate, gzip,') // opera
) {
return array('gzip', 'gzip');
}
// gzip checks (slow)
if (preg_match(
'@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae,
$m
)) {
return array('gzip', $m[1]);
}
if ($allowDeflate) {
// deflate checks
$aeRev = strrev($ae);
if (0 === strpos($aeRev, 'etalfed ,') // ie, webkit
|| 0 === strpos($aeRev, 'etalfed,') // gecko
|| 0 === strpos($ae, 'deflate,') // opera
// slow parsing
|| preg_match(
'@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae
)) {
return array('deflate', 'deflate');
}
}
if ($allowCompress && preg_match(
'@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae,
$m
)) {
return array('compress', $m[1]);
}
return array('', '');
}
/**
* Encode (compress) the content
*
* If the encode method is '' (none) or compression level is 0, or the 'zlib'
* extension isn't loaded, we return false.
*
* Then the appropriate gz_* function is called to compress the content. If
* this fails, false is returned.
*
* The header "Vary: Accept-Encoding" is added. If encoding is successful,
* the Content-Length header is updated, and Content-Encoding is also added.
*
* @param int $compressionLevel given to zlib functions. If not given, the
* class default will be used.
*
* @return bool success true if the content was actually compressed
*/
public function encode($compressionLevel = null)
{
if (! self::isBuggyIe()) {
$this->_headers['Vary'] = 'Accept-Encoding';
}
if (null === $compressionLevel) {
$compressionLevel = self::$compressionLevel;
}
if ('' === $this->_encodeMethod[0]
|| ($compressionLevel == 0)
|| !extension_loaded('zlib')) {
return false;
}
if ($this->_encodeMethod[0] === 'deflate') {
$encoded = gzdeflate($this->_content, $compressionLevel);
} elseif ($this->_encodeMethod[0] === 'gzip') {
$encoded = gzencode($this->_content, $compressionLevel);
} else {
$encoded = gzcompress($this->_content, $compressionLevel);
}
if (false === $encoded) {
return false;
}
$this->_headers['Content-Length'] = $this->_useMbStrlen
? (string)mb_strlen($encoded, '8bit')
: (string)strlen($encoded);
$this->_headers['Content-Encoding'] = $this->_encodeMethod[1];
$this->_content = $encoded;
return true;
}
/**
* Encode and send appropriate headers and content
*
* This is a convenience method for common use of the class
*
* @param string $content
*
* @param int $compressionLevel given to zlib functions. If not given, the
* class default will be used.
*
* @return bool success true if the content was actually compressed
*/
public static function output($content, $compressionLevel = null)
{
if (null === $compressionLevel) {
$compressionLevel = self::$compressionLevel;
}
$he = new HTTP_Encoder(array('content' => $content));
$ret = $he->encode($compressionLevel);
$he->sendAll();
return $ret;
}
/**
* Is the browser an IE version earlier than 6 SP2?
*
* @return bool
*/
public static function isBuggyIe()
{
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
$ua = $_SERVER['HTTP_USER_AGENT'];
// quick escape for non-IEs
if (0 !== strpos($ua, 'Mozilla/4.0 (compatible; MSIE ')
|| false !== strpos($ua, 'Opera')) {
return false;
}
// no regex = faaast
$version = (float)substr($ua, 30);
return self::$encodeToIe6
? ($version < 6 || ($version == 6 && false === strpos($ua, 'SV1')))
: ($version < 7);
}
protected $_content = '';
protected $_headers = array();
protected $_encodeMethod = array('', '');
protected $_useMbStrlen = false;
}

View File

@ -0,0 +1,759 @@
<?php
/**
* Class Minify
* @package Minify
*/
use Psr\Log\LoggerInterface;
/**
* Minify - Combines, minifies, and caches JavaScript and CSS files on demand.
*
* See README for usage instructions (for now).
*
* This library was inspired by {@link mailto:flashkot@mail.ru jscsscomp by Maxim Martynyuk}
* and by the article {@link http://www.hunlock.com/blogs/Supercharged_Javascript "Supercharged JavaScript" by Patrick Hunlock}.
*
* @package Minify
* @author Ryan Grove <ryan@wonko.com>
* @author Stephen Clay <steve@mrclay.org>
* @copyright 2008 Ryan Grove, Stephen Clay. All rights reserved.
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @link https://github.com/mrclay/minify
*/
class Minify
{
/**
* API version
*
* This is only bumped when API breaks are done and should follow the major version of the library
*
* @var int
*/
const VERSION = 3;
const TYPE_CSS = 'text/css';
const TYPE_HTML = 'text/html';
// there is some debate over the ideal JS Content-Type, but this is the
// Apache default and what Yahoo! uses..
const TYPE_JS = 'application/x-javascript';
const URL_DEBUG = 'https://github.com/mrclay/minify/blob/master/docs/Debugging.wiki.md';
/**
* Any Minify_Cache_* object or null (i.e. no server cache is used)
*
* @var Minify_CacheInterface
*/
private $cache;
/**
* Active controller for current request
*
* @var Minify_Controller_Base
*/
protected $controller;
/**
* @var Minify_Env
*/
protected $env;
/**
* @var Minify_SourceInterface[]
*/
protected $sources;
/**
* @var string
*/
protected $selectionId;
/**
* Options for current request
*
* @var array
*/
protected $options;
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* @param Minify_CacheInterface $cache
* @param LoggerInterface $logger
*/
public function __construct(Minify_CacheInterface $cache, LoggerInterface $logger = null)
{
$this->cache = $cache;
$this->logger = $logger;
}
/**
* Get default Minify options.
*
* @return array options for Minify
*/
public function getDefaultOptions()
{
return array(
'isPublic' => true,
'encodeOutput' => function_exists('gzdeflate'),
'encodeMethod' => null, // determine later
'encodeLevel' => 9,
'minifiers' => array(
Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
),
'minifierOptions' => array(), // no minifier options
'contentTypeCharset' => 'utf-8',
'maxAge' => 1800, // 30 minutes
'rewriteCssUris' => true,
'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.
'badRequestHeader' => 'HTTP/1.0 400 Bad Request',
'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
// callback function to see/modify content of all sources
'postprocessor' => null,
// file to require to load preprocessor
'postprocessorRequire' => null,
/**
* If this string is not empty AND the serve() option 'bubbleCssImports' is
* NOT set, then serve() will check CSS files for @import declarations that
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning.
*/
'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n"
);
}
/**
* Serve a request for a minified file.
*
* Here are the available options and defaults:
*
* 'isPublic' : send "public" instead of "private" in Cache-Control
* headers, allowing shared caches to cache the output. (default true)
*
* 'quiet' : set to true to have serve() return an array rather than sending
* any headers/output (default false)
*
* 'encodeOutput' : set to false to disable content encoding, and not send
* the Vary header (default true)
*
* 'encodeMethod' : generally you should let this be determined by
* HTTP_Encoder (leave null), but you can force a particular encoding
* to be returned, by setting this to 'gzip' or '' (no encoding)
*
* 'encodeLevel' : level of encoding compression (0 to 9, default 9)
*
* 'contentTypeCharset' : appended to the Content-Type header sent. Set to a falsey
* value to remove. (default 'utf-8')
*
* 'maxAge' : set this to the number of seconds the client should use its cache
* before revalidating with the server. This sets Cache-Control: max-age and the
* Expires header. Unlike the old 'setExpires' setting, this setting will NOT
* prevent conditional GETs. Note this has nothing to do with server-side caching.
*
* 'rewriteCssUris' : If true, serve() will automatically set the 'currentDir'
* minifier option to enable URI rewriting in CSS files (default true)
*
* 'bubbleCssImports' : If true, all @import declarations in combined CSS
* files will be move to the top. Note this may alter effective CSS values
* due to a change in order. (default false)
*
* 'debug' : set to true to minify all sources with the 'Lines' controller, which
* eases the debugging of combined files. This also prevents 304 responses.
* @see Minify_Lines::minify()
*
* 'concatOnly' : set to true to disable minification and simply concatenate the files.
* For JS, no minifier will be used. For CSS, only URI rewriting is still performed.
*
* 'minifiers' : to override Minify's default choice of minifier function for
* a particular content-type, specify your callback under the key of the
* content-type:
* <code>
* // call customCssMinifier($css) for all CSS minification
* $options['minifiers'][Minify::TYPE_CSS] = 'customCssMinifier';
*
* // don't minify Javascript at all
* $options['minifiers'][Minify::TYPE_JS] = 'Minify::nullMinifier';
* </code>
*
* 'minifierOptions' : to send options to the minifier function, specify your options
* under the key of the content-type. E.g. To send the CSS minifier an option:
* <code>
* // give CSS minifier array('optionName' => 'optionValue') as 2nd argument
* $options['minifierOptions'][Minify::TYPE_CSS]['optionName'] = 'optionValue';
* </code>
*
* 'contentType' : (optional) this is only needed if your file extension is not
* js/css/html. The given content-type will be sent regardless of source file
* extension, so this should not be used in a Groups config with other
* Javascript/CSS files.
*
* 'importWarning' : serve() will check CSS files for @import declarations that
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning. To disable this, set this option to empty string.
*
* Any controller options are documented in that controller's createConfiguration() method.
*
* @param Minify_ControllerInterface $controller instance of subclass of Minify_Controller_Base
*
* @param array $options controller/serve options
*
* @return null|array if the 'quiet' option is set to true, an array
* with keys "success" (bool), "statusCode" (int), "content" (string), and
* "headers" (array).
*
* @throws Exception
*/
public function serve(Minify_ControllerInterface $controller, $options = array())
{
$this->env = $controller->getEnv();
$options = array_merge($this->getDefaultOptions(), $options);
$config = $controller->createConfiguration($options);
$this->sources = $config->getSources();
$this->selectionId = $config->getSelectionId();
$this->options = $this->analyzeSources($config->getOptions());
if (!$this->options['quiet'] && !headers_sent()) {
ini_set('zlib.output_compression', '0');
}
// check request validity
if (!$this->sources) {
// invalid request!
if (! $this->options['quiet']) {
$this->errorExit($this->options['badRequestHeader'], self::URL_DEBUG);
} else {
list(, $statusCode) = explode(' ', $this->options['badRequestHeader']);
return array(
'success' => false,
'statusCode' => (int)$statusCode,
'content' => '',
'headers' => array(),
);
}
}
$this->controller = $controller;
if ($this->options['debug']) {
$this->setupDebug();
$this->options['maxAge'] = 0;
}
// determine encoding
if ($this->options['encodeOutput']) {
$sendVary = true;
if ($this->options['encodeMethod'] !== null) {
// controller specifically requested this
$contentEncoding = $this->options['encodeMethod'];
} else {
// sniff request header
// depending on what the client accepts, $contentEncoding may be
// 'x-gzip' while our internal encodeMethod is 'gzip'. Calling
// getAcceptedEncoding(false, false) leaves out compress and deflate as options.
$list = HTTP_Encoder::getAcceptedEncoding(false, false);
list($this->options['encodeMethod'], $contentEncoding) = $list;
$sendVary = ! HTTP_Encoder::isBuggyIe();
}
} else {
$this->options['encodeMethod'] = ''; // identity (no encoding)
}
// check client cache
$cgOptions = array(
'lastModifiedTime' => $this->options['lastModifiedTime'],
'isPublic' => $this->options['isPublic'],
'encoding' => $this->options['encodeMethod'],
);
if ($this->options['maxAge'] > 0) {
$cgOptions['maxAge'] = $this->options['maxAge'];
} elseif ($this->options['debug']) {
$cgOptions['invalidate'] = true;
}
$cg = new HTTP_ConditionalGet($cgOptions);
if ($cg->cacheIsValid) {
// client's cache is valid
if (! $this->options['quiet']) {
$cg->sendHeaders();
return;
}
return array(
'success' => true,
'statusCode' => 304,
'content' => '',
'headers' => $cg->getHeaders(),
);
}
// client will need output
$headers = $cg->getHeaders();
unset($cg);
if ($this->options['contentType'] === self::TYPE_CSS && $this->options['rewriteCssUris']) {
$this->setupUriRewrites();
}
if ($this->options['concatOnly']) {
$this->options['minifiers'][self::TYPE_JS] = false;
foreach ($this->sources as $key => $source) {
if ($this->options['contentType'] === self::TYPE_JS) {
$source->setMinifier('Minify::nullMinifier');
} elseif ($this->options['contentType'] === self::TYPE_CSS) {
$source->setMinifier(array('Minify_CSSmin', 'minify'));
$sourceOpts = $source->getMinifierOptions();
$sourceOpts['compress'] = false;
$source->setMinifierOptions($sourceOpts);
}
}
}
// check server cache
if (! $this->options['debug']) {
// using cache
// the goal is to use only the cache methods to sniff the length and
// output the content, as they do not require ever loading the file into
// memory.
$cacheId = $this->_getCacheId();
$fullCacheId = ($this->options['encodeMethod']) ? $cacheId . '.gz' : $cacheId;
// check cache for valid entry
$cacheIsReady = $this->cache->isValid($fullCacheId, $this->options['lastModifiedTime']);
if ($cacheIsReady) {
$cacheContentLength = $this->cache->getSize($fullCacheId);
} else {
// generate & cache content
try {
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
if (! $this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
$this->cache->store($cacheId, $content);
if (function_exists('gzencode') && $this->options['encodeMethod']) {
$this->cache->store($cacheId . '.gz', gzencode($content, $this->options['encodeLevel']));
}
}
} else {
// no cache
$cacheIsReady = false;
try {
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
if (! $this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
}
if (! $cacheIsReady && $this->options['encodeMethod']) {
// still need to encode
$content = gzencode($content, $this->options['encodeLevel']);
}
// add headers
if ($cacheIsReady) {
$headers['Content-Length'] = $cacheContentLength;
} else {
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
$headers['Content-Length'] = mb_strlen($content, '8bit');
} else {
$headers['Content-Length'] = strlen($content);
}
}
$headers['Content-Type'] = $this->options['contentType'];
if ($this->options['contentTypeCharset']) {
$headers['Content-Type'] .= '; charset=' . $this->options['contentTypeCharset'];
}
if ($this->options['encodeMethod'] !== '') {
$headers['Content-Encoding'] = $contentEncoding;
}
if ($this->options['encodeOutput'] && $sendVary) {
$headers['Vary'] = 'Accept-Encoding';
}
if (! $this->options['quiet']) {
// output headers & content
foreach ($headers as $name => $val) {
header($name . ': ' . $val);
}
if ($cacheIsReady) {
$this->cache->display($fullCacheId);
} else {
echo $content;
}
} else {
return array(
'success' => true,
'statusCode' => 200,
'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
'headers' => $headers,
);
}
}
/**
* Return combined minified content for a set of sources
*
* No internal caching will be used and the content will not be HTTP encoded.
*
* @param array $sources array of filepaths and/or Minify_Source objects
*
* @param array $options (optional) array of options for serve.
*
* @return string
*/
public function combine($sources, $options = array())
{
$tmpCache = $this->cache;
$this->cache = new Minify_Cache_Null();
$env = new Minify_Env();
$sourceFactory = new Minify_Source_Factory($env, array(
'checkAllowDirs' => false,
), $this->cache);
$controller = new Minify_Controller_Files($env, $sourceFactory, $this->logger);
$options = array_merge($options, array(
'files' => (array)$sources,
'quiet' => true,
'encodeMethod' => '',
'lastModifiedTime' => 0,
));
$out = $this->serve($controller, $options);
$this->cache = $tmpCache;
return $out['content'];
}
/**
* Show an error page
*
* @param string $header Full header. E.g. 'HTTP/1.0 500 Internal Server Error'
* @param string $url URL to direct the user to
* @param string $msgHtml HTML message for the client
*
* @return void
* @internal This is not part of the public API and is subject to change
* @access private
*/
public function errorExit($header, $url = '', $msgHtml = '')
{
$url = htmlspecialchars($url, ENT_QUOTES);
list(, $h1) = explode(' ', $header, 2);
$h1 = htmlspecialchars($h1);
// FastCGI environments require 3rd arg to header() to be set
list(, $code) = explode(' ', $header, 3);
header($header, true, $code);
header('Content-Type: text/html; charset=utf-8');
echo "<h1>$h1</h1>";
if ($msgHtml) {
echo $msgHtml;
}
if ($url) {
echo "<p>Please see <a href='$url'>$url</a>.</p>";
}
exit;
}
/**
* Default minifier for .min or -min JS files.
*
* @param string $content
* @return string
*/
public static function nullMinifier($content)
{
if (isset($content[0]) && $content[0] === "\xef") {
$content = substr($content, 3);
}
$content = str_replace("\r\n", "\n", $content);
return trim($content);
}
/**
* Setup CSS sources for URI rewriting
*/
protected function setupUriRewrites()
{
foreach ($this->sources as $key => $source) {
$file = $this->env->normalizePath($source->getFilePath());
$minifyOptions = $source->getMinifierOptions();
if ($file
&& !isset($minifyOptions['currentDir'])
&& !isset($minifyOptions['prependRelativePath'])) {
$minifyOptions['currentDir'] = dirname($file);
$source->setMinifierOptions($minifyOptions);
}
}
}
/**
* Set up sources to use Minify_Lines
*/
protected function setupDebug()
{
foreach ($this->sources as $source) {
$source->setMinifier(array('Minify_Lines', 'minify'));
$id = $source->getId();
$source->setMinifierOptions(array(
'id' => (is_file($id) ? basename($id) : $id),
));
}
}
/**
* Combines sources and minifies the result.
*
* @return string
*
* @throws Exception
*/
protected function combineMinify()
{
$type = $this->options['contentType']; // ease readability
// when combining scripts, make sure all statements separated and
// trailing single line comment is terminated
$implodeSeparator = ($type === self::TYPE_JS) ? "\n;" : '';
// allow the user to pass a particular array of options to each
// minifier (designated by type). source objects may still override
// these
if (isset($this->options['minifierOptions'][$type])) {
$defaultOptions = $this->options['minifierOptions'][$type];
} else {
$defaultOptions = array();
}
// if minifier not set, default is no minification. source objects
// may still override this
if (isset($this->options['minifiers'][$type])) {
$defaultMinifier = $this->options['minifiers'][$type];
} else {
$defaultMinifier = false;
}
// process groups of sources with identical minifiers/options
$content = array();
$i = 0;
$l = count($this->sources);
$groupToProcessTogether = array();
$lastMinifier = null;
$lastOptions = null;
do {
// get next source
$source = null;
if ($i < $l) {
$source = $this->sources[$i];
$sourceContent = $source->getContent();
// allow the source to override our minifier and options
$minifier = $source->getMinifier();
if (!$minifier) {
$minifier = $defaultMinifier;
}
$options = array_merge($defaultOptions, $source->getMinifierOptions());
}
// do we need to process our group right now?
if ($i > 0 // yes, we have at least the first group populated
&& (
! $source // yes, we ran out of sources
|| $type === self::TYPE_CSS // yes, to process CSS individually (avoiding PCRE bugs/limits)
|| $minifier !== $lastMinifier // yes, minifier changed
|| $options !== $lastOptions // yes, options changed
)) {
// minify previous sources with last settings
$imploded = implode($implodeSeparator, $groupToProcessTogether);
$groupToProcessTogether = array();
if ($lastMinifier) {
try {
$content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
} catch (Exception $e) {
throw new Exception("Exception in minifier: " . $e->getMessage());
}
} else {
$content[] = $imploded;
}
}
// add content to the group
if ($source) {
$groupToProcessTogether[] = $sourceContent;
$lastMinifier = $minifier;
$lastOptions = $options;
}
$i++;
} while ($source);
$content = implode($implodeSeparator, $content);
if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
$content = $this->handleCssImports($content);
}
// do any post-processing (esp. for editing build URIs)
if ($this->options['postprocessorRequire']) {
require_once $this->options['postprocessorRequire'];
}
if ($this->options['postprocessor']) {
$content = call_user_func($this->options['postprocessor'], $content, $type);
}
return $content;
}
/**
* Make a unique cache id for for this request.
*
* Any settings that could affect output are taken into consideration
*
* @param string $prefix
*
* @return string
*/
protected function _getCacheId($prefix = 'minify')
{
$name = preg_replace('/[^a-zA-Z0-9\\.=_,]/', '', $this->selectionId);
$name = preg_replace('/\\.+/', '.', $name);
$name = substr($name, 0, 100 - 34 - strlen($prefix));
$md5 = md5(serialize(array(
Minify_SourceSet::getDigest($this->sources),
$this->options['minifiers'],
$this->options['minifierOptions'],
$this->options['postprocessor'],
$this->options['bubbleCssImports'],
Minify::VERSION,
)));
return "{$prefix}_{$name}_{$md5}";
}
/**
* Bubble CSS @imports to the top or prepend a warning if an import is detected not at the top.
*
* @param string $css
*
* @return string
*/
protected function handleCssImports($css)
{
if ($this->options['bubbleCssImports']) {
// bubble CSS imports
preg_match_all('/@import.*?;/', $css, $imports);
$css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
return $css;
}
if ('' === $this->options['importWarning']) {
return $css;
}
// remove comments so we don't mistake { in a comment as a block
$noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
$lastImportPos = strrpos($noCommentCss, '@import');
$firstBlockPos = strpos($noCommentCss, '{');
if (false !== $lastImportPos
&& false !== $firstBlockPos
&& $firstBlockPos < $lastImportPos
) {
// { appears before @import : prepend warning
$css = $this->options['importWarning'] . $css;
}
return $css;
}
/**
* Analyze sources (if there are any) and set $options 'contentType'
* and 'lastModifiedTime' if they already aren't.
*
* @param array $options options for Minify
*
* @return array options for Minify
*/
protected function analyzeSources($options = array())
{
if (!$this->sources) {
return $options;
}
$type = null;
foreach ($this->sources as $source) {
$sourceType = $source->getContentType();
if (!empty($options['contentType'])) {
// just verify sources have null content type or match the options
if ($sourceType !== null && $sourceType !== $options['contentType']) {
$this->logger && $this->logger->warning("ContentType mismatch: '{$sourceType}' != '{$options['contentType']}'");
$this->sources = array();
return $options;
}
continue;
}
if ($type === null) {
$type = $sourceType;
} elseif ($sourceType !== $type) {
$this->logger && $this->logger->warning("ContentType mismatch: '{$sourceType}' != '{$type}'");
$this->sources = array();
return $options;
}
}
if (empty($options['contentType'])) {
if (null === $type) {
$type = 'text/plain';
}
$options['contentType'] = $type;
}
// last modified is needed for caching, even if setExpires is set
if (!isset($options['lastModifiedTime'])) {
$max = 0;
foreach ($this->sources as $source) {
$max = max($source->getLastModified(), $max);
}
$options['lastModifiedTime'] = $max;
}
return $options;
}
}

View File

@ -0,0 +1,299 @@
<?php
namespace Minify;
use Minify_Cache_File;
use Minify_CacheInterface;
use Minify_Controller_MinApp;
use Minify_ControllerInterface;
use Minify_DebugDetector;
use Minify_Env;
use Minify_Source_Factory;
use Props\Container;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Monolog;
use Minify;
/**
* @property Minify_CacheInterface $cache
* @property Config $config
* @property string $configPath
* @property Minify_ControllerInterface $controller
* @property string $dir
* @property string $docRoot
* @property Minify_Env $env
* @property Monolog\Handler\ErrorLogHandler $errorLogHandler
* @property array $groupsConfig
* @property string $groupsConfigPath
* @property LoggerInterface $logger
* @property \Minify $minify
* @property array $serveOptions
* @property Minify_Source_Factory $sourceFactory
* @property array $sourceFactoryOptions
*/
class App extends Container
{
/**
* Constructor
*
* @param string $dir Directory containing config files
*/
public function __construct($dir)
{
$that = $this;
$this->dir = rtrim($dir, '/\\');
$this->cache = function (App $app) use ($that) {
$config = $app->config;
if ($config->cachePath instanceof Minify_CacheInterface) {
return $config->cachePath;
}
if (!$config->cachePath || is_string($config->cachePath)) {
return new Minify_Cache_File($config->cachePath, $config->cacheFileLocking, $app->logger);
}
$type = $that->typeOf($config->cachePath);
throw new RuntimeException('$min_cachePath must be a path or implement Minify_CacheInterface.'
. " Given $type");
};
$this->config = function (App $app) {
$config = (require $app->configPath);
if ($config instanceof Minify\Config) {
return $config;
}
// copy from vars into properties
$config = new Minify\Config();
$propNames = array_keys(get_object_vars($config));
$prefixer = function ($name) {
return "min_$name";
};
$varNames = array_map($prefixer, $propNames);
$varDefined = get_defined_vars();
$varNames = array_filter($varNames, function ($name) use ($varDefined) {
return array_key_exists($name, $varDefined);
});
$vars = compact($varNames);
foreach ($varNames as $varName) {
if (isset($vars[$varName])) {
$config->{substr($varName, 4)} = $vars[$varName];
}
}
if ($config->documentRoot) {
// copy into env
if (empty($config->envArgs['server'])) {
$config->envArgs['server'] = $_SERVER;
}
$config->envArgs['server']['DOCUMENT_ROOT'] = $config->documentRoot;
}
return $config;
};
$this->configPath = "{$this->dir}/config.php";
$this->controller = function (App $app) use ($that) {
$config = $app->config;
if (empty($config->factories['controller'])) {
$ctrl = new Minify_Controller_MinApp($app->env, $app->sourceFactory, $app->logger);
} else {
$ctrl = call_user_func($config->factories['controller'], $app);
}
if ($ctrl instanceof Minify_ControllerInterface) {
return $ctrl;
}
$type = $that->typeOf($ctrl);
throw new RuntimeException('$min_factories["controller"] callable must return an implementation'
." of Minify_CacheInterface. Returned $type");
};
$this->docRoot = function (App $app) {
$config = $app->config;
if (empty($config->documentRoot)) {
return $app->env->getDocRoot();
}
return $app->env->normalizePath($config->documentRoot);
};
$this->env = function (App $app) {
return new Minify_Env($app->config->envArgs);
};
$this->errorLogHandler = function (App $app) {
$format = "%channel%.%level_name%: %message% %context% %extra%";
$handler = new Monolog\Handler\ErrorLogHandler();
$handler->setFormatter(new Monolog\Formatter\LineFormatter($format));
return $handler;
};
$this->groupsConfig = function (App $app) {
return (require $app->groupsConfigPath);
};
$this->groupsConfigPath = "{$this->dir}/groupsConfig.php";
$this->logger = function (App $app) use ($that) {
$value = $app->config->errorLogger;
if ($value instanceof LoggerInterface) {
return $value;
}
$logger = new Monolog\Logger('minify');
if (!$value) {
return $logger;
}
if ($value === true || $value instanceof \FirePHP) {
$logger->pushHandler($app->errorLogHandler);
$logger->pushHandler(new Monolog\Handler\FirePHPHandler());
return $logger;
}
if ($value instanceof Monolog\Handler\HandlerInterface) {
$logger->pushHandler($value);
return $logger;
}
// BC
if (is_object($value) && is_callable(array($value, 'log'))) {
$handler = new Minify\Logger\LegacyHandler($value);
$logger->pushHandler($handler);
return $logger;
}
$type = $that->typeOf($value);
throw new RuntimeException('If set, $min_errorLogger must be a PSR-3 logger or a Monolog handler.'
." Given $type");
};
$this->minify = function (App $app) use ($that) {
$config = $app->config;
if (empty($config->factories['minify'])) {
return new \Minify($app->cache, $app->logger);
}
$minify = call_user_func($config->factories['minify'], $app);
if ($minify instanceof \Minify) {
return $minify;
}
$type = $that->typeOf($minify);
throw new RuntimeException('$min_factories["minify"] callable must return a Minify object.'
." Returned $type");
};
$this->serveOptions = function (App $app) {
$config = $app->config;
$env = $app->env;
$ret = $config->serveOptions;
$ret['minifierOptions']['text/css']['docRoot'] = $app->docRoot;
$ret['minifierOptions']['text/css']['symlinks'] = $config->symlinks;
$ret['minApp']['symlinks'] = $config->symlinks;
// auto-add targets to allowDirs
foreach ($config->symlinks as $uri => $target) {
$ret['minApp']['allowDirs'][] = $target;
}
if ($config->allowDebugFlag) {
$ret['debug'] = Minify_DebugDetector::shouldDebugRequest($env);
}
if ($config->concatOnly) {
$ret['concatOnly'] = true;
}
// check for URI versioning
if ($env->get('v') !== null || preg_match('/&\\d/', $app->env->server('QUERY_STRING'))) {
$ret['maxAge'] = 31536000;
}
// need groups config?
if ($env->get('g') !== null) {
$ret['minApp']['groups'] = $app->groupsConfig;
}
return $ret;
};
$this->sourceFactory = function (App $app) {
return new Minify_Source_Factory($app->env, $app->sourceFactoryOptions, $app->cache);
};
$this->sourceFactoryOptions = function (App $app) {
$serveOptions = $app->serveOptions;
$ret = array();
// translate legacy setting to option for source factory
if (isset($serveOptions['minApp']['noMinPattern'])) {
$ret['noMinPattern'] = $serveOptions['minApp']['noMinPattern'];
}
if (isset($serveOptions['minApp']['allowDirs'])) {
$ret['allowDirs'] = $serveOptions['minApp']['allowDirs'];
}
if (isset($serveOptions['checkAllowDirs'])) {
$ret['checkAllowDirs'] = $serveOptions['checkAllowDirs'];
}
if (is_numeric($app->config->uploaderHoursBehind)) {
$ret['uploaderHoursBehind'] = $app->config->uploaderHoursBehind;
}
return $ret;
};
}
public function runServer()
{
if (!$this->env->get('f') && $this->env->get('g') === null) {
// no spec given
$msg = '<p>No "f" or "g" parameters were detected.</p>';
$url = 'https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#long-url-parameters-are-ignored';
$defaults = $this->minify->getDefaultOptions();
$this->minify->errorExit($defaults['badRequestHeader'], $url, $msg);
}
$this->minify->serve($this->controller, $this->serveOptions);
}
/**
* @param mixed $var
* @return string
*/
private function typeOf($var)
{
$type = gettype($var);
return $type === 'object' ? get_class($var) : $type;
}
}

View File

@ -0,0 +1,101 @@
<?php
/**
* Class Minify_Build
* @package Minify
*/
/**
* Maintain a single last modification time for a group of Minify sources to
* allow use of far off Expires headers in Minify.
*
* <code>
* // in config file
* $groupSources = array(
* 'js' => array('file1.js', 'file2.js')
* ,'css' => array('file1.css', 'file2.css', 'file3.css')
* )
*
* // during HTML generation
* $jsBuild = new Minify_Build($groupSources['js']);
* $cssBuild = new Minify_Build($groupSources['css']);
*
* $script = "<script type='text/javascript' src='"
* . $jsBuild->uri('/min.php/js') . "'></script>";
* $link = "<link rel='stylesheet' type='text/css' href='"
* . $cssBuild->uri('/min.php/css') . "'>";
*
* // in min.php
* Minify::serve('Groups', array(
* 'groups' => $groupSources
* ,'setExpires' => (time() + 86400 * 365)
* ));
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Build
{
/**
* Last modification time of all files in the build
*
* @var int
*/
public $lastModified = 0;
/**
* String to use as ampersand in uri(). Set this to '&' if
* you are not HTML-escaping URIs.
*
* @var string
*/
public static $ampersand = '&amp;';
/**
* Get a time-stamped URI
*
* <code>
* echo $b->uri('/site.js');
* // outputs "/site.js?1678242"
*
* echo $b->uri('/scriptaculous.js?load=effects');
* // outputs "/scriptaculous.js?load=effects&amp1678242"
* </code>
*
* @param string $uri
* @param boolean $forceAmpersand (default = false) Force the use of ampersand to
* append the timestamp to the URI.
* @return string
*/
public function uri($uri, $forceAmpersand = false)
{
$sep = ($forceAmpersand || strpos($uri, '?') !== false) ? self::$ampersand : '?';
return "{$uri}{$sep}{$this->lastModified}";
}
/**
* Create a build object
*
* @param array $sources array of Minify_Source objects and/or file paths
*
*/
public function __construct($sources)
{
$max = 0;
foreach ((array)$sources as $source) {
if ($source instanceof Minify_Source) {
$max = max($max, $source->getLastModified());
} elseif (is_string($source)) {
if (0 === strpos($source, '//')) {
$source = $_SERVER['DOCUMENT_ROOT'] . substr($source, 1);
}
if (is_file($source)) {
$max = max($max, filemtime($source));
}
}
}
$this->lastModified = $max;
}
}

View File

@ -0,0 +1,98 @@
<?php
/**
* Class Minify_CSS
* @package Minify
*/
/**
* Minify CSS
*
* This class uses Minify_CSS_Compressor and Minify_CSS_UriRewriter to
* minify CSS and rewrite relative URIs.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
*
* @deprecated Use Minify_CSSmin
*/
class Minify_CSS
{
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options available options:
*
* 'preserveComments': (default true) multi-line comments that begin
* with "/*!" will be preserved with newlines before and after to
* enhance readability.
*
* 'removeCharsets': (default true) remove all @charset at-rules
*
* 'prependRelativePath': (default null) if given, this string will be
* prepended to all relative URIs in import/url declarations
*
* 'currentDir': (default null) if given, this is assumed to be the
* directory of the current CSS file. Using this, minify will rewrite
* all relative URIs in import/url declarations to correctly point to
* the desired files. For this to work, the files *must* exist and be
* visible by the PHP process.
*
* 'symlinks': (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*
* 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
* see Minify_CSS_UriRewriter::rewrite
*
* @return string
*/
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'preserveComments' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
$css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
}
if ($options['compress']) {
if (! $options['preserveComments']) {
$css = Minify_CSS_Compressor::process($css, $options);
} else {
$processor = array('Minify_CSS_Compressor', 'process');
$css = Minify_CommentPreserver::process($css, $processor, array($options));
}
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
$currentDir = $options['currentDir'];
$docRoot = $options['docRoot'];
$symlinks = $options['symlinks'];
return Minify_CSS_UriRewriter::rewrite($css, $currentDir, $docRoot, $symlinks);
}
return Minify_CSS_UriRewriter::prepend($css, $options['prependRelativePath']);
}
}

View File

@ -0,0 +1,275 @@
<?php
/**
* Class Minify_CSS_Compressor
* @package Minify
*/
/**
* Compress CSS
*
* This is a heavy regex-based removal of whitespace, unnecessary
* comments and tokens, and some CSS value minimization, where practical.
* Many steps have been taken to avoid breaking comment-based hacks,
* including the ie5/mac filter (and its inversion), but expect tricky
* hacks involving comment tokens in 'content' value strings to break
* minimization badly. A test suite is available.
*
* Note: This replaces a lot of spaces with line breaks. It's rumored
* (https://github.com/yui/yuicompressor/blob/master/README.md#global-options)
* that some source control tools and old browsers don't like very long lines.
* Compressed files with shorter lines are also easier to diff. If this is
* unacceptable please use CSSmin instead.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
*
* @deprecated Use CSSmin (tubalmartin/cssmin)
*/
class Minify_CSS_Compressor
{
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options (currently ignored)
*
* @return string
*/
public static function process($css, $options = array())
{
$obj = new Minify_CSS_Compressor($options);
return $obj->_process($css);
}
/**
* @var array
*/
protected $_options = null;
/**
* Are we "in" a hack? I.e. are some browsers targetted until the next comment?
*
* @var bool
*/
protected $_inHack = false;
/**
* Constructor
*
* @param array $options (currently ignored)
*/
private function __construct($options)
{
$this->_options = $options;
}
/**
* Minify a CSS string
*
* @param string $css
*
* @return string
*/
protected function _process($css)
{
$css = str_replace("\r\n", "\n", $css);
// preserve empty comment after '>'
// http://www.webdevout.net/css-hacks#in_css-selectors
$css = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $css);
// preserve empty comment between property and value
// http://css-discuss.incutio.com/?page=BoxModelHack
$css = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $css);
$css = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $css);
// apply callback to all valid comments (and strip out surrounding ws
$pattern = '@\\s*/\\*([\\s\\S]*?)\\*/\\s*@';
$css = preg_replace_callback($pattern, array($this, '_commentCB'), $css);
// remove ws around { } and last semicolon in declaration block
$css = preg_replace('/\\s*{\\s*/', '{', $css);
$css = preg_replace('/;?\\s*}\\s*/', '}', $css);
// remove ws surrounding semicolons
$css = preg_replace('/\\s*;\\s*/', ';', $css);
// remove ws around urls
$pattern = '/
url\\( # url(
\\s*
([^\\)]+?) # 1 = the URL (really just a bunch of non right parenthesis)
\\s*
\\) # )
/x';
$css = preg_replace($pattern, 'url($1)', $css);
// remove ws between rules and colons
$pattern = '/
\\s*
([{;]) # 1 = beginning of block or rule separator
\\s*
([\\*_]?[\\w\\-]+) # 2 = property (and maybe IE filter)
\\s*
:
\\s*
(\\b|[#\'"-]) # 3 = first character of a value
/x';
$css = preg_replace($pattern, '$1$2:$3', $css);
// remove ws in selectors
$pattern = '/
(?: # non-capture
\\s*
[^~>+,\\s]+ # selector part
\\s*
[,>+~] # combinators
)+
\\s*
[^~>+,\\s]+ # selector part
{ # open declaration block
/x';
$css = preg_replace_callback($pattern, array($this, '_selectorsCB'), $css);
// minimize hex colors
$pattern = '/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i';
$css = preg_replace($pattern, '$1#$2$3$4$5', $css);
// remove spaces between font families
$pattern = '/font-family:([^;}]+)([;}])/';
$css = preg_replace_callback($pattern, array($this, '_fontFamilyCB'), $css);
$css = preg_replace('/@import\\s+url/', '@import url', $css);
// replace any ws involving newlines with a single newline
$css = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $css);
// separate common descendent selectors w/ newlines (to limit line lengths)
$pattern = '/([\\w#\\.\\*]+)\\s+([\\w#\\.\\*]+){/';
$css = preg_replace($pattern, "$1\n$2{", $css);
// Use newline after 1st numeric value (to limit line lengths).
$pattern = '/
((?:padding|margin|border|outline):\\d+(?:px|em)?) # 1 = prop : 1st numeric value
\\s+
/x';
$css = preg_replace($pattern, "$1\n", $css);
// prevent triggering IE6 bug: http://www.crankygeek.com/ie6pebug/
$css = preg_replace('/:first-l(etter|ine)\\{/', ':first-l$1 {', $css);
return trim($css);
}
/**
* Replace what looks like a set of selectors
*
* @param array $m regex matches
*
* @return string
*/
protected function _selectorsCB($m)
{
// remove ws around the combinators
return preg_replace('/\\s*([,>+~])\\s*/', '$1', $m[0]);
}
/**
* Process a comment and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _commentCB($m)
{
$hasSurroundingWs = (trim($m[0]) !== $m[1]);
$m = $m[1];
// $m is the comment content w/o the surrounding tokens,
// but the return value will replace the entire comment.
if ($m === 'keep') {
return '/**/';
}
if ($m === '" "') {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*" "*/';
}
if (preg_match('@";\\}\\s*\\}/\\*\\s+@', $m)) {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*";}}/* */';
}
if ($this->_inHack) {
// inversion: feeding only to one browser
$pattern = '@
^/ # comment started like /*/
\\s*
(\\S[\\s\\S]+?) # has at least some non-ws content
\\s*
/\\* # ends like /*/ or /**/
@x';
if (preg_match($pattern, $m, $n)) {
// end hack mode after this comment, but preserve the hack and comment content
$this->_inHack = false;
return "/*/{$n[1]}/**/";
}
}
if (substr($m, -1) === '\\') { // comment ends like \*/
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*\\*/';
}
if ($m !== '' && $m[0] === '/') { // comment looks like /*/ foo */
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*/*/';
}
if ($this->_inHack) {
// a regular comment ends hack mode but should be preserved
$this->_inHack = false;
return '/**/';
}
// Issue 107: if there's any surrounding whitespace, it may be important, so
// replace the comment with a single space
return $hasSurroundingWs ? ' ' : ''; // remove all other comments
}
/**
* Process a font-family listing and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _fontFamilyCB($m)
{
// Issue 210: must not eliminate WS between words in unquoted families
$flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
$pieces = preg_split('/(\'[^\']+\'|"[^"]+")/', $m[1], null, $flags);
$out = 'font-family:';
while (null !== ($piece = array_shift($pieces))) {
if ($piece[0] !== '"' && $piece[0] !== "'") {
$piece = preg_replace('/\\s+/', ' ', $piece);
$piece = preg_replace('/\\s?,\\s?/', ',', $piece);
}
$out .= $piece;
}
return $out . $m[2];
}
}

View File

@ -0,0 +1,358 @@
<?php
/**
* Class Minify_CSS_UriRewriter
* @package Minify
*/
/**
* Rewrite file-relative URIs as root-relative in CSS files
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_CSS_UriRewriter
{
/**
* rewrite() and rewriteRelative() append debugging information here
*
* @var string
*/
public static $debugText = '';
/**
* In CSS content, rewrite file relative URIs as root relative
*
* @param string $css
*
* @param string $currentDir The directory of the current CSS file.
*
* @param string $docRoot The document root of the web site in which
* the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
*
* @param array $symlinks (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*
* @return string
*/
public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array())
{
self::$_docRoot = self::_realpath(
$docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
);
self::$_currentDir = self::_realpath($currentDir);
self::$_symlinks = array();
// normalize symlinks in order to map to link
foreach ($symlinks as $link => $target) {
$link = ($link === '//') ? self::$_docRoot : str_replace('//', self::$_docRoot . '/', $link);
$link = strtr($link, '/', DIRECTORY_SEPARATOR);
self::$_symlinks[$link] = self::_realpath($target);
}
self::$debugText .= "docRoot : " . self::$_docRoot . "\n"
. "currentDir : " . self::$_currentDir . "\n";
if (self::$_symlinks) {
self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n";
}
self::$debugText .= "\n";
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
// rewrite
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
$pattern = '/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
$css = self::_unOwlify($css);
return $css;
}
/**
* In CSS content, prepend a path to relative URIs
*
* @param string $css
*
* @param string $path The path to prepend.
*
* @return string
*/
public static function prepend($css, $path)
{
self::$_prependPath = $path;
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
// append
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
$pattern = '/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
$css = self::_unOwlify($css);
self::$_prependPath = null;
return $css;
}
/**
* Get a root relative URI from a file relative URI
*
* <code>
* Minify_CSS_UriRewriter::rewriteRelative(
* '../img/hello.gif'
* , '/home/user/www/css' // path of CSS file
* , '/home/user/www' // doc root
* );
* // returns '/img/hello.gif'
*
* // example where static files are stored in a symlinked directory
* Minify_CSS_UriRewriter::rewriteRelative(
* 'hello.gif'
* , '/var/staticFiles/theme'
* , '/home/user/www'
* , array('/home/user/www/static' => '/var/staticFiles')
* );
* // returns '/static/theme/hello.gif'
* </code>
*
* @param string $uri file relative URI
*
* @param string $realCurrentDir realpath of the current file's directory.
*
* @param string $realDocRoot realpath of the site document root.
*
* @param array $symlinks (default = array()) If the file is stored in
* a symlink-ed directory, provide an array of link paths to
* real target paths, where the link paths "appear" to be within the document
* root. E.g.:
* <code>
* array('/home/foo/www/not/real/path' => '/real/target/path') // unix
* array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows
* </code>
*
* @return string
*/
public static function rewriteRelative($uri, $realCurrentDir, $realDocRoot, $symlinks = array())
{
// prepend path with current dir separator (OS-independent)
$path = strtr($realCurrentDir, '/', DIRECTORY_SEPARATOR);
$path .= DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
self::$debugText .= "file-relative URI : {$uri}\n"
. "path prepended : {$path}\n";
// "unresolve" a symlink back to doc root
foreach ($symlinks as $link => $target) {
if (0 === strpos($path, $target)) {
// replace $target with $link
$path = $link . substr($path, strlen($target));
self::$debugText .= "symlink unresolved : {$path}\n";
break;
}
}
// strip doc root
$path = substr($path, strlen($realDocRoot));
self::$debugText .= "docroot stripped : {$path}\n";
// fix to root-relative URI
$uri = strtr($path, '/\\', '//');
$uri = self::removeDots($uri);
self::$debugText .= "traversals removed : {$uri}\n\n";
return $uri;
}
/**
* Remove instances of "./" and "../" where possible from a root-relative URI
*
* @param string $uri
*
* @return string
*/
public static function removeDots($uri)
{
$uri = str_replace('/./', '/', $uri);
// inspired by patch from Oleg Cherniy
do {
$uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, 1, $changed);
} while ($changed);
return $uri;
}
/**
* Defines which class to call as part of callbacks, change this
* if you extend Minify_CSS_UriRewriter
*
* @var string
*/
protected static $className = 'Minify_CSS_UriRewriter';
/**
* Get realpath with any trailing slash removed. If realpath() fails,
* just remove the trailing slash.
*
* @param string $path
*
* @return mixed path with no trailing slash
*/
protected static function _realpath($path)
{
$realPath = realpath($path);
if ($realPath !== false) {
$path = $realPath;
}
return rtrim($path, '/\\');
}
/**
* Directory of this stylesheet
*
* @var string
*/
private static $_currentDir = '';
/**
* DOC_ROOT
*
* @var string
*/
private static $_docRoot = '';
/**
* directory replacements to map symlink targets back to their
* source (within the document root) E.g. '/var/www/symlink' => '/var/realpath'
*
* @var array
*/
private static $_symlinks = array();
/**
* Path to prepend
*
* @var string
*/
private static $_prependPath = null;
/**
* @param string $css
*
* @return string
*/
private static function _trimUrls($css)
{
$pattern = '/
url\\( # url(
\\s*
([^\\)]+?) # 1 = URI (assuming does not contain ")")
\\s*
\\) # )
/x';
return preg_replace($pattern, 'url($1)', $css);
}
/**
* @param array $m
*
* @return string
*/
private static function _processUriCB($m)
{
// $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
$isImport = ($m[0][0] === '@');
// determine URI and the quote character (if any)
if ($isImport) {
$quoteChar = $m[1];
$uri = $m[2];
} else {
// $m[1] is either quoted or not
$quoteChar = ($m[1][0] === "'" || $m[1][0] === '"') ? $m[1][0] : '';
$uri = ($quoteChar === '') ? $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
if (self::$_prependPath === null) {
$uri = self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks);
} else {
$uri = self::$_prependPath . $uri;
if ($uri[0] === '/') {
$root = '';
$rootRelative = $uri;
$uri = $root . self::removeDots($rootRelative);
} elseif (preg_match('@^((https?\:)?//([^/]+))/@', $uri, $m) && (false !== strpos($m[3], '.'))) {
$root = $m[1];
$rootRelative = substr($uri, strlen($root));
$uri = $root . self::removeDots($rootRelative);
}
}
}
if ($isImport) {
return "@import {$quoteChar}{$uri}{$quoteChar}";
} else {
return "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)
{
$pattern = '~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)url(\(\s*#\w+\s*\))~';
return preg_replace($pattern, '$1owl$2', $css);
}
/**
* Undo work of _owlify
*
* @see _owlifySvgPaths
*
* @param string $css
* @return string
*/
private static function _unOwlify($css)
{
$pattern = '~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)owl~';
return preg_replace($pattern, '$1url', $css);
}
}

View File

@ -0,0 +1,88 @@
<?php
/**
* Class Minify_CSSmin
* @package Minify
*/
use tubalmartin\CssMin\Minifier as CSSmin;
/**
* Wrapper for CSSmin
*
* This class uses CSSmin and Minify_CSS_UriRewriter to minify CSS and rewrite relative URIs.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_CSSmin
{
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options available options:
*
* 'removeCharsets': (default true) remove all @charset at-rules
*
* 'prependRelativePath': (default null) if given, this string will be
* prepended to all relative URIs in import/url declarations
*
* 'currentDir': (default null) if given, this is assumed to be the
* directory of the current CSS file. Using this, minify will rewrite
* all relative URIs in import/url declarations to correctly point to
* the desired files. For this to work, the files *must* exist and be
* visible by the PHP process.
*
* 'symlinks': (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*
* 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
* see Minify_CSS_UriRewriter::rewrite
*
* @return string
*/
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
$css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
}
if ($options['compress']) {
$obj = new CSSmin();
$css = $obj->run($css);
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
return Minify_CSS_UriRewriter::rewrite(
$css,
$options['currentDir'],
$options['docRoot'],
$options['symlinks']
);
}
return Minify_CSS_UriRewriter::prepend(
$css,
$options['prependRelativePath']
);
}
}

View File

@ -0,0 +1,136 @@
<?php
/**
* Class Minify_Cache_APC
* @package Minify
*/
/**
* APC-based cache class for Minify
*
* <code>
* Minify::setCache(new Minify_Cache_APC());
* </code>
*
* @package Minify
* @author Chris Edwards
**/
class Minify_Cache_APC implements Minify_CacheInterface
{
/**
* Create a Minify_Cache_APC object, to be passed to
* Minify::setCache().
*
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*
* @return null
*/
public function __construct($expire = 0)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return apc_store($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;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return 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 apc, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = apc_fetch($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}

View File

@ -0,0 +1,183 @@
<?php
/**
* Class Minify_Cache_File
* @package Minify
*/
use Psr\Log\LoggerInterface;
class Minify_Cache_File implements Minify_CacheInterface
{
/**
* @var string
*/
private $path;
/**
* @var bool
*/
private $locking;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @param string $path
* @param bool $fileLocking
* @param LoggerInterface $logger
*/
public function __construct($path = '', $fileLocking = false, LoggerInterface $logger = null)
{
if (! $path) {
$path = sys_get_temp_dir();
}
$this->locking = $fileLocking;
$this->path = $path;
if (!$logger) {
$logger = new \Monolog\Logger('minify');
}
$this->logger = $logger;
}
/**
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
$flag = $this->locking ? LOCK_EX : null;
$file = $this->path . '/' . $id;
if (! @file_put_contents($file, $data, $flag)) {
$this->logger->warning("Minify_Cache_File: Write failed to '$file'");
}
// write control
if ($data !== $this->fetch($id)) {
@unlink($file);
$this->logger->warning("Minify_Cache_File: Post-write read failed for '$file'");
return false;
}
return true;
}
/**
* Get the size of a cache entry
*
* @param string $id cache id (e.g. a filename)
*
* @return int size in bytes
*/
public function getSize($id)
{
return filesize($this->path . '/' . $id);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
$file = $this->path . '/' . $id;
return (is_file($file) && (filemtime($file) >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id (e.g. a filename)
*/
public function display($id)
{
if (!$this->locking) {
readfile($this->path . '/' . $id);
return;
}
$fp = fopen($this->path . '/' . $id, 'rb');
flock($fp, LOCK_SH);
fpassthru($fp);
flock($fp, LOCK_UN);
fclose($fp);
}
/**
* Fetch the cached content
*
* @param string $id cache id (e.g. a filename)
*
* @return string
*/
public function fetch($id)
{
if (!$this->locking) {
return file_get_contents($this->path . '/' . $id);
}
$fp = fopen($this->path . '/' . $id, 'rb');
if (!$fp) {
return false;
}
flock($fp, LOCK_SH);
$ret = stream_get_contents($fp);
flock($fp, LOCK_UN);
fclose($fp);
return $ret;
}
/**
* Fetch the cache path used
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get a usable temp directory
*
* @return string
* @deprecated
*/
public static function tmp()
{
trigger_error(__METHOD__ . ' is deprecated in Minfy 3.0', E_USER_DEPRECATED);
return sys_get_temp_dir();
}
/**
* Send message to the Minify logger
* @param string $msg
* @return null
* @deprecated Use $this->logger
*/
protected function _log($msg)
{
trigger_error(__METHOD__ . ' is deprecated in Minify 3.0.', E_USER_DEPRECATED);
$this->logger->warning($msg);
}
}

View File

@ -0,0 +1,141 @@
<?php
/**
* Class Minify_Cache_Memcache
* @package Minify
*/
/**
* Memcache-based cache class for Minify
*
* <code>
* // fall back to disk caching if memcache can't connect
* $memcache = new Memcache;
* if ($memcache->connect('localhost', 11211)) {
* Minify::setCache(new Minify_Cache_Memcache($memcache));
* } else {
* Minify::setCache();
* }
* </code>
**/
class Minify_Cache_Memcache implements Minify_CacheInterface
{
/**
* Create a Minify_Cache_Memcache object, to be passed to
* Minify::setCache().
*
* @param Memcache $memcache already-connected instance
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*/
public function __construct($memcache, $expire = 0)
{
$this->_mc = $memcache;
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return $this->_mc->set($id, "{$_SERVER['REQUEST_TIME']}|{$data}", 0, $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;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return 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 $_mc = null;
private $_exp = null;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
/**
* Fetch data and timestamp from memcache, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = $this->_mc->get($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}

View File

@ -0,0 +1,67 @@
<?php
/**
* Class Minify_Cache_Null
*
* If this is used, Minify will not use a cache and, for each 200 response, will
* need to recombine files, minify and encode the output.
*
* @package Minify
*/
class Minify_Cache_Null implements Minify_CacheInterface
{
/**
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
}
/**
* Get the size of a cache entry
*
* @param string $id cache id (e.g. a filename)
*
* @return int size in bytes
*/
public function getSize($id)
{
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
}
/**
* Send the cached content to output
*
* @param string $id cache id (e.g. a filename)
*/
public function display($id)
{
}
/**
* Fetch the cached content
*
* @param string $id cache id (e.g. a filename)
*
* @return string
*/
public function fetch($id)
{
}
}

View File

@ -0,0 +1,139 @@
<?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 implements Minify_CacheInterface
{
/**
* 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)
*
* @throws Exception
*/
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;
}
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return 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

@ -0,0 +1,130 @@
<?php
/**
* Class Minify_Cache_XCache
*
* @link http://xcache.lighttpd.net/
* @package Minify
*/
/**
* XCache-based cache class for Minify
* {@see http://xcache.lighttpd.net/wiki/XcacheApi XCache API}
*
* <code>
* Minify::setCache(new Minify_Cache_XCache());
* </code>
*
* @package Minify
* @author Elan Ruusamäe <glen@delfi.ee>
**/
class Minify_Cache_XCache implements Minify_CacheInterface
{
/**
* Create a Minify_Cache_XCache 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)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
* @param string $data
* @return bool success
*/
public function store($id, $data)
{
return xcache_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;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return 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 xcache, store in instance
*
* @param string $id
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = xcache_get($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}

View File

@ -0,0 +1,129 @@
<?php
/**
* Class Minify_Cache_ZendPlatform
* @package Minify
*/
/**
* ZendPlatform-based cache class for Minify
*
* Based on Minify_Cache_APC, uses output_cache_get/put (currently deprecated)
*
* <code>
* Minify::setCache(new Minify_Cache_ZendPlatform());
* </code>
*
* @package Minify
* @author Patrick van Dissel
*/
class Minify_Cache_ZendPlatform implements Minify_CacheInterface
{
/**
* Create a Minify_Cache_ZendPlatform 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)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return output_cache_put($id, "{$_SERVER['REQUEST_TIME']}|{$data}");
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
return $this->_fetch($id) ? strlen($this->_data) : false;
}
/**
* 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 ZendPlatform, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = output_cache_get($id, $this->_exp);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}

View File

@ -0,0 +1,58 @@
<?php
/**
* Interface Minify_CacheInterface
* @package Minify
*/
/**
* Interface for Minify cache adapters
*
* @package Minify
*/
interface Minify_CacheInterface
{
/**
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
* @param string $data
*
* @return bool success
*/
public function store($id, $data);
/**
* Get the size of a cache entry
*
* @param string $id cache id (e.g. a filename)
*
* @return int size in bytes
*/
public function getSize($id);
/**
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime);
/**
* Send the cached content to output
*
* @param string $id cache id (e.g. a filename)
*/
public function display($id);
/**
* Fetch the cached content
*
* @param string $id cache id (e.g. a filename)
*
* @return string
*/
public function fetch($id);
}

View File

@ -0,0 +1,240 @@
<?php
/**
* Class Minify_ClosureCompiler
* @package Minify
*/
/**
* Compress Javascript using the Closure Compiler
*
* You must set $jarFile and $tempDir before calling the minify functions.
* Also, depending on your shell's environment, you may need to specify
* the full path to java in $javaExecutable or use putenv() to setup the
* Java environment.
*
* <code>
* Minify_ClosureCompiler::$jarFile = '/path/to/closure-compiler-20120123.jar';
* Minify_ClosureCompiler::$tempDir = '/tmp';
* $code = Minify_ClosureCompiler::minify(
* $code,
* array('compilation_level' => 'SIMPLE_OPTIMIZATIONS')
* );
*
* --compilation_level WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS
*
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author Elan Ruusamäe <glen@delfi.ee>
*/
class Minify_ClosureCompiler
{
public static $isDebug = false;
/**
* Filepath of the Closure Compiler jar file. This must be set before
* calling minifyJs().
*
* @var string
*/
public static $jarFile;
/**
* Writable temp directory. This must be set before calling minifyJs().
*
* @var string
*/
public static $tempDir;
/**
* Filepath of "java" executable (may be needed if not in shell's PATH)
*
* @var string
*/
public static $javaExecutable = 'java';
/**
* Default command line options passed to closure-compiler
*
* @var array
*/
public static $defaultOptions = array(
'charset' => 'utf-8',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'warning_level' => 'QUIET',
);
/**
* Minify a Javascript string
*
* @param string $js
* @param array $options (verbose is ignored)
* @see https://code.google.com/p/closure-compiler/source/browse/trunk/README
* @return string
* @throws Minify_ClosureCompiler_Exception
*/
public static function minify($js, $options = array())
{
$min = new static();
return $min->process($js, $options);
}
/**
* Process $js using $options.
*
* @param string $js
* @param array $options
* @return string
* @throws Exception
* @throws Minify_ClosureCompiler_Exception
*/
public function process($js, $options)
{
$tmpFile = $this->dumpFile(self::$tempDir, $js);
try {
$result = $this->compile($tmpFile, $options);
} catch (Exception $e) {
unlink($tmpFile);
throw $e;
}
unlink($tmpFile);
return $result;
}
/**
* @param string $tmpFile
* @param array $options
* @return string
* @throws Minify_ClosureCompiler_Exception
*/
protected function compile($tmpFile, $options)
{
$command = $this->getCommand($options, $tmpFile);
return implode("\n", $this->shell($command));
}
/**
* @param array $userOptions
* @param string $tmpFile
* @return string
*/
protected function getCommand($userOptions, $tmpFile)
{
$args = array_merge(
$this->getCompilerCommandLine(),
$this->getOptionsCommandLine($userOptions)
);
return implode(' ', $args) . ' ' . escapeshellarg($tmpFile);
}
/**
* @return array
* @throws Minify_ClosureCompiler_Exception
*/
protected function getCompilerCommandLine()
{
$this->checkJar(self::$jarFile);
$server = array(
self::$javaExecutable,
'-jar',
escapeshellarg(self::$jarFile)
);
return $server;
}
/**
* @param array $userOptions
* @return array
*/
protected function getOptionsCommandLine($userOptions)
{
$args = array();
$options = array_merge(
static::$defaultOptions,
$userOptions
);
foreach ($options as $key => $value) {
$args[] = "--{$key} " . escapeshellarg($value);
}
return $args;
}
/**
* @param string $jarFile
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkJar($jarFile)
{
if (!is_file($jarFile)) {
throw new Minify_ClosureCompiler_Exception('$jarFile(' . $jarFile . ') is not a valid file.');
}
if (!is_readable($jarFile)) {
throw new Minify_ClosureCompiler_Exception('$jarFile(' . $jarFile . ') is not readable.');
}
}
/**
* @param string $tempDir
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkTempdir($tempDir)
{
if (!is_dir($tempDir)) {
throw new Minify_ClosureCompiler_Exception('$tempDir(' . $tempDir . ') is not a valid direcotry.');
}
if (!is_writable($tempDir)) {
throw new Minify_ClosureCompiler_Exception('$tempDir(' . $tempDir . ') is not writable.');
}
}
/**
* Write $content to a temporary file residing in $dir.
*
* @param string $dir
* @param string $content
* @return string
* @throws Minify_ClosureCompiler_Exception
*/
protected function dumpFile($dir, $content)
{
$this->checkTempdir($dir);
$tmpFile = tempnam($dir, 'cc_');
if (!$tmpFile) {
throw new Minify_ClosureCompiler_Exception('Could not create temp file in "' . $dir . '".');
}
file_put_contents($tmpFile, $content);
return $tmpFile;
}
/**
* Execute command, throw if exit code is not in $expectedCodes array
*
* @param string $command
* @param array $expectedCodes
* @return mixed
* @throws Minify_ClosureCompiler_Exception
*/
protected function shell($command, $expectedCodes = array(0))
{
exec($command, $output, $result_code);
if (!in_array($result_code, $expectedCodes)) {
throw new Minify_ClosureCompiler_Exception("Unpexpected return code: $result_code");
}
return $output;
}
}
class Minify_ClosureCompiler_Exception extends Exception
{
}

View File

@ -0,0 +1,87 @@
<?php
/**
* Class Minify_CommentPreserver
* @package Minify
*/
/**
* Process a string in pieces preserving C-style comments that begin with "/*!"
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_CommentPreserver
{
/**
* String to be prepended to each preserved comment
*
* @var string
*/
public static $prepend = "\n";
/**
* String to be appended to each preserved comment
*
* @var string
*/
public static $append = "\n";
/**
* Process a string outside of C-style comments that begin with "/*!"
*
* On each non-empty string outside these comments, the given processor
* function will be called. The comments will be surrounded by
* Minify_CommentPreserver::$preprend and Minify_CommentPreserver::$append.
*
* @param string $content
* @param callback $processor function
* @param array $args array of extra arguments to pass to the processor
* function (default = array())
* @return string
*/
public static function process($content, $processor, $args = array())
{
$ret = '';
while (true) {
list($beforeComment, $comment, $afterComment) = self::_nextComment($content);
if ('' !== $beforeComment) {
$callArgs = $args;
array_unshift($callArgs, $beforeComment);
$ret .= call_user_func_array($processor, $callArgs);
}
if (false === $comment) {
break;
}
$ret .= $comment;
$content = $afterComment;
}
return $ret;
}
/**
* Extract comments that YUI Compressor preserves.
*
* @param string $in input
*
* @return array 3 elements are returned. If a YUI comment is found, the
* 2nd element is the comment and the 1st and 3rd are the surrounding
* strings. If no comment is found, the entire string is returned as the
* 1st element and the other two are false.
*/
private static function _nextComment($in)
{
if (false === ($start = strpos($in, '/*!')) || false === ($end = strpos($in, '*/', $start + 3))) {
return array($in, false, false);
}
$beforeComment = substr($in, 0, $start);
$comment = self::$prepend . '/*!' . substr($in, $start + 3, $end - $start - 1) . self::$append;
$endChars = (strlen($in) - $end - 2);
$afterComment = (0 === $endChars) ? '' : substr($in, -$endChars);
return array($beforeComment, $comment, $afterComment);
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace Minify;
use Minify_CacheInterface;
class Config
{
/**
* @var bool
*/
public $enableBuilder = false;
/**
* @var bool
*/
public $enableStatic = false;
/**
* @var bool
*/
public $concatOnly = false;
/**
* @var string
*/
public $builderPassword = 'admin';
/**
* @var bool|object
*/
public $errorLogger = false;
/**
* @var bool
*/
public $allowDebugFlag = false;
/**
* @var string|Minify_CacheInterface
*/
public $cachePath = '';
/**
* @var string
*/
public $documentRoot = '';
/**
* @var bool
*/
public $cacheFileLocking = true;
/**
* @var array
*/
public $serveOptions = array();
/**
* @var array
*/
public $symlinks = array();
/**
* @var int
*/
public $uploaderHoursBehind = 0;
/**
* @var array
*/
public $envArgs = array();
/**
* @var callable[]
*/
public $factories = array();
}

View File

@ -0,0 +1,81 @@
<?php
/**
* Class Minify_Controller_Base
* @package Minify
*/
use Psr\Log\LoggerInterface;
use Monolog\Logger;
/**
* Base class for Minify controller
*
* The controller class validates a request and uses it to create a configuration for Minify::serve().
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
abstract class Minify_Controller_Base implements Minify_ControllerInterface
{
/**
* @var Minify_Env
*/
protected $env;
/**
* @var Minify_Source_Factory
*/
protected $sourceFactory;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @param Minify_Env $env
* @param Minify_Source_Factory $sourceFactory
* @param LoggerInterface $logger
*/
public function __construct(Minify_Env $env, Minify_Source_Factory $sourceFactory, LoggerInterface $logger = null)
{
$this->env = $env;
$this->sourceFactory = $sourceFactory;
if (!$logger) {
$logger = new Logger('minify');
}
$this->logger = $logger;
}
/**
* Create controller sources and options for Minify::serve()
*
* @param array $options controller and Minify options
*
* @return Minify_ServeConfiguration
*/
abstract public function createConfiguration(array $options);
/**
* Send message to the Minify logger
*
* @param string $msg
*
* @return null
* @deprecated use $this->logger
*/
public function log($msg)
{
trigger_error(__METHOD__ . ' is deprecated in Minify 3.0.', E_USER_DEPRECATED);
$this->logger->info($msg);
}
/**
* {@inheritdoc}
*/
public function getEnv()
{
return $this->env;
}
}

View File

@ -0,0 +1,70 @@
<?php
/**
* Class Minify_Controller_Files
* @package Minify
*/
use Monolog\Logger;
/**
* Controller class for minifying a set of files
*
* E.g. the following would serve the minified Javascript for a site
* <code>
* $options = [
* 'checkAllowDirs' => false, // allow files to be anywhere
* ];
* $sourceFactory = new Minify_Source_Factory($env, $options, $cache);
* $controller = new Minify_Controller_Files($env, $sourceFactory);
* $minify->serve($controller, [
* 'files' => [
* '//js/jquery.js',
* '//js/plugins.js',
* '/home/username/file.js',
* ],
* ]);
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_Files extends Minify_Controller_Base
{
/**
* Set up file sources
*
* @param array $options controller and Minify options
* @return Minify_ServeConfiguration
*
* Controller options:
*
* 'files': (required) array of complete file paths, or a single path
*/
public function createConfiguration(array $options)
{
// strip controller options
$files = $options['files'];
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
}
unset($options['files']);
$sources = array();
foreach ($files as $file) {
try {
$sources[] = $this->sourceFactory->makeSource($file);
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
return new Minify_ServeConfiguration($options);
}
}
return new Minify_ServeConfiguration($options, $sources);
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* Class Minify_Controller_Groups
* @package Minify
*/
/**
* Controller class for serving predetermined groups of minimized sets, selected
* by PATH_INFO
*
* <code>
* Minify::serve('Groups', array(
* 'groups' => array(
* 'css' => array('//css/type.css', '//css/layout.css')
* ,'js' => array('//js/jquery.js', '//js/site.js')
* )
* ));
* </code>
*
* If the above code were placed in /serve.php, it would enable the URLs
* /serve.php/js and /serve.php/css
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_Groups extends Minify_Controller_Files
{
/**
* Set up groups of files as sources
*
* @param array $options controller and Minify options
*
* 'groups': (required) array mapping PATH_INFO strings to arrays
* of complete file paths. @see Minify_Controller_Groups
*
* @return array Minify options
*/
public function createConfiguration(array $options)
{
// strip controller options
$groups = $options['groups'];
unset($options['groups']);
$server = $this->env->server();
// mod_fcgid places PATH_INFO in ORIG_PATH_INFO
if (isset($server['ORIG_PATH_INFO'])) {
$pathInfo = substr($server['ORIG_PATH_INFO'], 1);
} elseif (isset($server['PATH_INFO'])) {
$pathInfo = substr($server['PATH_INFO'], 1);
} else {
$pathInfo = false;
}
if (false === $pathInfo || ! isset($groups[$pathInfo])) {
// no PATH_INFO or not a valid group
$this->logger->info("Missing PATH_INFO or no group set for \"$pathInfo\"");
return new Minify_ServeConfiguration($options);
}
$files = $groups[$pathInfo];
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
}
$options['files'] = $files;
return parent::createConfiguration($options);
}
}

View File

@ -0,0 +1,196 @@
<?php
/**
* Class Minify_Controller_MinApp
* @package Minify
*/
/**
* Controller class for requests to /min/index.php
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_MinApp extends Minify_Controller_Base
{
/**
* Set up groups of files as sources
*
* @param array $options controller and Minify options
*
* @return array Minify options
*/
public function createConfiguration(array $options)
{
// PHP insecure by default: realpath() and other FS functions can't handle null bytes.
$get = $this->env->get();
foreach (array('g', 'b', 'f') as $key) {
if (isset($get[$key])) {
$get[$key] = str_replace("\x00", '', (string)$get[$key]);
}
}
// filter controller options
$defaults = array(
'groupsOnly' => false,
'groups' => array(),
'symlinks' => array(),
);
$minApp = isset($options['minApp']) ? $options['minApp'] : array();
$localOptions = array_merge($defaults, $minApp);
unset($options['minApp']);
// normalize $symlinks in order to map to target
$symlinks = array();
foreach ($localOptions['symlinks'] as $link => $target) {
if (0 === strpos($link, '//')) {
$link = rtrim(substr($link, 1), '/') . '/';
$target = rtrim($target, '/\\');
$symlinks[$link] = $target;
}
}
$sources = array();
$selectionId = '';
$firstMissing = null;
if (isset($get['g'])) {
// add group(s)
$selectionId .= 'g=' . $get['g'];
$keys = explode(',', $get['g']);
if ($keys != array_unique($keys)) {
$this->logger->info("Duplicate group key found.");
return new Minify_ServeConfiguration($options);
}
foreach ($keys as $key) {
if (! isset($localOptions['groups'][$key])) {
$this->logger->info("A group configuration for \"{$key}\" was not found");
return new Minify_ServeConfiguration($options);
}
$files = $localOptions['groups'][$key];
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
}
foreach ($files as $file) {
try {
$source = $this->sourceFactory->makeSource($file);
$sources[] = $source;
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
if (null === $firstMissing) {
$firstMissing = basename($file);
continue;
} else {
$secondMissing = basename($file);
$this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing'");
return new Minify_ServeConfiguration($options);
}
}
}
}
}
if (! $localOptions['groupsOnly'] && isset($get['f'])) {
// try user files
// The following restrictions are to limit the URLs that minify will
// respond to.
// verify at least one file, files are single comma separated, and are all same extension
$validPattern = preg_match('/^[^,]+\\.(css|less|scss|js)(?:,[^,]+\\.\\1)*$/', $get['f'], $m);
$hasComment = strpos($get['f'], '//') !== false;
$hasEscape = strpos($get['f'], '\\') !== false;
if (!$validPattern || $hasComment || $hasEscape) {
$this->logger->info("GET param 'f' was invalid");
return new Minify_ServeConfiguration($options);
}
$ext = ".{$m[1]}";
$files = explode(',', $get['f']);
if ($files != array_unique($files)) {
$this->logger->info("Duplicate files were specified");
return new Minify_ServeConfiguration($options);
}
if (isset($get['b'])) {
// check for validity
$isValidBase = preg_match('@^[^/]+(?:/[^/]+)*$@', $get['b']);
$hasDots = false !== strpos($get['b'], '..');
$isDot = $get['b'] === '.';
if ($isValidBase && !$hasDots && !$isDot) {
// valid base
$base = "/{$get['b']}/";
} else {
$this->logger->info("GET param 'b' was invalid");
return new Minify_ServeConfiguration($options);
}
} else {
$base = '/';
}
$basenames = array(); // just for cache id
foreach ($files as $file) {
$uri = $base . $file;
$path = $this->env->getDocRoot() . $uri;
// try to rewrite path
foreach ($symlinks as $link => $target) {
if (0 === strpos($uri, $link)) {
$path = $target . DIRECTORY_SEPARATOR . substr($uri, strlen($link));
break;
}
}
try {
$source = $this->sourceFactory->makeSource($path);
$sources[] = $source;
$basenames[] = basename($path, $ext);
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
if (null === $firstMissing) {
$firstMissing = $uri;
continue;
} else {
$secondMissing = $uri;
$this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing`'");
return new Minify_ServeConfiguration($options);
}
}
}
if ($selectionId) {
$selectionId .= '_f=';
}
$selectionId .= implode(',', $basenames) . $ext;
}
if (!$sources) {
$this->logger->info("No sources to serve");
return new Minify_ServeConfiguration($options);
}
if (null !== $firstMissing) {
array_unshift($sources, new Minify_Source(array(
'id' => 'missingFile',
// should not cause cache invalidation
'lastModified' => 0,
// due to caching, filename is unreliable.
'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n",
'minifier' => 'Minify::nullMinifier',
)));
}
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}

View File

@ -0,0 +1,68 @@
<?php
/**
* Class Minify_Controller_Page
* @package Minify
*/
/**
* Controller class for serving a single HTML page
*
* @link http://code.google.com/p/minify/source/browse/trunk/web/examples/1/index.php#59
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_Page extends Minify_Controller_Base
{
/**
* Set up source of HTML content
*
* @param array $options controller and Minify options
* @return array Minify options
*
* Controller options:
*
* 'content': (required) HTML markup
*
* 'id': (required) id of page (string for use in server-side caching)
*
* 'lastModifiedTime': timestamp of when this content changed. This
* is recommended to allow both server and client-side caching.
*
* 'minifyAll': should all CSS and Javascript blocks be individually
* minified? (default false)
*/
public function createConfiguration(array $options)
{
if (isset($options['file'])) {
$sourceSpec = array(
'filepath' => $options['file']
);
$f = $options['file'];
} else {
// strip controller options
$sourceSpec = array(
'content' => $options['content'],
'id' => $options['id'],
);
$f = $options['id'];
unset($options['content'], $options['id']);
}
// something like "builder,index.php" or "directory,file.html"
$selectionId = strtr(substr($f, 1 + strlen(dirname(dirname($f)))), '/\\', ',,');
if (isset($options['minifyAll'])) {
// this will be the 2nd argument passed to Minify_HTML::minify()
$sourceSpec['minifyOptions'] = array(
'cssMinifier' => array('Minify_CSSmin', 'minify'),
'jsMinifier' => array('JSMin\\JSMin', 'minify'),
);
unset($options['minifyAll']);
}
$sourceSpec['contentType'] = Minify::TYPE_HTML;
$sources[] = new Minify_Source($sourceSpec);
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}

View File

@ -0,0 +1,22 @@
<?php
interface Minify_ControllerInterface
{
/**
* Create controller sources and options for Minify::serve()
*
* @param array $options controller and Minify options
*
* @return Minify_ServeConfiguration
*/
public function createConfiguration(array $options);
/**
* Get the Env component
*
* @return Minify_Env
*/
public function getEnv();
}

View File

@ -0,0 +1,30 @@
<?php
/**
* Detect whether request should be debugged
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_DebugDetector
{
public static function shouldDebugRequest(Minify_Env $env)
{
if ($env->get('debug') !== null) {
return true;
}
$cookieValue = $env->cookie('minifyDebug');
if ($cookieValue) {
foreach (preg_split('/\\s+/', $cookieValue) as $debugUri) {
$pattern = '@' . preg_quote($debugUri, '@') . '@i';
$pattern = str_replace(array('\\*', '\\?'), array('.*', '.'), $pattern);
if (preg_match($pattern, $env->getRequestUri())) {
return true;
}
}
}
return false;
}
}

View File

@ -0,0 +1,127 @@
<?php
class Minify_Env
{
/**
* @return string
*/
public function getDocRoot()
{
return $this->server['DOCUMENT_ROOT'];
}
/**
* @return string
*/
public function getRequestUri()
{
return $this->server['REQUEST_URI'];
}
public function __construct($options = array())
{
$options = array_merge(array(
'server' => $_SERVER,
'get' => $_GET,
'post' => $_POST,
'cookie' => $_COOKIE,
), $options);
$this->server = $options['server'];
if (empty($this->server['DOCUMENT_ROOT'])) {
$this->server['DOCUMENT_ROOT'] = $this->computeDocRoot($options['server']);
} else {
$this->server['DOCUMENT_ROOT'] = rtrim($this->server['DOCUMENT_ROOT'], '/\\');
}
$this->server['DOCUMENT_ROOT'] = $this->normalizePath($this->server['DOCUMENT_ROOT']);
$this->get = $options['get'];
$this->post = $options['post'];
$this->cookie = $options['cookie'];
}
public function server($key = null)
{
if (null === $key) {
return $this->server;
}
return isset($this->server[$key]) ? $this->server[$key] : null;
}
public function cookie($key = null, $default = null)
{
if (null === $key) {
return $this->cookie;
}
return isset($this->cookie[$key]) ? $this->cookie[$key] : $default;
}
public function get($key = null, $default = null)
{
if (null === $key) {
return $this->get;
}
return isset($this->get[$key]) ? $this->get[$key] : $default;
}
public function post($key = null, $default = null)
{
if (null === $key) {
return $this->post;
}
return isset($this->post[$key]) ? $this->post[$key] : $default;
}
/**
* turn windows-style slashes into unix-style,
* remove trailing slash
* and lowercase drive letter
*
* @param string $path absolute path
*
* @return string
*/
public function normalizePath($path)
{
$realpath = realpath($path);
if ($realpath) {
$path = $realpath;
}
$path = str_replace('\\', '/', $path);
$path = rtrim($path, '/');
if (substr($path, 1, 1) === ':') {
$path = lcfirst($path);
}
return $path;
}
protected $server;
protected $get;
protected $post;
protected $cookie;
/**
* Compute $_SERVER['DOCUMENT_ROOT'] for IIS using SCRIPT_FILENAME and SCRIPT_NAME.
*
* @param array $server
* @return string
*/
protected function computeDocRoot(array $server)
{
if (isset($server['SERVER_SOFTWARE']) && 0 !== strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
throw new InvalidArgumentException('DOCUMENT_ROOT is not provided and could not be computed');
}
$substrLength = strlen($server['SCRIPT_FILENAME']) - strlen($server['SCRIPT_NAME']);
$docRoot = substr($server['SCRIPT_FILENAME'], 0, $substrLength);
return rtrim($docRoot, '\\');
}
}

View File

@ -0,0 +1,263 @@
<?php
/**
* Class Minify_HTML
* @package Minify
*/
/**
* Compress HTML
*
* This is a heavy regex-based removal of whitespace, unnecessary comments and
* tokens. IE conditional comments are preserved. There are also options to have
* STYLE and SCRIPT blocks compressed by callback functions.
*
* A test suite is available.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_HTML
{
/**
* @var boolean
*/
protected $_jsCleanComments = true;
/**
* "Minify" an HTML page
*
* @param string $html
*
* @param array $options
*
* 'cssMinifier' : (optional) callback function to process content of STYLE
* elements.
*
* 'jsMinifier' : (optional) callback function to process content of SCRIPT
* elements. Note: the type attribute is ignored.
*
* 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
* unset, minify will sniff for an XHTML doctype.
*
* @return string
*/
public static function minify($html, $options = array())
{
$min = new self($html, $options);
return $min->process();
}
/**
* Create a minifier object
*
* @param string $html
*
* @param array $options
*
* 'cssMinifier' : (optional) callback function to process content of STYLE
* elements.
*
* 'jsMinifier' : (optional) callback function to process content of SCRIPT
* elements. Note: the type attribute is ignored.
*
* 'jsCleanComments' : (optional) whether to remove HTML comments beginning and end of script block
*
* 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
* unset, minify will sniff for an XHTML doctype.
*/
public function __construct($html, $options = array())
{
$this->_html = str_replace("\r\n", "\n", trim($html));
if (isset($options['xhtml'])) {
$this->_isXhtml = (bool)$options['xhtml'];
}
if (isset($options['cssMinifier'])) {
$this->_cssMinifier = $options['cssMinifier'];
}
if (isset($options['jsMinifier'])) {
$this->_jsMinifier = $options['jsMinifier'];
}
if (isset($options['jsCleanComments'])) {
$this->_jsCleanComments = (bool)$options['jsCleanComments'];
}
}
/**
* Minify the markeup given in the constructor
*
* @return string
*/
public function process()
{
if ($this->_isXhtml === null) {
$this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
}
$this->_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
$this->_placeholders = array();
// replace SCRIPTs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/(\\s*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/iu',
array($this, '_removeScriptCB'),
$this->_html
);
// replace STYLEs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/iu',
array($this, '_removeStyleCB'),
$this->_html
);
// remove HTML comments (not containing IE conditional comments).
$this->_html = preg_replace_callback(
'/<!--([\\s\\S]*?)-->/u',
array($this, '_commentCB'),
$this->_html
);
// replace PREs with placeholders
$this->_html = preg_replace_callback('/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/iu', array($this, '_removePreCB'), $this->_html);
// replace TEXTAREAs with placeholders
$this->_html = preg_replace_callback(
'/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/iu',
array($this, '_removeTextareaCB'),
$this->_html
);
// trim each line.
// @todo take into account attribute values that span multiple lines.
$this->_html = preg_replace('/^\\s+|\\s+$/mu', '', $this->_html);
// remove ws around block/undisplayed elements
$this->_html = preg_replace('/\\s+(<\\/?(?:area|article|aside|base(?:font)?|blockquote|body'
.'|canvas|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|figcaption|figure|footer|form'
.'|frame(?:set)?|h[1-6]|head|header|hgroup|hr|html|legend|li|link|main|map|menu|meta|nav'
.'|ol|opt(?:group|ion)|output|p|param|section|t(?:able|body|head|d|h||r|foot|itle)'
.'|ul|video)\\b[^>]*>)/iu', '$1', $this->_html);
// remove ws outside of all elements
$this->_html = preg_replace(
'/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</u',
'>$1$2$3<',
$this->_html
);
// use newlines before 1st attribute in open tags (to limit line lengths)
$this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/iu', "$1\n$2", $this->_html);
// fill placeholders
$this->_html = str_replace(
array_keys($this->_placeholders),
array_values($this->_placeholders),
$this->_html
);
// issue 229: multi-pass to catch scripts that didn't get replaced in textareas
$this->_html = str_replace(
array_keys($this->_placeholders),
array_values($this->_placeholders),
$this->_html
);
return $this->_html;
}
protected function _commentCB($m)
{
return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<![') || 0 === strpos($m[1], '#'))
? $m[0]
: '';
}
protected function _reservePlace($content)
{
$placeholder = '%' . $this->_replacementHash . count($this->_placeholders) . '%';
$this->_placeholders[$placeholder] = $content;
return $placeholder;
}
protected $_isXhtml;
protected $_replacementHash;
protected $_placeholders = array();
protected $_cssMinifier;
protected $_jsMinifier;
protected function _removePreCB($m)
{
return $this->_reservePlace("<pre{$m[1]}");
}
protected function _removeTextareaCB($m)
{
return $this->_reservePlace("<textarea{$m[1]}");
}
protected function _removeStyleCB($m)
{
$openStyle = "<style{$m[1]}";
$css = $m[2];
// remove HTML comments
$css = preg_replace('/(?:^\\s*<!--|-->\\s*$)/u', '', $css);
// remove CDATA section markers
$css = $this->_removeCdata($css);
// minify
$minifier = $this->_cssMinifier
? $this->_cssMinifier
: 'trim';
$css = call_user_func($minifier, $css);
return $this->_reservePlace(
$this->_needsCdata($css)
? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
: "{$openStyle}{$css}</style>"
);
}
protected function _removeScriptCB($m)
{
$openScript = "<script{$m[2]}";
$js = $m[3];
// whitespace surrounding? preserve at least one space
$ws1 = ($m[1] === '') ? '' : ' ';
$ws2 = ($m[4] === '') ? '' : ' ';
// remove HTML comments (and ending "//" if present)
if ($this->_jsCleanComments) {
$js = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/u', '', $js);
}
// remove CDATA section markers
$js = $this->_removeCdata($js);
// minify
$minifier = $this->_jsMinifier
? $this->_jsMinifier
: 'trim';
$js = call_user_func($minifier, $js);
return $this->_reservePlace(
$this->_needsCdata($js)
? "{$ws1}{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>{$ws2}"
: "{$ws1}{$openScript}{$js}</script>{$ws2}"
);
}
protected function _removeCdata($str)
{
return (false !== strpos($str, '<![CDATA['))
? str_replace(array('<![CDATA[', ']]>'), '', $str)
: $str;
}
protected function _needsCdata($str)
{
return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/u', $str));
}
}

View File

@ -0,0 +1,250 @@
<?php
/**
* Class Minify_HTML_Helper
* @package Minify
*/
/**
* Helpers for writing Minify URIs into HTML
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_HTML_Helper
{
public $rewriteWorks = true;
public $minAppUri = '/min';
public $groupsConfigFile = '';
/**
* Get an HTML-escaped Minify URI for a group or set of files
*
* @param string|array $keyOrFiles a group key or array of filepaths/URIs
* @param array $opts options:
* 'farExpires' : (default true) append a modified timestamp for cache revving
* 'debug' : (default false) append debug flag
* 'charset' : (default 'UTF-8') for htmlspecialchars
* 'minAppUri' : (default '/min') URI of min directory
* 'rewriteWorks' : (default true) does mod_rewrite work in min app?
* 'groupsConfigFile' : specify if different
* @return string
*/
public static function getUri($keyOrFiles, $opts = array())
{
$opts = array_merge(array( // default options
'farExpires' => true,
'debug' => false,
'charset' => 'UTF-8',
'minAppUri' => '/min',
'rewriteWorks' => true,
'groupsConfigFile' => self::app()->groupsConfigPath,
), $opts);
$h = new self;
$h->minAppUri = $opts['minAppUri'];
$h->rewriteWorks = $opts['rewriteWorks'];
$h->groupsConfigFile = $opts['groupsConfigFile'];
if (is_array($keyOrFiles)) {
$h->setFiles($keyOrFiles, $opts['farExpires']);
} else {
$h->setGroup($keyOrFiles, $opts['farExpires']);
}
$uri = $h->getRawUri($opts['farExpires'], $opts['debug']);
return htmlspecialchars($uri, ENT_QUOTES, $opts['charset']);
}
/**
* Get non-HTML-escaped URI to minify the specified files
*
* @param bool $farExpires
* @param bool $debug
* @return string
*/
public function getRawUri($farExpires = true, $debug = false)
{
$path = rtrim($this->minAppUri, '/') . '/';
if (! $this->rewriteWorks) {
$path .= '?';
}
if (null === $this->_groupKey) {
// @todo: implement shortest uri
$path = self::_getShortestUri($this->_filePaths, $path);
} else {
$path .= "g=" . $this->_groupKey;
}
if ($debug) {
$path .= "&debug";
} elseif ($farExpires && $this->_lastModified) {
$path .= "&" . $this->_lastModified;
}
return $path;
}
/**
* Set the files that will comprise the URI we're building
*
* @param array $files
* @param bool $checkLastModified
*/
public function setFiles($files, $checkLastModified = true)
{
$this->_groupKey = null;
if ($checkLastModified) {
$this->_lastModified = self::getLastModified($files);
}
// normalize paths like in /min/f=<paths>
foreach ($files as $k => $file) {
if (0 === strpos($file, '//')) {
$file = substr($file, 2);
} elseif (0 === strpos($file, '/') || 1 === strpos($file, ':\\')) {
$file = substr($file, strlen(self::app()->env->getDocRoot()) + 1);
}
$file = strtr($file, '\\', '/');
$files[$k] = $file;
}
$this->_filePaths = $files;
}
/**
* Set the group of files that will comprise the URI we're building
*
* @param string $key
* @param bool $checkLastModified
*/
public function setGroup($key, $checkLastModified = true)
{
$this->_groupKey = $key;
if ($checkLastModified) {
if (! $this->groupsConfigFile) {
$this->groupsConfigFile = self::app()->groupsConfigPath;
}
if (is_file($this->groupsConfigFile)) {
$gc = (require $this->groupsConfigFile);
$keys = explode(',', $key);
foreach ($keys as $key) {
if (!isset($gc[$key])) {
// this can happen if value is null
// which could be solved with array_filter
continue;
}
$this->_lastModified = self::getLastModified($gc[$key], $this->_lastModified);
}
}
}
}
/**
* Get the max(lastModified) of all files
*
* @param array|string $sources
* @param int $lastModified
* @return int
*/
public static function getLastModified($sources, $lastModified = 0)
{
$max = $lastModified;
$factory = self::app()->sourceFactory;
/** @var Minify_Source $source */
foreach ((array)$sources as $source) {
$source = $factory->makeSource($source);
$max = max($max, $source->getLastModified());
}
return $max;
}
/**
* @param \Minify\App $app
* @return \Minify\App
* @internal
*/
public static function app(\Minify\App $app = null)
{
static $cached;
if ($app) {
$cached = $app;
return $app;
}
if ($cached === null) {
$cached = (require __DIR__ . '/../../../bootstrap.php');
}
return $cached;
}
protected $_groupKey = null; // if present, URI will be like g=...
protected $_filePaths = array();
protected $_lastModified = null;
/**
* In a given array of strings, find the character they all have at
* a particular index
*
* @param array $arr array of strings
* @param int $pos index to check
* @return mixed a common char or '' if any do not match
*/
protected static function _getCommonCharAtPos($arr, $pos)
{
if (!isset($arr[0][$pos])) {
return '';
}
$c = $arr[0][$pos];
$l = count($arr);
if ($l === 1) {
return $c;
}
for ($i = 1; $i < $l; ++$i) {
if ($arr[$i][$pos] !== $c) {
return '';
}
}
return $c;
}
/**
* Get the shortest URI to minify the set of source files
*
* @param array $paths root-relative URIs of files
* @param string $minRoot root-relative URI of the "min" application
* @return string
*/
protected static function _getShortestUri($paths, $minRoot = '/min/')
{
$pos = 0;
$base = '';
while (true) {
$c = self::_getCommonCharAtPos($paths, $pos);
if ($c === '') {
break;
} else {
$base .= $c;
}
++$pos;
}
$base = preg_replace('@[^/]+$@', '', $base);
$uri = $minRoot . 'f=' . implode(',', $paths);
if (substr($base, -1) === '/') {
// we have a base dir!
$basedPaths = $paths;
$l = count($paths);
for ($i = 0; $i < $l; ++$i) {
$basedPaths[$i] = substr($paths[$i], strlen($base));
}
$base = substr($base, 0, strlen($base) - 1);
$bUri = $minRoot . 'b=' . $base . '&f=' . implode(',', $basedPaths);
$uri = strlen($uri) < strlen($bUri) ? $uri : $bUri;
}
return $uri;
}
}

View File

@ -0,0 +1,217 @@
<?php
/**
* Class Minify_ImportProcessor
* @package Minify
*/
/**
* Linearize a CSS/JS file by including content specified by CSS import
* declarations. In CSS files, relative URIs are fixed.
*
* @imports will be processed regardless of where they appear in the source
* files; i.e. @imports commented out or in string content will still be
* processed!
*
* This has a unit test but should be considered "experimental".
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author Simon Schick <simonsimcity@gmail.com>
*/
class Minify_ImportProcessor
{
public static $filesIncluded = array();
public static function process($file)
{
self::$filesIncluded = array();
self::$_isCss = (strtolower(substr($file, -4)) === '.css');
$obj = new Minify_ImportProcessor(dirname($file));
return $obj->_getContent($file);
}
// allows callback funcs to know the current directory
private $_currentDir;
// allows callback funcs to know the directory of the file that inherits this one
private $_previewsDir;
// allows _importCB to write the fetched content back to the obj
private $_importedContent = '';
private static $_isCss;
/**
* @param String $currentDir
* @param String $previewsDir Is only used internally
*/
private function __construct($currentDir, $previewsDir = "")
{
$this->_currentDir = $currentDir;
$this->_previewsDir = $previewsDir;
}
private function _getContent($file, $is_imported = false)
{
$file = preg_replace('~\\?.*~', '', $file);
$file = realpath($file);
if (! $file
|| in_array($file, self::$filesIncluded)
|| false === ($content = @file_get_contents($file))) {
// file missing, already included, or failed read
return '';
}
self::$filesIncluded[] = realpath($file);
$this->_currentDir = dirname($file);
// remove UTF-8 BOM if present
if (pack("CCC", 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
$content = substr($content, 3);
}
// ensure uniform EOLs
$content = str_replace("\r\n", "\n", $content);
// process @imports
$pattern = '/
@import\\s+
(?:url\\(\\s*)? # maybe url(
[\'"]? # maybe quote
(.*?) # 1 = URI
[\'"]? # maybe end quote
(?:\\s*\\))? # maybe )
([a-zA-Z,\\s]*)? # 2 = media list
; # end token
/x';
$content = preg_replace_callback($pattern, array($this, '_importCB'), $content);
// You only need to rework the import-path if the script is imported
if (self::$_isCss && $is_imported) {
// rewrite remaining relative URIs
$pattern = '/url\\(\\s*([^\\)\\s]+)\\s*\\)/';
$content = preg_replace_callback($pattern, array($this, '_urlCB'), $content);
}
return $this->_importedContent . $content;
}
private function _importCB($m)
{
$url = $m[1];
$mediaList = preg_replace('/\\s+/', '', $m[2]);
if (strpos($url, '://') > 0) {
// protocol, leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
: "/* Minify_ImportProcessor will not include remote content */";
}
if ('/' === $url[0]) {
// protocol-relative or root path
$url = ltrim($url, '/');
$file = realpath($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR
. strtr($url, '/', DIRECTORY_SEPARATOR);
} else {
// relative to current path
$file = $this->_currentDir . DIRECTORY_SEPARATOR
. strtr($url, '/', DIRECTORY_SEPARATOR);
}
$obj = new Minify_ImportProcessor(dirname($file), $this->_currentDir);
$content = $obj->_getContent($file, true);
if ('' === $content) {
// failed. leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
: "/* Minify_ImportProcessor could not fetch '{$file}' */";
}
return (!self::$_isCss || preg_match('@(?:^$|\\ball\\b)@', $mediaList))
? $content
: "@media {$mediaList} {\n{$content}\n}\n";
}
private function _urlCB($m)
{
// $m[1] is either quoted or not
$quote = ($m[1][0] === "'" || $m[1][0] === '"') ? $m[1][0] : '';
$url = ($quote === '') ? $m[1] : substr($m[1], 1, strlen($m[1]) - 2);
if ('/' !== $url[0]) {
if (strpos($url, '//') > 0) {
// probably starts with protocol, do not alter
} else {
// prepend path with current dir separator (OS-independent)
$path = $this->_currentDir
. DIRECTORY_SEPARATOR . strtr($url, '/', DIRECTORY_SEPARATOR);
// update the relative path by the directory of the file that imported this one
$url = self::getPathDiff(realpath($this->_previewsDir), $path);
}
}
return "url({$quote}{$url}{$quote})";
}
/**
* @param string $from
* @param string $to
* @param string $ps
* @return string
*/
private function getPathDiff($from, $to, $ps = DIRECTORY_SEPARATOR)
{
$realFrom = $this->truepath($from);
$realTo = $this->truepath($to);
$arFrom = explode($ps, rtrim($realFrom, $ps));
$arTo = explode($ps, rtrim($realTo, $ps));
while (count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
array_shift($arFrom);
array_shift($arTo);
}
return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
}
/**
* This function is to replace PHP's extremely buggy realpath().
* @param string $path The original path, can be relative etc.
* @return string The resolved path, it might not exist.
* @see http://stackoverflow.com/questions/4049856/replace-phps-realpath
*/
private function truepath($path)
{
// whether $path is unix or not
$unipath = ('' === $path) || ($path[0] !== '/');
// attempts to detect if path is relative in which case, add cwd
if (strpos($path, ':') === false && $unipath) {
$path = $this->_currentDir . DIRECTORY_SEPARATOR . $path;
}
// resolve path parts (single dot, double dot and double delimiters)
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' === $part) {
continue;
}
if ('..' === $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
$path = implode(DIRECTORY_SEPARATOR, $absolutes);
// resolve any symlinks
if (file_exists($path) && linkinfo($path) > 0) {
$path = readlink($path);
}
// put initial separator that could have been lost
$path = !$unipath ? '/' . $path : $path;
return $path;
}
}

View File

@ -0,0 +1,237 @@
<?php
/**
* Class Minify_JS_ClosureCompiler
* @package Minify
*/
/**
* Minify Javascript using Google's Closure Compiler API
*
* @link http://code.google.com/closure/compiler/
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*
* @todo can use a stream wrapper to unit test this?
*/
class Minify_JS_ClosureCompiler
{
/**
* @var string The option key for the maximum POST byte size
*/
const OPTION_MAX_BYTES = 'maxBytes';
/**
* @var string The option key for additional params. @see __construct
*/
const OPTION_ADDITIONAL_OPTIONS = 'additionalParams';
/**
* @var string The option key for the fallback Minifier
*/
const OPTION_FALLBACK_FUNCTION = 'fallbackFunc';
/**
* @var string The option key for the service URL
*/
const OPTION_COMPILER_URL = 'compilerUrl';
/**
* @var int The default maximum POST byte size according to https://developers.google.com/closure/compiler/docs/api-ref
*/
const DEFAULT_MAX_BYTES = 200000;
/**
* @var string[] $DEFAULT_OPTIONS The default options to pass to the compiler service
*
* @note This would be a constant if PHP allowed it
*/
private static $DEFAULT_OPTIONS = array(
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS'
);
/**
* @var string $url URL of compiler server. defaults to Google's
*/
protected $serviceUrl = 'https://closure-compiler.appspot.com/compile';
/**
* @var int $maxBytes The maximum JS size that can be sent to the compiler server in bytes
*/
protected $maxBytes = self::DEFAULT_MAX_BYTES;
/**
* @var string[] $additionalOptions Additional options to pass to the compiler service
*/
protected $additionalOptions = array();
/**
* @var callable Function to minify JS if service fails. Default is JSMin
*/
protected $fallbackMinifier = array('JSMin\\JSMin', 'minify');
/**
* Minify JavaScript code via HTTP request to a Closure Compiler API
*
* @param string $js input code
* @param array $options Options passed to __construct(). @see __construct
*
* @return string
*/
public static function minify($js, array $options = array())
{
$obj = new self($options);
return $obj->min($js);
}
/**
* @param array $options Options with keys available below:
*
* fallbackFunc : (callable) function to minify if service unavailable. Default is JSMin.
*
* compilerUrl : (string) URL to closure compiler server
*
* maxBytes : (int) The maximum amount of bytes to be sent as js_code in the POST request.
* Defaults to 200000.
*
* additionalParams : (string[]) Additional parameters to pass to the compiler server. Can be anything named
* in https://developers.google.com/closure/compiler/docs/api-ref except for js_code and
* output_info
*/
public function __construct(array $options = array())
{
if (isset($options[self::OPTION_FALLBACK_FUNCTION])) {
$this->fallbackMinifier = $options[self::OPTION_FALLBACK_FUNCTION];
}
if (isset($options[self::OPTION_COMPILER_URL])) {
$this->serviceUrl = $options[self::OPTION_COMPILER_URL];
}
if (isset($options[self::OPTION_ADDITIONAL_OPTIONS]) && is_array($options[self::OPTION_ADDITIONAL_OPTIONS])) {
$this->additionalOptions = $options[self::OPTION_ADDITIONAL_OPTIONS];
}
if (isset($options[self::OPTION_MAX_BYTES])) {
$this->maxBytes = (int) $options[self::OPTION_MAX_BYTES];
}
}
/**
* Call the service to perform the minification
*
* @param string $js JavaScript code
* @return string
* @throws Minify_JS_ClosureCompiler_Exception
*/
public function min($js)
{
$postBody = $this->buildPostBody($js);
if ($this->maxBytes > 0) {
$bytes = (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($postBody, '8bit')
: strlen($postBody);
if ($bytes > $this->maxBytes) {
throw new Minify_JS_ClosureCompiler_Exception(
'POST content larger than ' . $this->maxBytes . ' bytes'
);
}
}
$response = $this->getResponse($postBody);
if (preg_match('/^Error\(\d\d?\):/', $response)) {
if (is_callable($this->fallbackMinifier)) {
// use fallback
$response = "/* Received errors from Closure Compiler API:\n$response"
. "\n(Using fallback minifier)\n*/\n";
$response .= call_user_func($this->fallbackMinifier, $js);
} else {
throw new Minify_JS_ClosureCompiler_Exception($response);
}
}
if ($response === '') {
$errors = $this->getResponse($this->buildPostBody($js, true));
throw new Minify_JS_ClosureCompiler_Exception($errors);
}
return $response;
}
/**
* Get the response for a given POST body
*
* @param string $postBody
* @return string
* @throws Minify_JS_ClosureCompiler_Exception
*/
protected function getResponse($postBody)
{
$allowUrlFopen = preg_match('/1|yes|on|true/i', ini_get('allow_url_fopen'));
if ($allowUrlFopen) {
$contents = file_get_contents($this->serviceUrl, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'compilation_level' => 'SIMPLE',
'output_format' => 'text',
'output_info' => 'compiled_code',
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
'content' => $postBody,
'max_redirects' => 0,
'timeout' => 15,
)
)));
} elseif (defined('CURLOPT_POST')) {
$ch = curl_init($this->serviceUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
$contents = curl_exec($ch);
curl_close($ch);
} else {
throw new Minify_JS_ClosureCompiler_Exception(
"Could not make HTTP request: allow_url_open is false and cURL not available"
);
}
if (false === $contents) {
throw new Minify_JS_ClosureCompiler_Exception(
"No HTTP response from server"
);
}
return trim($contents);
}
/**
* Build a POST request body
*
* @param string $js JavaScript code
* @param bool $returnErrors
* @return string
*/
protected function buildPostBody($js, $returnErrors = false)
{
return http_build_query(
array_merge(
self::$DEFAULT_OPTIONS,
$this->additionalOptions,
array(
'js_code' => $js,
'output_info' => ($returnErrors ? 'errors' : 'compiled_code')
)
),
null,
'&'
);
}
}
class Minify_JS_ClosureCompiler_Exception extends Exception
{
}

View File

@ -0,0 +1,48 @@
<?php
/**
* Class Minify\JS\JShrink
*
* @package Minify
*/
namespace Minify\JS;
/**
* Wrapper to Javascript Minifier built in PHP http://www.tedivm.com
*
* @package Minify
* @author Elan Ruusamäe <glen@pld-linux.org>
* @link https://github.com/tedious/JShrink
*
*/
class JShrink
{
/**
* Contains the default options for minification. This array is merged with
* the one passed in by the user to create the request specific set of
* options (stored in the $options attribute).
*
* @var string[]
*/
protected static $defaultOptions = array('flaggedComments' => true);
/**
* Takes a string containing javascript and removes unneeded characters in
* order to shrink the code without altering it's functionality.
*
* @param string $js The raw javascript to be minified
* @param array $options Various runtime options in an associative array
*
* @see JShrink\Minifier::minify()
* @return string
*/
public static function minify($js, array $options = array())
{
$options = array_merge(
self::$defaultOptions,
$options
);
return \JShrink\Minifier::minify($js, $options);
}
}

View File

@ -0,0 +1,128 @@
<?php
class Minify_LessCssSource extends Minify_Source
{
/**
* @var Minify_CacheInterface
*/
private $cache;
/**
* Parsed lessphp cache object
*
* @var array
*/
private $parsed;
/**
* @inheritdoc
*/
public function __construct(array $spec, Minify_CacheInterface $cache)
{
parent::__construct($spec);
$this->cache = $cache;
}
/**
* Get last modified of all parsed files
*
* @return int
*/
public function getLastModified()
{
$cache = $this->getCache();
return $cache['lastModified'];
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
$cache = $this->getCache();
return $cache['compiled'];
}
/**
* Get lessphp cache object
*
* @return array
*/
private function getCache()
{
// cache for single run
// so that getLastModified and getContent in single request do not add additional cache roundtrips (i.e memcache)
if (isset($this->parsed)) {
return $this->parsed;
}
// check from cache first
$cache = null;
$cacheId = $this->getCacheId();
if ($this->cache->isValid($cacheId, 0)) {
if ($cache = $this->cache->fetch($cacheId)) {
$cache = unserialize($cache);
}
}
$less = $this->getCompiler();
$input = $cache ? $cache : $this->filepath;
$cache = $less->cachedCompile($input);
if (!is_array($input) || $cache['updated'] > $input['updated']) {
$cache['lastModified'] = $this->getMaxLastModified($cache);
$this->cache->store($cacheId, serialize($cache));
}
return $this->parsed = $cache;
}
/**
* Calculate maximum last modified of all files,
* as the 'updated' timestamp in cache is not the same as file last modified timestamp:
* @link https://github.com/leafo/lessphp/blob/v0.4.0/lessc.inc.php#L1904
* @return int
*/
private function getMaxLastModified($cache)
{
$lastModified = 0;
foreach ($cache['files'] as $mtime) {
$lastModified = max($lastModified, $mtime);
}
return $lastModified;
}
/**
* Make a unique cache id for for this source.
*
* @param string $prefix
*
* @return string
*/
private function getCacheId($prefix = 'minify')
{
$md5 = md5($this->filepath);
return "{$prefix}_less2_{$md5}";
}
/**
* Get instance of less compiler
*
* @return lessc
*/
private function getCompiler()
{
$less = new lessc();
// do not spend CPU time letting less doing minify
$less->setPreserveComments(true);
return $less;
}
}

View File

@ -0,0 +1,209 @@
<?php
/**
* Class Minify_Lines
* @package Minify
*/
/**
* Add line numbers in C-style comments for easier debugging of combined content
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author Adam Pedersen (Issue 55 fix)
*/
class Minify_Lines
{
/**
* Add line numbers in C-style comments
*
* This uses a very basic parser easily fooled by comment tokens inside
* strings or regexes, but, otherwise, generally clean code will not be
* mangled. URI rewriting can also be performed.
*
* @param string $content
*
* @param array $options available options:
*
* 'id': (optional) string to identify file. E.g. file name/path
*
* 'currentDir': (default null) if given, this is assumed to be the
* directory of the current CSS file. Using this, minify will rewrite
* all relative URIs in import/url declarations to correctly point to
* the desired files, and prepend a comment with debugging information about
* this process.
*
* @return string
*/
public static function minify($content, $options = array())
{
$id = (isset($options['id']) && $options['id']) ? $options['id'] : '';
$content = str_replace("\r\n", "\n", $content);
$lines = explode("\n", $content);
$numLines = count($lines);
// determine left padding
$padTo = strlen((string) $numLines); // e.g. 103 lines = 3 digits
$inComment = false;
$i = 0;
$newLines = array();
while (null !== ($line = array_shift($lines))) {
if (('' !== $id) && (0 === $i % 50)) {
if ($inComment) {
array_push($newLines, '', "/* {$id} *|", '');
} else {
array_push($newLines, '', "/* {$id} */", '');
}
}
++$i;
$newLines[] = self::_addNote($line, $i, $inComment, $padTo);
$inComment = self::_eolInComment($line, $inComment);
}
$content = implode("\n", $newLines) . "\n";
// check for desired URI rewriting
if (isset($options['currentDir'])) {
Minify_CSS_UriRewriter::$debugText = '';
$docRoot = isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'];
$symlinks = isset($options['symlinks']) ? $options['symlinks'] : array();
$content = Minify_CSS_UriRewriter::rewrite($content, $options['currentDir'], $docRoot, $symlinks);
$content = "/* Minify_CSS_UriRewriter::\$debugText\n\n"
. Minify_CSS_UriRewriter::$debugText . "*/\n"
. $content;
}
return $content;
}
/**
* Is the parser within a C-style comment at the end of this line?
*
* @param string $line current line of code
*
* @param bool $inComment was the parser in a C-style comment at the
* beginning of the previous line?
*
* @return bool
*/
private static function _eolInComment($line, $inComment)
{
while (strlen($line)) {
if ($inComment) {
// only "*/" can end the comment
$index = self::_find($line, '*/');
if ($index === false) {
return true;
}
// stop comment and keep walking line
$inComment = false;
@$line = (string)substr($line, $index + 2);
continue;
}
// look for "//" and "/*"
$single = self::_find($line, '//');
$multi = self::_find($line, '/*');
if ($multi === false) {
return false;
}
if ($single === false || $multi < $single) {
// start comment and keep walking line
$inComment = true;
@$line = (string)substr($line, $multi + 2);
continue;
}
// a single-line comment preceeded it
return false;
}
return $inComment;
}
/**
* Prepend a comment (or note) to the given line
*
* @param string $line current line of code
*
* @param string $note content of note/comment
*
* @param bool $inComment was the parser in a comment at the
* beginning of the line?
*
* @param int $padTo minimum width of comment
*
* @return string
*/
private static function _addNote($line, $note, $inComment, $padTo)
{
if ($inComment) {
$line = '/* ' . str_pad($note, $padTo, ' ', STR_PAD_RIGHT) . ' *| ' . $line;
} else {
$line = '/* ' . str_pad($note, $padTo, ' ', STR_PAD_RIGHT) . ' */ ' . $line;
}
return rtrim($line);
}
/**
* Find a token trying to avoid false positives
*
* @param string $str String containing the token
* @param string $token Token being checked
* @return bool
*/
private static function _find($str, $token)
{
switch ($token) {
case '//':
$fakes = array(
'://' => 1,
'"//' => 1,
'\'//' => 1,
'".//' => 2,
'\'.//' => 2,
);
break;
case '/*':
$fakes = array(
'"/*' => 1,
'\'/*' => 1,
'"//*' => 2,
'\'//*' => 2,
'".//*' => 3,
'\'.//*' => 3,
'*/*' => 1,
'\\/*' => 1,
);
break;
default:
$fakes = array();
}
$index = strpos($str, $token);
$offset = 0;
while ($index !== false) {
foreach ($fakes as $fake => $skip) {
$check = substr($str, $index - $skip, strlen($fake));
if ($check === $fake) {
// move offset and scan again
$offset += $index + strlen($token);
$index = strpos($str, $token, $offset);
break;
}
}
// legitimate find
return $index;
}
return $index;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace Minify\Logger;
use Monolog\Handler\AbstractProcessingHandler;
class LegacyHandler extends AbstractProcessingHandler
{
private $obj;
public function __construct($obj)
{
if (!is_callable(array($obj, 'log'))) {
throw new \InvalidArgumentException('$obj must have a public log() method');
}
$this->obj = $obj;
parent::__construct();
}
protected function write(array $record)
{
$this->obj->log((string)$record['formatted']);
}
}

View File

@ -0,0 +1,113 @@
<?php
/**
* Class Minify_ClosureCompiler
* @package Minify
*/
/**
* Run Closure Compiler via NailGun
*
* @package Minify
* @author Elan Ruusamäe <glen@delfi.ee>
* @link https://github.com/martylamb/nailgun
*/
class Minify_NailgunClosureCompiler extends Minify_ClosureCompiler
{
const NG_SERVER = 'com.martiansoftware.nailgun.NGServer';
const CC_MAIN = 'com.google.javascript.jscomp.CommandLineRunner';
/**
* For some reasons Nailgun thinks that it's server
* broke the connection and returns 227 instead of 0
* We'll just handle this here instead of fixing
* the nailgun client itself.
*
* It also sometimes breaks on 229 on the devbox.
* To complete this whole madness and made future
* 'fixes' easier I added this nice little array...
* @var array
*/
private static $NG_EXIT_CODES = array(0, 227, 229);
/**
* Filepath of "ng" executable (from Nailgun package)
*
* @var string
*/
public static $ngExecutable = 'ng';
/**
* Filepath of the Nailgun jar file.
*
* @var string
*/
public static $ngJarFile;
/**
* Get command to launch NailGun server.
*
* @return array
*/
protected function getServerCommandLine()
{
$this->checkJar(self::$ngJarFile);
$this->checkJar(self::$jarFile);
$classPath = array(
self::$ngJarFile,
self::$jarFile,
);
// The command for the server that should show up in the process list
$server = array(
self::$javaExecutable,
'-server',
'-cp', implode(':', $classPath),
self::NG_SERVER,
);
return $server;
}
/**
* @return array
* @throws Minify_ClosureCompiler_Exception
*/
protected function getCompilerCommandLine()
{
$server = array(
self::$ngExecutable,
escapeshellarg(self::CC_MAIN)
);
return $server;
}
/**
* @param string $tmpFile
* @param array $options
* @return string
* @throws Minify_ClosureCompiler_Exception
*/
protected function compile($tmpFile, $options)
{
$this->startServer();
$command = $this->getCommand($options, $tmpFile);
return implode("\n", $this->shell($command, self::$NG_EXIT_CODES));
}
private function startServer()
{
$serverCommand = implode(' ', $this->getServerCommandLine());
$psCommand = $this->shell("ps -o cmd= -C " . self::$javaExecutable);
if (in_array($serverCommand, $psCommand, true)) {
// already started!
return;
}
$this->shell("$serverCommand </dev/null >/dev/null 2>/dev/null & sleep 10");
}
}

View File

@ -0,0 +1,31 @@
<?php
/**
* Class Minify_Packer
*
* To use this class you must first download the PHP port of Packer
* and place the file "class.JavaScriptPacker.php" in /lib (or your
* include_path).
* @link http://joliclic.free.fr/php/javascript-packer/en/
*
* Be aware that, as long as HTTP encoding is used, scripts minified with JSMin
* will provide better client-side performance, as they need not be unpacked in
* client-side code.
*
* @package Minify
*/
/**
* Minify Javascript using Dean Edward's Packer
*
* @package Minify
*/
class Minify_Packer
{
public static function minify($code, $options = array())
{
// @todo: set encoding options based on $options :)
$packer = new JavascriptPacker($code, 'Normal', true, false);
return trim($packer->pack());
}
}

View File

@ -0,0 +1,176 @@
<?php
use Leafo\ScssPhp\Compiler;
use Leafo\ScssPhp\Server;
use Leafo\ScssPhp\Version;
/**
* Class for using SCSS files
*
* @link https://github.com/leafo/scssphp/
*/
class Minify_ScssCssSource extends Minify_Source
{
/**
* @var Minify_CacheInterface
*/
private $cache;
/**
* Parsed SCSS cache object
*
* @var array
*/
private $parsed;
/**
* @inheritdoc
*/
public function __construct(array $spec, Minify_CacheInterface $cache)
{
parent::__construct($spec);
$this->cache = $cache;
}
/**
* Get last modified of all parsed files
*
* @return int
*/
public function getLastModified()
{
$cache = $this->getCache();
return $cache['updated'];
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
$cache = $this->getCache();
return $cache['content'];
}
/**
* Make a unique cache id for for this source.
*
* @param string $prefix
*
* @return string
*/
private function getCacheId($prefix = 'minify')
{
$md5 = md5($this->filepath);
return "{$prefix}_scss_{$md5}";
}
/**
* Get SCSS cache object
*
* Runs the compilation if needed
*
* Implements Leafo\ScssPhp\Server logic because we need to get parsed files without parsing actual content
*
* @return array
*/
private function getCache()
{
// cache for single run
// so that getLastModified and getContent in single request do not add additional cache roundtrips (i.e memcache)
if (isset($this->parsed)) {
return $this->parsed;
}
// check from cache first
$cache = null;
$cacheId = $this->getCacheId();
if ($this->cache->isValid($cacheId, 0)) {
if ($cache = $this->cache->fetch($cacheId)) {
$cache = unserialize($cache);
}
}
$input = $cache ? $cache : $this->filepath;
if ($this->cacheIsStale($cache)) {
$cache = $this->compile($this->filepath);
}
if (!is_array($input) || $cache['updated'] > $input['updated']) {
$this->cache->store($cacheId, serialize($cache));
}
return $this->parsed = $cache;
}
/**
* Determine whether .scss file needs to be re-compiled.
*
* @param array $cache Cache object
*
* @return boolean True if compile required.
*/
private function cacheIsStale($cache)
{
if (!$cache) {
return true;
}
$updated = $cache['updated'];
foreach ($cache['files'] as $import => $mtime) {
$filemtime = filemtime($import);
if ($filemtime !== $mtime || $filemtime > $updated) {
return true;
}
}
return false;
}
/**
* Compile .scss file
*
* @param string $filename Input path (.scss)
*
* @see Server::compile()
* @return array meta data result of the compile
*/
private function compile($filename)
{
$start = microtime(true);
$scss = new Compiler();
// set import path directory the input filename resides
// otherwise @import statements will not find the files
// and will treat the @import line as css import
$scss->setImportPaths(dirname($filename));
$css = $scss->compile(file_get_contents($filename), $filename);
$elapsed = round((microtime(true) - $start), 4);
$v = Version::VERSION;
$ts = date('r', $start);
$css = "/* compiled by scssphp $v on $ts (${elapsed}s) */\n\n" . $css;
$imports = $scss->getParsedFiles();
$updated = 0;
foreach ($imports as $mtime) {
$updated = max($updated, $mtime);
}
return array(
'elapsed' => $elapsed, // statistic, can be dropped
'updated' => $updated,
'content' => $css,
'files' => $imports,
);
}
}

View File

@ -0,0 +1,71 @@
<?php
/**
* Class Minify_ServeConfiguration
* @package Minify
*/
/**
* A configuration for Minify::serve() determined by a controller
*
* @package Minify
*/
class Minify_ServeConfiguration
{
/**
* @var Minify_SourceInterface[]
*/
protected $sources;
/**
* @var array
*/
protected $options;
/**
* @var string
*/
protected $selectionId = '';
/**
* @param array $options
* @param Minify_SourceInterface[] $sources
* @param string $selectionId
*/
public function __construct(array $options, array $sources = array(), $selectionId = '')
{
$this->options = $options;
$this->sources = $sources;
$this->selectionId = $selectionId;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @return Minify_SourceInterface[]
*/
public function getSources()
{
return $this->sources;
}
/**
* Short name to place inside cache id
*
* The setupSources() method may choose to set this, making it easier to
* recognize a particular set of sources/settings in the cache folder. It
* will be filtered and truncated to make the final cache id <= 250 bytes.
*
* @return string
*/
public function getSelectionId()
{
return $this->selectionId;
}
}

View File

@ -0,0 +1,219 @@
<?php
/**
* Class Minify_Source
* @package Minify
*/
/**
* A content source to be minified by Minify.
*
* This allows per-source minification options and the mixing of files with
* content from other sources.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Source implements Minify_SourceInterface
{
/**
* @var int time of last modification
*/
protected $lastModified;
/**
* @var callback minifier function specifically for this source.
*/
protected $minifier;
/**
* @var array minification options specific to this source.
*/
protected $minifyOptions = array();
/**
* @var string full path of file
*/
protected $filepath;
/**
* @var string HTTP Content Type (Minify requires one of the constants Minify::TYPE_*)
*/
protected $contentType;
/**
* @var string
*/
protected $content;
/**
* @var callable
*/
protected $getContentFunc;
/**
* @var string
*/
protected $id;
/**
* Create a Minify_Source
*
* In the $spec array(), you can either provide a 'filepath' to an existing
* file (existence will not be checked!) or give 'id' (unique string for
* the content), 'content' (the string content) and 'lastModified'
* (unixtime of last update).
*
* @param array $spec options
*/
public function __construct($spec)
{
if (isset($spec['filepath'])) {
$ext = pathinfo($spec['filepath'], PATHINFO_EXTENSION);
switch ($ext) {
case 'js': $this->contentType = Minify::TYPE_JS;
break;
case 'less': // fallthrough
case 'scss': // fallthrough
case 'css': $this->contentType = Minify::TYPE_CSS;
break;
case 'htm': // fallthrough
case 'html': $this->contentType = Minify::TYPE_HTML;
break;
}
$this->filepath = $spec['filepath'];
$this->id = $spec['filepath'];
// TODO ideally not touch disk in constructor
$this->lastModified = filemtime($spec['filepath']);
if (!empty($spec['uploaderHoursBehind'])) {
// offset for Windows uploaders with out of sync clocks
$this->lastModified += round($spec['uploaderHoursBehind'] * 3600);
}
} elseif (isset($spec['id'])) {
$this->id = 'id::' . $spec['id'];
if (isset($spec['content'])) {
$this->content = $spec['content'];
} else {
$this->getContentFunc = $spec['getContentFunc'];
}
$this->lastModified = isset($spec['lastModified']) ? $spec['lastModified'] : time();
}
if (isset($spec['contentType'])) {
$this->contentType = $spec['contentType'];
}
if (isset($spec['minifier'])) {
$this->setMinifier($spec['minifier']);
}
if (isset($spec['minifyOptions'])) {
$this->minifyOptions = $spec['minifyOptions'];
}
}
/**
* {@inheritdoc}
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* {@inheritdoc}
*/
public function getMinifier()
{
return $this->minifier;
}
/**
* {@inheritdoc}
*/
public function setMinifier($minifier = null)
{
if ($minifier === '') {
error_log(__METHOD__ . " cannot accept empty string. Use 'Minify::nullMinifier' or 'trim'.");
$minifier = 'Minify::nullMinifier';
}
if ($minifier !== null && !is_callable($minifier, true)) {
throw new InvalidArgumentException('minifier must be null or a valid callable');
}
$this->minifier = $minifier;
}
/**
* {@inheritdoc}
*/
public function getMinifierOptions()
{
return $this->minifyOptions;
}
/**
* {@inheritdoc}
*/
public function setMinifierOptions(array $options)
{
$this->minifyOptions = $options;
}
/**
* {@inheritdoc}
*/
public function getContentType()
{
return $this->contentType;
}
/**
* {@inheritdoc}
*/
public function getContent()
{
if (null === $this->filepath) {
if (null === $this->content) {
$content = call_user_func($this->getContentFunc, $this->id);
} else {
$content = $this->content;
}
} else {
$content = file_get_contents($this->filepath);
}
// remove UTF-8 BOM if present
if (strpos($content, "\xEF\xBB\xBF") === 0) {
return substr($content, 3);
}
return $content;
}
/**
* {@inheritdoc}
*/
public function getId()
{
return $this->id;
}
/**
* {@inheritdoc}
*/
public function getFilePath()
{
return $this->filepath;
}
/**
* {@inheritdoc}
*/
public function setupUriRewrites()
{
if ($this->filepath
&& !isset($this->minifyOptions['currentDir'])
&& !isset($this->minifyOptions['prependRelativePath'])) {
$this->minifyOptions['currentDir'] = dirname($this->filepath);
}
}
}

View File

@ -0,0 +1,197 @@
<?php
class Minify_Source_Factory
{
/**
* @var array
*/
protected $options;
/**
* @var callable[]
*/
protected $handlers = array();
/**
* @var Minify_Env
*/
protected $env;
/**
* @param Minify_Env $env
* @param array $options
*
* noMinPattern : Pattern matched against basename of the filepath (if present). If the pattern
* matches, Minify will try to avoid re-compressing the resource.
*
* fileChecker : Callable responsible for verifying the existence of the file.
*
* resolveDocRoot : If true, a leading "//" will be replaced with the document root.
*
* checkAllowDirs : If true, the filepath will be verified to be within one of the directories
* specified by allowDirs.
*
* allowDirs : Directory paths in which sources can be served.
*
* uploaderHoursBehind : How many hours behind are the file modification times of uploaded files?
* If you upload files from Windows to a non-Windows server, Windows may report
* incorrect mtimes for the files. Immediately after modifying and uploading a
* file, use the touch command to update the mtime on the server. If the mtime
* jumps ahead by a number of hours, set this variable to that number. If the mtime
* moves back, this should not be needed.
*
* @param Minify_CacheInterface $cache Optional cache for handling .less files.
*
*/
public function __construct(Minify_Env $env, array $options = array(), Minify_CacheInterface $cache = null)
{
$this->env = $env;
$this->options = array_merge(array(
'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
'fileChecker' => array($this, 'checkIsFile'),
'resolveDocRoot' => true,
'checkAllowDirs' => true,
'allowDirs' => array('//'),
'uploaderHoursBehind' => 0,
), $options);
// resolve // in allowDirs
$docRoot = $env->getDocRoot();
foreach ($this->options['allowDirs'] as $i => $dir) {
if (0 === strpos($dir, '//')) {
$this->options['allowDirs'][$i] = $docRoot . substr($dir, 1);
}
}
if ($this->options['fileChecker'] && !is_callable($this->options['fileChecker'])) {
throw new InvalidArgumentException("fileChecker option is not callable");
}
$this->setHandler('~\.less$~i', function ($spec) use ($cache) {
return new Minify_LessCssSource($spec, $cache);
});
$this->setHandler('~\.scss~i', function ($spec) use ($cache) {
return new Minify_ScssCssSource($spec, $cache);
});
$this->setHandler('~\.(js|css)$~i', function ($spec) {
return new Minify_Source($spec);
});
}
/**
* @param string $basenamePattern A pattern tested against basename. E.g. "~\.css$~"
* @param callable $handler Function that recieves a $spec array and returns a Minify_SourceInterface
*/
public function setHandler($basenamePattern, $handler)
{
$this->handlers[$basenamePattern] = $handler;
}
/**
* @param string $file
* @return string
*
* @throws Minify_Source_FactoryException
*/
public function checkIsFile($file)
{
$realpath = realpath($file);
if (!$realpath) {
throw new Minify_Source_FactoryException("File failed realpath(): $file");
}
$basename = basename($file);
if (0 === strpos($basename, '.')) {
throw new Minify_Source_FactoryException("Filename starts with period (may be hidden): $basename");
}
if (!is_file($realpath) || !is_readable($realpath)) {
throw new Minify_Source_FactoryException("Not a file or isn't readable: $file");
}
return $realpath;
}
/**
* @param mixed $spec
*
* @return Minify_SourceInterface
*
* @throws Minify_Source_FactoryException
*/
public function makeSource($spec)
{
if (is_string($spec)) {
$spec = array(
'filepath' => $spec,
);
} elseif ($spec instanceof Minify_SourceInterface) {
return $spec;
}
$source = null;
if (empty($spec['filepath'])) {
// not much we can check
return new Minify_Source($spec);
}
if ($this->options['resolveDocRoot'] && 0 === strpos($spec['filepath'], '//')) {
$spec['filepath'] = $this->env->getDocRoot() . substr($spec['filepath'], 1);
}
if (!empty($this->options['fileChecker'])) {
$spec['filepath'] = call_user_func($this->options['fileChecker'], $spec['filepath']);
}
if ($this->options['checkAllowDirs']) {
$allowDirs = (array)$this->options['allowDirs'];
$inAllowedDir = false;
$filePath = $this->env->normalizePath($spec['filepath']);
foreach ($allowDirs as $allowDir) {
if (strpos($filePath, $this->env->normalizePath($allowDir)) === 0) {
$inAllowedDir = true;
}
}
if (!$inAllowedDir) {
$allowDirsStr = implode(';', $allowDirs);
throw new Minify_Source_FactoryException("File '{$spec['filepath']}' is outside \$allowDirs "
. "($allowDirsStr). If the path is resolved via an alias/symlink, look into the "
. "\$min_symlinks option.");
}
}
$basename = basename($spec['filepath']);
if ($this->options['noMinPattern'] && preg_match($this->options['noMinPattern'], $basename)) {
if (preg_match('~\.(css|less)$~i', $basename)) {
$spec['minifyOptions']['compress'] = false;
// we still want URI rewriting to work for CSS
} else {
$spec['minifier'] = 'Minify::nullMinifier';
}
}
$hoursBehind = $this->options['uploaderHoursBehind'];
if ($hoursBehind != 0) {
$spec['uploaderHoursBehind'] = $hoursBehind;
}
foreach ($this->handlers as $basenamePattern => $handler) {
if (preg_match($basenamePattern, $basename)) {
$source = call_user_func($handler, $spec);
break;
}
}
if (!$source) {
throw new Minify_Source_FactoryException("Handler not found for file: $basename");
}
return $source;
}
}

View File

@ -0,0 +1,5 @@
<?php
class Minify_Source_FactoryException extends Exception
{
}

View File

@ -0,0 +1,82 @@
<?php
/**
* Interface Minify_SourceInterface
* @package Minify
*/
/**
* A content source to be minified by Minify.
*
* This allows per-source minification options and the mixing of files with
* content from other sources.
*
* @package Minify
*/
interface Minify_SourceInterface
{
/**
* Get the minifier
*
* @return callable|null
*/
public function getMinifier();
/**
* Set the minifier
*
* @param callable $minifier
* @return void
*/
public function setMinifier($minifier = null);
/**
* Get options for the minifier
*
* @return array
*/
public function getMinifierOptions();
/**
* Set options for the minifier
*
* @param array $options
* @return void
*/
public function setMinifierOptions(array $options);
/**
* Get the content type
*
* @return string|null
*/
public function getContentType();
/**
* Get content
*
* @return string
*/
public function getContent();
/**
* Get last modified timestamp
*
* @return int
*/
public function getLastModified();
/**
* Get id
*
* @return string
*/
public function getId();
/**
* Get the path of the file that this source is based on (may be null)
*
* @return string|null
*/
public function getFilePath();
}

View File

@ -0,0 +1,31 @@
<?php
/**
* Class Minify_SourceSet
* @package Minify
*/
/**
* @package Minify
*/
class Minify_SourceSet
{
/**
* Get unique string for a set of sources
*
* @param Minify_SourceInterface[] $sources Minify_Source instances
*
* @return string
*/
public static function getDigest($sources)
{
$info = array();
foreach ($sources as $source) {
$info[] = array(
$source->getId(), $source->getMinifier(), $source->getMinifierOptions()
);
}
return md5(serialize($info));
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* Class Minify_YUICompressor
* @package Minify
*/
/**
* Compress Javascript/CSS using the YUI Compressor
*
* You must set $jarFile and $tempDir before calling the minify functions.
* Also, depending on your shell's environment, you may need to specify
* the full path to java in $javaExecutable or use putenv() to setup the
* Java environment.
*
* <code>
* Minify_YUICompressor::$jarFile = '/path/to/yuicompressor-2.4.6.jar';
* Minify_YUICompressor::$tempDir = '/tmp';
* $code = Minify_YUICompressor::minifyJs(
* $code
* ,array('nomunge' => true, 'line-break' => 1000)
* );
* </code>
*
* Note: In case you run out stack (default is 512k), you may increase stack size in $options:
* array('stack-size' => '2048k')
*
* @todo unit tests, $options docs
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_YUICompressor
{
/**
* Filepath of the YUI Compressor jar file. This must be set before
* calling minifyJs() or minifyCss().
*
* @var string
*/
public static $jarFile;
/**
* Writable temp directory. This must be set before calling minifyJs()
* or minifyCss().
*
* @var string
*/
public static $tempDir;
/**
* Filepath of "java" executable (may be needed if not in shell's PATH)
*
* @var string
*/
public static $javaExecutable = 'java';
/**
* Minify a Javascript string
*
* @param string $js
*
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
*
* @return string
*/
public static function minifyJs($js, $options = array())
{
return self::_minify('js', $js, $options);
}
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
*
* @return string
*/
public static function minifyCss($css, $options = array())
{
return self::_minify('css', $css, $options);
}
private static function _minify($type, $content, $options)
{
self::_prepare();
if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
throw new Exception('Minify_YUICompressor : could not create temp file in "'.self::$tempDir.'".');
}
file_put_contents($tmpFile, $content);
exec(self::_getCmd($options, $type, $tmpFile), $output, $result_code);
unlink($tmpFile);
if ($result_code != 0) {
throw new Exception('Minify_YUICompressor : YUI compressor execution failed.');
}
return implode("\n", $output);
}
private static function _getCmd($userOptions, $type, $tmpFile)
{
$defaults = array(
'charset' => '',
'line-break' => 5000,
'type' => $type,
'nomunge' => false,
'preserve-semi' => false,
'disable-optimizations' => false,
'stack-size' => '',
);
$o = array_merge($defaults, $userOptions);
$cmd = self::$javaExecutable
. (!empty($o['stack-size']) ? ' -Xss' . $o['stack-size'] : '')
. ' -jar ' . escapeshellarg(self::$jarFile)
. " --type {$type}"
. (preg_match('/^[\\da-zA-Z0-9\\-]+$/', $o['charset'])
? " --charset {$o['charset']}"
: '')
. (is_numeric($o['line-break']) && $o['line-break'] >= 0
? ' --line-break ' . (int)$o['line-break']
: '');
if ($type === 'js') {
foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) {
$cmd .= $o[$opt]
? " --{$opt}"
: '';
}
}
return $cmd . ' ' . escapeshellarg($tmpFile);
}
private static function _prepare()
{
if (! is_file(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not a valid file.');
}
if (! is_readable(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not readable.');
}
if (! is_dir(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not a valid direcotry.');
}
if (! is_writable(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not writable.');
}
}
}

View File

@ -0,0 +1,392 @@
<?php
namespace MrClay;
use MrClay\Cli\Arg;
use InvalidArgumentException;
/**
* Forms a front controller for a console app, handling and validating arguments (options)
*
* Instantiate, add arguments, then call validate(). Afterwards, the user's valid arguments
* and their values will be available in $cli->values.
*
* You may also specify that some arguments be used to provide input/output. By communicating
* solely through the file pointers provided by openInput()/openOutput(), you can make your
* app more flexible to end users.
*
* @author Steve Clay <steve@mrclay.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Cli
{
/**
* @var array validation errors
*/
public $errors = array();
/**
* @var array option values available after validation.
*
* E.g. array(
* 'a' => false // option was missing
* ,'b' => true // option was present
* ,'c' => "Hello" // option had value
* ,'f' => "/home/user/file" // file path from root
* ,'f.raw' => "~/file" // file path as given to option
* )
*/
public $values = array();
/**
* @var array
*/
public $moreArgs = array();
/**
* @var array
*/
public $debug = array();
/**
* @var bool The user wants help info
*/
public $isHelpRequest = false;
/**
* @var Arg[]
*/
protected $_args = array();
/**
* @var resource
*/
protected $_stdin = null;
/**
* @var resource
*/
protected $_stdout = null;
/**
* @param bool $exitIfNoStdin (default true) Exit() if STDIN is not defined
*/
public function __construct($exitIfNoStdin = true)
{
if ($exitIfNoStdin && ! defined('STDIN')) {
exit('This script is for command-line use only.');
}
if (isset($GLOBALS['argv'][1])
&& ($GLOBALS['argv'][1] === '-?' || $GLOBALS['argv'][1] === '--help')) {
$this->isHelpRequest = true;
}
}
/**
* @param Arg|string $letter
* @return Arg
*/
public function addOptionalArg($letter)
{
return $this->addArgument($letter, false);
}
/**
* @param Arg|string $letter
* @return Arg
*/
public function addRequiredArg($letter)
{
return $this->addArgument($letter, true);
}
/**
* @param string $letter
* @param bool $required
* @param Arg|null $arg
* @return Arg
* @throws InvalidArgumentException
*/
public function addArgument($letter, $required, Arg $arg = null)
{
if (! preg_match('/^[a-zA-Z]$/', $letter)) {
throw new InvalidArgumentException('$letter must be in [a-zA-Z]');
}
if (! $arg) {
$arg = new Arg($required);
}
$this->_args[$letter] = $arg;
return $arg;
}
/**
* @param string $letter
* @return Arg|null
*/
public function getArgument($letter)
{
return isset($this->_args[$letter]) ? $this->_args[$letter] : null;
}
/*
* Read and validate options
*
* @return bool true if all options are valid
*/
public function validate()
{
$options = '';
$this->errors = array();
$this->values = array();
$this->_stdin = null;
if ($this->isHelpRequest) {
return false;
}
$lettersUsed = '';
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$options .= $letter;
$lettersUsed .= $letter;
if ($arg->mayHaveValue || $arg->mustHaveValue) {
$options .= ($arg->mustHaveValue ? ':' : '::');
}
}
$this->debug['argv'] = $GLOBALS['argv'];
$argvCopy = array_slice($GLOBALS['argv'], 1);
$o = getopt($options);
$this->debug['getopt_options'] = $options;
$this->debug['getopt_return'] = $o;
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$this->values[$letter] = false;
if (isset($o[$letter])) {
if (is_bool($o[$letter])) {
// remove from argv copy
$k = array_search("-$letter", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 1);
}
if ($arg->mustHaveValue) {
$this->addError($letter, "Missing value");
} else {
$this->values[$letter] = true;
}
} else {
// string
$this->values[$letter] = $o[$letter];
$v =& $this->values[$letter];
// remove from argv copy
// first look for -ovalue or -o=value
$pattern = "/^-{$letter}=?" . preg_quote($v, '/') . "$/";
$foundInArgv = false;
foreach ($argvCopy as $k => $argV) {
if (preg_match($pattern, $argV)) {
array_splice($argvCopy, $k, 1);
$foundInArgv = true;
break;
}
}
if (! $foundInArgv) {
// space separated
$k = array_search("-$letter", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 2);
}
}
// check that value isn't really another option
if (strlen($lettersUsed) > 1) {
$pattern = "/^-[" . str_replace($letter, '', $lettersUsed) . "]/i";
if (preg_match($pattern, $v)) {
$this->addError($letter, "Value was read as another option: %s", $v);
return false;
}
}
if ($arg->assertFile || $arg->assertDir) {
if ($v[0] !== '/' && $v[0] !== '~') {
$this->values["$letter.raw"] = $v;
$v = getcwd() . "/$v";
}
}
if ($arg->assertFile) {
if ($arg->useAsInfile) {
$this->_stdin = $v;
} elseif ($arg->useAsOutfile) {
$this->_stdout = $v;
}
if ($arg->assertReadable && ! is_readable($v)) {
$this->addError($letter, "File not readable: %s", $v);
continue;
}
if ($arg->assertWritable) {
if (is_file($v)) {
if (! is_writable($v)) {
$this->addError($letter, "File not writable: %s", $v);
}
} else {
if (! is_writable(dirname($v))) {
$this->addError($letter, "Directory not writable: %s", dirname($v));
}
}
}
} elseif ($arg->assertDir && $arg->assertWritable && ! is_writable($v)) {
$this->addError($letter, "Directory not readable: %s", $v);
}
}
} else {
if ($arg->isRequired()) {
$this->addError($letter, "Missing");
}
}
}
$this->moreArgs = $argvCopy;
reset($this->moreArgs);
return empty($this->errors);
}
/**
* Get the full paths of file(s) passed in as unspecified arguments
*
* @return array
*/
public function getPathArgs()
{
$r = $this->moreArgs;
foreach ($r as $k => $v) {
if ($v[0] !== '/' && $v[0] !== '~') {
$v = getcwd() . "/$v";
$v = str_replace('/./', '/', $v);
do {
$v = preg_replace('@/[^/]+/\\.\\./@', '/', $v, 1, $changed);
} while ($changed);
$r[$k] = $v;
}
}
return $r;
}
/**
* Get a short list of errors with options
*
* @return string
*/
public function getErrorReport()
{
if (empty($this->errors)) {
return '';
}
$r = "Some arguments did not pass validation:\n";
foreach ($this->errors as $letter => $arr) {
$r .= " $letter : " . implode(', ', $arr) . "\n";
}
$r .= "\n";
return $r;
}
/**
* @return string
*/
public function getArgumentsListing()
{
$r = "\n";
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$desc = $arg->getDescription();
$flag = " -$letter ";
if ($arg->mayHaveValue) {
$flag .= "[VAL]";
} elseif ($arg->mustHaveValue) {
$flag .= "VAL";
}
if ($arg->assertFile) {
$flag = str_replace('VAL', 'FILE', $flag);
} elseif ($arg->assertDir) {
$flag = str_replace('VAL', 'DIR', $flag);
}
if ($arg->isRequired()) {
$desc = "(required) $desc";
}
$flag = str_pad($flag, 12, " ", STR_PAD_RIGHT);
$desc = wordwrap($desc, 70);
$r .= $flag . str_replace("\n", "\n ", $desc) . "\n\n";
}
return $r;
}
/**
* Get resource of open input stream. May be STDIN or a file pointer
* to the file specified by an option with 'STDIN'.
*
* @return resource
*/
public function openInput()
{
if (null === $this->_stdin) {
return STDIN;
} else {
$this->_stdin = fopen($this->_stdin, 'rb');
return $this->_stdin;
}
}
public function closeInput()
{
if (null !== $this->_stdin) {
fclose($this->_stdin);
}
}
/**
* Get resource of open output stream. May be STDOUT or a file pointer
* to the file specified by an option with 'STDOUT'. The file will be
* truncated to 0 bytes on opening.
*
* @return resource
*/
public function openOutput()
{
if (null === $this->_stdout) {
return STDOUT;
} else {
$this->_stdout = fopen($this->_stdout, 'wb');
return $this->_stdout;
}
}
public function closeOutput()
{
if (null !== $this->_stdout) {
fclose($this->_stdout);
}
}
/**
* @param string $letter
* @param string $msg
* @param string $value
*/
protected function addError($letter, $msg, $value = null)
{
if ($value !== null) {
$value = var_export($value, 1);
}
$this->errors[$letter][] = sprintf($msg, $value);
}
}

View File

@ -0,0 +1,189 @@
<?php
namespace MrClay\Cli;
use BadMethodCallException;
/**
* An argument for a CLI app. This specifies the argument, what values it expects and
* how it's treated during validation.
*
* By default, the argument will be assumed to be an optional letter flag with no value following.
*
* If the argument may receive a value, call mayHaveValue(). If there's whitespace after the
* flag, the value will be returned as true instead of the string.
*
* If the argument MUST be accompanied by a value, call mustHaveValue(). In this case, whitespace
* is permitted between the flag and its value.
*
* Use assertFile() or assertDir() to indicate that the argument must return a string value
* specifying a file or directory. During validation, the value will be resolved to a
* full file/dir path (not necessarily existing!) and the original value will be accessible
* via a "*.raw" key. E.g. $cli->values['f.raw']
*
* Use assertReadable()/assertWritable() to cause the validator to test the file/dir for
* read/write permissions respectively.
*
* @method \MrClay\Cli\Arg mayHaveValue() Assert that the argument, if present, may receive a string value
* @method \MrClay\Cli\Arg mustHaveValue() Assert that the argument, if present, must receive a string value
* @method \MrClay\Cli\Arg assertFile() Assert that the argument's value must specify a file
* @method \MrClay\Cli\Arg assertDir() Assert that the argument's value must specify a directory
* @method \MrClay\Cli\Arg assertReadable() Assert that the specified file/dir must be readable
* @method \MrClay\Cli\Arg assertWritable() Assert that the specified file/dir must be writable
*
* @property-read bool mayHaveValue
* @property-read bool mustHaveValue
* @property-read bool assertFile
* @property-read bool assertDir
* @property-read bool assertReadable
* @property-read bool assertWritable
* @property-read bool useAsInfile
* @property-read bool useAsOutfile
*
* @author Steve Clay <steve@mrclay.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Arg
{
/**
* @return array
*/
public function getDefaultSpec()
{
return array(
'mayHaveValue' => false,
'mustHaveValue' => false,
'assertFile' => false,
'assertDir' => false,
'assertReadable' => false,
'assertWritable' => false,
'useAsInfile' => false,
'useAsOutfile' => false,
);
}
/**
* @var array
*/
protected $spec = array();
/**
* @var bool
*/
protected $required = false;
/**
* @var string
*/
protected $description = '';
/**
* @param bool $isRequired
*/
public function __construct($isRequired = false)
{
$this->spec = $this->getDefaultSpec();
$this->required = (bool) $isRequired;
if ($isRequired) {
$this->spec['mustHaveValue'] = true;
}
}
/**
* Assert that the argument's value points to a writable file. When
* Cli::openOutput() is called, a write pointer to this file will
* be provided.
* @return Arg
*/
public function useAsOutfile()
{
$this->spec['useAsOutfile'] = true;
return $this->assertFile()->assertWritable();
}
/**
* Assert that the argument's value points to a readable file. When
* Cli::openInput() is called, a read pointer to this file will
* be provided.
* @return Arg
*/
public function useAsInfile()
{
$this->spec['useAsInfile'] = true;
return $this->assertFile()->assertReadable();
}
/**
* @return array
*/
public function getSpec()
{
return $this->spec;
}
/**
* @param string $desc
* @return Arg
*/
public function setDescription($desc)
{
$this->description = $desc;
return $this;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @return bool
*/
public function isRequired()
{
return $this->required;
}
/**
* Note: magic methods declared in class PHPDOC
*
* @param string $name
* @param array $args
* @return Arg
* @throws BadMethodCallException
*/
public function __call($name, array $args = array())
{
if (array_key_exists($name, $this->spec)) {
$this->spec[$name] = true;
if ($name === 'assertFile' || $name === 'assertDir') {
$this->spec['mustHaveValue'] = true;
}
} else {
throw new BadMethodCallException('Method does not exist');
}
return $this;
}
/**
* Note: magic properties declared in class PHPDOC
*
* @param string $name
* @return bool|null
*/
public function __get($name)
{
if (array_key_exists($name, $this->spec)) {
return $this->spec[$name];
}
return null;
}
}

View File

@ -0,0 +1,30 @@
/*! This file exists only for testing a Minify installation. Its content is not used.
*
* http://example.org/min/f=min/quick-test.css
*/
@import url( more.css );
body, td, th {
font-family: Verdana , "Bitstream Vera Sans" , Arial Narrow, sans-serif ;
font-size : 12px;
}
.nav {
margin-left: 20%;
}
#main-nav {
background-color: red;
border: 1px solid #00ff77;
}
div#content
h1 + p {
padding-top: 0;
margin-top: 0;
}
@media all and (min-width: 640px) {
#media-queries-1 { background-color: #0f0; }
}

View File

@ -0,0 +1,74 @@
/*! This file exists only for testing a Minify installation. Its content is not used.
*
* http://example.org/min/f=min/quick-test.js
*/
/* Finds the lowest common multiple of two numbers */
function LCMCalculator(x, y) { // constructor function
var checkInt = function (x) { // inner function
if (x % 1 !== 0) {
throw new TypeError(x + " is not an integer"); // throw an exception
}
return x;
};
this.a = checkInt(x);
// ^ semicolons are optional
this.b = checkInt(y);
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately
gcd: function () { // method that calculates the greatest common divisor
// Euclidean algorithm:
var a = Math.abs(this.a), b = Math.abs(this.b), t;
if (a < b) {
// swap variables
t = b;
b = a;
a = t;
}
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
// Only need to calculate GCD once, so "redefine" this method.
// (Actually not redefinition - it's defined on the instance itself,
// so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.)
// Also, 'gcd' === "gcd", this['gcd'] === this.gcd
this['gcd'] = function () {
return a;
};
return a;
},
// Object property names can be specified by strings delimited by double (") or single (') quotes.
"lcm" : function () {
// Variable names don't collide with object properties, e.g. |lcm| is not |this.lcm|.
// not using |this.a * this.b| to avoid FP precision issues
var lcm = this.a / this.gcd() * this.b;
// Only need to calculate lcm once, so "redefine" this method.
this.lcm = function () {
return lcm;
};
return lcm;
},
toString: function () {
return "LCMCalculator: a = " + this.a + ", b = " + this.b;
}
};
//define generic output function; this implementation only works for web browsers
function output(x) {
document.write(x + "<br>");
}
// Note: Array's map() and forEach() are defined in JavaScript 1.6.
// They are used here to demonstrate JavaScript's inherent functional nature.
[[25, 55], [21, 56], [22, 58], [28, 56]].map(function (pair) { // array literal + mapping function
return new LCMCalculator(pair[0], pair[1]);
}).sort(function (a, b) { // sort with this comparative function
return a.lcm() - b.lcm();
}).forEach(function (obj) {
output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
});

View File

@ -0,0 +1,12 @@
/*! This file exists only for testing a Minify installation. Its content is not used.
*
* http://example.org/min/f=min/quick-test.less
*/
// LESS import statement shares syntax with the CSS import statement.
// If the file being imported ends in a .less extension, or no extension, then it is treated as a LESS
// import. Otherwise it is left alone and outputted directly.
// http://leafo.net/lessphp/docs/#import
@import "quick-test.css";
@import "quick-testinc.less";

View File

@ -0,0 +1,25 @@
/*! This file exists only for testing a Minify installation. Its content is not used.
*
* http://example.org/min/f=min/quick-test.less
*/
@base: 24px;
@border-color: #B2B;
.underline { border-bottom: 1px solid green }
#header {
color: black;
border: 1px solid @border-color + #222222;
.navigation {
font-size: @base / 2;
a {
.underline;
}
}
.logo {
width: 300px;
:hover { text-decoration: none }
}
}

View File

@ -0,0 +1,154 @@
<?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.');
}
function assertTrue($test, $message)
{
if (!$test) {
echo "Warning: $message\n";
}
return (bool)$test;
}
header('Content-Type: text/plain');
$file = __FILE__;
$tmp = sys_get_temp_dir();
echo <<<EOD
Cache directory : $tmp
__FILE__ : $file
SCRIPT_FILENAME : {$_SERVER['SCRIPT_FILENAME']}
DOCUMENT_ROOT : {$_SERVER['DOCUMENT_ROOT']}
SCRIPT_NAME : {$_SERVER['SCRIPT_NAME']}
REQUEST_URI : {$_SERVER['REQUEST_URI']}
EOD;
$noSlash = assertTrue(
0 === preg_match('@[\\\\/]$@', $_SERVER['DOCUMENT_ROOT']),
'DOCUMENT_ROOT ends in trailing slash'
);
$isRealPath = assertTrue(
false !== realpath($_SERVER['DOCUMENT_ROOT']),
'DOCUMENT_ROOT fails realpath()'
);
$containsThisFile = assertTrue(
0 === strpos(realpath(__FILE__), realpath($_SERVER['DOCUMENT_ROOT'])),
'DOCUMENT_ROOT contains this test file'
);
if (! $noSlash || ! $isRealPath || ! $containsThisFile) {
echo "If you cannot modify DOCUMENT_ROOT, consider setting \$min_documentRoot in config.php\n";
}
assertTrue(
empty($_SERVER['SUBDOMAIN_DOCUMENT_ROOT']),
"\$_SERVER['SUBDOMAIN_DOCUMENT_ROOT'] is set. You may want to set \$min_documentRoot to this in config.php"
);
assertTrue(
realpath(__FILE__) === realpath($_SERVER['DOCUMENT_ROOT'] . '/min/server-info.php'),
"/min/ is not directly inside DOCUMENT_ROOT."
);
// TODO: rework this
/*
function _test_environment_getHello($url)
{
$fp = fopen($url, 'r', false, stream_context_create(array(
'http' => array(
'method' => "GET",
'timeout' => '10',
'header' => "Accept-Encoding: deflate, gzip\r\n",
)
)));
$meta = stream_get_meta_data($fp);
$encoding = '';
$length = 0;
foreach ($meta['wrapper_data'] as $i => $header) {
if (preg_match('@^Content-Length:\\s*(\\d+)$@i', $header, $m)) {
$length = $m[1];
} elseif (preg_match('@^Content-Encoding:\\s*(\\S+)$@i', $header, $m)) {
if ($m[1] !== 'identity') {
$encoding = $m[1];
}
}
}
$streamContents = stream_get_contents($fp);
fclose($fp);
if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
if ($length != 6) {
echo "\nReturned content should be 6 bytes and not HTTP encoded.\n"
. "Headers returned by: {$url}\n\n";
var_export($meta['wrapper_data']);
echo "\n\n";
}
}
return array(
'length' => $length
,'encoding' => $encoding
,'bytes' => $streamContents
);
}
$thisUrl = 'http://'
. $_SERVER['HTTP_HOST'] // avoid redirects when SERVER_NAME doesn't match
. ('80' === $_SERVER['SERVER_PORT'] ? '' : ":{$_SERVER['SERVER_PORT']}")
. dirname($_SERVER['REQUEST_URI'])
. '/test_environment.php';
$oc = @file_get_contents($thisUrl . '?getOutputCompression=1');
if (false === $oc || ! preg_match('/^[01]$/', $oc)) {
echo "!---: environment : Local HTTP request failed. Testing cannot continue.\n";
return;
}
if ('1' === $oc) {
echo "!---: environment : zlib.output_compression is enabled in php.ini"
. " or .htaccess.\n";
}
$testJs = _test_environment_getHello($thisUrl . '?hello=js');
$passed = assertTrue(
$testJs['length'] == 6
,'environment : PHP/server should not auto-encode application/x-javascript output'
);
$testCss = _test_environment_getHello($thisUrl . '?hello=css');
$passed = $passed && assertTrue(
$testCss['length'] == 6
,'environment : PHP/server should not auto-encode text/css output'
);
$testHtml = _test_environment_getHello($thisUrl . '?hello=html');
$passed = $passed && assertTrue(
$testHtml['length'] == 6
,'environment : PHP/server should not auto-encode text/html output'
);
if (! $passed) {
$testFake = _test_environment_getHello($thisUrl . '?hello=faketype');
if ($testFake['length'] == 6) {
echo " environment : Server does not auto-encode arbitrary types. This\n"
. " may indicate that the auto-encoding is caused by Apache's\n"
. " AddOutputFilterByType.";
}
}
*/

View File

@ -0,0 +1,127 @@
<?php
// allows putting /static anywhere as long as you put a boostrap.php in it
if (is_file(__DIR__ . '/bootstrap.php')) {
$bootstrap_file = __DIR__ . '/bootstrap.php';
} else {
$bootstrap_file = __DIR__ . '/../bootstrap.php';
}
$send_400 = function ($content = 'Bad URL') {
http_response_code(400);
die($content);
};
$send_301 = function ($url) {
http_response_code(301);
header("Cache-Control: max-age=31536000");
header("Location: $url");
exit;
};
$app = (require $bootstrap_file);
/* @var \Minify\App $app */
if (!$app->config->enableStatic) {
die('Minify static serving is not enabled. Set $min_enableStatic = true; in config.php');
}
require __DIR__ . '/lib.php';
if (!is_writable(__DIR__)) {
http_response_code(500);
die('Directory is not writable.');
}
// parse request
// SCRIPT_NAME = /path/to/minify/static/gen.php
// REQUEST_URI = /path/to/minify/static/1467084520/b=path/to/minify&f=quick-test.js
// "/path/to/minify/static"
$root_uri = dirname($_SERVER['SCRIPT_NAME']);
// "/1467084520/b=path/to/minify&f=quick-test.js"
$uri = substr($_SERVER['REQUEST_URI'], strlen($root_uri));
if (!preg_match('~^/(\d+)/(.*)$~', $uri, $m)) {
http_response_code(404);
die('File not found');
}
// "1467084520"
$requested_cache_dir = $m[1];
// "b=path/to/minify&f=quick-test.js"
$query = $m[2];
// we basically want canonical querystrings because we make a file for each one.
// manual parsing is the only way to do this. The MinApp controller will validate
// these parameters anyway.
$get_params = array();
foreach (explode('&', $query) as $piece) {
if (false === strpos($piece, '=')) {
$send_400();
}
list($key, $value) = explode('=', $piece, 2);
if (!in_array($key, array('f', 'g', 'b', 'z'))) {
$send_400();
}
if (isset($get_params[$key])) {
// already used
$send_400();
}
if ($key === 'z' && !preg_match('~^\.(css|js)$~', $value, $m)) {
$send_400();
}
$get_params[$key] = urldecode($value);
}
$cache_time = Minify\StaticService\get_cache_time();
if (!$cache_time) {
http_response_code(500);
die('Directory is not writable.');
}
$app->env = new Minify_Env(array(
'get' => $get_params,
));
$ctrl = $app->controller;
$options = $app->serveOptions;
$sources = $ctrl->createConfiguration($options)->getSources();
if (!$sources) {
http_response_code(404);
die('File not found');
}
if ($sources[0]->getId() === 'id::missingFile') {
$send_400("Bad URL: missing file");
}
// we need URL to end in appropriate extension
$type = $sources[0]->getContentType();
$ext = ($type === Minify::TYPE_JS) ? '.js' : '.css';
if (substr($query, - strlen($ext)) !== $ext) {
$send_301("$root_uri/$cache_time/{$query}&z=$ext");
}
// fix the cache dir in the URL
if ($cache_time !== $requested_cache_dir) {
$send_301("$root_uri/$cache_time/$query");
}
$content = $app->minify->combine($sources);
// save and send file
$file = __DIR__ . "/$cache_time/$query";
if (!is_dir(dirname($file))) {
mkdir(dirname($file), 0777, true);
}
file_put_contents($file, $content);
header("Content-Type: $type;charset=utf-8");
header("Cache-Control: max-age=31536000");
echo $content;

View File

@ -0,0 +1,72 @@
<?php
namespace Minify\StaticService;
/**
* Build a URI for the static cache
*
* @param string $static_uri E.g. "/min/static"
* @param string $query E.g. "b=scripts&f=1.js,2.js"
* @param string $type "css" or "js"
* @return string
*/
function build_uri($static_uri, $query, $type)
{
$static_uri = rtrim($static_uri, '/');
$query = ltrim($query, '?');
$ext = ".$type";
if (substr($query, - strlen($ext)) !== $ext) {
$query .= "&z=$ext";
}
$cache_time = get_cache_time();
return "$static_uri/$cache_time/$query";
}
/**
* Get the name of the current cache directory within static/. E.g. "1467089473"
*
* @param bool $auto_create Automatically create the directory if missing?
* @return null|string null if missing or can't create
*/
function get_cache_time($auto_create = true)
{
foreach (scandir(__DIR__) as $entry) {
if (ctype_digit($entry)) {
return $entry;
break;
}
}
if (!$auto_create) {
return null;
}
$time = (string)time();
if (!mkdir(__DIR__ . "/$time")) {
return null;
}
return $time;
}
function flush_cache()
{
$time = get_cache_time(false);
if ($time) {
remove_tree(__DIR__ . "/$time");
}
}
function remove_tree($dir)
{
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
is_dir("$dir/$file") ? remove_tree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}

View File

@ -0,0 +1,78 @@
<?php
/**
* Utility functions for generating URIs in HTML files
*
* @warning These functions execute min/groupsConfig.php, sometimes multiple times.
* You must make sure that functions are not redefined, and if your use custom sources,
* you must require_once __DIR__ . '/lib/Minify/Source.php' so that
* class is available.
*
* @package Minify
*/
require __DIR__ . '/bootstrap.php';
/*
* Get an HTML-escaped Minify URI for a group or set of files. By default, URIs
* will contain timestamps to allow far-future Expires headers.
*
* <code>
* <link rel="stylesheet" type="text/css" href="<?= Minify_getUri('css'); ?>" />
* <script src="<?= Minify_getUri('js'); ?>"></script>
* <script src="<?= Minify_getUri(array(
* '//scripts/file1.js'
* ,'//scripts/file2.js'
* )); ?>"></script>
* </code>
*
* @param mixed $keyOrFiles a group key or array of file paths/URIs
* @param array $opts options:
* 'farExpires' : (default true) append a modified timestamp for cache revving
* 'debug' : (default false) append debug flag
* 'charset' : (default 'UTF-8') for htmlspecialchars
* 'minAppUri' : (default '/min') URI of min directory
* 'rewriteWorks' : (default true) does mod_rewrite work in min app?
* 'groupsConfigFile' : specify if different
* @return string
*/
function Minify_getUri($keyOrFiles, $opts = array())
{
return Minify_HTML_Helper::getUri($keyOrFiles, $opts);
}
/**
* Get the last modification time of several source js/css files. If you're
* caching the output of Minify_getUri(), you might want to know if one of the
* dependent source files has changed so you can update the HTML.
*
* Since this makes a bunch of stat() calls, you might not want to check this
* on every request.
*
* @param array $keysAndFiles group keys and/or file paths/URIs.
* @return int latest modification time of all given keys/files
*/
function Minify_mtime($keysAndFiles, $groupsConfigFile = null)
{
$gc = null;
if (! $groupsConfigFile) {
$groupsConfigFile = Minify_HTML_Helper::app()->groupsConfigPath;
}
$sources = array();
foreach ($keysAndFiles as $keyOrFile) {
if (is_object($keyOrFile)
|| 0 === strpos($keyOrFile, '/')
|| 1 === strpos($keyOrFile, ':\\')) {
// a file/source obj
$sources[] = $keyOrFile;
} else {
if (! $gc) {
$gc = (require $groupsConfigFile);
}
foreach ($gc[$keyOrFile] as $source) {
$sources[] = $source;
}
}
}
return Minify_HTML_Helper::getLastModified($sources);
}

View File

@ -0,0 +1,19 @@
Copyright (c) 2013 The Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,9 @@
<?php
namespace Props;
use Psr\Container\ContainerExceptionInterface;
class BadMethodCallException extends \Exception implements ContainerExceptionInterface
{
}

View File

@ -0,0 +1,249 @@
<?php
namespace Props;
use Psr\Container\ContainerInterface;
/**
* Container holding values which can be resolved upon reading and optionally stored and shared
* across reads.
*
* Values are read/set as properties.
*
* @note see scripts/example.php
*/
class Container implements ContainerInterface
{
/**
* @var callable[]
*/
private $factories = array();
/**
* @var array
*/
private $cache = array();
/**
* Fetch a value.
*
* @param string $name
* @return mixed
* @throws FactoryUncallableException|ValueUnresolvableException|NotFoundException
*/
public function __get($name)
{
if (array_key_exists($name, $this->cache)) {
return $this->cache[$name];
}
$value = $this->build($name);
$this->cache[$name] = $value;
return $value;
}
/**
* {@inheritdoc}
*/
public function get($name)
{
return $this->__get($name);
}
/**
* Set a value.
*
* @param string $name
* @param mixed $value
* @throws \InvalidArgumentException
*/
public function __set($name, $value)
{
if ($value instanceof \Closure) {
$this->setFactory($name, $value);
return;
}
$this->cache[$name] = $value;
unset($this->factories[$name]);
}
/**
* Set a value to be later returned as is. You only need to use this if you wish to store
* a Closure.
*
* @param string $name
* @param mixed $value
* @throws \InvalidArgumentException
*/
public function setValue($name, $value)
{
unset($this->factories[$name]);
$this->cache[$name] = $value;
}
/**
* @param string $name
*/
public function __unset($name)
{
unset($this->cache[$name]);
unset($this->factories[$name]);
}
/**
* @param string $name
* @return bool
*/
public function __isset($name)
{
return array_key_exists($name, $this->factories) || array_key_exists($name, $this->cache);
}
/**
* {@inheritdoc}
*/
public function has($name)
{
return $this->__isset($name);
}
/**
* Fetch a freshly-resolved value.
*
* @param string $method method name must start with "new_"
* @param array $args
* @return mixed
* @throws BadMethodCallException
*/
public function __call($method, $args)
{
if (0 !== strpos($method, 'new_')) {
throw new BadMethodCallException("Method name must begin with 'new_'");
}
return $this->build(substr($method, 4));
}
/**
* Can we fetch a new value via new_$name()?
*
* @param string $name
* @return bool
*/
public function hasFactory($name)
{
return array_key_exists($name, $this->factories);
}
/**
* Set a factory to generate a value when the container is read.
*
* @param string $name The name of the value
* @param callable $factory Factory for the value
* @throws FactoryUncallableException
*/
public function setFactory($name, $factory)
{
if (!is_callable($factory, true)) {
throw new FactoryUncallableException('$factory must appear callable');
}
unset($this->cache[$name]);
$this->factories[$name] = $factory;
}
/**
* Get an already-set factory callable (Closure, invokable, or callback)
*
* @param string $name The name of the value
* @return callable
* @throws NotFoundException
*/
public function getFactory($name)
{
if (!array_key_exists($name, $this->factories)) {
throw new NotFoundException("No factory available for: $name");
}
return $this->factories[$name];
}
/**
* Add a function that gets applied to the return value of an existing factory
*
* @note A cached value (from a previous property read) will thrown away. The next property read
* (and all new_NAME() calls) will call the original factory.
*
* @param string $name The name of the value
* @param callable $extender Function that is applied to extend the returned value
* @return \Closure
* @throws FactoryUncallableException|NotFoundException
*/
public function extend($name, $extender)
{
if (!is_callable($extender, true)) {
throw new FactoryUncallableException('$extender must appear callable');
}
if (!array_key_exists($name, $this->factories)) {
throw new NotFoundException("No factory available for: $name");
}
$factory = $this->factories[$name];
$newFactory = function (Container $c) use ($extender, $factory) {
return call_user_func($extender, call_user_func($factory, $c), $c);
};
$this->setFactory($name, $newFactory);
return $newFactory;
}
/**
* Get all keys available
*
* @return string[]
*/
public function getKeys()
{
$keys = array_keys($this->cache) + array_keys($this->factories);
return array_unique($keys);
}
/**
* Build a value
*
* @param string $name
* @return mixed
* @throws FactoryUncallableException|ValueUnresolvableException|NotFoundException
*/
private function build($name)
{
if (!array_key_exists($name, $this->factories)) {
throw new NotFoundException("Missing value: $name");
}
$factory = $this->factories[$name];
if (is_callable($factory)) {
try {
return call_user_func($factory, $this);
} catch (\Exception $e) {
throw new ValueUnresolvableException("Factory for '$name' threw an exception.", 0, $e);
}
}
$msg = "Factory for '$name' was uncallable";
if (is_string($factory)) {
$msg .= ": '$factory'";
} elseif (is_array($factory)) {
if (is_string($factory[0])) {
$msg .= ": '{$factory[0]}::{$factory[1]}'";
} else {
$msg .= ": " . get_class($factory[0]) . "->{$factory[1]}";
}
}
throw new FactoryUncallableException($msg);
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Props;
use Psr\Container\ContainerExceptionInterface;
class FactoryUncallableException extends \Exception implements ContainerExceptionInterface
{
}

View File

@ -0,0 +1,10 @@
<?php
namespace Props;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class NotFoundException extends \Exception implements ContainerExceptionInterface, NotFoundExceptionInterface
{
}

View File

@ -0,0 +1,56 @@
<?php
namespace Props;
/**
* A version of Pimple that uses property access instead of array access
*
* @author Steve Clay <steve@mrclay.org>
*/
class Pimple extends \Pimple\Container
{
/**
* Sets a parameter or an object.
*
* @param string $id The unique identifier for the parameter or object
* @param mixed $value The value of the parameter or a closure to define an object
* @throws \RuntimeException Prevent override of a frozen service
*/
public function __set($id, $value)
{
$this->offsetSet($id, $value);
}
/**
* Gets a parameter or an object.
*
* @param string $id The unique identifier for the parameter or object
* @return mixed The value of the parameter or an object
* @throws \InvalidArgumentException if the identifier is not defined
*/
public function __get($id)
{
return $this->offsetGet($id);
}
/**
* Checks if a parameter or an object is set.
*
* @param string $id The unique identifier for the parameter or object
* @return Boolean
*/
public function __isset($id)
{
return $this->offsetExists($id);
}
/**
* Unsets a parameter or an object.
*
* @param string $id The unique identifier for the parameter or object
*/
public function __unset($id)
{
$this->offsetUnset($id);
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Props;
use Psr\Container\ContainerExceptionInterface;
class ValueUnresolvableException extends \Exception implements ContainerExceptionInterface
{
}