74bf065e3aaf3d0f4c6953bfd89d8bf489973e12
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_compressor.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2010 Steffen Gebert (steffen@steffen-gebert.de)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * Compressor
30 * This class can currently merge CSS files of the TYPO3 Backend.
31 *
32 * @author Steffen Gebert <steffen@steffen-gebert.de>
33 * @package TYPO3
34 * @subpackage t3lib
35 * $Id$
36 */
37 class t3lib_compressor {
38
39 protected $targetDirectory = 'typo3temp/compressor/';
40
41 // gzipped versions are only created if $TYPO3_CONF_VARS[TYPO3_MODE]['compressionLevel'] is set
42 protected $createGzipped = FALSE;
43 // default compression level is -1
44 protected $gzipCompressionLevel = -1;
45
46 /**
47 * Constructor
48 */
49 public function __construct() {
50
51 // we check for existance of our targetDirectory
52 if (!is_dir(PATH_site . $this->targetDirectory)) {
53 t3lib_div::mkdir(PATH_site . $this->targetDirectory);
54 }
55
56 // decide whether we should create gzipped versions or not
57 $compressionLevel = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel'];
58 // we need zlib for gzencode()
59 if (extension_loaded('zlib') && $compressionLevel) {
60 $this->createGzipped = TRUE;
61 // $compressionLevel can also be TRUE
62 if (t3lib_div::testInt($compressionLevel)) {
63 $this->gzipCompressionLevel = $compressionLevel;
64 }
65 }
66 }
67
68 /**
69 * Concatenates the cssFiles
70 *
71 * Options:
72 * baseDirectories If set, only include files below one of the base directories
73 *
74 * @param array $cssFiles CSS files added to the PageRenderer
75 * @param array $options Additional options
76 * @return array CSS files
77 */
78 public function concatenateCssFiles(array $cssFiles, $options = array()) {
79 $filesToInclude = array();
80 foreach ($cssFiles as $filename => $fileOptions) {
81 // we remove BACK_PATH from $filename, so make it relative to TYPO3_mainDir
82 $filenameFromMainDir = substr($filename, strlen($GLOBALS['BACK_PATH']));
83 // if $options['baseDirectories'] set, we only include files below these directories
84 if ((!isset($options['baseDirectories'])
85 || $this->checkBaseDirectory($filenameFromMainDir, array_merge($options['baseDirectories'], array($this->targetDirectory))))
86 && ($fileOptions['media'] === 'all')
87 ) {
88
89 $filesToInclude[] = $filenameFromMainDir;
90 // remove the file from the incoming file array
91 unset($cssFiles[$filename]);
92 }
93 }
94
95 if (count($filesToInclude)) {
96 $targetFile = $this->createMergedCssFile($filesToInclude);
97 $concatenatedOptions = array(
98 'rel' => 'stylesheet',
99 'media' => 'all',
100 'compress' => TRUE,
101 );
102 $targetFileRelative = $GLOBALS['BACK_PATH'] . '../' . $targetFile;
103 // place the merged stylesheet on top of the stylesheets
104 $cssFiles = array_merge(array($targetFileRelative => $concatenatedOptions), $cssFiles);
105 }
106 return $cssFiles;
107 }
108
109 /**
110 * Creates a merged CSS file
111 *
112 * @param array $filesToInclude Files which should be merged, paths relative to TYPO3_mainDir
113 * @return mixed Filename of the merged file
114 */
115 protected function createMergedCssFile(array $filesToInclude) {
116 // we add up the filenames, filemtimes and filsizes to later build a checksum over
117 // it and include it in the temporary file name
118 $unique = '';
119
120 foreach ($filesToInclude as $filename) {
121 $filepath = t3lib_div::resolveBackPath(PATH_typo3 . $filename);
122 $unique .= $filename . filemtime($filepath) . filesize($filepath);
123 }
124 $targetFile = $this->targetDirectory . 'merged-'. md5($unique) . '.css';
125
126 // if the file doesn't already exist, we create it
127 if (!file_exists(PATH_site . $targetFile)) {
128 $concatenated = '';
129 // concatenate all the files together
130 foreach ($filesToInclude as $filename) {
131 $contents = t3lib_div::getUrl(t3lib_div::resolveBackPath(PATH_typo3 . $filename));
132 // only fix paths if files aren't already in typo3temp (already processed)
133 if (!t3lib_div::isFirstPartOfStr($filename, $this->targetDirectory)) {
134 $concatenated .= $this->cssFixRelativeUrlPaths($contents, dirname($filename) . '/');
135 } else {
136 $concatenated .= $contents;
137 }
138 }
139 t3lib_div::writeFile(PATH_site . $targetFile, $concatenated);
140 }
141 return $targetFile;
142 }
143
144 /**
145 * Compress multiple css files
146 *
147 * @param array $cssFiles The files to compress (array key = filename)
148 * @return array The CSS files after compression (array key = new filename)
149 */
150 public function compressCssFiles(array $cssFiles) {
151 $filesAfterCompression = array();
152 foreach ($cssFiles as $filename => $fileOptions) {
153 // we remove BACK_PATH from $filename, so make it relative to TYPO3_mainDir
154 $filenameFromMainDir = substr($filename, strlen($GLOBALS['BACK_PATH']));
155 // if compression is enabled
156 if ($fileOptions['compress']) {
157 $filesAfterCompression[$GLOBALS['BACK_PATH'] . $this->compressCssFile($filename)] = $fileOptions;
158 } else {
159 $filesAfterCompression[$filename] = $fileOptions;
160 }
161 }
162 return $filesAfterCompression;
163 }
164
165 /**
166 * Compresses a CSS file
167 *
168 * Options:
169 * baseDirectories If set, only include files below one of the base directories
170 *
171 * removes comments and whitespaces
172 * Adopted from http://drupal.org/files/issues/minify_css.php__1.txt
173 *
174 * @param string $filename Source filename
175 * @return string Filename of the compressed file
176 */
177 public function compressCssFile($filename) {
178 // generate the unique name of the file
179 $filenameAbsolute = t3lib_div::resolveBackPath(PATH_typo3 . substr($filename, strlen($GLOBALS['BACK_PATH'])));
180 $unique = $filenameAbsolute . filemtime($filenameAbsolute) . filesize($filenameAbsolute);
181
182 $pathinfo = pathinfo($filename);
183 $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.css';
184 // only create it, if it doesn't exist, yet
185 if (!file_exists(PATH_site . $targetFile) || ($this->createGzipped && !file_exists(PATH_site . $targetFile . '.gz'))) {
186 $contents = t3lib_div::getUrl($filenameAbsolute);
187 // Perform some safe CSS optimizations.
188 $contents = str_replace("\r", '', $contents); // Strip any and all carriage returns.
189 // Match and process strings, comments and everything else, one chunk at a time.
190 // To understand this regex, read: "Mastering Regular Expressions 3rd Edition" chapter 6.
191 $contents = preg_replace_callback('%
192 # One-regex-to-rule-them-all! - version: 20100220_0100
193 # Group 1: Match a double quoted string.
194 ("[^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+") | # or...
195 # Group 2: Match a single quoted string.
196 (\'[^\'\\\\]*+(?:\\\\.[^\'\\\\]*+)*+\') | # or...
197 # Group 3: Match a regular non-MacIE5-hack comment.
198 (/\*[^\\\\*]*+\*++(?:[^\\\\*/][^\\\\*]*+\*++)*+/) | # or...
199 # Group 4: Match a MacIE5-type1 comment.
200 (/\*(?:[^*\\\\]*+\**+(?!/))*+\\\\[^*]*+\*++(?:[^*/][^*]*+\*++)*+/(?<!\\\\\*/)) | # or...
201 # Group 5: Match a MacIE5-type2 comment.
202 (/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(?<=\\\\\*/)) # folllowed by...
203 # Group 6: Match everything up to final closing regular comment
204 ([^/]*+(?:(?!\*)/[^/]*+)*?)
205 # Group 7: Match final closing regular comment
206 (/\*[^/]++(?:(?<!\*)/(?!\*)[^/]*+)*+/(?<=(?<!\\\\)\*/)) | # or...
207 # Group 8: Match regular non-string, non-comment text.
208 ([^"\'/]*+(?:(?!/\*)/[^"\'/]*+)*+)
209 %Ssx', array('self','compressCssPregCallback'), $contents); // Do it!
210 $contents = preg_replace('/^\s++/', '', $contents); // Strip leading whitespace.
211 $contents = preg_replace('/[ \t]*+\n\s*+/S', "\n", $contents); // Consolidate multi-lines space.
212 $contents = preg_replace('/(?<!\s)\s*+$/S', "\n", $contents); // Ensure file ends in newline.
213 // we have to fix relative paths, if we aren't working on a file in our target directory
214 if (!is_int(strpos($filename, $this->targetDirectory))) {
215 $filenameRelativeToMainDir = substr($filename, strlen($GLOBALS['BACK_PATH']));
216 $contents = $this->cssFixRelativeUrlPaths($contents, dirname($filenameRelativeToMainDir) . '/');
217 }
218 $this->writeFileAndCompressed($targetFile, $contents);
219 }
220
221 return '../' . $this->returnFileReference($targetFile);
222 }
223
224 /**
225 * Callback function for preg_replace
226 *
227 * @see compressCssFile
228 * @param array $matches
229 * @return string the compressed string
230 */
231 public static function compressCssPregCallback($matches) {
232 if ($matches[1]) { // Group 1: Double quoted string.
233 return $matches[1]; // Return the string unmodified.
234 } elseif ($matches[2]) { // Group 2: Single quoted string.
235 return $matches[2]; // Return the string unmodified.
236 } elseif ($matches[3]) { // Group 3: Regular non-MacIE5-hack comment.
237 return "\n"; // Return single space.
238 } elseif ($matches[4]) { // Group 4: MacIE5-hack-type-1 comment.
239 return "\n/*\\T1*/\n"; // Return minimal MacIE5-hack-type-1 comment.
240 }
241 elseif ($matches[5]) { // Group 5,6,7: MacIE5-hack-type-2 comment
242 $matches[6] = preg_replace('/\s++([+>{};,)])/S', '$1', $matches[6]); // Clean pre-punctuation.
243 $matches[6] = preg_replace('/([+>{}:;,(])\s++/S', '$1', $matches[6]); // Clean post-punctuation.
244 $matches[6] = preg_replace('/;?\}/S', "}\n", $matches[6]); // Add a touch of formatting.
245 return "\n/*T2\\*/" . $matches[6] . "\n/*T2E*/\n"; // Minify and reassemble composite type2 comment.
246 } elseif (isset($matches[8])) { // Group 8: Non-string, non-comment. Safe to clean whitespace here.
247 $matches[8] = preg_replace('/^\s++/', '', $matches[8]); // Strip all leading whitespace.
248 $matches[8] = preg_replace('/\s++$/', '', $matches[8]); // Strip all trailing whitespace.
249 $matches[8] = preg_replace('/\s{2,}+/', ' ', $matches[8]); // Consolidate multiple whitespace.
250 $matches[8] = preg_replace('/\s++([+>{};,)])/S', '$1', $matches[8]); // Clean pre-punctuation.
251 $matches[8] = preg_replace('/([+>{}:;,(])\s++/S', '$1', $matches[8]); // Clean post-punctuation.
252 $matches[8] = preg_replace('/;?\}/S', "}\n", $matches[8]); // Add a touch of formatting.
253 return $matches[8];
254 }
255 return $matches[0] . "\n/* ERROR! Unexpected _proccess_css_minify() parameter */\n"; // never get here
256 }
257
258 /**
259 * Decides whether a CSS file comes from one of the baseDirectories
260 *
261 * @param string $filename Filename
262 * @return boolean File belongs to a skin or not
263 */
264 protected function checkBaseDirectory($filename, array $baseDirectories) {
265 foreach ($baseDirectories as $baseDirectory) {
266 // check, if $filename starts with $skinStylesheetDirectory
267 if (t3lib_div::isFirstPartOfStr($filename, $baseDirectory)) {
268 return TRUE;
269 }
270 }
271 return FALSE;
272 }
273
274 /**
275 * Fixes the relative paths inside of url() references in CSS files
276 *
277 * @param string $contents Data to process
278 * @param string $oldDir Directory of the originial file, relative to TYPO3_mainDir
279 * @return string Processed data
280 */
281 protected function cssFixRelativeUrlPaths($contents, $oldDir) {
282 $matches = array();
283
284 preg_match_all('/url(\(\s*["\']?([^"\']+)["\']?\s*\))/iU', $contents, $matches);
285 foreach ($matches[2] as $matchCount => $match) {
286 // remove '," or white-spaces around
287 $match = preg_replace('/[\"\'\s]/', '', $match);
288 $newPath = t3lib_div::resolveBackPath('../../' . TYPO3_mainDir . $oldDir . $match);
289
290 $contents = str_replace($matches[1][$matchCount], '(\'' . $newPath . '\')', $contents);
291 }
292 return $contents;
293 }
294
295 /**
296 * Writes $contents into file $filename together with a gzipped version into $filename.gz
297 *
298 * @param string $filename Target filename
299 * @param strings $contents File contents
300 * @return void
301 */
302 protected function writeFileAndCompressed($filename, $contents) {
303 // write uncompressed file
304 t3lib_div::writeFile(PATH_site . $filename, $contents);
305
306 if ($this->createGzipped) {
307 // create compressed version
308 $compressionLevel = -1;
309 if (isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel']) && is_numeric($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel'])) {
310 $compressionLevel = intval($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel']);
311 }
312 t3lib_div::writeFile(PATH_site . $filename . '.gz', gzencode($contents, $compressionLevel));
313 }
314 }
315
316 /**
317 * Decides whether a client can deal with gzipped content or not and returns the according file name,
318 * based on HTTP_ACCEPT_ENCODING
319 *
320 * @param string $filename File name
321 * @return string $filename suffixed with '.gz' or not - dependent on HTTP_ACCEPT_ENCODING
322 */
323 protected function returnFileReference($filename) {
324 // if the client accepts gzip and we can create gzipped files, we give him compressed versions
325 if ($this->createGzipped && strpos(t3lib_div::getIndpEnv('HTTP_ACCEPT_ENCODING'), 'gzip') !== FALSE) {
326 return $filename . '.gz';
327 } else {
328 return $filename;
329 }
330 }
331 }
332 ?>