source: trunk/www.guidonia.net/wp/wp-content/plugins/ferdinand-wordbook/phpthumb/phpthumb.functions.php@ 44

Last change on this file since 44 was 44, checked in by luciano, 14 years ago
File size: 32.3 KB
Line 
1<?php
2//////////////////////////////////////////////////////////////
3/// phpThumb() by James Heinrich <info@silisoftware.com> //
4// available at http://phpthumb.sourceforge.net ///
5//////////////////////////////////////////////////////////////
6/// //
7// phpthumb.functions.php - general support functions //
8// ///
9//////////////////////////////////////////////////////////////
10
11class phpthumb_functions {
12
13 function user_function_exists($functionname) {
14 if (function_exists('get_defined_functions')) {
15 static $get_defined_functions = array();
16 if (empty($get_defined_functions)) {
17 $get_defined_functions = get_defined_functions();
18 }
19 return in_array(strtolower($functionname), $get_defined_functions['user']);
20 }
21 return function_exists($functionname);
22 }
23
24
25 function builtin_function_exists($functionname) {
26 if (function_exists('get_defined_functions')) {
27 static $get_defined_functions = array();
28 if (empty($get_defined_functions)) {
29 $get_defined_functions = get_defined_functions();
30 }
31 return in_array(strtolower($functionname), $get_defined_functions['internal']);
32 }
33 return function_exists($functionname);
34 }
35
36
37 function version_compare_replacement_sub($version1, $version2, $operator='') {
38 // If you specify the third optional operator argument, you can test for a particular relationship.
39 // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
40 // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
41
42 // If a part contains special version strings these are handled in the following order: dev < (alpha = a) < (beta = b) < RC < pl
43 static $versiontype_lookup = array();
44 if (empty($versiontype_lookup)) {
45 $versiontype_lookup['dev'] = 10001;
46 $versiontype_lookup['a'] = 10002;
47 $versiontype_lookup['alpha'] = 10002;
48 $versiontype_lookup['b'] = 10003;
49 $versiontype_lookup['beta'] = 10003;
50 $versiontype_lookup['RC'] = 10004;
51 $versiontype_lookup['pl'] = 10005;
52 }
53 if (isset($versiontype_lookup[$version1])) {
54 $version1 = $versiontype_lookup[$version1];
55 }
56 if (isset($versiontype_lookup[$version2])) {
57 $version2 = $versiontype_lookup[$version2];
58 }
59
60 switch ($operator) {
61 case '<':
62 case 'lt':
63 return intval($version1 < $version2);
64 break;
65 case '<=':
66 case 'le':
67 return intval($version1 <= $version2);
68 break;
69 case '>':
70 case 'gt':
71 return intval($version1 > $version2);
72 break;
73 case '>=':
74 case 'ge':
75 return intval($version1 >= $version2);
76 break;
77 case '==':
78 case '=':
79 case 'eq':
80 return intval($version1 == $version2);
81 break;
82 case '!=':
83 case '<>':
84 case 'ne':
85 return intval($version1 != $version2);
86 break;
87 }
88 if ($version1 == $version2) {
89 return 0;
90 } elseif ($version1 < $version2) {
91 return -1;
92 }
93 return 1;
94 }
95
96
97 function version_compare_replacement($version1, $version2, $operator='') {
98 if (function_exists('version_compare')) {
99 // built into PHP v4.1.0+
100 return version_compare($version1, $version2, $operator);
101 }
102
103 // The function first replaces _, - and + with a dot . in the version strings
104 $version1 = strtr($version1, '_-+', '...');
105 $version2 = strtr($version2, '_-+', '...');
106
107 // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
108 // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
109 $version1 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version1);
110 $version2 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version2);
111
112 $parts1 = explode('.', $version1);
113 $parts2 = explode('.', $version1);
114 $parts_count = max(count($parts1), count($parts2));
115 for ($i = 0; $i < $parts_count; $i++) {
116 $comparison = phpthumb_functions::version_compare_replacement_sub($version1, $version2, $operator);
117 if ($comparison != 0) {
118 return $comparison;
119 }
120 }
121 return 0;
122 }
123
124
125 function phpinfo_array() {
126 static $phpinfo_array = array();
127 if (empty($phpinfo_array)) {
128 ob_start();
129 phpinfo();
130 $phpinfo = ob_get_contents();
131 ob_end_clean();
132 $phpinfo_array = explode("\n", $phpinfo);
133 }
134 return $phpinfo_array;
135 }
136
137
138 function exif_info() {
139 static $exif_info = array();
140 if (empty($exif_info)) {
141 // based on code by johnschaefer at gmx dot de
142 // from PHP help on gd_info()
143 $exif_info = array(
144 'EXIF Support' => '',
145 'EXIF Version' => '',
146 'Supported EXIF Version' => '',
147 'Supported filetypes' => ''
148 );
149 $phpinfo_array = phpthumb_functions::phpinfo_array();
150 foreach ($phpinfo_array as $line) {
151 $line = trim(strip_tags($line));
152 foreach ($exif_info as $key => $value) {
153 if (strpos($line, $key) === 0) {
154 $newvalue = trim(str_replace($key, '', $line));
155 $exif_info[$key] = $newvalue;
156 }
157 }
158 }
159 }
160 return $exif_info;
161 }
162
163
164 function ImageTypeToMIMEtype($imagetype) {
165 if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
166 // PHP v4.3.0+
167 return image_type_to_mime_type($imagetype);
168 }
169 static $image_type_to_mime_type = array(
170 1 => 'image/gif', // IMAGETYPE_GIF
171 2 => 'image/jpeg', // IMAGETYPE_JPEG
172 3 => 'image/png', // IMAGETYPE_PNG
173 4 => 'application/x-shockwave-flash', // IMAGETYPE_SWF
174 5 => 'image/psd', // IMAGETYPE_PSD
175 6 => 'image/bmp', // IMAGETYPE_BMP
176 7 => 'image/tiff', // IMAGETYPE_TIFF_II (intel byte order)
177 8 => 'image/tiff', // IMAGETYPE_TIFF_MM (motorola byte order)
178 9 => 'application/octet-stream', // IMAGETYPE_JPC
179 10 => 'image/jp2', // IMAGETYPE_JP2
180 11 => 'application/octet-stream', // IMAGETYPE_JPX
181 12 => 'application/octet-stream', // IMAGETYPE_JB2
182 13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
183 14 => 'image/iff', // IMAGETYPE_IFF
184 15 => 'image/vnd.wap.wbmp', // IMAGETYPE_WBMP
185 16 => 'image/xbm', // IMAGETYPE_XBM
186
187 'gif' => 'image/gif', // IMAGETYPE_GIF
188 'jpg' => 'image/jpeg', // IMAGETYPE_JPEG
189 'jpeg' => 'image/jpeg', // IMAGETYPE_JPEG
190 'png' => 'image/png', // IMAGETYPE_PNG
191 'bmp' => 'image/bmp', // IMAGETYPE_BMP
192 'ico' => 'image/x-icon',
193 );
194
195 return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
196 }
197
198
199 function TranslateWHbyAngle($width, $height, $angle) {
200 if (($angle % 180) == 0) {
201 return array($width, $height);
202 }
203 $newwidth = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
204 $newheight = (abs(sin(deg2rad($angle))) * $width) + (abs(cos(deg2rad($angle))) * $height);
205 return array($newwidth, $newheight);
206 }
207
208 function HexCharDisplay($string) {
209 $len = strlen($string);
210 $output = '';
211 for ($i = 0; $i < $len; $i++) {
212 $output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
213 }
214 return $output;
215 }
216
217
218 function IsHexColor($HexColorString) {
219 return eregi('^[0-9A-F]{6}$', $HexColorString);
220 }
221
222
223 function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
224 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.2', '>=') && ($alpha !== false)) {
225 return ImageColorAllocateAlpha($gdimg_hexcolorallocate, $R, $G, $B, intval($alpha));
226 } else {
227 return ImageColorAllocate($gdimg_hexcolorallocate, $R, $G, $B);
228 }
229 }
230
231 function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
232 if (!is_resource($gdimg_hexcolorallocate)) {
233 die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
234 }
235 if (phpthumb_functions::IsHexColor($HexColorString)) {
236 $R = hexdec(substr($HexColorString, 0, 2));
237 $G = hexdec(substr($HexColorString, 2, 2));
238 $B = hexdec(substr($HexColorString, 4, 2));
239 return phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
240 }
241 if ($dieOnInvalid) {
242 die('Invalid hex color string: "'.$HexColorString.'"');
243 }
244 return ImageColorAllocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
245 }
246
247
248 function HexColorXOR($hexcolor) {
249 return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
250 }
251
252
253 function GetPixelColor(&$img, $x, $y) {
254 if (!is_resource($img)) {
255 return false;
256 }
257 return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
258 }
259
260
261 function PixelColorDifferencePercent($currentPixel, $targetPixel) {
262 $diff = 0;
263 foreach ($targetPixel as $channel => $currentvalue) {
264 $diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
265 }
266 return $diff * 100;
267 }
268
269 function GrayscaleValue($r, $g, $b) {
270 return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
271 }
272
273
274 function GrayscalePixel($OriginalPixel) {
275 $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
276 return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
277 }
278
279
280 function GrayscalePixelRGB($rgb) {
281 $r = ($rgb >> 16) & 0xFF;
282 $g = ($rgb >> 8) & 0xFF;
283 $b = $rgb & 0xFF;
284 return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
285 }
286
287
288 function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
289 $maxwidth = (is_null($maxwidth) ? $width : $maxwidth);
290 $maxheight = (is_null($maxheight) ? $height : $maxheight);
291 $scale_x = 1;
292 $scale_y = 1;
293 if (($width > $maxwidth) || ($width < $maxwidth)) {
294 $scale_x = ($maxwidth / $width);
295 }
296 if (($height > $maxheight) || ($height < $maxheight)) {
297 $scale_y = ($maxheight / $height);
298 }
299 $scale = min($scale_x, $scale_y);
300 if (!$allow_enlarge) {
301 $scale = min($scale, 1);
302 }
303 if (!$allow_reduce) {
304 $scale = max($scale, 1);
305 }
306 return $scale;
307 }
308
309 function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
310 // ron at korving dot demon dot nl
311 // http://www.php.net/imagecopyresampled
312
313 $scaleX = ($src_w - 1) / $dst_w;
314 $scaleY = ($src_h - 1) / $dst_h;
315
316 $scaleX2 = $scaleX / 2.0;
317 $scaleY2 = $scaleY / 2.0;
318
319 $isTrueColor = ImageIsTrueColor($src_img);
320
321 for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
322 $sY = $y * $scaleY;
323 $siY = (int) $sY;
324 $siY2 = (int) $sY + $scaleY2;
325
326 for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
327 $sX = $x * $scaleX;
328 $siX = (int) $sX;
329 $siX2 = (int) $sX + $scaleX2;
330
331 if ($isTrueColor) {
332
333 $c1 = ImageColorAt($src_img, $siX, $siY2);
334 $c2 = ImageColorAt($src_img, $siX, $siY);
335 $c3 = ImageColorAt($src_img, $siX2, $siY2);
336 $c4 = ImageColorAt($src_img, $siX2, $siY);
337
338 $r = (( $c1 + $c2 + $c3 + $c4 ) >> 2) & 0xFF0000;
339 $g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
340 $b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
341
342 } else {
343
344 $c1 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY2));
345 $c2 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY));
346 $c3 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY2));
347 $c4 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY));
348
349 $r = ($c1['red'] + $c2['red'] + $c3['red'] + $c4['red'] ) << 14;
350 $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
351 $b = ($c1['blue'] + $c2['blue'] + $c3['blue'] + $c4['blue'] ) >> 2;
352
353 }
354 ImageSetPixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
355 }
356 }
357 return true;
358 }
359
360
361 function ImageCreateFunction($x_size, $y_size) {
362 $ImageCreateFunction = 'ImageCreate';
363 if (phpthumb_functions::gd_version() >= 2.0) {
364 $ImageCreateFunction = 'ImageCreateTrueColor';
365 }
366 if (!function_exists($ImageCreateFunction)) {
367 return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
368 }
369 if (($x_size <= 0) || ($y_size <= 0)) {
370 return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
371 }
372 return $ImageCreateFunction(round($x_size), round($y_size));
373 }
374
375
376 function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
377 $opacipct = $opacity_pct / 100;
378 for ($x = $src_x; $x < $src_w; $x++) {
379 for ($y = $src_y; $y < $src_h; $y++) {
380 $RealPixel = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
381 $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
382 $alphapct = $OverlayPixel['alpha'] / 127;
383 $overlaypct = (1 - $alphapct) * $opacipct;
384
385 $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe(
386 $dst_im,
387 round($RealPixel['red'] * (1 - $overlaypct)) + ($OverlayPixel['red'] * $overlaypct),
388 round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
389 round($RealPixel['blue'] * (1 - $overlaypct)) + ($OverlayPixel['blue'] * $overlaypct),
390 //$RealPixel['alpha']);
391 0);
392
393 ImageSetPixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
394 }
395 }
396 return true;
397 }
398
399
400 function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
401 $old_aspect_ratio = $old_width / $old_height;
402 if (($new_width === false) && ($new_height === false)) {
403 return false;
404 } elseif ($new_width === false) {
405 $new_width = $new_height * $old_aspect_ratio;
406 } elseif ($new_height === false) {
407 $new_height = $new_width / $old_aspect_ratio;
408 }
409 $new_aspect_ratio = $new_width / $new_height;
410 if ($new_aspect_ratio == $old_aspect_ratio) {
411 // great, done
412 } elseif ($new_aspect_ratio < $old_aspect_ratio) {
413 // limited by width
414 $new_height = $new_width / $old_aspect_ratio;
415 } elseif ($new_aspect_ratio > $old_aspect_ratio) {
416 // limited by height
417 $new_width = $new_height * $old_aspect_ratio;
418 }
419 return array(intval(round($new_width)), intval(round($new_height)));
420 }
421
422
423 function FunctionIsDisabled($function) {
424 static $DisabledFunctions = null;
425 if (is_null($DisabledFunctions)) {
426 $disable_functions_local = explode(',', strtolower(@ini_get('disable_functions')));
427 $disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
428 foreach ($disable_functions_local as $key => $value) {
429 $DisabledFunctions[trim($value)] = 'local';
430 }
431 foreach ($disable_functions_global as $key => $value) {
432 $DisabledFunctions[trim($value)] = 'global';
433 }
434 if (@ini_get('safe_mode')) {
435 $DisabledFunctions['shell_exec'] = 'local';
436 $DisabledFunctions['set_time_limit'] = 'local';
437 }
438 }
439 return isset($DisabledFunctions[strtolower($function)]);
440 }
441
442
443 function SafeExec($command) {
444 static $AllowedExecFunctions = array();
445 if (empty($AllowedExecFunctions)) {
446 $AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
447 foreach ($AllowedExecFunctions as $key => $value) {
448 $AllowedExecFunctions[$key] = !phpthumb_functions::FunctionIsDisabled($key);
449 }
450 }
451 $command .= ' 2>&1'; // force redirect stderr to stdout
452 foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
453 if (!$is_allowed) {
454 continue;
455 }
456 $returnvalue = false;
457 switch ($execfunction) {
458 case 'passthru':
459 case 'system':
460 ob_start();
461 $execfunction($command);
462 $returnvalue = ob_get_contents();
463 ob_end_clean();
464 break;
465
466 case 'exec':
467 $output = array();
468 $lastline = $execfunction($command, $output);
469 $returnvalue = implode("\n", $output);
470 break;
471
472 case 'shell_exec':
473 ob_start();
474 $returnvalue = $execfunction($command);
475 ob_end_clean();
476 break;
477 }
478 return $returnvalue;
479 }
480 return false;
481 }
482
483
484 function ApacheLookupURIarray($filename) {
485 // apache_lookup_uri() only works when PHP is installed as an Apache module.
486 if (php_sapi_name() == 'apache') {
487 $keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
488 if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
489 $apacheLookupURIarray = array();
490 foreach ($keys as $key) {
491 $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
492 }
493 return $apacheLookupURIarray;
494 }
495 }
496 return false;
497 }
498
499
500 function gd_is_bundled() {
501 static $isbundled = null;
502 if (is_null($isbundled)) {
503 $gd_info = gd_info();
504 $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
505 }
506 return $isbundled;
507 }
508
509
510 function gd_version($fullstring=false) {
511 static $cache_gd_version = array();
512 if (empty($cache_gd_version)) {
513 $gd_info = gd_info();
514 if (eregi('bundled \((.+)\)$', $gd_info['GD Version'], $matches)) {
515 $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "bundled (2.0.15 compatible)"
516 $cache_gd_version[0] = (float) $matches[1]; // e.g. "2.0" (not "bundled (2.0.15 compatible)")
517 } else {
518 $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "1.6.2 or higher"
519 $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
520 }
521 }
522 return $cache_gd_version[intval($fullstring)];
523 }
524
525
526 function filesize_remote($remotefile, $timeout=10) {
527 $size = false;
528 $url = phpthumb_functions::ParseURLbetter($remotefile);
529 if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
530 fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
531 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
532 stream_set_timeout($fp, $timeout);
533 }
534 while (!feof($fp)) {
535 $headerline = fgets($fp, 4096);
536 if (eregi('^Content-Length: (.*)', $headerline, $matches)) {
537 $size = intval($matches[1]);
538 break;
539 }
540 }
541 fclose ($fp);
542 }
543 return $size;
544 }
545
546
547 function filedate_remote($remotefile, $timeout=10) {
548 $date = false;
549 $url = phpthumb_functions::ParseURLbetter($remotefile);
550 if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
551 fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
552 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
553 stream_set_timeout($fp, $timeout);
554 }
555 while (!feof($fp)) {
556 $headerline = fgets($fp, 4096);
557 if (eregi('^Last-Modified: (.*)', $headerline, $matches)) {
558 $date = strtotime($matches[1]) - date('Z');
559 break;
560 }
561 }
562 fclose ($fp);
563 }
564 return $date;
565 }
566
567
568 function md5_file_safe($filename) {
569 // md5_file() doesn't exist in PHP < 4.2.0
570 if (function_exists('md5_file')) {
571 return md5_file($filename);
572 }
573 if ($fp = @fopen($filename, 'rb')) {
574 $rawData = '';
575 do {
576 $buffer = fread($fp, 8192);
577 $rawData .= $buffer;
578 } while (strlen($buffer) > 0);
579 fclose($fp);
580 return md5($rawData);
581 }
582 return false;
583 }
584
585
586 function nonempty_min() {
587 $arg_list = func_get_args();
588 $acceptable = array();
589 foreach ($arg_list as $arg) {
590 if ($arg) {
591 $acceptable[] = $arg;
592 }
593 }
594 return min($acceptable);
595 }
596
597
598 function LittleEndian2String($number, $minbytes=1) {
599 $intstring = '';
600 while ($number > 0) {
601 $intstring = $intstring.chr($number & 255);
602 $number >>= 8;
603 }
604 return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
605 }
606
607 function OneOfThese() {
608 // return the first useful (non-empty/non-zero/non-false) value from those passed
609 $arg_list = func_get_args();
610 foreach ($arg_list as $key => $value) {
611 if ($value) {
612 return $value;
613 }
614 }
615 return false;
616 }
617
618 function CaseInsensitiveInArray($needle, $haystack) {
619 $needle = strtolower($needle);
620 foreach ($haystack as $key => $value) {
621 if (is_array($value)) {
622 // skip?
623 } elseif ($needle == strtolower($value)) {
624 return true;
625 }
626 }
627 return false;
628 }
629
630 function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
631 if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
632 $errstr = 'fsockopen() unavailable';
633 return false;
634 }
635 if ($fp = @fsockopen($host, 80, $errno, $errstr, $timeout)) {
636 $out = 'GET '.$file.' HTTP/1.0'."\r\n";
637 $out .= 'Host: '.$host."\r\n";
638 $out .= 'Connection: Close'."\r\n\r\n";
639 fwrite($fp, $out);
640
641 $isHeader = true;
642 $Data_header = '';
643 $Data_body = '';
644 $header_newlocation = '';
645 while (!feof($fp)) {
646 $line = fgets($fp, 1024);
647 if ($isHeader) {
648 $Data_header .= $line;
649 } else {
650 $Data_body .= $line;
651 }
652 if (eregi('^HTTP/[\\.0-9]+ ([0-9]+) (.+)$', rtrim($line), $matches)) {
653 list($dummy, $errno, $errstr) = $matches;
654 $errno = intval($errno);
655 } elseif (eregi('^Location: (.*)$', rtrim($line), $matches)) {
656 $header_newlocation = $matches[1];
657 }
658 if ($isHeader && ($line == "\r\n")) {
659 $isHeader = false;
660 if ($successonly) {
661 switch ($errno) {
662 case 200:
663 // great, continue
664 break;
665
666 default:
667 $errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
668 fclose($fp);
669 return false;
670 break;
671 }
672 }
673 }
674 }
675 fclose($fp);
676 return $Data_body;
677 }
678 return null;
679 }
680
681 function CleanUpURLencoding($url, $queryseperator='&') {
682 if (!eregi('^http', $url)) {
683 return $url;
684 }
685 $parse_url = phpthumb_functions::ParseURLbetter($url);
686 $pathelements = explode('/', $parse_url['path']);
687 $CleanPathElements = array();
688 $TranslationMatrix = array(' '=>'%20');
689 foreach ($pathelements as $key => $pathelement) {
690 $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
691 }
692 foreach ($CleanPathElements as $key => $value) {
693 if ($value === '') {
694 unset($CleanPathElements[$key]);
695 }
696 }
697
698 $queries = explode($queryseperator, @$parse_url['query']);
699 $CleanQueries = array();
700 foreach ($queries as $key => $query) {
701 @list($param, $value) = explode('=', $query);
702 $CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
703 }
704 foreach ($CleanQueries as $key => $value) {
705 if ($value === '') {
706 unset($CleanQueries[$key]);
707 }
708 }
709
710 $cleaned_url = $parse_url['scheme'].'://';
711 $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
712 $cleaned_url .= $parse_url['host'];
713 $cleaned_url .= '/'.implode('/', $CleanPathElements);
714 $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
715 return $cleaned_url;
716 }
717
718 function ParseURLbetter($url) {
719 $parsedURL = @parse_url($url);
720 if (!@$parsedURL['port']) {
721 switch (strtolower(@$parsedURL['scheme'])) {
722 case 'ftp':
723 $parsedURL['port'] = 21;
724 break;
725 case 'https':
726 $parsedURL['port'] = 443;
727 break;
728 case 'http':
729 $parsedURL['port'] = 80;
730 break;
731 }
732 }
733 return $parsedURL;
734 }
735
736 function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
737 $error = '';
738
739 $parsed_url = phpthumb_functions::ParseURLbetter($url);
740 $alreadyLookedAtURLs[trim($url)] = true;
741
742 while (true) {
743 $tryagain = false;
744 $rawData = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
745 if (eregi('302 [a-z ]+; Location\\: (http.*)', $errstr, $matches)) {
746 $matches[1] = trim(@$matches[1]);
747 if (!@$alreadyLookedAtURLs[$matches[1]]) {
748 // loop through and examine new URL
749 $error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
750
751 $tryagain = true;
752 $alreadyLookedAtURLs[$matches[1]] = true;
753 $parsed_url = phpthumb_functions::ParseURLbetter($matches[1]);
754 }
755 }
756 if (!$tryagain) {
757 break;
758 }
759 }
760
761 if ($rawData === false) {
762 $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
763 return false;
764 } elseif ($rawData === null) {
765 // fall through
766 $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
767 } else {
768 return $rawData;
769 }
770
771 if (function_exists('curl_version') && !phpthumb_functions::FunctionIsDisabled('curl_exec')) {
772 $ch = curl_init();
773 curl_setopt($ch, CURLOPT_URL, $url);
774 curl_setopt($ch, CURLOPT_HEADER, false);
775 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
776 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
777 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
778 $rawData = curl_exec($ch);
779 curl_close($ch);
780 if (strlen($rawData) > 0) {
781 $error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
782 return $rawData;
783 }
784 $error .= 'CURL available but returned no data; ';
785 } else {
786 $error .= 'CURL unavailable; ';
787 }
788
789 $BrokenURLfopenPHPversions = array('4.4.2');
790 if (in_array(phpversion(), $BrokenURLfopenPHPversions)) {
791 $error .= 'fopen(URL) broken in PHP v'.phpversion().'; ';
792 } elseif (@ini_get('allow_url_fopen')) {
793 $rawData = '';
794 $error_fopen = '';
795 ob_start();
796 if ($fp = fopen($url, 'rb')) {
797 do {
798 $buffer = fread($fp, 8192);
799 $rawData .= $buffer;
800 } while (strlen($buffer) > 0);
801 fclose($fp);
802 } else {
803 $error_fopen .= trim(strip_tags(ob_get_contents()));
804 }
805 ob_end_clean();
806 $error .= $error_fopen;
807 if (!$error_fopen) {
808 $error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
809 return $rawData;
810 }
811 $error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
812 } else {
813 $error .= '"allow_url_fopen" disabled; ';
814 }
815
816 return false;
817 }
818
819 function EnsureDirectoryExists($dirname) {
820 $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
821 $startoffset = (!$directory_elements[0] ? 2 : 1); // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
822 $open_basedirs = split('[;:]', ini_get('open_basedir'));
823 foreach ($open_basedirs as $key => $open_basedir) {
824 if (ereg('^'.preg_quote($open_basedir), $dirname) && (strlen($dirname) > strlen($open_basedir))) {
825 $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
826 break;
827 }
828 }
829 $i = $startoffset;
830 $endoffset = count($directory_elements);
831 for ($i = $startoffset; $i <= $endoffset; $i++) {
832 $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
833 if (!$test_directory) {
834 continue;
835 }
836 if (!@is_dir($test_directory)) {
837 if (@file_exists($test_directory)) {
838 // directory name already exists as a file
839 return false;
840 }
841 @mkdir($test_directory, 0755);
842 @chmod($test_directory, 0755);
843 if (!@is_dir($test_directory) || !@is_writeable($test_directory)) {
844 return false;
845 }
846 }
847 }
848 return true;
849 }
850
851
852 function GetAllFilesInSubfolders($dirname) {
853 $AllFiles = array();
854 $dirname = rtrim(realpath($dirname), '/\\');
855 if ($dirhandle = @opendir($dirname)) {
856 while (($file = readdir($dirhandle)) !== false) {
857 $fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
858 if (is_file($fullfilename)) {
859 $AllFiles[] = $fullfilename;
860 } elseif (is_dir($fullfilename)) {
861 switch ($file) {
862 case '.':
863 case '..':
864 break;
865
866 default:
867 $AllFiles[] = $fullfilename;
868 $subfiles = phpthumb_functions::GetAllFilesInSubfolders($fullfilename);
869 foreach ($subfiles as $filename) {
870 $AllFiles[] = $filename;
871 }
872 break;
873 }
874 } else {
875 // ignore?
876 }
877 }
878 closedir($dirhandle);
879 }
880 sort($AllFiles);
881 return array_unique($AllFiles);
882 }
883
884
885 function SanitizeFilename($filename) {
886 $filename = ereg_replace('[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]', '_', $filename);
887 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
888 $filename = trim($filename, '.');
889 }
890 return $filename;
891 }
892
893}
894
895
896////////////// END: class phpthumb_functions //////////////
897
898
899if (!function_exists('gd_info')) {
900 // built into PHP v4.3.0+ (with bundled GD2 library)
901 function gd_info() {
902 static $gd_info = array();
903 if (empty($gd_info)) {
904 // based on code by johnschaefer at gmx dot de
905 // from PHP help on gd_info()
906 $gd_info = array(
907 'GD Version' => '',
908 'FreeType Support' => false,
909 'FreeType Linkage' => '',
910 'T1Lib Support' => false,
911 'GIF Read Support' => false,
912 'GIF Create Support' => false,
913 'JPG Support' => false,
914 'PNG Support' => false,
915 'WBMP Support' => false,
916 'XBM Support' => false
917 );
918 $phpinfo_array = phpthumb_functions::phpinfo_array();
919 foreach ($phpinfo_array as $line) {
920 $line = trim(strip_tags($line));
921 foreach ($gd_info as $key => $value) {
922 //if (strpos($line, $key) !== false) {
923 if (strpos($line, $key) === 0) {
924 $newvalue = trim(str_replace($key, '', $line));
925 $gd_info[$key] = $newvalue;
926 }
927 }
928 }
929 if (empty($gd_info['GD Version'])) {
930 // probable cause: "phpinfo() disabled for security reasons"
931 if (function_exists('ImageTypes')) {
932 $imagetypes = ImageTypes();
933 if ($imagetypes & IMG_PNG) {
934 $gd_info['PNG Support'] = true;
935 }
936 if ($imagetypes & IMG_GIF) {
937 $gd_info['GIF Create Support'] = true;
938 }
939 if ($imagetypes & IMG_JPG) {
940 $gd_info['JPG Support'] = true;
941 }
942 if ($imagetypes & IMG_WBMP) {
943 $gd_info['WBMP Support'] = true;
944 }
945 }
946 // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
947 if (function_exists('ImageCreateFromGIF')) {
948 if ($tempfilename = phpthumb::phpThumb_tempnam()) {
949 if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
950 fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
951 fclose($fp_tempfile);
952
953 // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
954 $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
955 }
956 unlink($tempfilename);
957 }
958 }
959 if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1, 1)) {
960 $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
961 } elseif (function_exists('ImageCreate') && @ImageCreate(1, 1)) {
962 $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
963 }
964 }
965 }
966 return $gd_info;
967 }
968}
969
970
971if (!function_exists('is_executable')) {
972 // in PHP v3+, but v5.0+ for Windows
973 function is_executable($filename) {
974 // poor substitute, but better than nothing
975 return file_exists($filename);
976 }
977}
978
979
980if (!function_exists('preg_quote')) {
981 // included in PHP v3.0.9+, but may be unavailable if not compiled in
982 function preg_quote($string, $delimiter='\\') {
983 static $preg_quote_array = array();
984 if (empty($preg_quote_array)) {
985 $escapeables = '.\\+*?[^]$(){}=!<>|:';
986 for ($i = 0; $i < strlen($escapeables); $i++) {
987 $strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
988 }
989 }
990 return strtr($string, $strtr_preg_quote);
991 }
992}
993
994if (!function_exists('file_get_contents')) {
995 // included in PHP v4.3.0+
996 function file_get_contents($filename) {
997 if (eregi('^(f|ht)tp\://', $filename)) {
998 return SafeURLread($filename, $error);
999 }
1000 if ($fp = @fopen($filename, 'rb')) {
1001 $rawData = '';
1002 do {
1003 $buffer = fread($fp, 8192);
1004 $rawData .= $buffer;
1005 } while (strlen($buffer) > 0);
1006 fclose($fp);
1007 return $rawData;
1008 }
1009 return false;
1010 }
1011}
1012
1013
1014if (!function_exists('file_put_contents')) {
1015 // included in PHP v5.0.0+
1016 function file_put_contents($filename, $filedata) {
1017 if ($fp = @fopen($filename, 'wb')) {
1018 fwrite($fp, $filedata);
1019 fclose($fp);
1020 return true;
1021 }
1022 return false;
1023 }
1024}
1025
1026if (!function_exists('imagealphablending')) {
1027 // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1028 function imagealphablending(&$img, $blendmode=true) {
1029 // do nothing, this function is declared here just to
1030 // prevent runtime errors if GD2 is not available
1031 return true;
1032 }
1033}
1034
1035if (!function_exists('imagesavealpha')) {
1036 // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1037 function imagesavealpha(&$img, $blendmode=true) {
1038 // do nothing, this function is declared here just to
1039 // prevent runtime errors if GD2 is not available
1040 return true;
1041 }
1042}
1043
1044?>
Note: See TracBrowser for help on using the repository browser.