root/devel-backup/units/phpthumb/phpthumb.functions.php

Revision 45, 16.3 kB (checked in by sven, 3 years ago)

dos2unix to clean line endings, set svn property eol-style native, some whitespace homogenisation

  • Property svn:eol-style set to native
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
11 class 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     function builtin_function_exists($functionname) {
25         if (function_exists('get_defined_functions')) {
26             static $get_defined_functions = array();
27             if (empty($get_defined_functions)) {
28                 $get_defined_functions = get_defined_functions();
29             }
30             return in_array(strtolower($functionname), $get_defined_functions['internal']);
31         }
32         return function_exists($functionname);
33     }
34
35     function version_compare_replacement_sub($version1, $version2, $operator='') {
36         // If you specify the third optional operator argument, you can test for a particular relationship.
37         // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
38         // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
39
40         // If a part contains special version strings these are handled in the following order: dev < (alpha = a) < (beta = b) < RC < pl
41         static $versiontype_lookup = array();
42         if (empty($versiontype_lookup)) {
43             $versiontype_lookup['dev']   = 10001;
44             $versiontype_lookup['a']     = 10002;
45             $versiontype_lookup['alpha'] = 10002;
46             $versiontype_lookup['b']     = 10003;
47             $versiontype_lookup['beta']  = 10003;
48             $versiontype_lookup['RC']    = 10004;
49             $versiontype_lookup['pl']    = 10005;
50         }
51         if (isset($versiontype_lookup[$version1])) {
52             $version1 = $versiontype_lookup[$version1];
53         }
54         if (isset($versiontype_lookup[$version2])) {
55             $version2 = $versiontype_lookup[$version2];
56         }
57
58         switch ($operator) {
59             case '<':
60             case 'lt':
61                 return intval($version1 < $version2);
62                 break;
63             case '<=':
64             case 'le':
65                 return intval($version1 <= $version2);
66                 break;
67             case '>':
68             case 'gt':
69                 return intval($version1 > $version2);
70                 break;
71             case '>=':
72             case 'ge':
73                 return intval($version1 >= $version2);
74                 break;
75             case '==':
76             case '=':
77             case 'eq':
78                 return intval($version1 == $version2);
79                 break;
80             case '!=':
81             case '<>':
82             case 'ne':
83                 return intval($version1 != $version2);
84                 break;
85         }
86         if ($version1 == $version2) {
87             return 0;
88         } elseif ($version1 < $version2) {
89             return -1;
90         }
91         return 1;
92     }
93
94     function version_compare_replacement($version1, $version2, $operator='') {
95         if (function_exists('version_compare')) {
96             // built into PHP v4.1.0+
97             return version_compare($version1, $version2, $operator);
98         }
99
100         // The function first replaces _, - and + with a dot . in the version strings
101         $version1 = strtr($version1, '_-+', '...');
102         $version2 = strtr($version2, '_-+', '...');
103
104         // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
105         // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
106         $version1 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version1);
107         $version2 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version2);
108
109         $parts1 = explode('.', $version1);
110         $parts2 = explode('.', $version1);
111         $parts_count = max(count($parts1), count($parts2));
112         for ($i = 0; $i < $parts_count; $i++) {
113             $comparison = phpthumb_functions::version_compare_replacement_sub($version1, $version2, $operator);
114             if ($comparison != 0) {
115                 return $comparison;
116             }
117         }
118         return 0;
119     }
120
121     function phpinfo_array() {
122         static $phpinfo_array = array();
123         if (empty($phpinfo_array)) {
124             ob_start();
125             phpinfo();
126             $phpinfo = ob_get_contents();
127             ob_end_clean();
128             $phpinfo_array = explode("\n", $phpinfo);
129         }
130         return $phpinfo_array;
131     }
132
133     function exif_info() {
134         static $exif_info = array();
135         if (empty($exif_info)) {
136             // based on code by johnschaefer at gmx dot de
137             // from PHP help on gd_info()
138             $exif_info = array(
139                 'EXIF Support'           => '',
140                 'EXIF Version'           => '',
141                 'Supported EXIF Version' => '',
142                 'Supported filetypes'    => ''
143             );
144             $phpinfo_array = phpthumb_functions::phpinfo_array();
145             foreach ($phpinfo_array as $line) {
146                 $line = trim(strip_tags($line));
147                 foreach ($exif_info as $key => $value) {
148                     if (strpos($line, $key) === 0) {
149                         $newvalue = trim(str_replace($key, '', $line));
150                         $exif_info[$key] = $newvalue;
151                     }
152                 }
153             }
154         }
155         return $exif_info;
156     }
157
158     function ImageTypeToMIMEtype($imagetype) {
159         if (function_exists('image_type_to_mime_type')) {
160             return image_type_to_mime_type($imagetype);
161         }
162         static $image_type_to_mime_type = array(
163             => 'image/gif',                     // IMAGETYPE_GIF
164             => 'image/jpeg',                    // IMAGETYPE_JPEG
165             => 'image/png',                     // IMAGETYPE_PNG
166             => 'application/x-shockwave-flash', // IMAGETYPE_SWF
167             => 'image/psd',                     // IMAGETYPE_PSD
168             => 'image/bmp',                     // IMAGETYPE_BMP
169             => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
170             => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
171             => 'application/octet-stream',      // IMAGETYPE_JPC
172             10 => 'image/jp2',                     // IMAGETYPE_JP2
173             11 => 'application/octet-stream',      // IMAGETYPE_JPX
174             12 => 'application/octet-stream',      // IMAGETYPE_JB2
175             13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
176             14 => 'image/iff',                     // IMAGETYPE_IFF
177             15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
178             16 => 'image/xbm');                    // IMAGETYPE_XBM
179
180         return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
181     }
182
183     function HexCharDisplay($string) {
184         $len = strlen($string);
185         $output = '';
186         for ($i = 0; $i < $len; $i++) {
187             $output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
188         }
189         return $output;
190     }
191
192     function IsHexColor($HexColorString) {
193         return eregi('^[0-9A-F]{6}$', $HexColorString);
194     }
195
196     function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
197         if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.2', '>=') && ($alpha !== false)) {
198             return ImageColorAllocateAlpha($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
199         } else {
200             return ImageColorAllocate($gdimg_hexcolorallocate, $R, $G, $B);
201         }
202     }
203
204     function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
205         if (!is_resource($gdimg_hexcolorallocate)) {
206             die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
207         }
208         if (phpthumb_functions::IsHexColor($HexColorString)) {
209             $R = hexdec(substr($HexColorString, 0, 2));
210             $G = hexdec(substr($HexColorString, 2, 2));
211             $B = hexdec(substr($HexColorString, 4, 2));
212             return phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
213         }
214         if ($dieOnInvalid) {
215             die('Invalid hex color string: "'.$HexColorString.'"');
216         }
217         return ImageColorAllocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
218     }
219
220     function HexColorXOR($hexcolor) {
221         return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
222     }
223
224     function GetPixelColor(&$img, $x, $y) {
225         return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
226     }
227
228     function GrayscalePixel($OriginalPixel) {
229         $gray = round(($OriginalPixel['red'] * 0.30) + ($OriginalPixel['green'] * 0.59) + ($OriginalPixel['blue'] * 0.11));
230         return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
231     }
232
233     function ImageResizeFunction(&$dst_im, &$src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) {
234         if (phpthumb_functions::gd_version() >= 2.0) {
235             return ImageCopyResampled($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
236         }
237         return ImageCopyResized($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
238     }
239
240     function ImageCreateFunction($x_size, $y_size) {
241         $ImageCreateFunction = 'ImageCreate';
242         if (phpthumb_functions::gd_version() >= 2.0) {
243             $ImageCreateFunction = 'ImageCreateTrueColor';
244         }
245         if (!function_exists($ImageCreateFunction)) {
246             return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
247         }
248         if (($x_size <= 0) || ($y_size <= 0)) {
249             return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
250         }
251         return $ImageCreateFunction($x_size, $y_size);
252     }
253
254     function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct=100) {
255         for ($x = $src_x; $x < $src_w; $x++) {
256             for ($y = $src_y; $y < $src_h; $y++) {
257                 $RealPixel    = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
258                 $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
259                 $alphapct = $OverlayPixel['alpha'] / 127;
260                 $opacipct = $pct / 100;
261                 $overlaypct = (1 - $alphapct) * $opacipct;
262
263                 $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe(
264                     $dst_im,
265                     round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
266                     round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
267                     round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
268                     //$RealPixel['alpha']);
269                     0);
270
271                 ImageSetPixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
272             }
273         }
274         return true;
275     }
276
277     function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
278         $old_aspect_ratio = $old_width / $old_height;
279         if (($new_width === false) && ($new_height === false)) {
280             return false;
281         } elseif ($new_width === false) {
282             $new_width = $new_height * $old_aspect_ratio;
283         } elseif ($new_height === false) {
284             $new_height = $new_width / $old_aspect_ratio;
285         }
286         $new_aspect_ratio = $new_width / $new_height;
287         if ($new_aspect_ratio == $old_aspect_ratio) {
288             // great, done
289         } elseif ($new_aspect_ratio < $old_aspect_ratio) {
290             // limited by width
291             $new_height = $new_width / $old_aspect_ratio;
292         } elseif ($new_aspect_ratio > $old_aspect_ratio) {
293             // limited by height
294             $new_width = $new_height * $old_aspect_ratio;
295         }
296         return array(round($new_width), round($new_height));
297     }
298
299     function SafeBackTick($command) {
300         static $BacktickDisabled = null;
301         if (is_null($BacktickDisabled)) {
302             $disable_functions = explode(',', @ini_get('disable_functions'));
303             if (@ini_get('safe_mode')) {
304                 $BacktickDisabled = true;
305             } else if (in_array('shell_exec', $disable_functions) || in_array('exec', $disable_functions) || in_array('system', $disable_functions)) {
306                 $BacktickDisabled = true;
307             } else {
308                 $BacktickDisabled = false;
309             }
310         }
311         if ($BacktickDisabled) {
312             return '';
313         }
314         return `$command`;
315     }
316
317     function ApacheLookupURIarray($filename) {
318         // apache_lookup_uri() only works when PHP is installed as an Apache module.
319         if (php_sapi_name() == 'apache') {
320             $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');
321             if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
322                 $apacheLookupURIarray = array();
323                 foreach ($keys as $key) {
324                     $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
325                 }
326                 return $apacheLookupURIarray;
327             }
328         }
329         return false;
330     }
331
332     function gd_version($fullstring=false) {
333         static $cache_gd_version = array();
334         if (empty($cache_gd_version)) {
335             $gd_info = phpthumb_functions::gd_info();
336             if (substr($gd_info['GD Version'], 0, strlen('bundled (')) == 'bundled (') {
337                 $cache_gd_version[1] = $gd_info['GD Version'];                                         // e.g. "bundled (2.0.15 compatible)"
338                 $cache_gd_version[0] = (float) substr($gd_info['GD Version'], strlen('bundled ('), 3); // e.g. "2.0" (not "bundled (2.0.15 compatible)")
339             } else {
340                 $cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
341                 $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
342             }
343         }
344         return $cache_gd_version[intval($fullstring)];
345     }
346
347     function gd_info() {
348         if (function_exists('gd_info')) {
349             // built into PHP v4.3.0+ (with bundled GD2 library)
350             return gd_info();
351         }
352
353         static $gd_info = array();
354         if (empty($gd_info)) {
355             // based on code by johnschaefer at gmx dot de
356             // from PHP help on gd_info()
357             $gd_info = array(
358                 'GD Version'         => '',
359                 'FreeType Support'   => false,
360                 'FreeType Linkage'   => '',
361                 'T1Lib Support'      => false,
362                 'GIF Read Support'   => false,
363                 'GIF Create Support' => false,
364                 'JPG Support'        => false,
365                 'PNG Support'        => false,
366                 'WBMP Support'       => false,
367                 'XBM Support'        => false
368             );
369             $phpinfo_array = phpthumb_functions::phpinfo_array();
370             foreach ($phpinfo_array as $line) {
371                 $line = trim(strip_tags($line));
372                 foreach ($gd_info as $key => $value) {
373                     //if (strpos($line, $key) !== false) {
374                     if (strpos($line, $key) === 0) {
375                         $newvalue = trim(str_replace($key, '', $line));
376                         $gd_info[$key] = $newvalue;
377                     }
378                 }
379             }
380             if (empty($gd_info['GD Version'])) {
381                 // probable cause: "phpinfo() disabled for security reasons"
382                 if (function_exists('ImageTypes')) {
383                     $imagetypes = ImageTypes();
384                     if ($imagetypes & IMG_PNG) {
385                         $gd_info['PNG Support'] = true;
386                     }
387                     if ($imagetypes & IMG_GIF) {
388                         $gd_info['GIF Create Support'] = true;
389                     }
390                     if ($imagetypes & IMG_JPG) {
391                         $gd_info['JPG Support'] = true;
392                     }
393                     if ($imagetypes & IMG_WBMP) {
394                         $gd_info['WBMP Support'] = true;
395                     }
396                 }
397                 // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
398                 if (function_exists('ImageCreateFromGIF')) {
399                     if ($tempfilename = phpthumb::phpThumb_tempnam()) {
400                         if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
401                             fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
402                             fclose($fp_tempfile);
403
404                             // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
405                             $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
406                         }
407                         unlink($tempfilename);
408                     }
409                 }
410                 if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1,