first commit

This commit is contained in:
2024-11-10 21:08:49 +01:00
commit 0d932ce5ee
14455 changed files with 2567501 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
DO NOT leave this directory on a site in production. Some scripts within may be
resource intensive and some allow file uploads.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This directory contains testing scripts and a few example applications built
with the Minify library classes.
tools/
Two utility web apps that upload a file, alter it, and send it back to the
user. One applies HTTP encoding, the other minifies CSS/JS/HTML.

View File

@@ -0,0 +1,81 @@
#!/usr/bin/env php
<?php
die('Must be rewritten for new API');
require __DIR__ . '/../../bootstrap.php';
$cli = new MrClay\Cli;
$cli->addOptionalArg('d')->assertDir()->setDescription('Your webserver\'s DOCUMENT_ROOT: Relative paths will be rewritten relative to this path. This is required if you\'re passing in CSS.');
$cli->addOptionalArg('o')->useAsOutfile()->setDescription('Outfile: If given, output will be placed in this file.');
$cli->addOptionalArg('t')->mustHaveValue()->setDescription('Type: must be "css", "js", or "html". This must be provided if passing content via STDIN.');
if (! $cli->validate()) {
if ($cli->isHelpRequest) {
echo "The Minify CLI tool!\n\n";
}
echo "USAGE: ./minify.php [-t TYPE] [-d DOC_ROOT] [-o OUTFILE] file ...\n";
if ($cli->isHelpRequest) {
echo $cli->getArgumentsListing();
}
echo "EXAMPLE: ./minify.php ../../tests/_test_files/js/*.js\n";
echo "EXAMPLE: ./minify.php -d../.. ../../tests/_test_files/css/*.css\n";
echo "EXAMPLE: echo \"var js = 'Awesome' && /cool/;\" | ./minify.php -t js\n";
echo "EXAMPLE: echo \"sel > ector { prop: 'value '; }\" | ./minify.php -t css\n";
echo "\n";
exit(0);
}
$outfile = $cli->values['o'];
$docRoot = $cli->values['d'];
$type = $cli->values['t'];
if (is_string($type)) {
if (! in_array($type, array('js', 'css', 'html'))) {
echo "Type argument invalid\n";
exit(1);
}
$type = constant('Minify::TYPE_' . strtoupper($type));
}
$paths = $cli->getPathArgs();
$sources = array();
if ($paths) {
foreach ($paths as $path) {
if (is_file($path)) {
$sources[] = new Minify_Source(array(
'filepath' => $path,
'minifyOptions' => array('docRoot' => $docRoot),
));
} else {
$sources[] = new Minify_Source(array(
'id' => $path,
'content' => "/*** $path not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}
}
} else {
// not paths input, expect STDIN
if (! $type) {
echo "Type must be specified to use STDIN\n";
exit(1);
}
$in = $cli->openInput();
$sources[] = new Minify_Source(array(
'id' => 'one',
'content' => stream_get_contents($in),
'contentType' => $type,
));
$cli->closeInput();
}
$combined = Minify::combine($sources) . "\n";
$fp = $cli->openOutput();
fwrite($fp, $combined);
$cli->closeOutput();

View File

@@ -0,0 +1,61 @@
#!/usr/bin/php
<?php
die('Must be rewritten for new API');
require __DIR__ . '/../../bootstrap.php';
$cli = new MrClay\Cli;
$cli->addRequiredArg('d')->assertDir()->setDescription('Your webserver\'s DOCUMENT_ROOT: Relative paths will be rewritten relative to this path.');
$cli->addOptionalArg('o')->useAsOutfile()->setDescription('Outfile: If given, output will be placed in this file.');
$cli->addOptionalArg('t')->setDescription('Test run: Return output followed by rewriting algorithm.');
if (! $cli->validate()) {
echo "USAGE: ./rewrite-uris.php [-t] -d DOC_ROOT [-o OUTFILE] file ...\n";
if ($cli->isHelpRequest) {
echo $cli->getArgumentsListing();
}
echo "EXAMPLE: ./rewrite-uris.php -v -d../.. ../../tests/_test_files/css/paths_rewrite.css ../../tests/_test_files/css/comments.css
\n";
exit(0);
}
$outfile = $cli->values['o'];
$testRun = $cli->values['t'];
$docRoot = $cli->values['d'];
$pathRewriter = function ($css, $options) {
return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot']);
};
$paths = $cli->getPathArgs();
$sources = array();
foreach ($paths as $path) {
if (is_file($path)) {
$sources[] = new Minify_Source(array(
'filepath' => $path,
'minifier' => $pathRewriter,
'minifyOptions' => array('docRoot' => $docRoot),
));
} else {
$sources[] = new Minify_Source(array(
'id' => $path,
'content' => "/*** $path not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}
}
$combined = Minify::combine($sources) . "\n";
if ($testRun) {
echo $combined;
echo Minify_CSS_UriRewriter::$debugText . "\n";
} else {
$fp = $cli->openOutput();
fwrite($fp, $combined);
$cli->closeOutput();
}

View File

@@ -0,0 +1,9 @@
<?php
// using same lib path and cache path specified in /min/config.php
require __DIR__ . '/../config.php';
$minifyCachePath = isset($min_cachePath)
? $min_cachePath
: '';

View File

@@ -0,0 +1,183 @@
<?php
die('Disabled: use this only for testing');
$app = (require __DIR__ . '/../../bootstrap.php');
/* @var \Minify\App $app */
// use FirePHP if not already setup
if (!$app->config->errorLogger) {
$app->config->errorLogger = true;
}
$app->cache = new Minify_Cache_Null();
$env = $app->env;
function h($txt)
{
return htmlspecialchars($txt, ENT_QUOTES, 'UTF-8');
}
if ($env->post('textIn')) {
$textIn = str_replace("\r\n", "\n", $env->post('textIn'));
}
if ($env->post('method') === 'Minify and serve') {
$base = trim($env->post('base'));
if ($base) {
$textIn = preg_replace(
'@(<head\\b[^>]*>)@i',
'$1<base href="' . h($base) . '" />',
$textIn
);
}
$sourceSpec['content'] = $textIn;
$sourceSpec['id'] = 'foo';
if (isset($_POST['minJs'])) {
$sourceSpec['minifyOptions']['jsMinifier'] = array('JSMin\\JSMin', 'minify');
}
if (isset($_POST['minCss'])) {
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSSmin', 'minify');
}
$source = new Minify_Source($sourceSpec);
$controller = new Minify_Controller_Files($env, $app->sourceFactory, $app->logger);
try {
$app->minify->serve($controller, array(
'files' => $source,
'contentType' => Minify::TYPE_HTML,
));
} catch (Exception $e) {
echo h($e->getMessage());
}
exit;
}
$tpl = array();
$tpl['classes'] = array('Minify_HTML', 'JSMin\\JSMin', 'Minify_CSS', 'Minify_Lines');
if (in_array($env->post('method'), $tpl['classes'])) {
$args = array($textIn);
if ($env->post('method') === 'Minify_HTML') {
$args[] = array(
'cssMinifier' => array('Minify_CSSmin', 'minify')
,'jsMinifier' => array('JSMin\\JSMin', 'minify')
);
}
$func = array($env->post('method'), 'minify');
$tpl['inBytes'] = strlen($textIn);
$startTime = microtime(true);
try {
$tpl['output'] = call_user_func_array($func, $args);
} 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)) {
$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>minifyTextarea</title></head>
<p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p>
<?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>Minify with:
<?php foreach ($vars['classes'] as $minClass): ?>
<input type="submit" name="method" value="<?php echo $minClass; ?>">
<?php endforeach; ?>
</p>
<p>...or <input type="submit" name="method" value="Minify and serve"> this HTML to the browser. Also minify:
<label>CSS <input type="checkbox" name="minCss" checked></label> :
<label>JS <input type="checkbox" name="minJs" checked></label>.
<label>Insert BASE element w/ href: <input type="text" name="base" size="20"></label>
</p>
</form>
<?php if (isset($vars['selectByte'])) { ?>
<script>
function selectText(el, begin, end) {
var len = el.value.length;
end = end || len;
if (begin == null) {
el.select();
} else {
if (el.setSelectionRange) {
el.setSelectionRange(begin, end);
} else {
if (el.createTextRange) {
var tr = el.createTextRange()
,c = "character";
tr.moveStart(c, begin);
tr.moveEnd(c, end - len);
tr.select();
} else {
el.select();
}
}
}
el.focus();
}
window.onload = function () {
var ta = document.querySelector('textarea[name="textIn"]');
selectText(ta, <?= $vars['selectByte'] ?>, <?= ($vars['selectByte'] + 1) ?>);
};
</script>
<?php }
exit;
}

View File

@@ -0,0 +1,172 @@
<?php
die('Disabled: use this only for testing');
/**
* Fetch and minify a URL (auto-detect HTML/JS/CSS)
*/
$app = (require __DIR__ . '/../../bootstrap.php');
/* @var \Minify\App $app */
$app->cache = new Minify_Cache_Null();
$env = $app->env;
function getPost($key)
{
if (! isset($_POST[$key])) {
return null;
}
return (PHP_VERSION_ID < 50400 && get_magic_quotes_gpc())
? stripslashes($_POST[$key])
: $_POST[$key];
}
function sniffType($headers)
{
$charset = 'utf-8';
$type = null;
$headers = "\n\n" . implode("\n\n", $headers) . "\n\n";
if (preg_match(
'@\\n\\nContent-Type: *([\\w/\\+-]+)( *; *charset *= *([\\w-]+))? *\\n\\n@i',
$headers,
$m
)) {
$sentType = $m[1];
if (isset($m[3])) {
$charset = $m[3];
}
if (preg_match('@^(?:text|application)/(?:x-)?(?:java|ecma)script$@i', $sentType)) {
$type = 'application/x-javascript';
} elseif (preg_match('@^(?:text|application)/(?:html|xml|xhtml+xml)$@i', $sentType, $m)) {
$type = 'text/html';
} elseif ($sentType === 'text/css') {
$type = $sentType;
}
}
return array(
'minify' => $type
,'sent' => $sentType
,'charset' => $charset
);
}
if (isset($_POST['url'])) {
require '../config.php';
$url = trim($env->post('url'));
$ua = trim($env->post('ua'));
$cook = trim($env->post('cook'));
if (! preg_match('@^https?://@', $url)) {
die('HTTP(s) only.');
}
$httpOpts = array(
'max_redirects' => 0
,'timeout' => 3
);
if ($ua !== '') {
$httpOpts['user_agent'] = $ua;
}
if ($cook !== '') {
$httpOpts['header'] = "Cookie: {$cook}\r\n";
}
$ctx = stream_context_create(array(
'http' => $httpOpts
));
// fetch
if (! ($fp = @fopen($url, 'r', false, $ctx))) {
die('Couldn\'t open URL.');
}
$meta = stream_get_meta_data($fp);
$content = stream_get_contents($fp);
fclose($fp);
// get type info
$type = sniffType($meta['wrapper_data']);
if (! $type['minify']) {
die('Unrecognized Content-Type: ' . $type['sent']);
}
if ($type['minify'] === 'text/html'
&& isset($_POST['addBase'])
&& ! preg_match('@<base\\b@i', $content)) {
$content = preg_replace(
'@(<head\\b[^>]*>)@i',
'$1<base href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" />',
$content
);
}
$sourceSpec['content'] = $content;
$sourceSpec['id'] = 'foo';
$sourceSpec['contentType'] = $type['minify'];
if ($type['minify'] === 'text/html') {
if ($env->post('minJs')) {
$sourceSpec['minifyOptions']['jsMinifier'] = array('JSMin\\JSMin', 'minify');
}
if ($env->post('minCss')) {
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSSmin', 'minify');
}
}
$source = new Minify_Source($sourceSpec);
$sendType = 'text/plain';
if ($type['minify'] === 'text/html' && $env->post('asText') === null) {
$sendType = $type['sent'];
}
if ($type['charset']) {
$sendType .= ';charset=' . $type['charset'];
}
header('Content-Type: ' . $sendType);
// using combine instead of serve because it allows us to specify a
// Content-Type like application/xhtml+xml IF we need to
try {
echo $app->minify->combine(array($source));
} catch (Exception $e) {
header('Content-Type: text/html;charset=utf-8');
echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}
exit();
}
header('Content-Type: text/html; charset=utf-8');
$ua = $env->server('HTTP_USER_AGENT');
?>
<!DOCTYPE html><head><title>Minify URL</title></head>
<p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p>
<h1>Fetch and Minify a URL</h1>
<p>This tool will retrieve the contents of a URL and minify it.
The fetched resource Content-Type will determine the minifier used.</p>
<form action="?2" method="post">
<p><label>URL: <input type="text" name="url" value="https://code.jquery.com/jquery-2.2.1.js" size="60"></label></p>
<p><input type="submit" value="Fetch and minify"></p>
<fieldset><legend>HTML options</legend>
<p>If the resource above is sent with an (x)HTML Content-Type, the following options will apply:</p>
<ul>
<li><label><input type="checkbox" name="asText" checked> Return plain text (o/w send the original content type)</label>
<li><label><input type="checkbox" name="minCss" checked> Minify CSS</label>
<li><label><input type="checkbox" name="minJs" checked> Minify JS</label>
<li><label><input type="checkbox" name="addBase" checked> Add BASE element (if not present)</label>
</ul>
</fieldset>
<fieldset><legend>Retreival options</legend>
<ul>
<li><label>User-Agent: <input type="text" name="ua" size="60" value="<?php echo htmlspecialchars($ua, ENT_QUOTES, 'UTF-8'); ?>"></label>
<li><label>Cookie: <input type="text" name="cook" size="60"></label>
</ul>
</fieldset>
</form>

View File

@@ -0,0 +1,55 @@
<?php
die('Disabled: use this only for testing');
$app = (require __DIR__ . '/../../bootstrap.php');
/* @var \Minify\App $app */
$env = $app->env;
header('Content-Type: text/html;charset=utf-8');
function h($str)
{
return htmlspecialchars($str, ENT_QUOTES);
}
function getInput($name, $default = '', $size = 50)
{
global $env;
$val = $env->post($name, $default);
return "<input type='text' name='{$name}' value='" . h($val) . "' size='{$size}' />";
}
$defaultCurrentDir = __DIR__;
$defaultDocRoot = realpath($env->getDocRoot());
$defaultSymLink = '//symlinkPath';
$defaultSymTarget = ($defaultCurrentDir[0] === '/') ? '/tmp' : 'C:\\WINDOWS\\Temp';
$defaultCss = "url(hello.gif)\nurl(../hello.gif)\nurl(../../hello.gif)\nurl(up/hello.gif)";
$out = '';
if ($env->post('css')) {
$symlinks = array();
if ('' !== ($target = $env->post('symTarget'))) {
$symlinks[$env->post('symLink')] = $target;
}
$css = Minify_CSS_UriRewriter::rewrite(
$env->post('css'),
$env->post('currentDir'),
$env->post('docRoot'),
$symlinks
);
$out = "<hr /><pre><code>" . h($css) . '</code></pre>';
}
?>
<h1>Test <code>Minify_CSS_UriRewriter::rewrite()</code></h1>
<p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p>
<form action="" method="post">
<div><label>document root: <?php echo getInput('docRoot', $defaultDocRoot); ?></label></div>
<div><label>symlink: <?php echo getInput('symLink', $defaultSymLink); ?> => <?php echo getInput('symTarget', $defaultSymTarget); ?></label></div>
<div><label>current directory: <?php echo getInput('currentDir', $defaultCurrentDir); ?></label></div>
<p><label>input CSS: <textarea name="css" cols="80" rows="5"><?php echo h($env->post('css', $defaultCss)); ?></textarea></label></p>
<p><input type="submit" value="rewrite()" /></p>
</form>
<?php echo $out; ?>