1
0
mirror of https://github.com/mrclay/minify.git synced 2025-08-08 15:16:56 +02:00

CSS/UriRewriter.php : refactoring + better docs

testRewriteUri.php : for testing Minify_CSS_UriRewriter::rewrite()
This commit is contained in:
Steve Clay
2009-03-18 18:30:04 +00:00
parent e315788a43
commit b021ed0c56
2 changed files with 169 additions and 56 deletions

View File

@@ -43,27 +43,28 @@ class Minify_CSS_UriRewriter {
*/
public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array())
{
self::$_docRoot = $docRoot
? $docRoot
: $_SERVER['DOCUMENT_ROOT'];
self::$_docRoot = realpath(self::$_docRoot);
self::$_currentDir = realpath($currentDir);
self::$_docRoot = self::_realpath(
$docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
);
self::$_currentDir = self::_realpath($currentDir);
self::$_symlinks = array();
// normalize symlinks
foreach ($symlinks as $link => $target) {
$link = str_replace('//', realpath(self::$_docRoot) . '/', $link);
$link = ($link === '//')
? self::$_docRoot
: str_replace('//', self::$_docRoot . '/', $link);
$link = strtr($link, '/', DIRECTORY_SEPARATOR);
self::$_symlinks[$link] = realpath($target);
self::$_symlinks[$link] = self::_realpath($target);
}
$css = self::_trimUrls($css);
// rewrite
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
,array(self::$className, '_uriCB'), $css);
,array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
,array(self::$className, '_uriCB'), $css);
,array(self::$className, '_processUriCB'), $css);
return $css;
}
@@ -85,9 +86,9 @@ class Minify_CSS_UriRewriter {
// append
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
,array(self::$className, '_uriCB'), $css);
,array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
,array(self::$className, '_uriCB'), $css);
,array(self::$className, '_processUriCB'), $css);
self::$_prependPath = null;
return $css;
@@ -115,27 +116,26 @@ class Minify_CSS_UriRewriter {
*/
private static $_prependPath = null;
private static function _trimUrls($css)
{
return preg_replace('/
url\\( # url(
\\s*
([^\\)]+?) # 1 = URI (really just a bunch of non right parenthesis)
([^\\)]+?) # 1 = URI (assuming does not contain ")")
\\s*
\\) # )
/x', 'url($1)', $css);
}
private static function _uriCB($m)
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 {
// is url()
// $m[1] is either quoted or not
$quoteChar = ($m[1][0] === "'" || $m[1][0] === '"')
? $m[1][0]
@@ -144,47 +144,101 @@ class Minify_CSS_UriRewriter {
? $m[1]
: substr($m[1], 1, strlen($m[1]) - 2);
}
if ('/' !== $uri[0]) {
if (strpos($uri, '//') > 0
|| 0 === strpos($uri, 'data:')
) {
// probably starts with protocol, do not alter
} else {
// it's a file relative URI!
// choose mode
if (self::$_prependPath !== null) {
// prepend path
$uri = self::$_prependPath . $uri;
} else {
// rewrite path
// prepend path with current dir separator (OS-independent)
$path = strtr(self::$_currentDir, '/', DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
// "unresolve" a symlink back to doc root
foreach (self::$_symlinks as $link => $target) {
if (0 === strpos($path, $target)) {
// replace $target with $link
$path = $link . substr($path, strlen($target));
break;
}
}
// strip doc root
$path = substr($path, strlen(self::$_docRoot));
// fix to root-relative URI
$uri = strtr($path, DIRECTORY_SEPARATOR, '/');
// remove /./ and /../ where possible
$uri = str_replace('/./', '/', $uri);
// inspired by patch from Oleg Cherniy
do {
$uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, -1, $changed);
} while ($changed);
}
}
// analyze URI
if ('/' !== $uri[0] // root-relative
&& false === strpos($uri, '//') // protocol (non-data)
&& 0 !== strpos($uri, 'data:') // data protocol
) {
// URI is file-relative: rewrite depending on options
$uri = (self::$_prependPath !== null)
? (self::$_prependPath . $uri)
: self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks);
}
if ($isImport) {
return "@import {$quoteChar}{$uri}{$quoteChar}";
} else {
return "url({$quoteChar}{$uri}{$quoteChar})";
return $isImport
? "@import {$quoteChar}{$uri}{$quoteChar}"
: "url({$quoteChar}{$uri}{$quoteChar})";
}
/**
* Rewrite a file relative URI as root relative
*
* <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)
. DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
// "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));
break;
}
}
// strip doc root
$path = substr($path, strlen($realDocRoot));
// fix to root-relative URI
$uri = strtr($path, DIRECTORY_SEPARATOR, '/');
// remove /./ and /../ where possible
$uri = str_replace('/./', '/', $uri);
// inspired by patch from Oleg Cherniy
do {
$uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, -1, $changed);
} while ($changed);
return $uri;
}
/**
* Get realpath with any trailing slash removed
*
* @param string $path
*
* @return mixed real path or false on realpath() failure
*/
protected static function _realpath($path)
{
$path = realpath($path);
if (! $path) {
return false;
}
$last = $path[strlen($path) - 1];
return ($last === '/' || $last === '\\')
? substr($path, 0, strlen($path) - 1)
: $path;
}
}

View File

@@ -0,0 +1,59 @@
<?php
header('Content-Type: text/html;charset=utf-8');
function h($str) { return htmlspecialchars($str, ENT_QUOTES); }
function getPost($name, $default = '') { return isset($_POST[$name]) ? $_POST[$name] : $default; }
function getInput($name, $default = '', $size = 50) {
$val = h(isset($_POST[$name]) ? $_POST[$name] : $default);
return "<input type='text' name='{$name}' value='{$val}' size='{$size}' />";
}
// validate user POST (no arrays and fix slashes)
if (! empty($_POST)) {
foreach ($_POST as $name => $val) {
if (! is_string($val)) {
unset($_POST[$name]);
continue;
}
if (get_magic_quotes_gpc()) {
$_POST[$name] = stripslashes($val);
}
}
}
$defaultCurrentDir = dirname(__FILE__);
$defaultDocRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$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 (isset($_POST['css'])) {
require '../config.php';
require 'Minify/CSS/UriRewriter.php';
$symlinks = array();
if ('' !== ($target = getPost('symTarget'))) {
$symlinks[getPost('symLink')] = $target;
}
$css = Minify_CSS_UriRewriter::rewrite(
getPost('css')
, getPost('currentDir')
, getPost('docRoot')
, $symlinks
);
$out = "<hr /><pre><code>" . h($css) . '</code></pre>';
}
?>
<h1>Test <code>Minify_CSS_UriRewriter::rewrite()</code></h1>
<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(getPost('css', $defaultCss)); ?></textarea></label></p>
<p><input type="submit" value="rewrite()" /></p>
</form>
<?php echo $out; ?>