Issues (1210)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

thumbs/phpthumb.functions.php (7 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
//////////////////////////////////////////////////////////////
3
//   phpThumb() by James Heinrich <[email protected]>   //
4
//        available at http://phpthumb.sourceforge.net      //
5
//         and/or https://github.com/JamesHeinrich/phpThumb //
6
//////////////////////////////////////////////////////////////
7
///                                                         //
8
// phpthumb.functions.php - general support functions       //
9
//                                                         ///
10
//////////////////////////////////////////////////////////////
11
12
/**
13
 * Class phpthumb_functions
14
 */
15
class phpthumb_functions
16
{
17
18
    /**
19
     * @param $functionname
20
     * @return bool
21
     */
22 View Code Duplication
    public static function user_function_exists($functionname)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
23
    {
24
        if (function_exists('get_defined_functions')) {
25
            static $get_defined_functions = array();
26
            if (empty($get_defined_functions)) {
27
                $get_defined_functions = get_defined_functions();
28
            }
29
30
            return in_array(strtolower($functionname), $get_defined_functions['user']);
31
        }
32
33
        return function_exists($functionname);
34
    }
35
36
    /**
37
     * @param $functionname
38
     * @return bool
39
     */
40 View Code Duplication
    public static function builtin_function_exists($functionname)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
41
    {
42
        if (function_exists('get_defined_functions')) {
43
            static $get_defined_functions = array();
44
            if (empty($get_defined_functions)) {
45
                $get_defined_functions = get_defined_functions();
46
            }
47
48
            return in_array(strtolower($functionname), $get_defined_functions['internal']);
49
        }
50
51
        return function_exists($functionname);
52
    }
53
54
    /**
55
     * @param         $version1
56
     * @param         $version2
57
     * @param  string $operator
58
     * @return int
59
     */
60
    public static function version_compare_replacement_sub($version1, $version2, $operator = '')
61
    {
62
        // If you specify the third optional operator argument, you can test for a particular relationship.
63
        // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
64
        // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
65
66
        // If a part contains special version strings these are handled in the following order:
67
        // (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
68
        static $versiontype_lookup = array();
69
        if (empty($versiontype_lookup)) {
70
            $versiontype_lookup['dev']   = 10001;
71
            $versiontype_lookup['a']     = 10002;
72
            $versiontype_lookup['alpha'] = 10002;
73
            $versiontype_lookup['b']     = 10003;
74
            $versiontype_lookup['beta']  = 10003;
75
            $versiontype_lookup['RC']    = 10004;
76
            $versiontype_lookup['rc']    = 10004;
77
            $versiontype_lookup['#']     = 10005;
78
            $versiontype_lookup['pl']    = 10006;
79
            $versiontype_lookup['p']     = 10006;
80
        }
81
        $version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
82
        $version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
83
84
        switch ($operator) {
85
            case '<':
86
            case 'lt':
87
                return (int)($version1 < $version2);
88
                break;
89
            case '<=':
90
            case 'le':
91
                return (int)($version1 <= $version2);
92
                break;
93
            case '>':
94
            case 'gt':
95
                return (int)($version1 > $version2);
96
                break;
97
            case '>=':
98
            case 'ge':
99
                return (int)($version1 >= $version2);
100
                break;
101
            case '==':
102
            case '=':
103
            case 'eq':
104
                return (int)($version1 == $version2);
105
                break;
106
            case '!=':
107
            case '<>':
108
            case 'ne':
109
                return (int)($version1 != $version2);
110
                break;
111
        }
112
        if ($version1 == $version2) {
113
            return 0;
114
        } elseif ($version1 < $version2) {
115
            return -1;
116
        }
117
118
        return 1;
119
    }
120
121
    /**
122
     * @param            $version1
123
     * @param            $version2
124
     * @param  string    $operator
125
     * @return int|mixed
126
     */
127
    public static function version_compare_replacement($version1, $version2, $operator = '')
128
    {
129
        if (function_exists('version_compare')) {
130
            // built into PHP v4.1.0+
131
            return version_compare($version1, $version2, $operator);
132
        }
133
134
        // The function first replaces _, - and + with a dot . in the version strings
135
        $version1 = strtr($version1, '_-+', '...');
136
        $version2 = strtr($version2, '_-+', '...');
137
138
        // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
139
        // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
140
        $version1 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', '$1.$2.$3', $version1);
141
        $version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', '$1.$2.$3', $version2);
142
143
        $parts1      = explode('.', $version1);
144
        $parts2      = explode('.', $version1);
145
        $parts_count = max(count($parts1), count($parts2));
146
        for ($i = 0; $i < $parts_count; $i++) {
147
            $comparison = phpthumb_functions::version_compare_replacement_sub($version1, $version2, $operator);
148
            if ($comparison != 0) {
149
                return $comparison;
150
            }
151
        }
152
153
        return 0;
154
    }
155
156
    /**
157
     * @param $arg
158
     * @return string
159
     */
160
    public static function escapeshellarg_replacement($arg)
161
    {
162
        if (function_exists('escapeshellarg') && !phpthumb_functions::FunctionIsDisabled('escapeshellarg')) {
163
            return escapeshellarg($arg);
164
        }
165
166
        return '\'' . str_replace('\'', '\\\'', $arg) . '\'';
167
    }
168
169
    /**
170
     * @return array
171
     */
172
    public static function phpinfo_array()
173
    {
174
        static $phpinfo_array = array();
175
        if (empty($phpinfo_array)) {
176
            ob_start();
177
            phpinfo();
178
            $phpinfo = ob_get_contents();
179
            ob_end_clean();
180
            $phpinfo_array = explode("\n", $phpinfo);
181
        }
182
183
        return $phpinfo_array;
184
    }
185
186
    /**
187
     * @return array
188
     */
189
    public static function exif_info()
190
    {
191
        static $exif_info = array();
192
        if (empty($exif_info)) {
193
            // based on code by johnschaefer at gmx dot de
194
            // from PHP help on gd_info()
195
            $exif_info     = array(
196
                'EXIF Support'           => '',
197
                'EXIF Version'           => '',
198
                'Supported EXIF Version' => '',
199
                'Supported filetypes'    => ''
200
            );
201
            $phpinfo_array = phpthumb_functions::phpinfo_array();
202 View Code Duplication
            foreach ($phpinfo_array as $line) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
                $line = trim(strip_tags($line));
204
                foreach ($exif_info as $key => $value) {
205
                    if (strpos($line, $key) === 0) {
206
                        $newvalue        = trim(str_replace($key, '', $line));
207
                        $exif_info[$key] = $newvalue;
208
                    }
209
                }
210
            }
211
        }
212
213
        return $exif_info;
214
    }
215
216
    /**
217
     * @param $imagetype
218
     * @return bool|mixed|string
219
     */
220
    public static function ImageTypeToMIMEtype($imagetype)
221
    {
222
        if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
223
            // PHP v4.3.0+
224
            return image_type_to_mime_type($imagetype);
225
        }
226
        static $image_type_to_mime_type = array(
227
            1  => 'image/gif',                     // IMAGETYPE_GIF
228
            2  => 'image/jpeg',                    // IMAGETYPE_JPEG
229
            3  => 'image/png',                     // IMAGETYPE_PNG
230
            4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
231
            5  => 'image/psd',                     // IMAGETYPE_PSD
232
            6  => 'image/bmp',                     // IMAGETYPE_BMP
233
            7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
234
            8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
235
            9  => 'application/octet-stream',      // IMAGETYPE_JPC
236
            10 => 'image/jp2',                     // IMAGETYPE_JP2
237
            11 => 'application/octet-stream',      // IMAGETYPE_JPX
238
            12 => 'application/octet-stream',      // IMAGETYPE_JB2
239
            13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
240
            14 => 'image/iff',                     // IMAGETYPE_IFF
241
            15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
242
            16 => 'image/xbm',                     // IMAGETYPE_XBM
243
244
            'gif'  => 'image/gif',                 // IMAGETYPE_GIF
245
            'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
246
            'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
247
            'png'  => 'image/png',                 // IMAGETYPE_PNG
248
            'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
249
            'ico'  => 'image/x-icon'
250
        );
251
252
        return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
253
    }
254
255
    /**
256
     * @param $width
257
     * @param $height
258
     * @param $angle
259
     * @return array
260
     */
261
    public static function TranslateWHbyAngle($width, $height, $angle)
262
    {
263
        if (($angle % 180) == 0) {
264
            return array($width, $height);
265
        }
266
        $newwidth  = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
267
        $newheight = (abs(sin(deg2rad($angle))) * $width) + (abs(cos(deg2rad($angle))) * $height);
268
269
        return array($newwidth, $newheight);
270
    }
271
272
    /**
273
     * @param $string
274
     * @return string
275
     */
276 View Code Duplication
    public static function HexCharDisplay($string)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
277
    {
278
        $len    = strlen($string);
279
        $output = '';
280
        for ($i = 0; $i < $len; $i++) {
281
            $output .= ' 0x' . str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
282
        }
283
284
        return $output;
285
    }
286
287
    /**
288
     * @param $HexColorString
289
     * @return int
290
     */
291
    public static function IsHexColor($HexColorString)
292
    {
293
        return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
294
    }
295
296
    /**
297
     * @param       $gdimg_hexcolorallocate
298
     * @param       $R
299
     * @param       $G
300
     * @param       $B
301
     * @param  bool $alpha
302
     * @return int
303
     */
304
    public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha = false)
305
    {
306
        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.2', '>=') && ($alpha !== false)) {
307
            return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int)$alpha);
308
        } else {
309
            return imagecolorallocate($gdimg_hexcolorallocate, $R, $G, $B);
310
        }
311
    }
312
313
    /**
314
     * @param       $gdimg_hexcolorallocate
315
     * @param       $HexColorString
316
     * @param  bool $dieOnInvalid
317
     * @param  bool $alpha
318
     * @return int
319
     */
320
    public static function ImageHexColorAllocate(
321
        &$gdimg_hexcolorallocate,
322
        $HexColorString,
323
        $dieOnInvalid = false,
324
        $alpha = false
325
    ) {
326
        if (!is_resource($gdimg_hexcolorallocate)) {
327
            die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
328
        }
329
        if (phpthumb_functions::IsHexColor($HexColorString)) {
330
            $R = hexdec(substr($HexColorString, 0, 2));
331
            $G = hexdec(substr($HexColorString, 2, 2));
332
            $B = hexdec(substr($HexColorString, 4, 2));
333
334
            return phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
335
        }
336
        if ($dieOnInvalid) {
337
            die('Invalid hex color string: "' . $HexColorString . '"');
338
        }
339
340
        return imagecolorallocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
341
    }
342
343
    /**
344
     * @param $hexcolor
345
     * @return string
346
     */
347
    public static function HexColorXOR($hexcolor)
348
    {
349
        return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
350
    }
351
352
    /**
353
     * @param $img
354
     * @param $x
355
     * @param $y
356
     * @return array|bool
357
     */
358
    public static function GetPixelColor(&$img, $x, $y)
359
    {
360
        if (!is_resource($img)) {
361
            return false;
362
        }
363
364
        return @imagecolorsforindex($img, @imagecolorat($img, $x, $y));
365
    }
366
367
    /**
368
     * @param $currentPixel
369
     * @param $targetPixel
370
     * @return int|mixed
371
     */
372
    public static function PixelColorDifferencePercent($currentPixel, $targetPixel)
373
    {
374
        $diff = 0;
375
        foreach ($targetPixel as $channel => $currentvalue) {
376
            $diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
377
        }
378
379
        return $diff * 100;
380
    }
381
382
    /**
383
     * @param $r
384
     * @param $g
385
     * @param $b
386
     * @return float
387
     */
388
    public static function GrayscaleValue($r, $g, $b)
389
    {
390
        return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
391
    }
392
393
    /**
394
     * @param $OriginalPixel
395
     * @return array
396
     */
397
    public static function GrayscalePixel($OriginalPixel)
398
    {
399
        $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
400
401
        return array('red' => $gray, 'green' => $gray, 'blue' => $gray);
402
    }
403
404
    /**
405
     * @param $rgb
406
     * @return int
407
     */
408
    public static function GrayscalePixelRGB($rgb)
409
    {
410
        $r = ($rgb >> 16) & 0xFF;
411
        $g = ($rgb >> 8) & 0xFF;
412
        $b = $rgb & 0xFF;
413
414
        return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
415
    }
416
417
    /**
418
     * @param        $width
419
     * @param        $height
420
     * @param  null  $maxwidth
421
     * @param  null  $maxheight
422
     * @param  bool  $allow_enlarge
423
     * @param  bool  $allow_reduce
424
     * @return mixed
425
     */
426
    public static function ScaleToFitInBox(
427
        $width,
428
        $height,
429
        $maxwidth = null,
430
        $maxheight = null,
431
        $allow_enlarge = true,
432
        $allow_reduce = true
433
    ) {
434
        $maxwidth  = (is_null($maxwidth) ? $width : $maxwidth);
435
        $maxheight = (is_null($maxheight) ? $height : $maxheight);
436
        $scale_x   = 1;
437
        $scale_y   = 1;
438
        if (($width > $maxwidth) || ($width < $maxwidth)) {
439
            $scale_x = ($maxwidth / $width);
440
        }
441
        if (($height > $maxheight) || ($height < $maxheight)) {
442
            $scale_y = ($maxheight / $height);
443
        }
444
        $scale = min($scale_x, $scale_y);
445
        if (!$allow_enlarge) {
446
            $scale = min($scale, 1);
447
        }
448
        if (!$allow_reduce) {
449
            $scale = max($scale, 1);
450
        }
451
452
        return $scale;
453
    }
454
455
    /**
456
     * @param $dst_img
457
     * @param $src_img
458
     * @param $dst_x
459
     * @param $dst_y
460
     * @param $src_x
461
     * @param $src_y
462
     * @param $dst_w
463
     * @param $dst_h
464
     * @param $src_w
465
     * @param $src_h
466
     * @return bool
467
     */
468
    public static function ImageCopyResampleBicubic(
469
        $dst_img,
470
        $src_img,
471
        $dst_x,
472
        $dst_y,
473
        $src_x,
474
        $src_y,
475
        $dst_w,
476
        $dst_h,
477
        $src_w,
478
        $src_h
479
    ) {
480
        // ron at korving dot demon dot nl
481
        // http://www.php.net/imagecopyresampled
482
483
        $scaleX = ($src_w - 1) / $dst_w;
484
        $scaleY = ($src_h - 1) / $dst_h;
485
486
        $scaleX2 = $scaleX / 2.0;
487
        $scaleY2 = $scaleY / 2.0;
488
489
        $isTrueColor = imageistruecolor($src_img);
490
491
        for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
492
            $sY   = $y * $scaleY;
493
            $siY  = (int)$sY;
494
            $siY2 = (int)$sY + $scaleY2;
495
496
            for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
497
                $sX   = $x * $scaleX;
498
                $siX  = (int)$sX;
499
                $siX2 = (int)$sX + $scaleX2;
500
501
                if ($isTrueColor) {
502
                    $c1 = imagecolorat($src_img, $siX, $siY2);
503
                    $c2 = imagecolorat($src_img, $siX, $siY);
504
                    $c3 = imagecolorat($src_img, $siX2, $siY2);
505
                    $c4 = imagecolorat($src_img, $siX2, $siY);
506
507
                    $r = (($c1 + $c2 + $c3 + $c4) >> 2) & 0xFF0000;
508
                    $g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
509
                    $b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
510
                } else {
511
                    $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
512
                    $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
513
                    $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
514
                    $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
515
516
                    $r = ($c1['red'] + $c2['red'] + $c3['red'] + $c4['red']) << 14;
517
                    $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
518
                    $b = ($c1['blue'] + $c2['blue'] + $c3['blue'] + $c4['blue']) >> 2;
519
                }
520
                imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r + $g + $b);
521
            }
522
        }
523
524
        return true;
525
    }
526
527
    /**
528
     * @param $x_size
529
     * @param $y_size
530
     * @return bool
531
     */
532
    public static function ImageCreateFunction($x_size, $y_size)
533
    {
534
        $ImageCreateFunction = 'ImageCreate';
535
        if (phpthumb_functions::gd_version() >= 2.0) {
536
            $ImageCreateFunction = 'ImageCreateTrueColor';
537
        }
538
        if (!function_exists($ImageCreateFunction)) {
539
            return phpthumb::ErrorImage($ImageCreateFunction . '() does not exist - no GD support?');
540
        }
541
        if (($x_size <= 0) || ($y_size <= 0)) {
542
            return phpthumb::ErrorImage('Invalid image dimensions: ' . $ImageCreateFunction . '(' . $x_size . ', ' . $y_size . ')');
543
        }
544
545
        return $ImageCreateFunction(round($x_size), round($y_size));
546
    }
547
548
    /**
549
     * @param       $dst_im
550
     * @param       $src_im
551
     * @param       $dst_x
552
     * @param       $dst_y
553
     * @param       $src_x
554
     * @param       $src_y
555
     * @param       $src_w
556
     * @param       $src_h
557
     * @param  int  $opacity_pct
558
     * @return bool
559
     */
560
    public static function ImageCopyRespectAlpha(
561
        &$dst_im,
562
        &$src_im,
563
        $dst_x,
564
        $dst_y,
565
        $src_x,
566
        $src_y,
567
        $src_w,
568
        $src_h,
569
        $opacity_pct = 100
570
    ) {
571
        $opacipct = $opacity_pct / 100;
572
        for ($x = $src_x; $x < $src_w; $x++) {
573
            for ($y = $src_y; $y < $src_h; $y++) {
574
                $RealPixel    = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
575
                $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
576
                $alphapct     = $OverlayPixel['alpha'] / 127;
577
                $overlaypct   = (1 - $alphapct) * $opacipct;
578
579
                $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe($dst_im, round($RealPixel['red'] * (1 - $overlaypct)) + ($OverlayPixel['red'] * $overlaypct),
580
                                                                            round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
581
                                                                            round($RealPixel['blue'] * (1 - $overlaypct)) + ($OverlayPixel['blue'] * $overlaypct), //$RealPixel['alpha']);
582
                                                                            0);
583
584
                imagesetpixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
585
            }
586
        }
587
588
        return true;
589
    }
590
591
    /**
592
     * @param             $old_width
593
     * @param             $old_height
594
     * @param  bool       $new_width
595
     * @param  bool       $new_height
596
     * @return array|bool
597
     */
598
    public static function ProportionalResize($old_width, $old_height, $new_width = false, $new_height = false)
599
    {
600
        $old_aspect_ratio = $old_width / $old_height;
601
        if (($new_width === false) && ($new_height === false)) {
602
            return false;
603
        } elseif ($new_width === false) {
604
            $new_width = $new_height * $old_aspect_ratio;
605
        } elseif ($new_height === false) {
606
            $new_height = $new_width / $old_aspect_ratio;
607
        }
608
        $new_aspect_ratio = $new_width / $new_height;
609
        if ($new_aspect_ratio == $old_aspect_ratio) {
610
            // great, done
611
        } elseif ($new_aspect_ratio < $old_aspect_ratio) {
612
            // limited by width
613
            $new_height = $new_width / $old_aspect_ratio;
614
        } elseif ($new_aspect_ratio > $old_aspect_ratio) {
615
            // limited by height
616
            $new_width = $new_height * $old_aspect_ratio;
617
        }
618
619
        return array((int)round($new_width), (int)round($new_height));
620
    }
621
622
    /**
623
     * @param $function
624
     * @return bool
625
     */
626
    public static function FunctionIsDisabled($function)
627
    {
628
        static $DisabledFunctions = null;
629
        if (is_null($DisabledFunctions)) {
630
            $disable_functions_local  = explode(',', strtolower(@ini_get('disable_functions')));
631
            $disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
632
            foreach ($disable_functions_local as $key => $value) {
633
                $DisabledFunctions[trim($value)] = 'local';
634
            }
635
            foreach ($disable_functions_global as $key => $value) {
636
                $DisabledFunctions[trim($value)] = 'global';
637
            }
638
            if (@ini_get('safe_mode')) {
639
                $DisabledFunctions['shell_exec']     = 'local';
640
                $DisabledFunctions['set_time_limit'] = 'local';
641
            }
642
        }
643
644
        return isset($DisabledFunctions[strtolower($function)]);
645
    }
646
647
    /**
648
     * @param $command
649
     * @return bool|string
650
     */
651
    public static function SafeExec($command)
652
    {
653
        static $AllowedExecFunctions = array();
654
        if (empty($AllowedExecFunctions)) {
655
            $AllowedExecFunctions = array('shell_exec' => true, 'passthru' => true, 'system' => true, 'exec' => true);
656
            foreach ($AllowedExecFunctions as $key => $value) {
657
                $AllowedExecFunctions[$key] = !phpthumb_functions::FunctionIsDisabled($key);
658
            }
659
        }
660
        $command .= ' 2>&1'; // force redirect stderr to stdout
661
        foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
662
            if (!$is_allowed) {
663
                continue;
664
            }
665
            $returnvalue = false;
666
            switch ($execfunction) {
667
                case 'passthru':
668
                case 'system':
669
                    ob_start();
670
                    $execfunction($command);
671
                    $returnvalue = ob_get_contents();
672
                    ob_end_clean();
673
                    break;
674
675
                case 'exec':
676
                    $output      = array();
677
                    $lastline    = $execfunction($command, $output);
678
                    $returnvalue = implode("\n", $output);
679
                    break;
680
681
                case 'shell_exec':
682
                    ob_start();
683
                    $returnvalue = $execfunction($command);
684
                    ob_end_clean();
685
                    break;
686
            }
687
688
            return $returnvalue;
689
        }
690
691
        return false;
692
    }
693
694
    /**
695
     * @param $filename
696
     * @return array|bool
697
     */
698
    public static function ApacheLookupURIarray($filename)
699
    {
700
        // apache_lookup_uri() only works when PHP is installed as an Apache module.
701
        if (php_sapi_name() == 'apache') {
702
            //$property_exists_exists = function_exists('property_exists');
703
            $keys = array(
704
                'status',
705
                'the_request',
706
                'status_line',
707
                'method',
708
                'content_type',
709
                'handler',
710
                'uri',
711
                'filename',
712
                'path_info',
713
                'args',
714
                'boundary',
715
                'no_cache',
716
                'no_local_copy',
717
                'allowed',
718
                'send_bodyct',
719
                'bytes_sent',
720
                'byterange',
721
                'clength',
722
                'unparsed_uri',
723
                'mtime',
724
                'request_time'
725
            );
726
            if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
727
                $apacheLookupURIarray = array();
728
                foreach ($keys as $key) {
729
                    $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
730
                }
731
732
                return $apacheLookupURIarray;
733
            }
734
        }
735
736
        return false;
737
    }
738
739
    /**
740
     * @return bool|null
741
     */
742
    public static function gd_is_bundled()
743
    {
744
        static $isbundled = null;
745
        if (is_null($isbundled)) {
746
            $gd_info   = gd_info();
747
            $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
748
        }
749
750
        return $isbundled;
751
    }
752
753
    /**
754
     * @param  bool $fullstring
755
     * @return mixed
756
     */
757
    public static function gd_version($fullstring = false)
758
    {
759
        static $cache_gd_version = array();
760
        if (empty($cache_gd_version)) {
761
            $gd_info = gd_info();
762
            if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
763
                $cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
764
                $cache_gd_version[0] = (float)$matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
765
            } else {
766
                $cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
767
                $cache_gd_version[0] = (float)substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
768
            }
769
        }
770
771
        return $cache_gd_version[(int)$fullstring];
772
    }
773
774
    /**
775
     * @param           $remotefile
776
     * @param  int      $timeout
777
     * @return bool|int
778
     */
779
    public static function filesize_remote($remotefile, $timeout = 10)
780
    {
781
        $size = false;
782
        $url  = phpthumb_functions::ParseURLbetter($remotefile);
783
        if ($fp = @fsockopen($url['host'], ($url['port'] ?: 80), $errno, $errstr, $timeout)) {
784
            fwrite($fp, 'HEAD ' . @$url['path'] . @$url['query'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . @$url['host'] . "\r\n\r\n");
785
            if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
786
                stream_set_timeout($fp, $timeout);
787
            }
788
            while (!feof($fp)) {
789
                $headerline = fgets($fp, 4096);
790
                if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
791
                    $size = (int)$matches[1];
792
                    break;
793
                }
794
            }
795
            fclose($fp);
796
        }
797
798
        return $size;
799
    }
800
801
    /**
802
     * @param           $remotefile
803
     * @param  int      $timeout
804
     * @return bool|int
805
     */
806
    public static function filedate_remote($remotefile, $timeout = 10)
807
    {
808
        $date = false;
809
        $url  = phpthumb_functions::ParseURLbetter($remotefile);
810
        if ($fp = @fsockopen($url['host'], ($url['port'] ?: 80), $errno, $errstr, $timeout)) {
811
            fwrite($fp, 'HEAD ' . @$url['path'] . @$url['query'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . @$url['host'] . "\r\n\r\n");
812
            if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
813
                stream_set_timeout($fp, $timeout);
814
            }
815
            while (!feof($fp)) {
816
                $headerline = fgets($fp, 4096);
817
                if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
818
                    $date = strtotime($matches[1]) - date('Z');
819
                    break;
820
                }
821
            }
822
            fclose($fp);
823
        }
824
825
        return $date;
826
    }
827
828
    /**
829
     * @param $filename
830
     * @return bool|string
831
     */
832 View Code Duplication
    public static function md5_file_safe($filename)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
833
    {
834
        // md5_file() doesn't exist in PHP < 4.2.0
835
        if (function_exists('md5_file')) {
836
            return md5_file($filename);
837
        }
838
        if ($fp = @fopen($filename, 'rb')) {
839
            $rawData = '';
840
            do {
841
                $buffer  = fread($fp, 8192);
842
                $rawData .= $buffer;
843
            } while (strlen($buffer) > 0);
844
            fclose($fp);
845
846
            return md5($rawData);
847
        }
848
849
        return false;
850
    }
851
852
    /**
853
     * @return mixed
854
     */
855
    public static function nonempty_min()
856
    {
857
        $arg_list   = func_get_args();
858
        $acceptable = array();
859
        foreach ($arg_list as $arg) {
860
            if ($arg) {
861
                $acceptable[] = $arg;
862
            }
863
        }
864
865
        return min($acceptable);
866
    }
867
868
    /**
869
     * @param         $number
870
     * @param  int    $minbytes
871
     * @return string
872
     */
873
    public static function LittleEndian2String($number, $minbytes = 1)
874
    {
875
        $intstring = '';
876
        while ($number > 0) {
877
            $intstring .= chr($number & 255);
878
            $number    >>= 8;
879
        }
880
881
        return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
882
    }
883
884
    /**
885
     * @return bool
886
     */
887
    public static function OneOfThese()
888
    {
889
        // return the first useful (non-empty/non-zero/non-false) value from those passed
890
        $arg_list = func_get_args();
891
        foreach ($arg_list as $key => $value) {
892
            if ($value) {
893
                return $value;
894
            }
895
        }
896
897
        return false;
898
    }
899
900
    /**
901
     * @param $needle
902
     * @param $haystack
903
     * @return bool
904
     */
905
    public static function CaseInsensitiveInArray($needle, $haystack)
906
    {
907
        $needle = strtolower($needle);
908
        foreach ($haystack as $key => $value) {
909
            if (is_array($value)) {
910
                // skip?
911
            } elseif ($needle == strtolower($value)) {
912
                return true;
913
            }
914
        }
915
916
        return false;
917
    }
918
919
    /**
920
     * @param                   $host
921
     * @param                   $file
922
     * @param                   $errstr
923
     * @param  bool             $successonly
924
     * @param  int              $port
925
     * @param  int              $timeout
926
     * @return bool|null|string
927
     */
928
    public static function URLreadFsock($host, $file, &$errstr, $successonly = true, $port = 80, $timeout = 10)
929
    {
930
        if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
931
            $errstr = 'fsockopen() unavailable';
932
933
            return false;
934
        }
935
        //if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
936
        if ($fp = @fsockopen((($port == 443) ? 'ssl://' : '') . $host, $port, $errno, $errstr, $timeout)) { // https://github.com/JamesHeinrich/phpThumb/issues/39
937
            $out = 'GET ' . $file . ' HTTP/1.0' . "\r\n";
938
            $out .= 'Host: ' . $host . "\r\n";
939
            $out .= 'Connection: Close' . "\r\n\r\n";
940
            fwrite($fp, $out);
941
942
            $isHeader           = true;
943
            $Data_header        = '';
944
            $Data_body          = '';
945
            $header_newlocation = '';
946
            while (!feof($fp)) {
947
                $line = fgets($fp, 1024);
948
                if ($isHeader) {
949
                    $Data_header .= $line;
950
                } else {
951
                    $Data_body .= $line;
952
                }
953
                if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
954
                    list($dummy, $errno, $errstr) = $matches;
955
                    $errno = (int)$errno;
956
                } elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
957
                    $header_newlocation = $matches[1];
958
                }
959
                if ($isHeader && ($line == "\r\n")) {
960
                    $isHeader = false;
961
                    if ($successonly) {
962
                        switch ($errno) {
963
                            case 200:
964
                                // great, continue
965
                                break;
966
967
                            default:
968
                                $errstr = $errno . ' ' . $errstr . ($header_newlocation ? '; Location: ' . $header_newlocation : '');
969
                                fclose($fp);
970
971
                                return false;
972
                                break;
973
                        }
974
                    }
975
                }
976
            }
977
            fclose($fp);
978
979
            return $Data_body;
980
        }
981
982
        return null;
983
    }
984
985
    /**
986
     * @param         $url
987
     * @param  string $queryseperator
988
     * @return string
989
     */
990
    public static function CleanUpURLencoding($url, $queryseperator = '&')
991
    {
992
        if (!preg_match('#^http#i', $url)) {
993
            return $url;
994
        }
995
        $parse_url         = phpthumb_functions::ParseURLbetter($url);
996
        $pathelements      = explode('/', $parse_url['path']);
997
        $CleanPathElements = array();
998
        $TranslationMatrix = array(' ' => '%20');
999
        foreach ($pathelements as $key => $pathelement) {
1000
            $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
1001
        }
1002
        foreach ($CleanPathElements as $key => $value) {
1003
            if ($value === '') {
1004
                unset($CleanPathElements[$key]);
1005
            }
1006
        }
1007
1008
        $queries      = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
1009
        $CleanQueries = array();
1010
        foreach ($queries as $key => $query) {
1011
            @list($param, $value) = explode('=', $query);
1012
            $CleanQueries[] = strtr($param, $TranslationMatrix) . ($value ? '=' . strtr($value, $TranslationMatrix) : '');
1013
        }
1014
        foreach ($CleanQueries as $key => $value) {
1015
            if ($value === '') {
1016
                unset($CleanQueries[$key]);
1017
            }
1018
        }
1019
1020
        $cleaned_url = $parse_url['scheme'] . '://';
1021
        $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'] . (@$parse_url['password'] ? ':' . $parse_url['password'] : '') . '@' : '');
1022
        $cleaned_url .= $parse_url['host'];
1023
        $cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':' . $parse_url['port'] : '');
1024
        $cleaned_url .= '/' . implode('/', $CleanPathElements);
1025
        $cleaned_url .= (@$CleanQueries ? '?' . implode($queryseperator, $CleanQueries) : '');
1026
1027
        return $cleaned_url;
1028
    }
1029
1030
    /**
1031
     * @param $url
1032
     * @return mixed
1033
     */
1034
    public static function ParseURLbetter($url)
1035
    {
1036
        $parsedURL = @parse_url($url);
1037
        if (!@$parsedURL['port']) {
1038
            switch (strtolower(@$parsedURL['scheme'])) {
1039
                case 'ftp':
1040
                    $parsedURL['port'] = 21;
1041
                    break;
1042
                case 'https':
1043
                    $parsedURL['port'] = 443;
1044
                    break;
1045
                case 'http':
1046
                    $parsedURL['port'] = 80;
1047
                    break;
1048
            }
1049
        }
1050
1051
        return $parsedURL;
1052
    }
1053
1054
    /**
1055
     * @param                         $url
1056
     * @param                         $error
1057
     * @param  int                    $timeout
1058
     * @param  bool                   $followredirects
1059
     * @return bool|mixed|null|string
1060
     */
1061
    public static function SafeURLread($url, &$error, $timeout = 10, $followredirects = true)
1062
    {
1063
        $error = '';
1064
1065
        $parsed_url                      = phpthumb_functions::ParseURLbetter($url);
1066
        $alreadyLookedAtURLs[trim($url)] = true;
1067
1068
        while (true) {
1069
            $tryagain = false;
1070
            $rawData  = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'] . '?' . @$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ?: 80), $timeout);
1071
            if (preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
1072
                $matches[1] = trim(@$matches[1]);
1073
                if (!@$alreadyLookedAtURLs[$matches[1]]) {
1074
                    // loop through and examine new URL
1075
                    $error .= 'URL "' . $url . '" redirected to "' . $matches[1] . '"';
1076
1077
                    $tryagain                         = true;
1078
                    $alreadyLookedAtURLs[$matches[1]] = true;
1079
                    $parsed_url                       = phpthumb_functions::ParseURLbetter($matches[1]);
1080
                }
1081
            }
1082
            if (!$tryagain) {
1083
                break;
1084
            }
1085
        }
1086
1087
        if ($rawData === false) {
1088
            $error .= 'Error opening "' . $url . '":' . "\n\n" . $errstr;
1089
1090
            return false;
1091
        } elseif ($rawData === null) {
1092
            // fall through
1093
            $error .= 'Error opening "' . $url . '":' . "\n\n" . $errstr;
1094
        } else {
1095
            return $rawData;
1096
        }
1097
1098
        if (function_exists('curl_version') && !phpthumb_functions::FunctionIsDisabled('curl_exec')) {
1099
            $ch = curl_init();
1100
            curl_setopt($ch, CURLOPT_URL, $url);
1101
            curl_setopt($ch, CURLOPT_HEADER, false);
1102
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1103
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
1104
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);    // changed for XOOPS
1105
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // changed for XOOPS
1106
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1107
            $rawData = curl_exec($ch);
1108
            curl_close($ch);
1109
            if (strlen($rawData) > 0) {
1110
                $error .= 'CURL succeeded (' . strlen($rawData) . ' bytes); ';
1111
1112
                return $rawData;
1113
            }
1114
            $error .= 'CURL available but returned no data; ';
1115
        } else {
1116
            $error .= 'CURL unavailable; ';
1117
        }
1118
1119
        $BrokenURLfopenPHPversions = array('4.4.2');
1120
        if (in_array(PHP_VERSION, $BrokenURLfopenPHPversions)) {
1121
            $error .= 'fopen(URL) broken in PHP v' . PHP_VERSION . '; ';
1122
        } elseif (@ini_get('allow_url_fopen')) {
1123
            $rawData     = '';
1124
            $error_fopen = '';
1125
            ob_start();
1126
            if ($fp = fopen($url, 'rb')) {
1127
                do {
1128
                    $buffer  = fread($fp, 8192);
1129
                    $rawData .= $buffer;
1130
                } while (strlen($buffer) > 0);
1131
                fclose($fp);
1132
            } else {
1133
                $error_fopen .= trim(strip_tags(ob_get_contents()));
1134
            }
1135
            ob_end_clean();
1136
            $error .= $error_fopen;
1137
            if (!$error_fopen) {
1138
                $error .= '; "allow_url_fopen" succeeded (' . strlen($rawData) . ' bytes); ';
1139
1140
                return $rawData;
1141
            }
1142
            $error .= '; "allow_url_fopen" enabled but returned no data (' . $error_fopen . '); ';
1143
        } else {
1144
            $error .= '"allow_url_fopen" disabled; ';
1145
        }
1146
1147
        return false;
1148
    }
1149
1150
    /**
1151
     * @param $dirname
1152
     * @return bool
1153
     */
1154
    public static function EnsureDirectoryExists($dirname)
1155
    {
1156
        $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
1157
        $startoffset        = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
1158
        $open_basedirs      = preg_split('#[;:]#', ini_get('open_basedir'));
1159
        foreach ($open_basedirs as $key => $open_basedir) {
1160
            if (preg_match('#^' . preg_quote($open_basedir) . '#', $dirname)
1161
                && (strlen($dirname) > strlen($open_basedir))
1162
            ) {
1163
                $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
1164
                break;
1165
            }
1166
        }
1167
        $i         = $startoffset;
1168
        $endoffset = count($directory_elements);
1169
        for ($i = $startoffset; $i <= $endoffset; $i++) {
1170
            $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
1171
            if (!$test_directory) {
1172
                continue;
1173
            }
1174
            if (!@is_dir($test_directory)) {
1175
                if (@file_exists($test_directory)) {
1176
                    // directory name already exists as a file
1177
                    return false;
1178
                }
1179
                @mkdir($test_directory, 0755);
1180
                @chmod($test_directory, 0755);
1181
                if (!@is_dir($test_directory) || !@is_writable($test_directory)) {
1182
                    return false;
1183
                }
1184
            }
1185
        }
1186
1187
        return true;
1188
    }
1189
1190
    /**
1191
     * @param $dirname
1192
     * @return array
1193
     */
1194
    public static function GetAllFilesInSubfolders($dirname)
1195
    {
1196
        $AllFiles = array();
1197
        $dirname  = rtrim(realpath($dirname), '/\\');
1198
        if ($dirhandle = @opendir($dirname)) {
1199
            while (($file = readdir($dirhandle)) !== false) {
1200
                $fullfilename = $dirname . DIRECTORY_SEPARATOR . $file;
1201
                if (is_file($fullfilename)) {
1202
                    $AllFiles[] = $fullfilename;
1203
                } elseif (is_dir($fullfilename)) {
1204
                    switch ($file) {
1205
                        case '.':
1206
                        case '..':
1207
                            break;
1208
1209
                        default:
1210
                            $AllFiles[] = $fullfilename;
1211
                            $subfiles   = phpthumb_functions::GetAllFilesInSubfolders($fullfilename);
1212
                            foreach ($subfiles as $filename) {
1213
                                $AllFiles[] = $filename;
1214
                            }
1215
                            break;
1216
                    }
1217
                } else {
1218
                    // ignore?
1219
                }
1220
            }
1221
            closedir($dirhandle);
1222
        }
1223
        sort($AllFiles);
1224
1225
        return array_unique($AllFiles);
1226
    }
1227
1228
    /**
1229
     * @param $filename
1230
     * @return mixed|string
1231
     */
1232
    public static function SanitizeFilename($filename)
1233
    {
1234
        $filename = preg_replace('/[^' . preg_quote(' !#$%^()+,-.;<>=@[]_{}') . 'a-zA-Z0-9]/', '_', $filename);
1235
        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.1.0', '>=')) {
1236
            $filename = trim($filename, '.');
1237
        }
1238
1239
        return $filename;
1240
    }
1241
1242
    /**
1243
     * @param $password
1244
     * @return int
1245
     */
1246
    public static function PasswordStrength($password)
1247
    {
1248
        $strength = 0;
1249
        $strength += strlen(preg_replace('#[^a-z]#', '', $password)) * 0.5; // lowercase characters are weak
1250
        $strength += strlen(preg_replace('#[^A-Z]#', '', $password)) * 0.8; // uppercase characters are somewhat better
1251
        $strength += strlen(preg_replace('#[^0-9]#', '', $password)) * 1.0; // numbers are somewhat better
1252
        $strength += strlen(preg_replace('#[a-zA-Z0-9]#', '', $password)) * 2.0; // other non-alphanumeric characters are best
1253
        return $strength;
1254
    }
1255
}
1256
1257
////////////// END: class phpthumb_functions //////////////
1258
1259
if (!function_exists('gd_info')) {
1260
    // built into PHP v4.3.0+ (with bundled GD2 library)
1261
    /**
1262
     * @return array
1263
     */
1264
    function gd_info()
1265
    {
1266
        static $gd_info = array();
1267
        if (empty($gd_info)) {
1268
            // based on code by johnschaefer at gmx dot de
1269
            // from PHP help on gd_info()
1270
            $gd_info       = array(
1271
                'GD Version'         => '',
1272
                'FreeType Support'   => false,
1273
                'FreeType Linkage'   => '',
1274
                'T1Lib Support'      => false,
1275
                'GIF Read Support'   => false,
1276
                'GIF Create Support' => false,
1277
                'JPG Support'        => false,
1278
                'PNG Support'        => false,
1279
                'WBMP Support'       => false,
1280
                'XBM Support'        => false
1281
            );
1282
            $phpinfo_array = phpthumb_functions::phpinfo_array();
1283 View Code Duplication
            foreach ($phpinfo_array as $line) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1284
                $line = trim(strip_tags($line));
1285
                foreach ($gd_info as $key => $value) {
1286
                    //if (strpos($line, $key) !== false) {
1287
                    if (strpos($line, $key) === 0) {
1288
                        $newvalue      = trim(str_replace($key, '', $line));
1289
                        $gd_info[$key] = $newvalue;
1290
                    }
1291
                }
1292
            }
1293
            if (empty($gd_info['GD Version'])) {
1294
                // probable cause: "phpinfo() disabled for security reasons"
1295
                if (function_exists('ImageTypes')) {
1296
                    $imagetypes = imagetypes();
1297
                    if ($imagetypes & IMG_PNG) {
1298
                        $gd_info['PNG Support'] = true;
1299
                    }
1300
                    if ($imagetypes & IMG_GIF) {
1301
                        $gd_info['GIF Create Support'] = true;
1302
                    }
1303
                    if ($imagetypes & IMG_JPG) {
1304
                        $gd_info['JPG Support'] = true;
1305
                    }
1306
                    if ($imagetypes & IMG_WBMP) {
1307
                        $gd_info['WBMP Support'] = true;
1308
                    }
1309
                }
1310
                // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
1311
                if (function_exists('ImageCreateFromGIF')) {
1312
                    if ($tempfilename = phpthumb::phpThumb_tempnam()) {
1313
                        if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
1314
                            fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
1315
                            fclose($fp_tempfile);
1316
1317
                            // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
1318
                            $gd_info['GIF Read Support'] = (bool)@imagecreatefromgif($tempfilename);
1319
                        }
1320
                        unlink($tempfilename);
1321
                    }
1322
                }
1323
                if (function_exists('ImageCreateTrueColor') && @imagecreatetruecolor(1, 1)) {
1324
                    $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
1325
                } elseif (function_exists('ImageCreate') && @imagecreate(1, 1)) {
1326
                    $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
1327
                }
1328
            }
1329
        }
1330
1331
        return $gd_info;
1332
    }
1333
}
1334
1335
if (!function_exists('is_executable')) {
1336
    // in PHP v3+, but v5.0+ for Windows
1337
    /**
1338
     * @param $filename
1339
     * @return bool
1340
     */
1341
    function is_executable($filename)
1342
    {
1343
        // poor substitute, but better than nothing
1344
        return file_exists($filename);
1345
    }
1346
}
1347
1348
if (!function_exists('preg_quote')) {
1349
    // included in PHP v3.0.9+, but may be unavailable if not compiled in
1350
    /**
1351
     * @param         $string
1352
     * @param  string $delimiter
1353
     * @return string
1354
     */
1355
    function preg_quote($string, $delimiter = '\\')
1356
    {
1357
        static $preg_quote_array = array();
1358
        if (empty($preg_quote_array)) {
1359
            $escapeables = '.\\+*?[^]$(){}=!<>|:';
1360
            for ($i = 0, $iMax = strlen($escapeables); $i < $iMax; $i++) {
1361
                $strtr_preg_quote[$escapeables{$i}] = $delimiter . $escapeables{$i};
1362
            }
1363
        }
1364
1365
        return strtr($string, $strtr_preg_quote);
1366
    }
1367
}
1368
1369
if (!function_exists('file_get_contents')) {
1370
    // included in PHP v4.3.0+
1371
    /**
1372
     * @param $filename
1373
     * @return bool|string
1374
     */
1375 View Code Duplication
    function file_get_contents($filename)
0 ignored issues
show
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1376
    {
1377
        if (preg_match('#^(f|ht)tp\://#i', $filename)) {
1378
            return SafeURLread($filename, $error);
1379
        }
1380
        if ($fp = @fopen($filename, 'rb')) {
1381
            $rawData = '';
1382
            do {
1383
                $buffer  = fread($fp, 8192);
1384
                $rawData .= $buffer;
1385
            } while (strlen($buffer) > 0);
1386
            fclose($fp);
1387
1388
            return $rawData;
1389
        }
1390
1391
        return false;
1392
    }
1393
}
1394
1395
if (!function_exists('file_put_contents')) {
1396
    // included in PHP v5.0.0+
1397
    /**
1398
     * @param $filename
1399
     * @param $filedata
1400
     * @return bool
1401
     */
1402
    function file_put_contents($filename, $filedata)
1403
    {
1404
        if ($fp = @fopen($filename, 'wb')) {
1405
            fwrite($fp, $filedata);
1406
            fclose($fp);
1407
1408
            return true;
1409
        }
1410
1411
        return false;
1412
    }
1413
}
1414
1415
if (!function_exists('imagealphablending')) {
1416
    // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1417
    /**
1418
     * @param       $img
1419
     * @param  bool $blendmode
1420
     * @return bool
1421
     */
1422
    function imagealphablending(&$img, $blendmode = true)
1423
    {
1424
        // do nothing, this function is declared here just to
1425
        // prevent runtime errors if GD2 is not available
1426
        return true;
1427
    }
1428
}
1429
1430
if (!function_exists('imagesavealpha')) {
1431
    // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1432
    /**
1433
     * @param       $img
1434
     * @param  bool $blendmode
1435
     * @return bool
1436
     */
1437
    function imagesavealpha(&$img, $blendmode = true)
1438
    {
1439
        // do nothing, this function is declared here just to
1440
        // prevent runtime errors if GD2 is not available
1441
        return true;
1442
    }
1443
}
1444