839c6e764d320e9d4f0d7ef9f76b9fec2ec52241
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / ResourceCompressor.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\PathUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Utility\StringUtility;
20
21 /**
22 * Compressor
23 * This merges and compresses CSS and JavaScript files of the TYPO3 Backend.
24 *
25 * @author Steffen Gebert <steffen@steffen-gebert.de>
26 */
27 class ResourceCompressor {
28
29 protected $targetDirectory = 'typo3temp/compressor/';
30
31 protected $relativePath = '';
32
33 protected $rootPath = '';
34
35 protected $backPath = '';
36
37 // gzipped versions are only created if $TYPO3_CONF_VARS[TYPO3_MODE]['compressionLevel'] is set
38 protected $createGzipped = FALSE;
39
40 // default compression level is -1
41 protected $gzipCompressionLevel = -1;
42
43 protected $htaccessTemplate = '<FilesMatch "\\.(js|css)(\\.gzip)?$">
44 <IfModule mod_expires.c>
45 ExpiresActive on
46 ExpiresDefault "access plus 7 days"
47 </IfModule>
48 FileETag MTime Size
49 </FilesMatch>';
50
51 /**
52 * Constructor
53 */
54 public function __construct() {
55 // we check for existence of our targetDirectory
56 if (!is_dir((PATH_site . $this->targetDirectory))) {
57 GeneralUtility::mkdir(PATH_site . $this->targetDirectory);
58 }
59 // if enabled, we check whether we should auto-create the .htaccess file
60 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['generateApacheHtaccess']) {
61 // check whether .htaccess exists
62 $htaccessPath = PATH_site . $this->targetDirectory . '.htaccess';
63 if (!file_exists($htaccessPath)) {
64 GeneralUtility::writeFile($htaccessPath, $this->htaccessTemplate);
65 }
66 }
67 // decide whether we should create gzipped versions or not
68 $compressionLevel = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel'];
69 // we need zlib for gzencode()
70 if (extension_loaded('zlib') && $compressionLevel) {
71 $this->createGzipped = TRUE;
72 // $compressionLevel can also be TRUE
73 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($compressionLevel)) {
74 $this->gzipCompressionLevel = (int)$compressionLevel;
75 }
76 }
77 $this->setInitialPaths();
78 }
79
80 /**
81 * Sets initial values for paths.
82 *
83 * @return void
84 */
85 public function setInitialPaths() {
86 $this->setInitialRelativePath();
87 $this->setInitialRootPath();
88 $this->setInitialBackPath();
89 }
90
91 /**
92 * Sets relative back path
93 *
94 * @return void
95 */
96 protected function setInitialBackPath() {
97 $backPath = TYPO3_MODE === 'BE' ? $GLOBALS['BACK_PATH'] : '';
98 $this->setBackPath($backPath);
99 }
100
101 /**
102 * Sets absolute path to working directory
103 *
104 * @return void
105 */
106 protected function setInitialRootPath() {
107 $rootPath = TYPO3_MODE === 'BE' ? PATH_typo3 : PATH_site;
108 $this->setRootPath($rootPath);
109 }
110
111 /**
112 * Sets relative path to PATH_site
113 *
114 * @return void
115 */
116 protected function setInitialRelativePath() {
117 $relativePath = TYPO3_MODE === 'BE' ? $GLOBALS['BACK_PATH'] . '../' : '';
118 $this->setRelativePath($relativePath);
119 }
120
121 /**
122 * Sets relative path to PATH_site
123 *
124 * @param string $relativePath Relative path to site root
125 * @return void
126 */
127 public function setRelativePath($relativePath) {
128 if (is_string($relativePath)) {
129 $this->relativePath = $relativePath;
130 }
131 }
132
133 /**
134 * Sets absolute path to working directory
135 *
136 * @param string $rootPath Absolute path
137 * @return void
138 */
139 public function setRootPath($rootPath) {
140 if (is_string($rootPath)) {
141 $this->rootPath = $rootPath;
142 }
143 }
144
145 /**
146 * Sets relative back path
147 *
148 * @param string $backPath Back path
149 * @return void
150 */
151 public function setBackPath($backPath) {
152 if (is_string($backPath)) {
153 $this->backPath = $backPath;
154 }
155 }
156
157 /**
158 * Concatenates the Stylesheet files
159 *
160 * Options:
161 * baseDirectories If set, only include files below one of the base directories
162 *
163 * @param array $cssFiles CSS files to process
164 * @param array $options Additional options
165 * @return array CSS files
166 */
167 public function concatenateCssFiles(array $cssFiles, array $options = array()) {
168 $filesToInclude = array();
169 foreach ($cssFiles as $key => $fileOptions) {
170 // no concatenation allowed for this file, so continue
171 if (!empty($fileOptions['excludeFromConcatenation'])) {
172 continue;
173 }
174 // we remove BACK_PATH from $filename, so make it relative to root path
175 $filenameFromMainDir = $this->getFilenameFromMainDir($fileOptions['file']);
176 // if $options['baseDirectories'] set, we only include files below these directories
177 if ((!isset($options['baseDirectories']) || $this->checkBaseDirectory($filenameFromMainDir, array_merge($options['baseDirectories'], array($this->targetDirectory)))) && $fileOptions['media'] === 'all') {
178 if ($fileOptions['forceOnTop']) {
179 array_unshift($filesToInclude, $filenameFromMainDir);
180 } else {
181 $filesToInclude[] = $filenameFromMainDir;
182 }
183 // remove the file from the incoming file array
184 unset($cssFiles[$key]);
185 }
186 }
187 if (!empty($filesToInclude)) {
188 $targetFile = $this->createMergedCssFile($filesToInclude);
189 $targetFileRelative = $this->relativePath . $targetFile;
190 $concatenatedOptions = array(
191 'file' => $targetFileRelative,
192 'rel' => 'stylesheet',
193 'media' => 'all',
194 'compress' => TRUE,
195 'excludeFromConcatenation' => TRUE,
196 'forceOnTop' => FALSE,
197 'allWrap' => ''
198 );
199 // place the merged stylesheet on top of the stylesheets
200 $cssFiles = array_merge(array($targetFileRelative => $concatenatedOptions), $cssFiles);
201 }
202 return $cssFiles;
203 }
204
205 /**
206 * Concatenates the JavaScript files
207 *
208 * @param array $jsFiles JavaScript files to process
209 * @return array JS files
210 */
211 public function concatenateJsFiles(array $jsFiles) {
212 $filesToInclude = array();
213 foreach ($jsFiles as $key => $fileOptions) {
214 // invalid section found or no concatenation allowed, so continue
215 if (empty($fileOptions['section']) || !empty($fileOptions['excludeFromConcatenation'])) {
216 continue;
217 }
218 if (!isset($filesToInclude[$fileOptions['section']])) {
219 $filesToInclude[$fileOptions['section']] = array();
220 }
221 // we remove BACK_PATH from $filename, so make it relative to root path
222 $filenameFromMainDir = $this->getFilenameFromMainDir($fileOptions['file']);
223 if ($fileOptions['forceOnTop']) {
224 array_unshift($filesToInclude[$fileOptions['section']], $filenameFromMainDir);
225 } else {
226 $filesToInclude[$fileOptions['section']][] = $filenameFromMainDir;
227 }
228 // remove the file from the incoming file array
229 unset($jsFiles[$key]);
230 }
231 if (!empty($filesToInclude)) {
232 foreach ($filesToInclude as $section => $files) {
233 $targetFile = $this->createMergedJsFile($files);
234 $targetFileRelative = $this->relativePath . $targetFile;
235 $concatenatedOptions = array(
236 'file' => $targetFileRelative,
237 'type' => 'text/javascript',
238 'section' => $section,
239 'compress' => TRUE,
240 'excludeFromConcatenation' => TRUE,
241 'forceOnTop' => FALSE,
242 'allWrap' => ''
243 );
244 // place the merged javascript on top of the JS files
245 $jsFiles = array_merge(array($targetFileRelative => $concatenatedOptions), $jsFiles);
246 }
247 }
248 return $jsFiles;
249 }
250
251 /**
252 * Creates a merged CSS file
253 *
254 * @param array $filesToInclude Files which should be merged, paths relative to root path
255 * @return mixed Filename of the merged file
256 */
257 protected function createMergedCssFile(array $filesToInclude) {
258 return $this->createMergedFile($filesToInclude, 'css');
259 }
260
261 /**
262 * Creates a merged JS file
263 *
264 * @param array $filesToInclude Files which should be merged, paths relative to root path
265 * @return mixed Filename of the merged file
266 */
267 protected function createMergedJsFile(array $filesToInclude) {
268 return $this->createMergedFile($filesToInclude, 'js');
269 }
270
271 /**
272 * Creates a merged file with given file type
273 *
274 * @param array $filesToInclude Files which should be merged, paths relative to root path
275 * @param string $type File type
276 *
277 * @throws \InvalidArgumentException
278 * @return mixed Filename of the merged file
279 */
280 protected function createMergedFile(array $filesToInclude, $type = 'css') {
281 // Get file type
282 $type = strtolower(trim($type, '. '));
283 if (empty($type)) {
284 throw new \InvalidArgumentException('Error in TYPO3\\CMS\\Core\\Resource\\ResourceCompressor: No valid file type given for merged file', 1308957498);
285 }
286 // we add up the filenames, filemtimes and filsizes to later build a checksum over
287 // it and include it in the temporary file name
288 $unique = '';
289 foreach ($filesToInclude as $key => $filename) {
290 if (GeneralUtility::isValidUrl($filename)) {
291 // check if it is possibly a local file with fully qualified URL
292 if (GeneralUtility::isOnCurrentHost($filename) &&
293 GeneralUtility::isFirstPartOfStr(
294 $filename,
295 GeneralUtility::getIndpEnv('TYPO3_SITE_URL')
296 )
297 ) {
298 // attempt to turn it into a local file path
299 $localFilename = substr($filename, strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_URL')));
300 if (@is_file(GeneralUtility::resolveBackPath($this->rootPath . $localFilename))) {
301 $filesToInclude[$key] = $localFilename;
302 } else {
303 $filesToInclude[$key] = $this->retrieveExternalFile($filename);
304 }
305 } else {
306 $filesToInclude[$key] = $this->retrieveExternalFile($filename);
307 }
308 $filename = $filesToInclude[$key];
309 }
310 $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $filename);
311 if (@file_exists($filenameAbsolute)) {
312 $fileStatus = stat($filenameAbsolute);
313 $unique .= $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size'];
314 } else {
315 $unique .= $filenameAbsolute;
316 }
317 }
318 $targetFile = $this->targetDirectory . 'merged-' . md5($unique) . '.' . $type;
319 // if the file doesn't already exist, we create it
320 if (!file_exists((PATH_site . $targetFile))) {
321 $concatenated = '';
322 // concatenate all the files together
323 foreach ($filesToInclude as $filename) {
324 $contents = GeneralUtility::getUrl(GeneralUtility::resolveBackPath($this->rootPath . $filename));
325 // remove any UTF-8 byte order mark (BOM) from files
326 if (StringUtility::beginsWith($contents, "\xEF\xBB\xBF")) {
327 $contents = substr($contents, 3);
328 }
329 // only fix paths if files aren't already in typo3temp (already processed)
330 if ($type === 'css' && !GeneralUtility::isFirstPartOfStr($filename, $this->targetDirectory)) {
331 $contents = $this->cssFixRelativeUrlPaths($contents, PathUtility::dirname($filename) . '/');
332 }
333 $concatenated .= LF . $contents;
334 }
335 // move @charset, @import and @namespace statements to top of new file
336 if ($type === 'css') {
337 $concatenated = $this->cssFixStatements($concatenated);
338 }
339 GeneralUtility::writeFile(PATH_site . $targetFile, $concatenated);
340 }
341 return $targetFile;
342 }
343
344 /**
345 * Compress multiple css files
346 *
347 * @param array $cssFiles The files to compress (array key = filename), relative to requested page
348 * @return array The CSS files after compression (array key = new filename), relative to requested page
349 */
350 public function compressCssFiles(array $cssFiles) {
351 $filesAfterCompression = array();
352 foreach ($cssFiles as $key => $fileOptions) {
353 // if compression is enabled
354 if ($fileOptions['compress']) {
355 $filename = $this->compressCssFile($fileOptions['file']);
356 $fileOptions['compress'] = FALSE;
357 $fileOptions['file'] = $filename;
358 $filesAfterCompression[$filename] = $fileOptions;
359 } else {
360 $filesAfterCompression[$key] = $fileOptions;
361 }
362 }
363 return $filesAfterCompression;
364 }
365
366 /**
367 * Compresses a CSS file
368 *
369 * Options:
370 * baseDirectories If set, only include files below one of the base directories
371 *
372 * removes comments and whitespaces
373 * Adopted from http://drupal.org/files/issues/minify_css.php__1.txt
374 *
375 * @param string $filename Source filename, relative to requested page
376 * @return string Compressed filename, relative to requested page
377 */
378 public function compressCssFile($filename) {
379 // generate the unique name of the file
380 $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $this->getFilenameFromMainDir($filename));
381 if (@file_exists($filenameAbsolute)) {
382 $fileStatus = stat($filenameAbsolute);
383 $unique = $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size'];
384 } else {
385 $unique = $filenameAbsolute;
386 }
387
388 $pathinfo = PathUtility::pathinfo($filename);
389 $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.css';
390 // only create it, if it doesn't exist, yet
391 if (!file_exists((PATH_site . $targetFile)) || $this->createGzipped && !file_exists((PATH_site . $targetFile . '.gzip'))) {
392 $contents = GeneralUtility::getUrl($filenameAbsolute);
393 // Perform some safe CSS optimizations.
394 $contents = str_replace(CR, '', $contents);
395 // Strip any and all carriage returns.
396 // Match and process strings, comments and everything else, one chunk at a time.
397 // To understand this regex, read: "Mastering Regular Expressions 3rd Edition" chapter 6.
398 $contents = preg_replace_callback('%
399 # One-regex-to-rule-them-all! - version: 20100220_0100
400 # Group 1: Match a double quoted string.
401 ("[^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+") | # or...
402 # Group 2: Match a single quoted string.
403 (\'[^\'\\\\]*+(?:\\\\.[^\'\\\\]*+)*+\') | # or...
404 # Group 3: Match a regular non-MacIE5-hack comment.
405 (/\\*[^\\\\*]*+\\*++(?:[^\\\\*/][^\\\\*]*+\\*++)*+/) | # or...
406 # Group 4: Match a MacIE5-type1 comment.
407 (/\\*(?:[^*\\\\]*+\\**+(?!/))*+\\\\[^*]*+\\*++(?:[^*/][^*]*+\\*++)*+/(?<!\\\\\\*/)) | # or...
408 # Group 5: Match a MacIE5-type2 comment.
409 (/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/(?<=\\\\\\*/)) # folllowed by...
410 # Group 6: Match everything up to final closing regular comment
411 ([^/]*+(?:(?!\\*)/[^/]*+)*?)
412 # Group 7: Match final closing regular comment
413 (/\\*[^/]++(?:(?<!\\*)/(?!\\*)[^/]*+)*+/(?<=(?<!\\\\)\\*/)) | # or...
414 # Group 8: Match regular non-string, non-comment text.
415 ([^"\'/]*+(?:(?!/\\*)/[^"\'/]*+)*+)
416 %Ssx', array('self', 'compressCssPregCallback'), $contents);
417 // Do it!
418 $contents = preg_replace('/^\\s++/', '', $contents);
419 // Strip leading whitespace.
420 $contents = preg_replace('/[ \\t]*+\\n\\s*+/S', '
421 ', $contents);
422 // Consolidate multi-lines space.
423 $contents = preg_replace('/(?<!\\s)\\s*+$/S', '
424 ', $contents);
425 // Ensure file ends in newline.
426 // we have to fix relative paths, if we aren't working on a file in our target directory
427 if (strpos($filename, $this->targetDirectory) === FALSE) {
428 $filenameRelativeToMainDir = substr($filename, strlen($this->backPath));
429 $contents = $this->cssFixRelativeUrlPaths($contents, PathUtility::dirname($filenameRelativeToMainDir) . '/');
430 }
431 $this->writeFileAndCompressed($targetFile, $contents);
432 }
433 return $this->relativePath . $this->returnFileReference($targetFile);
434 }
435
436 /**
437 * Callback function for preg_replace
438 *
439 * @see compressCssFile
440 * @param array $matches
441 * @return string the compressed string
442 */
443 static public function compressCssPregCallback($matches) {
444 if ($matches[1]) {
445 // Group 1: Double quoted string.
446 return $matches[1];
447 } elseif ($matches[2]) {
448 // Group 2: Single quoted string.
449 return $matches[2];
450 } elseif ($matches[3]) {
451 // Group 3: Regular non-MacIE5-hack comment.
452 return '
453 ';
454 } elseif ($matches[4]) {
455 // Group 4: MacIE5-hack-type-1 comment.
456 return '
457 /*\\T1*/
458 ';
459 } elseif ($matches[5]) {
460 // Group 5,6,7: MacIE5-hack-type-2 comment
461 $matches[6] = preg_replace('/\\s++([+>{};,)])/S', '$1', $matches[6]);
462 // Clean pre-punctuation.
463 $matches[6] = preg_replace('/([+>{}:;,(])\\s++/S', '$1', $matches[6]);
464 // Clean post-punctuation.
465 $matches[6] = preg_replace('/;?\\}/S', '}
466 ', $matches[6]);
467 // Add a touch of formatting.
468 return '
469 /*T2\\*/' . $matches[6] . '
470 /*T2E*/
471 ';
472 } elseif (isset($matches[8])) {
473 // Group 8: Non-string, non-comment. Safe to clean whitespace here.
474 $matches[8] = preg_replace('/^\\s++/', '', $matches[8]);
475 // Strip all leading whitespace.
476 $matches[8] = preg_replace('/\\s++$/', '', $matches[8]);
477 // Strip all trailing whitespace.
478 $matches[8] = preg_replace('/\\s{2,}+/', ' ', $matches[8]);
479 // Consolidate multiple whitespace.
480 $matches[8] = preg_replace('/\\s++([+>{};,)])/S', '$1', $matches[8]);
481 // Clean pre-punctuation.
482 $matches[8] = preg_replace('/([+>{}:;,(])\\s++/S', '$1', $matches[8]);
483 // Clean post-punctuation.
484 $matches[8] = preg_replace('/;?\\}/S', '}
485 ', $matches[8]);
486 // Add a touch of formatting.
487 return $matches[8];
488 }
489 return $matches[0] . '
490 /* ERROR! Unexpected _proccess_css_minify() parameter */
491 ';
492 }
493
494 /**
495 * Compress multiple javascript files
496 *
497 * @param array $jsFiles The files to compress (array key = filename), relative to requested page
498 * @return array The js files after compression (array key = new filename), relative to requested page
499 */
500 public function compressJsFiles(array $jsFiles) {
501 $filesAfterCompression = array();
502 foreach ($jsFiles as $fileName => $fileOptions) {
503 // If compression is enabled
504 if ($fileOptions['compress']) {
505 $compressedFilename = $this->compressJsFile($fileOptions['file']);
506 $fileOptions['compress'] = FALSE;
507 $fileOptions['file'] = $compressedFilename;
508 $filesAfterCompression[$compressedFilename] = $fileOptions;
509 } else {
510 $filesAfterCompression[$fileName] = $fileOptions;
511 }
512 }
513 return $filesAfterCompression;
514 }
515
516 /**
517 * Compresses a javascript file
518 *
519 * @param string $filename Source filename, relative to requested page
520 * @return string Filename of the compressed file, relative to requested page
521 */
522 public function compressJsFile($filename) {
523 // generate the unique name of the file
524 $filenameAbsolute = GeneralUtility::resolveBackPath($this->rootPath . $this->getFilenameFromMainDir($filename));
525 if (@file_exists($filenameAbsolute)) {
526 $fileStatus = stat($filenameAbsolute);
527 $unique = $filenameAbsolute . $fileStatus['mtime'] . $fileStatus['size'];
528 } else {
529 $unique = $filenameAbsolute;
530 }
531 $pathinfo = PathUtility::pathinfo($filename);
532 $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.js';
533 // only create it, if it doesn't exist, yet
534 if (!file_exists((PATH_site . $targetFile)) || $this->createGzipped && !file_exists((PATH_site . $targetFile . '.gzip'))) {
535 $contents = GeneralUtility::getUrl($filenameAbsolute);
536 $this->writeFileAndCompressed($targetFile, $contents);
537 }
538 return $this->relativePath . $this->returnFileReference($targetFile);
539 }
540
541 /**
542 * Finds the relative path to a file, relative to the root path.
543 *
544 * @param string $filename the name of the file
545 * @return string the path to the file relative to the root path
546 */
547 protected function getFilenameFromMainDir($filename) {
548 // if BACK_PATH is empty return $filename
549 if (empty($this->backPath)) {
550 return $filename;
551 }
552 // if the file exists in the root path, just return the $filename
553 if (strpos($filename, $this->backPath) === 0) {
554 $file = str_replace($this->backPath, '', $filename);
555 if (is_file(GeneralUtility::resolveBackPath($this->rootPath . $file))) {
556 return $file;
557 }
558 }
559 // if the file is from a special TYPO3 internal directory, add the missing typo3/ prefix
560 if (is_file(realpath(PATH_site . TYPO3_mainDir . $filename))) {
561 $filename = TYPO3_mainDir . $filename;
562 }
563 // build the file path relatively to the PATH_site
564 $backPath = str_replace(TYPO3_mainDir, '', $this->backPath);
565 $file = str_replace($backPath, '', $filename);
566 if (substr($file, 0, 3) === '../') {
567 $file = GeneralUtility::resolveBackPath(PATH_typo3 . $file);
568 } else {
569 $file = PATH_site . $file;
570 }
571 // check if the file exists, and if so, return the path relative to TYPO3_mainDir
572 if (is_file($file)) {
573 $mainDirDepth = substr_count(TYPO3_mainDir, '/');
574 return str_repeat('../', $mainDirDepth) . str_replace(PATH_site, '', $file);
575 }
576 // none of above conditions were met, fallback to default behaviour
577 return substr($filename, strlen($this->backPath));
578 }
579
580 /**
581 * Decides whether a file comes from one of the baseDirectories
582 *
583 * @param string $filename Filename
584 * @param array $baseDirectories Base directories
585 * @return boolean File belongs to a base directory or not
586 */
587 protected function checkBaseDirectory($filename, array $baseDirectories) {
588 foreach ($baseDirectories as $baseDirectory) {
589 // check, if $filename starts with base directory
590 if (GeneralUtility::isFirstPartOfStr($filename, $baseDirectory)) {
591 return TRUE;
592 }
593 }
594 return FALSE;
595 }
596
597 /**
598 * Fixes the relative paths inside of url() references in CSS files
599 *
600 * @param string $contents Data to process
601 * @param string $oldDir Directory of the original file, relative to TYPO3_mainDir
602 * @return string Processed data
603 */
604 protected function cssFixRelativeUrlPaths($contents, $oldDir) {
605 $mainDir = TYPO3_MODE === 'BE' ? TYPO3_mainDir : '';
606 $newDir = '../../' . $mainDir . $oldDir;
607 // Replace "url()" paths
608 if (stripos($contents, 'url') !== FALSE) {
609 $regex = '/url(\\(\\s*["\']?(?!\\/)([^"\']+)["\']?\\s*\\))/iU';
610 $contents = $this->findAndReplaceUrlPathsByRegex($contents, $regex, $newDir, '(\'|\')');
611 }
612 // Replace "@import" paths
613 if (stripos($contents, '@import') !== FALSE) {
614 $regex = '/@import\\s*(["\']?(?!\\/)([^"\']+)["\']?)/i';
615 $contents = $this->findAndReplaceUrlPathsByRegex($contents, $regex, $newDir, '"|"');
616 }
617 return $contents;
618 }
619
620 /**
621 * Finds and replaces all URLs by using a given regex
622 *
623 * @param string $contents Data to process
624 * @param string $regex Regex used to find URLs in content
625 * @param string $newDir Path to prepend to the original file
626 * @param string $wrap Wrap around replaced values
627 * @return string Processed data
628 */
629 protected function findAndReplaceUrlPathsByRegex($contents, $regex, $newDir, $wrap = '|') {
630 $matches = array();
631 $replacements = array();
632 $wrap = explode('|', $wrap);
633 preg_match_all($regex, $contents, $matches);
634 foreach ($matches[2] as $matchCount => $match) {
635 // remove '," or white-spaces around
636 $match = trim($match, '\'" ');
637 // we must not rewrite paths containing ":" or "url(", e.g. data URIs (see RFC 2397)
638 if (strpos($match, ':') === FALSE && !preg_match('/url\\s*\\(/i', $match)) {
639 $newPath = GeneralUtility::resolveBackPath($newDir . $match);
640 $replacements[$matches[1][$matchCount]] = $wrap[0] . $newPath . $wrap[1];
641 }
642 }
643 // replace URL paths in content
644 if (!empty($replacements)) {
645 $contents = str_replace(array_keys($replacements), array_values($replacements), $contents);
646 }
647 return $contents;
648 }
649
650 /**
651 * Moves @charset, @import and @namespace statements to the top of
652 * the content, because they must occur before all other CSS rules
653 *
654 * @param string $contents Data to process
655 * @return string Processed data
656 */
657 protected function cssFixStatements($contents) {
658 $matches = array();
659 $comment = LF . '/* moved by compressor */' . LF;
660 // nothing to do, so just return contents
661 if (stripos($contents, '@charset') === FALSE && stripos($contents, '@import') === FALSE && stripos($contents, '@namespace') === FALSE) {
662 return $contents;
663 }
664 $regex = '/@(charset|import|namespace)\\s*(url)?\\s*\\(?\\s*["\']?[^"\'\\)]+["\']?\\s*\\)?\\s*;/i';
665 preg_match_all($regex, $contents, $matches);
666 if (!empty($matches[0])) {
667 // remove existing statements
668 $contents = str_replace($matches[0], '', $contents);
669 // add statements to the top of contents in the order they occur in original file
670 $contents = $comment . implode($comment, $matches[0]) . LF . trim($contents);
671 }
672 return $contents;
673 }
674
675 /**
676 * Writes $contents into file $filename together with a gzipped version into $filename.gz
677 *
678 * @param string $filename Target filename
679 * @param string $contents File contents
680 * @return void
681 */
682 protected function writeFileAndCompressed($filename, $contents) {
683 // write uncompressed file
684 GeneralUtility::writeFile(PATH_site . $filename, $contents);
685 if ($this->createGzipped) {
686 // create compressed version
687 GeneralUtility::writeFile(PATH_site . $filename . '.gzip', gzencode($contents, $this->gzipCompressionLevel));
688 }
689 }
690
691 /**
692 * Decides whether a client can deal with gzipped content or not and returns the according file name,
693 * based on HTTP_ACCEPT_ENCODING
694 *
695 * @param string $filename File name
696 * @return string $filename suffixed with '.gzip' or not - dependent on HTTP_ACCEPT_ENCODING
697 */
698 protected function returnFileReference($filename) {
699 // if the client accepts gzip and we can create gzipped files, we give him compressed versions
700 if ($this->createGzipped && strpos(GeneralUtility::getIndpEnv('HTTP_ACCEPT_ENCODING'), 'gzip') !== FALSE) {
701 return $filename . '.gzip';
702 } else {
703 return $filename;
704 }
705 }
706
707 /**
708 * Retrieves an external file and stores it locally.
709 *
710 * @param string $url
711 * @return string Temporary local filename for the externally-retrieved file
712 */
713 protected function retrieveExternalFile($url) {
714 $externalContent = GeneralUtility::getUrl($url);
715 $filename = $this->targetDirectory . 'external-' . md5($url);
716 // write only if file does not exist and md5 of the content is not the same as fetched one
717 if (!file_exists(PATH_site . $filename) &&
718 (md5($externalContent) !== md5(GeneralUtility::getUrl(PATH_site . $filename)))
719 ) {
720 GeneralUtility::writeFile(PATH_site . $filename, $externalContent);
721 }
722 return $filename;
723 }
724
725 }