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