Follow-up to bug #12499: re-added the removed function call and moved the deprecation...
[Packages/TYPO3.CMS.git] / t3lib / class.gzip_encode.php
1 <?php
2 /**
3 * News: I had once said that when PHP 4.0.5 comes out I will reccomend the built in
4 * ob_gzhandler over my code unless you are generating flash or images on the fly.
5 *
6 * I was wrong. PHP 4.0.5 is out and ob_gzhandler doesn't work for me.
7 *
8 * Note: This is rather cool: http://leknor.com/code/gziped.php
9 * It will calculate the effects of this class on a page.
10 * compression level, cpu time, download time, etc
11 *
12 * Note: this may be better for some sites:
13 * http://www.remotecommunications.com/apache/mod_gzip/
14 * I've read that the above doesn't work with PHP output.
15 *
16 * Changes compared to the upstream version:
17 *
18 * 2007-03-27 Oliver Hader <oh@inpublica.de>
19 * - Fixed bug #4623: Content encoding with x-gzip not allowed
20 * - Fixed missing comments and line formats (cleaner)
21 * 2005-12-09 Peter Niederlag <peter@niederlag.de>
22 * - Fixed bug #1976: PHP5 type-conversion of string 'true' and boolean
23 *
24 * $Id$
25 *
26 * @author Sandy McArthur, Jr. <leknor@leknor.com>
27 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
28 */
29 /**
30 * [CLASS/FUNCTION INDEX of SCRIPT]
31 *
32 *
33 *
34 * 53: class gzip_encode
35 * 193: function gzip_encode($level = 3, $debug=false, $outputCompressedSizes=false)
36 * 268: function gzip_accepted()
37 * 317: function get_complevel()
38 * 342: function linux_loadavg()
39 * 363: function freebsd_loadavg()
40 *
41 * TOTAL FUNCTIONS: 5
42 * (This index is automatically created/updated by the extension "extdeveval")
43 *
44 */
45
46
47
48 /**
49 * gzip_encode - a class to gzip encode php output
50 *
51 * @author Sandy McArthur, Jr. <Leknor@Leknor.com>
52 * @package TYPO3
53 * @subpackage t3lib
54 */
55 class gzip_encode {
56 /**
57 * gzip_encode - a class to gzip encode php output
58 *
59 * By Sandy McArthur, Jr. <Leknor@Leknor.com>
60 *
61 * Copyright 2001 (c) All Rights Reserved, All Responsibility Yours.
62 * One very slight modification 2005 for PHP5 compatibility reasons for TYPO3 port by Peter Niederlag
63 *
64 * This code is released under the GNU LGPL Go read it over here:
65 * http://www.gnu.org/copyleft/lesser.html
66 *
67 * I do make one optional request, I would like an account on or a
68 * copy of where this code is used. If that is not possible then
69 * an email would be cool.
70 *
71 * How to use:
72 * 1. Output buffering has to be turned on. You can do this with ob_start()
73 * <http://php.net/manual/function.ob-start.php> or in the php config
74 * file. Nothing bad happens if output buffering isn't turned on, your
75 * page just won't get compressed.
76 * 2. Include the class file.
77 * 3. At the _very_ end of your script create an instance of the encode
78 * class.
79 *
80 * eg:
81 * ------------Start of file----------
82 * |<?php
83 * | ob_start();
84 * | include('class.gzip_encode.php');
85 * |?>
86 * |<HTML>
87 * |... the page ...
88 * |</HTML>
89 * |<?php
90 * | new gzip_encode();
91 * |?>
92 * -------------End of file-----------
93 *
94 * Things to note:
95 * 1. There is no space before the beginning of the file and the '<?php ' tag
96 * 2. The ob_start() line is optional if output buffering is turned on in
97 * the main config file.
98 * 3. Turning on and off output buffering just won't work.
99 * 4. There must be nothing after the last '?>' tag at the end of the file.
100 * Be careful of a space hiding there.
101 * 5. There are better ways to compress served content but I think this is
102 * the only way to compress php output.
103 * 6. Your auto_prepend_file is a good place for the ob_start() and
104 * your auto_append_file is a good place for new gzip_encode().
105 * 7. If you put new gzip_encode() in your auto.append file then you can
106 * call ob_end_flush() in your script to disable compression.
107 *
108 * This was written from scratch from info freely available on the web.
109 *
110 * These site(s) were useful to me:
111 * http://www.php.net/manual/
112 * http://www.ietf.org/rfc/rfc2616.txt (Sections: 3.5, 14.3, 14.11)
113 *
114 * Requirments:
115 * PHP 4.0.1+: I use the '===' operator, and output buffering, crc32();
116 * zlib: Needed for the gzip encoding. (Odds are you have it)
117 *
118 * Benchmarks:
119 * Take a look at http://Leknor.com/code/gziped.php and feed it a page to
120 * get an idea of how it will preform on your data or page.
121 *
122 * To Do:
123 * 1. I have reports of no content errors. I can't seem to duplicate this.
124 * Please visit my discussion boards if you think you may be able to help
125 * 2. The Accept-Encoding isn't handled to spec. Check out 14.3 in RFC 2616
126 * to see how it should be done.
127 *
128 * Change Log:
129 * 0.66: Big bug fix. It wouldn't compress when it should.
130 * 0.65: Fix for PHP-4.0.5 suddenly removing the connection_timeout() function.
131 * 0.62: Fixed a typo
132 * 0.61: Detect file types more like described in the magic number files, also
133 * added detection for gzip and pk zip files.
134 * 0.6: Detect common file types that shouldn't be compressed, mainly
135 * for images and swf (Shockwave Flash doesn't really accept gzip)
136 * 0.53: Made gzip_accepted() method so everyone can detect if a page
137 * will be gzip'ed with ease.
138 * 0.52: Detection and graceful handling of improper install/missing libs
139 * 0.51: Added FreeBSD load average detection.
140 * 0.5: Passing true as the first parameter will try to calculate the
141 * compression level from the server's load average. Passing true
142 * as the second parameter will turn on debugging.
143 * 0.4: No longer uses a temp file to compress the output. Should speed
144 * thing up a bit and reduce wear on your hard disk. Also test if
145 * the http headers have been sent.
146 * 0.31: Made a small change to the tempnam() line to hopefully be more
147 * portable.
148 * 0.3: Added code for the 'x-gzip'. This is untested, I don't know of
149 * any browser that uses it but the RFC said to look out for it.
150 * 0.2: Checks for 'gzip' in the Accept-Encoding header
151 * 0.1: First working version.
152 *
153 * Thanks To (Suggestions and stuff):
154 * ?@boas.anthro.mnsu.edu http://php.net/manual/function.gzcompress.php
155 * Kaoslord <kaoslord@chaos-productions.com>
156 * Michael R. Gile <gilem@wsg.net>
157 * Christian Hamm <chh@admaster.de>
158 *
159 * The most recent version is available at:
160 * http://Leknor.com/code/
161 *
162 */
163
164 var $_version = 0.66; // Version of the gzip_encode class
165
166 var $level; // Compression level
167 var $encoding; // Encoding type
168 var $crc; // crc of the output
169 var $size; // size of the uncompressed content
170 var $gzsize; // size of the compressed content
171
172 /**
173 * gzip_encode constructor - gzip encodes the current output buffer
174 * if the browser supports it.
175 *
176 * Note: all arguments are optionial.
177 *
178 * You can specify one of the following for the first argument:
179 * 0: No compression
180 * 1: Min compression
181 * ... Some compression (integer from 1 to 9)
182 * 9: Max compression
183 * true: Determin the compression level from the system load. The
184 * higher the load the less the compression.
185 *
186 * You can specify one of the following for the second argument:
187 * true: Don't actully output the compressed form but run as if it
188 * had. Used for debugging.
189 *
190 * @param integer $level: Define the level of compression between 0 (none) and 9 (best compression)
191 * @param boolean $debug: If true, no data will be outputted (default: false)
192 * @param boolean $outputCompressedSizes: If true, the original and compressed size appended as HTML (default: false)
193 * @return void
194 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
195 */
196 function gzip_encode($level=3, $debug=false, $outputCompressedSizes=false) {
197 t3lib_div::logDeprecatedFunction();
198
199 if (!function_exists('gzcompress')) {
200 trigger_error('gzcompress not found, ' .
201 'zlib needs to be installed for gzip_encode',
202 E_USER_WARNING);
203 return;
204 }
205 if (!function_exists('crc32')) {
206 trigger_error('crc32() not found, ' .
207 'PHP >= 4.0.1 needed for gzip_encode', E_USER_WARNING);
208 return;
209 }
210 if (headers_sent()) return;
211 if (connection_status() !== 0) return;
212 $encoding = $this->gzip_accepted();
213 if (!$encoding) return;
214 $this->encoding = $encoding;
215
216 if (strtolower($level) == 'true' || $level === true) {
217 $level = $this->get_complevel();
218 }
219 $this->level = $level;
220
221 $contents = ob_get_contents();
222 if ($contents === false) return;
223
224 $gzdata = "\x1f\x8b\x08\x00\x00\x00\x00\x00"; // gzip header
225
226 // By Kasper Skaarhoj, start
227 if ($outputCompressedSizes) {
228 $contents.=chr(10)."<!-- Compressed, level ".$level.", original size was ".strlen($contents)." bytes. New size is ".strlen(gzcompress($contents, $level))." bytes -->";
229 $size = strlen($contents); // Must set again!
230 }
231 // By Kasper Skaarhoj, end
232
233 $size = strlen($contents);
234 $crc = crc32($contents);
235 $gzdata .= gzcompress($contents, $level);
236 $gzdata = substr($gzdata, 0, strlen($gzdata) - 4); // fix crc bug
237 $gzdata .= pack("V",$crc) . pack("V", $size);
238
239 $this->size = $size;
240 $this->crc = $crc;
241 $this->gzsize = strlen($gzdata);
242
243 if ($debug) {
244 return;
245 }
246
247 ob_end_clean();
248 Header('Content-Encoding: ' . $encoding);
249 Header('Content-Length: ' . strlen($gzdata));
250 Header('X-Content-Encoded-By: class.gzip_encode '.$this->_version);
251
252 echo $gzdata;
253 }
254
255
256 /**
257 * gzip_accepted() - Test headers for Accept-Encoding: gzip
258 * Returns: if proper headers aren't found: false
259 * if proper headers are found: 'gzip' or 'x-gzip'
260 *
261 * Tip: using this function you can test if the class will gzip the output
262 * without actually compressing it yet, eg:
263 * if (gzip_encode::gzip_accepted()) {
264 * echo "Page will be gziped";
265 * }
266 * note the double colon syntax, I don't know where it is documented but
267 * somehow it got in my brain.
268 *
269 * @return mixed Returns 'gzip' if the client browser accepts gzip encoding, otherwise false
270 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
271 */
272 function gzip_accepted() {
273 t3lib_div::logDeprecatedFunction();
274
275 // Checks, if the accepted encoding supports gzip or x-gzip.
276 // Furthermore a qvalue check is done. "gzip;q=0" means no gzip accepted at all.
277 $acceptEncoding = t3lib_div::getIndpEnv('HTTP_ACCEPT_ENCODING');
278 if (preg_match('/(^|,\s*)(x-)?gzip(;q=(\d(\.\d+)?))?(,|$)/i', $acceptEncoding, $match) && ($match[4] === '' || $match[4] > 0)) {
279 $encoding = 'gzip';
280 } else {
281 return false;
282 }
283
284 // Test file type. I wish I could get HTTP response headers.
285 $magic = substr(ob_get_contents(),0,4);
286 if (substr($magic,0,2) === '^_') {
287 // gzip data
288 $encoding = false;
289 } else if (substr($magic,0,3) === 'GIF') {
290 // gif images
291 $encoding = false;
292 } else if (substr($magic,0,2) === "\xFF\xD8") {
293 // jpeg images
294 $encoding = false;
295 } else if (substr($magic,0,4) === "\x89PNG") {
296 // png images
297 $encoding = false;
298 } else if (substr($magic,0,3) === 'FWS') {
299 // Don't gzip Shockwave Flash files. Flash on windows incorrectly
300 // claims it accepts gzip'd content.
301 $encoding = false;
302 } else if (substr($magic,0,2) === 'PK') {
303 // pk zip file
304 $encoding = false;
305 }
306
307 return $encoding;
308 }
309
310 /**
311 * get_complevel() - The level of compression we should use.
312 *
313 * Returns an int between 0 and 9 inclusive.
314 *
315 * Tip: $gzleve = gzip_encode::get_complevel(); to get the compression level
316 * that will be used with out actually compressing the output.
317 *
318 * Help: if you use an OS other then linux please send me code to make
319 * this work with your OS - Thanks
320 *
321 * @return integer Suggests a level of compression (0..9) for the current situation
322 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
323 */
324 function get_complevel() {
325 t3lib_div::logDeprecatedFunction();
326
327 $uname = posix_uname();
328 switch ($uname['sysname']) {
329 case 'Linux':
330 $cl = (1 - $this->linux_loadavg()) * 10;
331 $level = (int)max(min(9, $cl), 0);
332 break;
333 case 'FreeBSD':
334 $cl = (1 - $this->freebsd_loadavg()) * 10;
335 $level = (int)max(min(9, $cl), 0);
336 break;
337 default:
338 $level = 3;
339 break;
340 }
341 return $level;
342 }
343
344 /**
345 * linux_loadavg() - Gets the max() system load average from /proc/loadavg
346 *
347 * The max() Load Average will be returned
348 *
349 * @return float Returns the current load average
350 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
351 */
352 function linux_loadavg() {
353 t3lib_div::logDeprecatedFunction();
354
355 $buffer = '0 0 0';
356 $f = @fopen('/proc/loadavg', 'rb');
357 if ($f) {
358 if (!feof($f)) {
359 $buffer = fgets($f, 1024);
360 }
361 fclose($f);
362 }
363 $load = explode(' ', $buffer);
364 return max((float)$load[0], (float)$load[1], (float)$load[2]);
365 }
366
367 /**
368 * freebsd_loadavg() - Gets the max() system load average from uname(1)
369 *
370 * The max() Load Average will be returned
371 *
372 * I've been told the code below will work on solaris too, anyone wanna
373 * test it?
374 *
375 * @return float Returns the current load average
376 * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, we're using the "ob_gzhandler" for compression now.
377 */
378 function freebsd_loadavg() {
379 t3lib_div::logDeprecatedFunction();
380
381 $buffer= `uptime`;
382 $load = array();
383 preg_match('/averag(es|e): ([0-9][.][0-9][0-9]), ([0-9][.][0-9][0-9]), ([0-9][.][0-9][0-9]*)/', $buffer, $load);
384
385 return max((float)$load[2], (float)$load[3], (float)$load[4]);
386 }
387 }
388
389 ?>