OSDN Git Service

original file
[nucleus-jp/nucleus-plugins.git] / trunk / NP_TinyMCE2j / tinymce2j / plugins / ibrowser / scripts / phpThumb / phpthumb.functions.php
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                         1  => 'image/gif',                     // IMAGETYPE_GIF
164                         2  => 'image/jpeg',                    // IMAGETYPE_JPEG
165                         3  => 'image/png',                     // IMAGETYPE_PNG
166                         4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
167                         5  => 'image/psd',                     // IMAGETYPE_PSD
168                         6  => 'image/bmp',                     // IMAGETYPE_BMP
169                         7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
170                         8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
171                         9  => '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, intval($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 GrayscaleValue($r, $g, $b) {
229                 return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
230         }
231
232         function GrayscalePixel($OriginalPixel) {
233                 $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
234                 return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
235         }
236
237         function ImageResizeFunction(&$dst_im, &$src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) {
238                 if (phpthumb_functions::gd_version() >= 2.0) {
239                         return ImageCopyResampled($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
240                 }
241                 return ImageCopyResized($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
242         }
243
244         function ImageCreateFunction($x_size, $y_size) {
245                 $ImageCreateFunction = 'ImageCreate';
246                 if (phpthumb_functions::gd_version() >= 2.0) {
247                         $ImageCreateFunction = 'ImageCreateTrueColor';
248                 }
249                 if (!function_exists($ImageCreateFunction)) {
250                         return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
251                 }
252                 if (($x_size <= 0) || ($y_size <= 0)) {
253                         return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
254                 }
255                 return $ImageCreateFunction($x_size, $y_size);
256         }
257
258         function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct=100) {
259                 for ($x = $src_x; $x < $src_w; $x++) {
260                         for ($y = $src_y; $y < $src_h; $y++) {
261                                 $RealPixel    = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
262                                 $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
263                                 $alphapct = $OverlayPixel['alpha'] / 127;
264                                 $opacipct = $pct / 100;
265                                 $overlaypct = (1 - $alphapct) * $opacipct;
266
267                                 $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe(
268                                         $dst_im,
269                                         round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
270                                         round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
271                                         round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
272                                         //$RealPixel['alpha']);
273                                         0);
274
275                                 ImageSetPixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
276                         }
277                 }
278                 return true;
279         }
280
281         function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
282                 $old_aspect_ratio = $old_width / $old_height;
283                 if (($new_width === false) && ($new_height === false)) {
284                         return false;
285                 } elseif ($new_width === false) {
286                         $new_width = $new_height * $old_aspect_ratio;
287                 } elseif ($new_height === false) {
288                         $new_height = $new_width / $old_aspect_ratio;
289                 }
290                 $new_aspect_ratio = $new_width / $new_height;
291                 if ($new_aspect_ratio == $old_aspect_ratio) {
292                         // great, done
293                 } elseif ($new_aspect_ratio < $old_aspect_ratio) {
294                         // limited by width
295                         $new_height = $new_width / $old_aspect_ratio;
296                 } elseif ($new_aspect_ratio > $old_aspect_ratio) {
297                         // limited by height
298                         $new_width = $new_height * $old_aspect_ratio;
299                 }
300                 return array(round($new_width), round($new_height));
301         }
302
303         function SafeExec($command) {
304                 static $AllowedExecFunctions = array();
305                 if (empty($AllowedExecFunctions)) {
306                         $AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
307                         if (@ini_get('safe_mode')) {
308                                 $AllowedExecFunctions['shell_exec'] = false;
309                         }
310                         $disable_functions = explode(',', @ini_get('disable_functions'));
311                         foreach ($AllowedExecFunctions as $key => $value) {
312                                 if (in_array($key, $disable_functions)) {
313                                         $AllowedExecFunctions[$key] = false;
314                                 }
315                         }
316                 }
317                 foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
318                         if (!$is_allowed) {
319                                 continue;
320                         }
321                         if ($execfunction == 'passthru') {
322                                 ob_start();
323                                 $execfunction($command);
324                                 $returnvalue = ob_get_contents();
325                                 ob_end_clean();
326                         } else {
327                                 $returnvalue = @$execfunction($command);
328                         }
329                         return $returnvalue;
330                 }
331                 return false;
332         }
333
334         function ApacheLookupURIarray($filename) {
335                 // apache_lookup_uri() only works when PHP is installed as an Apache module.
336                 if (php_sapi_name() == 'apache') {
337                         $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');
338                         if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
339                                 $apacheLookupURIarray = array();
340                                 foreach ($keys as $key) {
341                                         $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
342                                 }
343                                 return $apacheLookupURIarray;
344                         }
345                 }
346                 return false;
347         }
348
349         function gd_is_bundled() {
350                 static $isbundled = null;
351                 if (is_null($isbundled)) {
352                         $gd_info = phpthumb_functions::gd_info();
353                         $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
354                 }
355                 return $isbundled;
356         }
357
358         function gd_version($fullstring=false) {
359                 static $cache_gd_version = array();
360                 if (empty($cache_gd_version)) {
361                         $gd_info = phpthumb_functions::gd_info();
362                         if (eregi('bundled \((.+)\)$', $gd_info['GD Version'], $matches)) {
363                                 $cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
364                                 $cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
365                         } else {
366                                 $cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
367                                 $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
368                         }
369                 }
370                 return $cache_gd_version[intval($fullstring)];
371         }
372
373         function gd_info() {
374                 if (function_exists('gd_info')) {
375                         // built into PHP v4.3.0+ (with bundled GD2 library)
376                         return gd_info();
377                 }
378
379                 static $gd_info = array();
380                 if (empty($gd_info)) {
381                         // based on code by johnschaefer at gmx dot de
382                         // from PHP help on gd_info()
383                         $gd_info = array(
384                                 'GD Version'         => '',
385                                 'FreeType Support'   => false,
386                                 'FreeType Linkage'   => '',
387                                 'T1Lib Support'      => false,
388                                 'GIF Read Support'   => false,
389                                 'GIF Create Support' => false,
390                                 'JPG Support'        => false,
391                                 'PNG Support'        => false,
392                                 'WBMP Support'       => false,
393                                 'XBM Support'        => false
394                         );
395                         $phpinfo_array = phpthumb_functions::phpinfo_array();
396                         foreach ($phpinfo_array as $line) {
397                                 $line = trim(strip_tags($line));
398                                 foreach ($gd_info as $key => $value) {
399                                         //if (strpos($line, $key) !== false) {
400                                         if (strpos($line, $key) === 0) {
401                                                 $newvalue = trim(str_replace($key, '', $line));
402                                                 $gd_info[$key] = $newvalue;
403                                         }
404                                 }
405                         }
406                         if (empty($gd_info['GD Version'])) {
407                                 // probable cause: "phpinfo() disabled for security reasons"
408                                 if (function_exists('ImageTypes')) {
409                                         $imagetypes = ImageTypes();
410                                         if ($imagetypes & IMG_PNG) {
411                                                 $gd_info['PNG Support'] = true;
412                                         }
413                                         if ($imagetypes & IMG_GIF) {
414                                                 $gd_info['GIF Create Support'] = true;
415                                         }
416                                         if ($imagetypes & IMG_JPG) {
417                                                 $gd_info['JPG Support'] = true;
418                                         }
419                                         if ($imagetypes & IMG_WBMP) {
420                                                 $gd_info['WBMP Support'] = true;
421                                         }
422                                 }
423                                 // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
424                                 if (function_exists('ImageCreateFromGIF')) {
425                                         if ($tempfilename = phpthumb::phpThumb_tempnam()) {
426                                                 if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
427                                                         fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
428                                                         fclose($fp_tempfile);
429
430                                                         // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
431                                                         $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
432                                                 }
433                                                 unlink($tempfilename);
434                                         }
435                                 }
436                                 if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1, 1)) {
437                                         $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
438                                 } elseif (function_exists('ImageCreate') && @ImageCreate(1, 1)) {
439                                         $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
440                                 }
441                         }
442                 }
443                 return $gd_info;
444         }
445
446         function filesize_remote($remotefile, $timeout=10) {
447                 $size = false;
448                 $url = parse_url($remotefile);
449                 if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
450                         fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
451                         if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
452                                 stream_set_timeout($fp, $timeout);
453                         }
454                         while (!feof($fp)) {
455                                 $headerline = fgets($fp, 4096);
456                                 if (eregi('^Content-Length: (.*)', $headerline, $matches)) {
457                                         $size = intval($matches[1]);
458                                         break;
459                                 }
460                         }
461                         fclose ($fp);
462                 }
463                 return $size;
464         }
465
466         function filedate_remote($remotefile, $timeout=10) {
467                 $date = false;
468                 $url = parse_url($remotefile);
469                 if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
470                         fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
471                         if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
472                                 stream_set_timeout($fp, $timeout);
473                         }
474                         while (!feof($fp)) {
475                                 $headerline = fgets($fp, 4096);
476                                 if (eregi('^Last-Modified: (.*)', $headerline, $matches)) {
477                                         $date = strtotime($matches[1]) - date('Z');
478                                         break;
479                                 }
480                         }
481                         fclose ($fp);
482                 }
483                 return $date;
484         }
485
486         function md5_file_safe($filename) {
487                 // md5_file() doesn't exist in PHP < 4.2.0
488                 if (function_exists('md5_file')) {
489                         return md5_file($filename);
490                 }
491                 if ($fp = @fopen($filename, 'rb')) {
492                         $filedata = fread($fp, filesize($filename));
493                         fclose($fp);
494                         return md5($filedata);
495                 }
496                 return false;
497         }
498
499         function nonempty_min() {
500                 $arg_list = func_get_args();
501                 $acceptable = array();
502                 foreach ($arg_list as $arg) {
503                         if ($arg) {
504                                 $acceptable[] = $arg;
505                         }
506                 }
507                 return min($acceptable);
508         }
509
510 }
511
512 ?>