UriRewriter.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. /**
  3. * Class Minify_CSS_UriRewriter
  4. * @package Minify
  5. */
  6. /**
  7. * Rewrite file-relative URIs as root-relative in CSS files
  8. *
  9. * @package Minify
  10. * @author Stephen Clay <steve@mrclay.org>
  11. */
  12. class Minify_CSS_UriRewriter {
  13. /**
  14. * rewrite() and rewriteRelative() append debugging information here
  15. *
  16. * @var string
  17. */
  18. public static $debugText = '';
  19. /**
  20. * In CSS content, rewrite file relative URIs as root relative
  21. *
  22. * @param string $css
  23. *
  24. * @param string $currentDir The directory of the current CSS file.
  25. *
  26. * @param string $docRoot The document root of the web site in which
  27. * the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
  28. *
  29. * @param array $symlinks (default = array()) If the CSS file is stored in
  30. * a symlink-ed directory, provide an array of link paths to
  31. * target paths, where the link paths are within the document root. Because
  32. * paths need to be normalized for this to work, use "//" to substitute
  33. * the doc root in the link paths (the array keys). E.g.:
  34. * <code>
  35. * array('//symlink' => '/real/target/path') // unix
  36. * array('//static' => 'D:\\staticStorage') // Windows
  37. * </code>
  38. *
  39. * @return string
  40. */
  41. public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array())
  42. {
  43. self::$_docRoot = self::_realpath(
  44. $docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
  45. );
  46. self::$_currentDir = self::_realpath($currentDir);
  47. self::$_symlinks = array();
  48. // normalize symlinks
  49. foreach ($symlinks as $link => $target) {
  50. $link = ($link === '//')
  51. ? self::$_docRoot
  52. : str_replace('//', self::$_docRoot . '/', $link);
  53. $link = strtr($link, '/', DIRECTORY_SEPARATOR);
  54. self::$_symlinks[$link] = self::_realpath($target);
  55. }
  56. self::$debugText .= "docRoot : " . self::$_docRoot . "\n"
  57. . "currentDir : " . self::$_currentDir . "\n";
  58. if (self::$_symlinks) {
  59. self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n";
  60. }
  61. self::$debugText .= "\n";
  62. $css = self::_trimUrls($css);
  63. // rewrite
  64. $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
  65. ,array(self::$className, '_processUriCB'), $css);
  66. $css = preg_replace_callback('/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/'
  67. ,array(self::$className, '_processUriCB'), $css);
  68. return $css;
  69. }
  70. /**
  71. * In CSS content, prepend a path to relative URIs
  72. *
  73. * @param string $css
  74. *
  75. * @param string $path The path to prepend.
  76. *
  77. * @return string
  78. */
  79. public static function prepend($css, $path)
  80. {
  81. self::$_prependPath = $path;
  82. $css = self::_trimUrls($css);
  83. // append
  84. $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
  85. ,array(self::$className, '_processUriCB'), $css);
  86. $css = preg_replace_callback('/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/'
  87. ,array(self::$className, '_processUriCB'), $css);
  88. self::$_prependPath = null;
  89. return $css;
  90. }
  91. /**
  92. * Get a root relative URI from a file relative URI
  93. *
  94. * <code>
  95. * Minify_CSS_UriRewriter::rewriteRelative(
  96. * '../img/hello.gif'
  97. * , '/home/user/www/css' // path of CSS file
  98. * , '/home/user/www' // doc root
  99. * );
  100. * // returns '/img/hello.gif'
  101. *
  102. * // example where static files are stored in a symlinked directory
  103. * Minify_CSS_UriRewriter::rewriteRelative(
  104. * 'hello.gif'
  105. * , '/var/staticFiles/theme'
  106. * , '/home/user/www'
  107. * , array('/home/user/www/static' => '/var/staticFiles')
  108. * );
  109. * // returns '/static/theme/hello.gif'
  110. * </code>
  111. *
  112. * @param string $uri file relative URI
  113. *
  114. * @param string $realCurrentDir realpath of the current file's directory.
  115. *
  116. * @param string $realDocRoot realpath of the site document root.
  117. *
  118. * @param array $symlinks (default = array()) If the file is stored in
  119. * a symlink-ed directory, provide an array of link paths to
  120. * real target paths, where the link paths "appear" to be within the document
  121. * root. E.g.:
  122. * <code>
  123. * array('/home/foo/www/not/real/path' => '/real/target/path') // unix
  124. * array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows
  125. * </code>
  126. *
  127. * @return string
  128. */
  129. public static function rewriteRelative($uri, $realCurrentDir, $realDocRoot, $symlinks = array())
  130. {
  131. // prepend path with current dir separator (OS-independent)
  132. $path = strtr($realCurrentDir, '/', DIRECTORY_SEPARATOR)
  133. . DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
  134. self::$debugText .= "file-relative URI : {$uri}\n"
  135. . "path prepended : {$path}\n";
  136. // "unresolve" a symlink back to doc root
  137. foreach ($symlinks as $link => $target) {
  138. if (0 === strpos($path, $target)) {
  139. // replace $target with $link
  140. $path = $link . substr($path, strlen($target));
  141. self::$debugText .= "symlink unresolved : {$path}\n";
  142. break;
  143. }
  144. }
  145. // strip doc root
  146. $path = substr($path, strlen($realDocRoot));
  147. self::$debugText .= "docroot stripped : {$path}\n";
  148. // fix to root-relative URI
  149. $uri = strtr($path, '/\\', '//');
  150. $uri = self::removeDots($uri);
  151. self::$debugText .= "traversals removed : {$uri}\n\n";
  152. return $uri;
  153. }
  154. /**
  155. * Remove instances of "./" and "../" where possible from a root-relative URI
  156. *
  157. * @param string $uri
  158. *
  159. * @return string
  160. */
  161. public static function removeDots($uri)
  162. {
  163. $uri = str_replace('/./', '/', $uri);
  164. // inspired by patch from Oleg Cherniy
  165. do {
  166. $uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, 1, $changed);
  167. } while ($changed);
  168. return $uri;
  169. }
  170. /**
  171. * Defines which class to call as part of callbacks, change this
  172. * if you extend Minify_CSS_UriRewriter
  173. *
  174. * @var string
  175. */
  176. protected static $className = 'Minify_CSS_UriRewriter';
  177. /**
  178. * Get realpath with any trailing slash removed. If realpath() fails,
  179. * just remove the trailing slash.
  180. *
  181. * @param string $path
  182. *
  183. * @return mixed path with no trailing slash
  184. */
  185. protected static function _realpath($path)
  186. {
  187. $realPath = realpath($path);
  188. if ($realPath !== false) {
  189. $path = $realPath;
  190. }
  191. return rtrim($path, '/\\');
  192. }
  193. /**
  194. * Directory of this stylesheet
  195. *
  196. * @var string
  197. */
  198. private static $_currentDir = '';
  199. /**
  200. * DOC_ROOT
  201. *
  202. * @var string
  203. */
  204. private static $_docRoot = '';
  205. /**
  206. * directory replacements to map symlink targets back to their
  207. * source (within the document root) E.g. '/var/www/symlink' => '/var/realpath'
  208. *
  209. * @var array
  210. */
  211. private static $_symlinks = array();
  212. /**
  213. * Path to prepend
  214. *
  215. * @var string
  216. */
  217. private static $_prependPath = null;
  218. /**
  219. * @param string $css
  220. *
  221. * @return string
  222. */
  223. private static function _trimUrls($css)
  224. {
  225. return preg_replace('/
  226. url\\( # url(
  227. \\s*
  228. ([^\\)]+?) # 1 = URI (assuming does not contain ")")
  229. \\s*
  230. \\) # )
  231. /x', 'url($1)', $css);
  232. }
  233. /**
  234. * @param array $m
  235. *
  236. * @return string
  237. */
  238. private static function _processUriCB($m)
  239. {
  240. // $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
  241. $isImport = ($m[0][0] === '@');
  242. // determine URI and the quote character (if any)
  243. if ($isImport) {
  244. $quoteChar = $m[1];
  245. $uri = $m[2];
  246. } else {
  247. // $m[1] is either quoted or not
  248. $quoteChar = ($m[1][0] === "'" || $m[1][0] === '"')
  249. ? $m[1][0]
  250. : '';
  251. $uri = ($quoteChar === '')
  252. ? $m[1]
  253. : substr($m[1], 1, strlen($m[1]) - 2);
  254. }
  255. // if not root/scheme relative and not starts with scheme
  256. if (!preg_match('~^(/|[a-z]+\:)~', $uri)) {
  257. // URI is file-relative: rewrite depending on options
  258. if (self::$_prependPath === null) {
  259. $uri = self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks);
  260. } else {
  261. $uri = self::$_prependPath . $uri;
  262. if ($uri[0] === '/') {
  263. $root = '';
  264. $rootRelative = $uri;
  265. $uri = $root . self::removeDots($rootRelative);
  266. } elseif (preg_match('@^((https?\:)?//([^/]+))/@', $uri, $m) && (false !== strpos($m[3], '.'))) {
  267. $root = $m[1];
  268. $rootRelative = substr($uri, strlen($root));
  269. $uri = $root . self::removeDots($rootRelative);
  270. }
  271. }
  272. }
  273. return $isImport
  274. ? "@import {$quoteChar}{$uri}{$quoteChar}"
  275. : "url({$quoteChar}{$uri}{$quoteChar})";
  276. }
  277. }