Fixed bug #17662: Remove deprecated class gzip_encode
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_compressor.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2010-2011 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 merges and compresses CSS and JavaScript 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 protected $htaccessTemplate = '<FilesMatch "\.(js|css)(\.gzip)?$">
47 <IfModule mod_expires.c>
48 ExpiresActive on
49 ExpiresDefault "access plus 7 days"
50 </IfModule>
51 FileETag MTime Size
52 </FilesMatch>';
53
54 /**
55 * Constructor
56 */
57 public function __construct() {
58
59 // we check for existance of our targetDirectory
60 if (!is_dir(PATH_site . $this->targetDirectory)) {
61 t3lib_div::mkdir(PATH_site . $this->targetDirectory);
62 }
63
64 // if enabled, we check whether we should auto-create the .htaccess file
65 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['generateApacheHtaccess']) {
66 // check whether .htaccess exists
67 $htaccessPath = PATH_site . $this->targetDirectory . '.htaccess';
68 if (!file_exists($htaccessPath)) {
69 t3lib_div::writeFile($htaccessPath, $this->htaccessTemplate);
70 }
71 }
72
73 // decide whether we should create gzipped versions or not
74 $compressionLevel = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['compressionLevel'];
75 // we need zlib for gzencode()
76 if (extension_loaded('zlib') && $compressionLevel) {
77 $this->createGzipped = TRUE;
78 // $compressionLevel can also be TRUE
79 if (t3lib_div::testInt($compressionLevel)) {
80 $this->gzipCompressionLevel = intval($compressionLevel);
81 }
82 }
83 }
84
85 /**
86 * Concatenates the cssFiles
87 *
88 * Options:
89 * baseDirectories If set, only include files below one of the base directories
90 *
91 * @param array $cssFiles CSS files to process
92 * @param array $options Additional options
93 * @return array CSS files
94 */
95 public function concatenateCssFiles(array $cssFiles, $options = array()) {
96
97 $filesToInclude = array();
98 foreach ($cssFiles as $filename => $fileOptions) {
99 // we remove BACK_PATH from $filename, so make it relative to TYPO3_mainDir
100 $filenameFromMainDir = $this->getFilenameFromMainDir($filename);
101 // if $options['baseDirectories'] set, we only include files below these directories
102 if ((!isset($options['baseDirectories'])
103 || $this->checkBaseDirectory($filenameFromMainDir, array_merge($options['baseDirectories'], array($this->targetDirectory))))
104 && ($fileOptions['media'] === 'all')
105 ) {
106
107 $filesToInclude[] = $filenameFromMainDir;
108 // remove the file from the incoming file array
109 unset($cssFiles[$filename]);
110 }
111 }
112
113 if (count($filesToInclude)) {
114 $targetFile = $this->createMergedCssFile($filesToInclude);
115 $concatenatedOptions = array(
116 'rel' => 'stylesheet',
117 'media' => 'all',
118 'compress' => TRUE,
119 );
120 $targetFileRelative = $GLOBALS['BACK_PATH'] . '../' . $targetFile;
121 // place the merged stylesheet on top of the stylesheets
122 $cssFiles = array_merge(array($targetFileRelative => $concatenatedOptions), $cssFiles);
123 }
124 return $cssFiles;
125 }
126
127 /**
128 * Finds the relative path to a file, relative to the TYPO3_mainDir.
129 *
130 * @param string $filename the name of the file
131 * @return string the path to the file relative to the TYPO3_mainDir
132 */
133 private function getFilenameFromMainDir($filename) {
134 // if the file exists in the typo3/ folder or the BACK_PATH is empty, just return the $filename
135 $file = str_replace($GLOBALS['BACK_PATH'], '', $filename);
136 if (is_file(PATH_typo3 . $file) || empty($GLOBALS['BACK_PATH'])) {
137 return $file;
138 }
139
140 // build the file path relatively to the PATH_site
141 $backPath = str_replace(TYPO3_mainDir, '', $GLOBALS['BACK_PATH']);
142 $file = str_replace($backPath, '', $filename);
143 if (substr($file, 0, 3) === '../') {
144 $file = t3lib_div::resolveBackPath(PATH_typo3 . $file);
145 } else {
146 $file = PATH_site . $file;
147 }
148
149 // check if the file exists, and if so, return the path relative to TYPO3_mainDir
150 if (is_file($file)) {
151 $mainDirDepth = substr_count(TYPO3_mainDir, '/');
152 return str_repeat('../', $mainDirDepth) . str_replace(PATH_site, '', $file);
153 }
154
155 // none of above conditions were met, fallback to default behaviour
156 return substr($filename, strlen($GLOBALS['BACK_PATH']));
157 }
158
159 /**
160 * Creates a merged CSS file
161 *
162 * @param array $filesToInclude Files which should be merged, paths relative to TYPO3_mainDir
163 * @return mixed Filename of the merged file
164 */
165 protected function createMergedCssFile(array $filesToInclude) {
166 // we add up the filenames, filemtimes and filsizes to later build a checksum over
167 // it and include it in the temporary file name
168 $unique = '';
169
170 foreach ($filesToInclude as $filename) {
171 $filepath = t3lib_div::resolveBackPath(PATH_typo3 . $filename);
172 $unique .= $filename . filemtime($filepath) . filesize($filepath);
173 }
174 $targetFile = $this->targetDirectory . 'merged-' . md5($unique) . '.css';
175
176 // if the file doesn't already exist, we create it
177 if (!file_exists(PATH_site . $targetFile)) {
178 $concatenated = '';
179 // concatenate all the files together
180 foreach ($filesToInclude as $filename) {
181 $contents = t3lib_div::getUrl(t3lib_div::resolveBackPath(PATH_typo3 . $filename));
182 // only fix paths if files aren't already in typo3temp (already processed)
183 if (!t3lib_div::isFirstPartOfStr($filename, $this->targetDirectory)) {
184 $concatenated .= $this->cssFixRelativeUrlPaths($contents, dirname($filename) . '/');
185 } else {
186 $concatenated .= $contents;
187 }
188 }
189 t3lib_div::writeFile(PATH_site . $targetFile, $concatenated);
190 }
191 return $targetFile;
192 }
193
194 /**
195 * Compress multiple css files
196 *
197 * @param array $cssFiles The files to compress (array key = filename), relative to requested page
198 * @return array The CSS files after compression (array key = new filename), relative to requested page
199 */
200 public function compressCssFiles(array $cssFiles) {
201 $filesAfterCompression = array();
202 foreach ($cssFiles as $filename => $fileOptions) {
203 // if compression is enabled
204 if ($fileOptions['compress']) {
205 $filesAfterCompression[$this->compressCssFile($filename)] = $fileOptions;
206 } else {
207 $filesAfterCompression[$filename] = $fileOptions;
208 }
209 }
210 return $filesAfterCompression;
211 }
212
213 /**
214 * Compresses a CSS file
215 *
216 * Options:
217 * baseDirectories If set, only include files below one of the base directories
218 *
219 * removes comments and whitespaces
220 * Adopted from http://drupal.org/files/issues/minify_css.php__1.txt
221 *
222 * @param string $filename Source filename, relative to requested page
223 * @return string Compressed filename, relative to requested page
224 */
225 public function compressCssFile($filename) {
226 // generate the unique name of the file
227 $filenameAbsolute = t3lib_div::resolveBackPath(PATH_typo3 . substr($filename, strlen($GLOBALS['BACK_PATH'])));
228 $unique = $filenameAbsolute . filemtime($filenameAbsolute) . filesize($filenameAbsolute);
229
230 $pathinfo = pathinfo($filename);
231 $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.css';
232 // only create it, if it doesn't exist, yet
233 if (!file_exists(PATH_site . $targetFile) || ($this->createGzipped && !file_exists(PATH_site . $targetFile . '.gzip'))) {
234 $contents = t3lib_div::getUrl($filenameAbsolute);
235 // Perform some safe CSS optimizations.
236 $contents = str_replace("\r", '', $contents); // Strip any and all carriage returns.
237 // Match and process strings, comments and everything else, one chunk at a time.
238 // To understand this regex, read: "Mastering Regular Expressions 3rd Edition" chapter 6.
239 $contents = preg_replace_callback('%
240 # One-regex-to-rule-them-all! - version: 20100220_0100
241 # Group 1: Match a double quoted string.
242 ("[^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+") | # or...
243 # Group 2: Match a single quoted string.
244 (\'[^\'\\\\]*+(?:\\\\.[^\'\\\\]*+)*+\') | # or...
245 # Group 3: Match a regular non-MacIE5-hack comment.
246 (/\*[^\\\\*]*+\*++(?:[^\\\\*/][^\\\\*]*+\*++)*+/) | # or...
247 # Group 4: Match a MacIE5-type1 comment.
248 (/\*(?:[^*\\\\]*+\**+(?!/))*+\\\\[^*]*+\*++(?:[^*/][^*]*+\*++)*+/(?<!\\\\\*/)) | # or...
249 # Group 5: Match a MacIE5-type2 comment.
250 (/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(?<=\\\\\*/)) # folllowed by...
251 # Group 6: Match everything up to final closing regular comment
252 ([^/]*+(?:(?!\*)/[^/]*+)*?)
253 # Group 7: Match final closing regular comment
254 (/\*[^/]++(?:(?<!\*)/(?!\*)[^/]*+)*+/(?<=(?<!\\\\)\*/)) | # or...
255 # Group 8: Match regular non-string, non-comment text.
256 ([^"\'/]*+(?:(?!/\*)/[^"\'/]*+)*+)
257 %Ssx', array('self', 'compressCssPregCallback'), $contents); // Do it!
258 $contents = preg_replace('/^\s++/', '', $contents); // Strip leading whitespace.
259 $contents = preg_replace('/[ \t]*+\n\s*+/S', "\n", $contents); // Consolidate multi-lines space.
260 $contents = preg_replace('/(?<!\s)\s*+$/S', "\n", $contents); // Ensure file ends in newline.
261 // we have to fix relative paths, if we aren't working on a file in our target directory
262 if (!is_int(strpos($filename, $this->targetDirectory))) {
263 $filenameRelativeToMainDir = substr($filename, strlen($GLOBALS['BACK_PATH']));
264 $contents = $this->cssFixRelativeUrlPaths($contents, dirname($filenameRelativeToMainDir) . '/');
265 }
266 $this->writeFileAndCompressed($targetFile, $contents);
267 }
268
269 return $GLOBALS['BACK_PATH'] . '../' . $this->returnFileReference($targetFile);
270 }
271
272 /**
273 * Callback function for preg_replace
274 *
275 * @see compressCssFile
276 * @param array $matches
277 * @return string the compressed string
278 */
279 public static function compressCssPregCallback($matches) {
280 if ($matches[1]) { // Group 1: Double quoted string.
281 return $matches[1]; // Return the string unmodified.
282 } elseif ($matches[2]) { // Group 2: Single quoted string.
283 return $matches[2]; // Return the string unmodified.
284 } elseif ($matches[3]) { // Group 3: Regular non-MacIE5-hack comment.
285 return "\n"; // Return single space.
286 } elseif ($matches[4]) { // Group 4: MacIE5-hack-type-1 comment.
287 return "\n/*\\T1*/\n"; // Return minimal MacIE5-hack-type-1 comment.
288 }
289 elseif ($matches[5]) { // Group 5,6,7: MacIE5-hack-type-2 comment
290 $matches[6] = preg_replace('/\s++([+>{};,)])/S', '$1', $matches[6]); // Clean pre-punctuation.
291 $matches[6] = preg_replace('/([+>{}:;,(])\s++/S', '$1', $matches[6]); // Clean post-punctuation.
292 $matches[6] = preg_replace('/;?\}/S', "}\n", $matches[6]); // Add a touch of formatting.
293 return "\n/*T2\\*/" . $matches[6] . "\n/*T2E*/\n"; // Minify and reassemble composite type2 comment.
294 } elseif (isset($matches[8])) { // Group 8: Non-string, non-comment. Safe to clean whitespace here.
295 $matches[8] = preg_replace('/^\s++/', '', $matches[8]); // Strip all leading whitespace.
296 $matches[8] = preg_replace('/\s++$/', '', $matches[8]); // Strip all trailing whitespace.
297 $matches[8] = preg_replace('/\s{2,}+/', ' ', $matches[8]); // Consolidate multiple whitespace.
298 $matches[8] = preg_replace('/\s++([+>{};,)])/S', '$1', $matches[8]); // Clean pre-punctuation.
299 $matches[8] = preg_replace('/([+>{}:;,(])\s++/S', '$1', $matches[8]); // Clean post-punctuation.
300 $matches[8] = preg_replace('/;?\}/S', "}\n", $matches[8]); // Add a touch of formatting.
301 return $matches[8];
302 }
303 return $matches[0] . "\n/* ERROR! Unexpected _proccess_css_minify() parameter */\n"; // never get here
304 }
305
306 /**
307 * Compress multiple javascript files
308 *
309 * @param array $jsFiles The files to compress (array key = filename), relative to requested page
310 * @return array The js files after compression (array key = new filename), relative to requested page
311 */
312 public function compressJsFiles(array $jsFiles) {
313 $filesAfterCompression = array();
314 foreach ($jsFiles as $filename => $fileOptions) {
315 // we remove BACK_PATH from $filename, so make it relative to TYPO3_mainDir
316 $filenameFromMainDir = $this->getFilenameFromMainDir($filename);
317 // if compression is enabled
318 if ($fileOptions['compress']) {
319 $filesAfterCompression[$this->compressJsFile($filename)] = $fileOptions;
320 } else {
321 $filesAfterCompression[$filename] = $fileOptions;
322 }
323 }
324 return $filesAfterCompression;
325 }
326
327 /**
328 * Compresses a javascript file
329 *
330 * Options:
331 * baseDirectories If set, only include files below one of the base directories
332 *
333 * @param string $filename Source filename, relative to requested page
334 * @return string Filename of the compressed file, relative to requested page
335 */
336 public function compressJsFile($filename) {
337 // generate the unique name of the file
338 $filenameAbsolute = t3lib_div::resolveBackPath(PATH_typo3 . $this->getFilenameFromMainDir($filename));
339 $unique = $filenameAbsolute . filemtime($filenameAbsolute) . filesize($filenameAbsolute);
340
341 $pathinfo = pathinfo($filename);
342 $targetFile = $this->targetDirectory . $pathinfo['filename'] . '-' . md5($unique) . '.js';
343 // only create it, if it doesn't exist, yet
344 if (!file_exists(PATH_site . $targetFile) || ($this->createGzipped && !file_exists(PATH_site . $targetFile . '.gzip'))) {
345 $contents = t3lib_div::getUrl($filenameAbsolute);
346 $this->writeFileAndCompressed($targetFile, $contents);
347 }
348 return $GLOBALS['BACK_PATH'] . '../' . $this->returnFileReference($targetFile);
349 }
350
351 /**
352 * Decides whether a CSS file comes from one of the baseDirectories
353 *
354 * @param string $filename Filename
355 * @return boolean File belongs to a skin or not
356 */
357 protected function checkBaseDirectory($filename, array $baseDirectories) {
358 foreach ($baseDirectories as $baseDirectory) {
359 // check, if $filename starts with $skinStylesheetDirectory
360 if (t3lib_div::isFirstPartOfStr($filename, $baseDirectory)) {
361 return TRUE;
362 }
363 }
364 return FALSE;
365 }
366
367 /**
368 * Fixes the relative paths inside of url() references in CSS files
369 *
370 * @param string $contents Data to process
371 * @param string $oldDir Directory of the originial file, relative to TYPO3_mainDir
372 * @return string Processed data
373 */
374 protected function cssFixRelativeUrlPaths($contents, $oldDir) {
375 $matches = array();
376
377 preg_match_all('/url(\(\s*["\']?([^"\']+)["\']?\s*\))/iU', $contents, $matches);
378 foreach ($matches[2] as $matchCount => $match) {
379 // remove '," or white-spaces around
380 $match = preg_replace('/[\"\'\s]/', '', $match);
381
382 // we must not rewrite paths containing ":", e.g. data URIs (see RFC 2397)
383 if (strpos($match, ':') === FALSE) {
384 $newPath = t3lib_div::resolveBackPath('../../' . TYPO3_mainDir . $oldDir . $match);
385 $contents = str_replace($matches[1][$matchCount], '(\'' . $newPath . '\')', $contents);
386 }
387 }
388 return $contents;
389 }
390
391 /**
392 * Writes $contents into file $filename together with a gzipped version into $filename.gz
393 *
394 * @param string $filename Target filename
395 * @param strings $contents File contents
396 * @return void
397 */
398 protected function writeFileAndCompressed($filename, $contents) {
399 // write uncompressed file
400 t3lib_div::writeFile(PATH_site . $filename, $contents);
401
402 if ($this->createGzipped) {
403 // create compressed version
404 t3lib_div::writeFile(PATH_site . $filename . '.gzip', gzencode($contents, $this->gzipCompressionLevel));
405 }
406 }
407
408 /**
409 * Decides whether a client can deal with gzipped content or not and returns the according file name,
410 * based on HTTP_ACCEPT_ENCODING
411 *
412 * @param string $filename File name
413 * @return string $filename suffixed with '.gzip' or not - dependent on HTTP_ACCEPT_ENCODING
414 */
415 protected function returnFileReference($filename) {
416 // if the client accepts gzip and we can create gzipped files, we give him compressed versions
417 if ($this->createGzipped && strpos(t3lib_div::getIndpEnv('HTTP_ACCEPT_ENCODING'), 'gzip') !== FALSE) {
418 return $filename . '.gzip';
419 } else {
420 return $filename;
421 }
422 }
423 }
424
425 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_compressor.php'])) {
426 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_compressor.php']);
427 }
428
429 ?>