root/afridex/plugins/Flutter/phpthumb.functions.php

Revision 21, 29.7 kB (checked in by admin, 18 years ago)
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 HexCharDisplay($string) {
200                $len = strlen($string);
201                $output = '';
202                for ($i = 0; $i < $len; $i++) {
203                        $output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
204                }
205                return $output;
206        }
207
208
209        function IsHexColor($HexColorString) {
210                return eregi('^[0-9A-F]{6}$', $HexColorString);
211        }
212
213
214        function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
215                if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.2', '>=') && ($alpha !== false)) {
216                        return ImageColorAllocateAlpha($gdimg_hexcolorallocate, $R, $G, $B, intval($alpha));
217                } else {
218                        return ImageColorAllocate($gdimg_hexcolorallocate, $R, $G, $B);
219                }
220        }
221
222        function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
223                if (!is_resource($gdimg_hexcolorallocate)) {
224                        die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
225                }
226                if (phpthumb_functions::IsHexColor($HexColorString)) {
227                        $R = hexdec(substr($HexColorString, 0, 2));
228                        $G = hexdec(substr($HexColorString, 2, 2));
229                        $B = hexdec(substr($HexColorString, 4, 2));
230                        return phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
231                }
232                if ($dieOnInvalid) {
233                        die('Invalid hex color string: "'.$HexColorString.'"');
234                }
235                return ImageColorAllocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
236        }
237
238
239        function HexColorXOR($hexcolor) {
240                return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
241        }
242
243
244        function GetPixelColor(&$img, $x, $y) {
245                if (!is_resource($img)) {
246                        return false;
247                }
248                return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
249        }
250
251
252        function GrayscaleValue($r, $g, $b) {
253                return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
254        }
255
256
257        function GrayscalePixel($OriginalPixel) {
258                $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
259                return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
260        }
261
262
263        function GrayscalePixelRGB($rgb) {
264                $r = ($rgb >> 16) & 0xFF;
265                $g = ($rgb >>  8) & 0xFF;
266                $b =  $rgb        & 0xFF;
267                return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
268        }
269
270
271        function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
272                // ron at korving dot demon dot nl
273                // http://www.php.net/imagecopyresampled
274
275                $scaleX = ($src_w - 1) / $dst_w;
276                $scaleY = ($src_h - 1) / $dst_h;
277
278                $scaleX2 = $scaleX / 2.0;
279                $scaleY2 = $scaleY / 2.0;
280
281                $isTrueColor = ImageIsTrueColor($src_img);
282
283                for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
284                        $sY   = $y * $scaleY;
285                        $siY  = (int) $sY;
286                        $siY2 = (int) $sY + $scaleY2;
287
288                        for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
289                                $sX   = $x * $scaleX;
290                                $siX  = (int) $sX;
291                                $siX2 = (int) $sX + $scaleX2;
292
293                                if ($isTrueColor) {
294
295                                        $c1 = ImageColorAt($src_img, $siX, $siY2);
296                                        $c2 = ImageColorAt($src_img, $siX, $siY);
297                                        $c3 = ImageColorAt($src_img, $siX2, $siY2);
298                                        $c4 = ImageColorAt($src_img, $siX2, $siY);
299
300                                        $r = (( $c1             +  $c2             +  $c3             +  $c4            ) >> 2) & 0xFF0000;
301                                        $g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
302                                        $b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
303
304                                } else {
305
306                                        $c1 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY2));
307                                        $c2 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY));
308                                        $c3 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY2));
309                                        $c4 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY));
310
311                                        $r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red'] )  << 14;
312                                        $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) <<  6;
313                                        $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >>  2;
314
315                                }
316                                ImageSetPixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
317                        }
318                }
319                return true;
320        }
321
322
323        function ImageCreateFunction($x_size, $y_size) {
324                $ImageCreateFunction = 'ImageCreate';
325                if (phpthumb_functions::gd_version() >= 2.0) {
326                        $ImageCreateFunction = 'ImageCreateTrueColor';
327                }
328                if (!function_exists($ImageCreateFunction)) {
329                        return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
330                }
331                if (($x_size <= 0) || ($y_size <= 0)) {
332                        return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
333                }
334                return $ImageCreateFunction($x_size, $y_size);
335        }
336
337
338        function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct=100) {
339                for ($x = $src_x; $x < $src_w; $x++) {
340                        for ($y = $src_y; $y < $src_h; $y++) {
341                                $RealPixel    = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
342                                $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
343                                $alphapct = $OverlayPixel['alpha'] / 127;
344                                $opacipct = $pct / 100;
345                                $overlaypct = (1 - $alphapct) * $opacipct;
346
347                                $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe(
348                                        $dst_im,
349                                        round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
350                                        round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
351                                        round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
352                                        //$RealPixel['alpha']);
353                                        0);
354
355                                ImageSetPixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
356                        }
357                }
358                return true;
359        }
360
361
362        function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
363                $old_aspect_ratio = $old_width / $old_height;
364                if (($new_width === false) && ($new_height === false)) {
365                        return false;
366                } elseif ($new_width === false) {
367                        $new_width = $new_height * $old_aspect_ratio;
368                } elseif ($new_height === false) {
369                        $new_height = $new_width / $old_aspect_ratio;
370                }
371                $new_aspect_ratio = $new_width / $new_height;
372                if ($new_aspect_ratio == $old_aspect_ratio) {
373                        // great, done
374                } elseif ($new_aspect_ratio < $old_aspect_ratio) {
375                        // limited by width
376                        $new_height = $new_width / $old_aspect_ratio;
377                } elseif ($new_aspect_ratio > $old_aspect_ratio) {
378                        // limited by height
379                        $new_width = $new_height * $old_aspect_ratio;
380                }
381                return array(round($new_width), round($new_height));
382        }
383
384
385        function FunctionIsDisabled($function) {
386                static $DisabledFunctions = null;
387                if (is_null($DisabledFunctions)) {
388                        $disable_functions_local  = explode(',',     @ini_get('disable_functions'));
389                        $disable_functions_global = explode(',', @get_cfg_var('disable_functions'));
390                        foreach ($disable_functions_local as $key => $value) {
391                                $DisabledFunctions[$value] = 'local';
392                        }
393                        foreach ($disable_functions_global as $key => $value) {
394                                $DisabledFunctions[$value] = 'global';
395                        }
396                        if (@ini_get('safe_mode')) {
397                                $DisabledFunctions['shell_exec'] = 'local';
398                        }
399                }
400                return isset($DisabledFunctions[$function]);
401        }
402
403
404        function SafeExec($command) {
405                static $AllowedExecFunctions = array();
406                if (empty($AllowedExecFunctions)) {
407                        $AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
408                        foreach ($AllowedExecFunctions as $key => $value) {
409                                $AllowedExecFunctions[$key] = !phpthumb_functions::FunctionIsDisabled($key);
410                        }
411                }
412                foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
413                        if (!$is_allowed) {
414                                continue;
415                        }
416                        switch ($execfunction) {
417                                case 'passthru':
418                                        ob_start();
419                                        $execfunction($command);
420                                        $returnvalue = ob_get_contents();
421                                        ob_end_clean();
422                                        break;
423
424                                case 'shell_exec':
425                                case 'system':
426                                case 'exec':
427                                default:
428                                        ob_start();
429                                        $returnvalue = $execfunction($command);
430                                        ob_end_clean();
431                                        break;
432                        }
433                        return $returnvalue;
434                }
435                return false;
436        }
437
438
439        function ApacheLookupURIarray($filename) {
440                // apache_lookup_uri() only works when PHP is installed as an Apache module.
441                if (php_sapi_name() == 'apache') {
442                        $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');
443                        if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
444                                $apacheLookupURIarray = array();
445                                foreach ($keys as $key) {
446                                        $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
447                                }
448                                return $apacheLookupURIarray;
449                        }
450                }
451                return false;
452        }
453
454
455        function gd_is_bundled() {
456                static $isbundled = null;
457                if (is_null($isbundled)) {
458                        $gd_info = gd_info();
459                        $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
460                }
461                return $isbundled;
462        }
463
464
465        function gd_version($fullstring=false) {
466                static $cache_gd_version = array();
467                if (empty($cache_gd_version)) {
468                        $gd_info = gd_info();
469                        if (eregi('bundled \((.+)\)$', $gd_info['GD Version'], $matches)) {
470                                $cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
471                                $cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
472                        } else {
473                                $cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
474                                $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
475                        }
476                }
477                return $cache_gd_version[intval($fullstring)];
478        }
479
480
481        function filesize_remote($remotefile, $timeout=10) {
482                $size = false;
483                $url = parse_url($remotefile);
484                if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
485                        fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
486                        if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
487                                stream_set_timeout($fp, $timeout);
488                        }
489                        while (!feof($fp)) {
490                                $headerline = fgets($fp, 4096);
491                                if (eregi('^Content-Length: (.*)', $headerline, $matches)) {
492                                        $size = intval($matches[1]);
493                                        break;
494                                }
495                        }
496                        fclose ($fp);
497                }
498                return $size;
499        }
500
501
502        function filedate_remote($remotefile, $timeout=10) {
503                $date = false;
504                $url = parse_url($remotefile);
505                if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
506                        fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
507                        if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
508                                stream_set_timeout($fp, $timeout);
509                        }
510                        while (!feof($fp)) {
511                                $headerline = fgets($fp, 4096);
512                                if (eregi('^Last-Modified: (.*)', $headerline, $matches)) {
513                                        $date = strtotime($matches[1]) - date('Z');
514                                        break;
515                                }
516                        }
517                        fclose ($fp);
518                }
519                return $date;
520        }
521
522
523        function md5_file_safe($filename) {
524                // md5_file() doesn't exist in PHP < 4.2.0
525                if (function_exists('md5_file')) {
526                        return md5_file($filename);
527                }
528                if ($fp = @fopen($filename, 'rb')) {
529                        $rawData = '';
530                        do {
531                                $buffer = fread($fp, 8192);
532                                $rawData .= $buffer;
533                        } while (strlen($buffer) > 0);
534                        fclose($fp);
535                        return md5($rawData);
536                }
537                return false;
538        }
539
540
541        function nonempty_min() {
542                $arg_list = func_get_args();
543                $acceptable = array();
544                foreach ($arg_list as $arg) {
545                        if ($arg) {
546                                $acceptable[] = $arg;
547                        }
548                }
549                return min($acceptable);
550        }
551
552
553        function LittleEndian2String($number, $minbytes=1) {
554                $intstring = '';
555                while ($number > 0) {
556                        $intstring = $intstring.chr($number & 255);
557                        $number >>= 8;
558                }
559                return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
560        }
561
562        function OneOfThese() {
563                // return the first useful (non-empty/non-zero/non-false) value from those passed
564                $arg_list = func_get_args();
565                foreach ($arg_list as $key => $value) {
566                        if ($value) {
567                                return $value;
568                        }
569                }
570                return false;
571        }
572
573        function CaseInsensitiveInArray($needle, $haystack) {
574                $needle = strtolower($needle);
575                foreach ($haystack as $key => $value) {
576                        if (is_array($value)) {
577                                // skip?
578                        } elseif ($needle == strtolower($value)) {
579                                return true;
580                        }
581                }
582                return false;
583        }
584
585        function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
586                if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
587                        $errstr = 'fsockopen() unavailable';
588                        return false;
589                }
590                if ($fp = @fsockopen($host, 80, $errno, $errstr, $timeout)) {
591                        $out  = 'GET '.$file.' HTTP/1.0'."\r\n";
592                        $out .= 'Host: '.$host."\r\n";
593                        $out .= 'Connection: Close'."\r\n\r\n";
594                        fwrite($fp, $out);
595
596                        $isHeader = true;
597                        $Data_header = '';
598                        $Data_body   = '';
599                        $header_newlocation = '';
600                        while (!feof($fp)) {
601                                $line = fgets($fp, 1024);
602                                if ($isHeader) {
603                                        $Data_header .= $line;
604                                } else {
605                                        $Data_body .= $line;
606                                }
607                                if (eregi('^HTTP/[\\.0-9]+ ([0-9]+) (.+)$', rtrim($line), $matches)) {
608                                        list($dummy, $errno, $errstr) = $matches;
609                                        $errno = intval($errno);
610                                } elseif (eregi('^Location: (.*)$', rtrim($line), $matches)) {
611                                        $header_newlocation = $matches[1];
612                                }
613                                if ($isHeader && ($line == "\r\n")) {
614                                        $isHeader = false;
615                                        if ($successonly) {
616                                                switch ($errno) {
617                                                        case 200:
618                                                                // great, continue
619                                                                break;
620
621                                                        default:
622                                                                $errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
623                                                                fclose($fp);
624                                                                return false;
625                                                                break;
626                                                }
627                                        }
628                                }
629                        }
630                        fclose($fp);
631                        return $Data_body;
632                }
633                return null;
634        }
635
636        function CleanUpURLencoding($url, $queryseperator='&') {
637                if (!eregi('^http', $url)) {
638                        return $url;
639                }
640                $parse_url = @parse_url($url);
641                $pathelements = explode('/', $parse_url['path']);
642                $CleanPathElements = array();
643                $TranslationMatrix = array(' '=>'%20');
644                foreach ($pathelements as $key => $pathelement) {
645                        $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
646                }
647                foreach ($CleanPathElements as $key => $value) {
648                        if (!$value) {
649                                unset($CleanPathElements[$key]);
650                        }
651                }
652
653                $queries = explode($queryseperator, @$parse_url['query']);
654                $CleanQueries = array();
655                foreach ($queries as $key => $query) {
656                        @list($param, $value) = explode('=', $query);
657                        $CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
658                }
659                foreach ($CleanQueries as $key => $value) {
660                        if (!$value) {
661                                unset($CleanQueries[$key]);
662                        }
663                }
664
665                $cleaned_url  = $parse_url['scheme'].'://';
666                $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
667                $cleaned_url .= $parse_url['host'];
668                $cleaned_url .= '/'.implode('/', $CleanPathElements);
669                $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
670                return $cleaned_url;
671        }
672
673        function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
674                $error = '';
675
676                $parsed_url = @parse_url($url);
677                $alreadyLookedAtURLs[trim($url)] = true;
678                do {
679                        $rawData = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
680                        if (eregi('302 Found; Location\\: (http.*)', $errstr, $matches)) {
681                                $matches[1] = trim(@$matches[1]);
682                                if ($alreadyLookedAtURLs[$matches[1]]) {
683                                        break;
684                                }
685                                $alreadyLookedAtURLs[$matches[1]] = true;
686                                $parsed_url = @parse_url($matches[1]);
687                        } else {
688                                break;
689                        }
690                } while (true);
691                $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
692                if ($rawData === false) {
693                        return false;
694                } elseif ($rawData === null) {
695                        // fall through
696                } else {
697                        return $rawData;
698                }
699
700                if (function_exists('curl_version') && !phpthumb_functions::FunctionIsDisabled('curl_exec')) {
701                        $ch = curl_init();
702                        curl_setopt($ch, CURLOPT_URL, $url);
703                        curl_setopt($ch, CURLOPT_HEADER, false);
704                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
705                        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
706                        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
707                        $rawData = curl_exec($ch);
708                        curl_close($ch);
709                        if (strlen($rawData) > 0) {
710                                return $rawData;
711                        }
712                        $error .= 'CURL available but returned no data; ';
713                } else {
714                        $error .= 'CURL unavailable; ';
715                }
716
717                $BrokenURLfopenPHPversions = array('4.4.2');
718                if (in_array(phpversion(), $BrokenURLfopenPHPversions)) {
719                        $error .= 'fopen(URL) broken in PHP v'.phpversion().'; ';
720                } elseif (@ini_get('allow_url_fopen')) {
721                        $rawData = '';
722                        ob_start();
723                        if ($fp = fopen($url, 'rb')) {
724                                do {
725                                        $buffer = fread($fp, 8192);
726                                        $rawData .= $buffer;
727                                } while (strlen($buffer) > 0);
728                                fclose($fp);
729                        } else {
730                                $error .= trim(strip_tags(ob_get_contents()));
731                        }
732                        ob_end_clean();
733                        if (!$error) {
734                                return $rawData;
735                        }
736                        $error .= '; "allow_url_fopen" enabled but returned no data; ';
737                } else {
738                        $error .= '"allow_url_fopen" disabled; ';
739                }
740
741                return false;
742        }
743
744        function EnsureDirectoryExists($dirname) {
745                $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
746                $startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
747                $open_basedirs = explode(':', ini_get('open_basedir'));
748                foreach ($open_basedirs as $key => $open_basedir) {
749                        if (ereg('^'.preg_quote($open_basedir), $dirname) && (strlen($dirname) > strlen($open_basedir))) {
750                                $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
751                                break;
752                        }
753                }
754                $i = $startoffset;
755                $endoffset = count($directory_elements);
756                for ($i = $startoffset; $i <= $endoffset; $i++) {
757                        $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
758                        if (!$test_directory) {
759                                continue;
760                        }
761                        if (!@is_dir($test_directory)) {
762                                if (@file_exists($test_directory)) {
763                                        // directory name already exists as a file
764                                        return false;
765                                }
766                                @mkdir($test_directory, 0755);
767                                @chmod($test_directory, 0755);
768                                if (!@is_dir($test_directory) || !@is_writeable($test_directory)) {
769                                        return false;
770                                }
771                        }
772                }
773                return true;
774        }
775
776
777        function GetAllFilesInSubfolders($dirname) {
778                $AllFiles = array();
779                $dirname = rtrim(realpath($dirname), '/\\');
780                if ($dirhandle = @opendir($dirname)) {
781                        while ($file = readdir($dirhandle)) {
782                                $fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
783                                if (is_file($fullfilename)) {
784                                        $AllFiles[] = $fullfilename;
785                                } elseif (is_dir($fullfilename)) {
786                                        if (($file == '.') || ($file == '..')) {
787                                                continue;
788                                        }
789                                        $subfiles = phpthumb_functions::GetAllFilesInSubfolders($fullfilename);
790                                        foreach ($subfiles as $filename) {
791                                                $AllFiles[] = $filename;
792                                        }
793                                } else {
794                                        // ignore?
795                                }
796                        }
797                        closedir($dirhandle);
798                }
799                sort($AllFiles);
800                return array_unique($AllFiles);
801        }
802
803
804        function SanitizeFilename($filename) {
805                $filename = ereg_replace('[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]', '_', $filename);
806                if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
807                        $filename = trim($filename, '.');
808                }
809                return $filename;
810        }
811
812}
813
814
815////////////// END: class phpthumb_functions //////////////
816
817
818if (!function_exists('gd_info')) {
819        // built into PHP v4.3.0+ (with bundled GD2 library)
820        function gd_info() {
821                static $gd_info = array();
822                if (empty($gd_info)) {
823                        // based on code by johnschaefer at gmx dot de
824                        // from PHP help on gd_info()
825                        $gd_info = array(
826                                'GD Version'         => '',
827                                'FreeType Support'   => false,
828                                'FreeType Linkage'   => '',
829                                'T1Lib Support'      => false,
830                                'GIF Read Support'   => false,
831                                'GIF Create Support' => false,
832                                'JPG Support'        => false,
833                                'PNG Support'        => false,
834                                'WBMP Support'       => false,
835                                'XBM Support'        => false
836                        );
837                        $phpinfo_array = phpthumb_functions::phpinfo_array();
838                        foreach ($phpinfo_array as $line) {
839                                $line = trim(strip_tags($line));
840                                foreach ($gd_info as $key => $value) {
841                                        //if (strpos($line, $key) !== false) {
842                                        if (strpos($line, $key) === 0) {
843                                                $newvalue = trim(str_replace($key, '', $line));
844                                                $gd_info[$key] = $newvalue;
845                                        }
846                                }
847                        }
848                        if (empty($gd_info['GD Version'])) {
849                                // probable cause: "phpinfo() disabled for security reasons"
850                                if (function_exists('ImageTypes')) {
851                                        $imagetypes = ImageTypes();
852                                        if ($imagetypes & IMG_PNG) {
853                                                $gd_info['PNG Support'] = true;
854                                        }
855                                        if ($imagetypes & IMG_GIF) {
856                                                $gd_info['GIF Create Support'] = true;
857                                        }
858                                        if ($imagetypes & IMG_JPG) {
859                                                $gd_info['JPG Support'] = true;
860                                        }
861                                        if ($imagetypes & IMG_WBMP) {
862                                                $gd_info['WBMP Support'] = true;
863                                        }
864                                }
865                                // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
866                                if (function_exists('ImageCreateFromGIF')) {
867                                        if ($tempfilename = phpthumb::phpThumb_tempnam()) {
868                                                if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
869                                                        fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
870                                                        fclose($fp_tempfile);
871
872                                                        // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
873                                                        $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
874                                                }
875                                                unlink($tempfilename);
876                                        }
877                                }
878                                if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1, 1)) {
879                                        $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
880                                } elseif (function_exists('ImageCreate') && @ImageCreate(1, 1)) {
881                                        $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
882                                }
883                        }
884                }
885                return $gd_info;
886        }
887}
888
889
890if (!function_exists('is_executable')) {
891        // in PHP v3+, but v5.0+ for Windows
892        function is_executable($filename) {
893                // poor substitute, but better than nothing
894                return file_exists($filename);
895        }
896}
897
898
899if (!function_exists('preg_quote')) {
900        // included in PHP v3.0.9+, but may be unavailable if not compiled in
901        function preg_quote($string, $delimiter='\\') {
902                static $preg_quote_array = array();
903                if (empty($preg_quote_array)) {
904                        $escapeables = '.\\+*?[^]$(){}=!<>|:';
905                        for ($i = 0; $i < strlen($escapeables); $i++) {
906                                $strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
907                        }
908                }
909                return strtr($string, $strtr_preg_quote);
910        }
911}
912
913if (!function_exists('file_get_contents')) {
914        // included in PHP v4.3.0+
915        function file_get_contents($filename) {
916                if (eregi('^(f|ht)tp\://', $filename)) {
917                        return SafeURLread($filename, $error);
918                }
919                if ($fp = @fopen($filename, 'rb')) {
920                        $rawData = '';
921                        do {
922                                $buffer = fread($fp, 8192);
923                                $rawData .= $buffer;
924                        } while (strlen($buffer) > 0);
925                        fclose($fp);
926                        return $rawData;
927                }
928                return false;
929        }
930}
931
932
933if (!function_exists('file_put_contents')) {
934        // included in PHP v5.0.0+
935        function file_put_contents($filename, $filedata) {
936                if ($fp = @fopen($filename, 'wb')) {
937                        fwrite($fp, $filedata);
938                        fclose($fp);
939                        return true;
940                }
941                return false;
942        }
943}
944
945if (!function_exists('imagealphablending')) {
946        // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
947        function imagealphablending(&$img, $blendmode=true) {
948                // do nothing, this function is declared here just to
949                // prevent runtime errors if GD2 is not available
950                return true;
951        }
952}
953
954if (!function_exists('imagesavealpha')) {
955        // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
956        function imagesavealpha(&$img, $blendmode=true) {
957                // do nothing, this function is declared here just to
958                // prevent runtime errors if GD2 is not available
959                return true;
960        }
961}
962
963?>
Note: See TracBrowser for help on using the browser.