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