Passed
Push — master ( 2744eb...81ba93 )
by Michael
02:46
created

sf_createThumbnail()   F

Complexity

Conditions 30
Paths 8006

Size

Total Lines 119
Code Lines 83

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 119
rs 2
c 0
b 0
f 0
cc 30
eloc 83
nc 8006
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 25 and the first side effect is on line 22.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
 * You may not change or alter any portion of this comment or credits
4
 * of supporting developers from this source code or any supporting source code
5
 * which is considered copyrighted (c) material of the original comment or credit authors.
6
 *
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
/**
13
 * @copyright      {@link https://xoops.org/ XOOPS Project}
14
 * @license        {@link http://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later}
15
 * @package
16
 * @since
17
 * @author         XOOPS Development Team, phppp (D.J., [email protected])
18
 */
19
20
use XoopsModules\Smartfaq;
21
/** @var Smartfaq\Helper $helper */
22
$helper = Smartfaq\Helper::getInstance();
23
24
if (!defined('NEWBB_FUNCTIONS_IMAGE')) :
25
    define('NEWBB_FUNCTIONS_IMAGE', true);
26
27
    /**
28
     * @param $source
29
     * @return string
30
     */
31
    function sf_attachmentImage($source)
32
    {
33
        /** @var Smartfaq\Helper $helper */
34
        $helper = Smartfaq\Helper::getInstance();
35
36
        $img_path   = XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments');
0 ignored issues
show
Bug introduced by
The constant XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
37
        $img_url    = XOOPS_URL . '/' . $helper->getConfig('dir_attachments');
0 ignored issues
show
Bug introduced by
The constant XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
38
        $thumb_path = $img_path . '/thumbs';
39
        $thumb_url  = $img_url . '/thumbs';
40
41
        $thumb     = $thumb_path . '/' . $source;
42
        $image     = $img_path . '/' . $source;
43
        $thumb_url = $thumb_url . '/' . $source;
44
        $image_url = $img_url . '/' . $source;
45
46
        $imginfo  = @getimagesize($image);
47
        $img_info = (count($imginfo) > 0) ? $imginfo[0] . 'X' . $imginfo[1] . ' px' : '';
0 ignored issues
show
Bug introduced by
It seems like $imginfo can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

47
        $img_info = (count(/** @scrutinizer ignore-type */ $imginfo) > 0) ? $imginfo[0] . 'X' . $imginfo[1] . ' px' : '';
Loading history...
48
49
        if ($helper->getConfig('max_image_width') > 0 && $helper->getConfig('max_image_height') > 0) {
50
            if ($imginfo[0] > $helper->getConfig('max_image_width')
51
                || $imginfo[1] > $helper->getConfig('max_image_height')) {
52
                //if (!file_exists($thumb_path.'/'.$source) && $imginfo[0] > $helper->getConfig('max_img_width')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
53
                if (!file_exists($thumb_path . '/' . $source)) {
54
                    sf_createThumbnail($source, $helper->getConfig('max_image_width'));
55
                }
56
            }
57
58
            if ($imginfo[0] > $helper->getConfig('max_image_width')
59
                || $imginfo[1] > $helper->getConfig('max_image_height')) {
60
                $pseudo_width  = $helper->getConfig('max_image_width');
61
                $pseudo_height = $helper->getConfig('max_image_width') * ($imginfo[1] / $imginfo[0]);
62
                $pseudo_size   = "width='" . $pseudo_width . "px' height='" . $pseudo_height . "px'";
63
            }
64
            // irmtfan to fix Undefined variable: pseudo_height
65
            if (!empty($pseudo_height) && $helper->getConfig('max_image_height') > 0
66
                && $pseudo_height > $helper->getConfig('max_image_height')) {
67
                $pseudo_height = $helper->getConfig('max_image_height');
68
                $pseudo_width  = $helper->getConfig('max_image_height') * ($imginfo[0] / $imginfo[1]);
69
                $pseudo_size   = "width='" . $pseudo_width . "px' height='" . $pseudo_height . "px'";
70
            }
71
        }
72
73
        if (file_exists($thumb)) {
74
            $attachmentImage = '<a href="' . $image_url . '" title="' . $source . ' ' . $img_info . '" target="_blank">';
75
            $attachmentImage .= '<img src="' . $thumb_url . '" alt="' . $source . ' ' . $img_info . '">';
76
            $attachmentImage .= '</a>';
77
        } elseif (!empty($pseudo_size)) {
78
            $attachmentImage = '<a href="' . $image_url . '" title="' . $source . ' ' . $img_info . '" target="_blank">';
79
            $attachmentImage .= '<img src="' . $image_url . '" ' . $pseudo_size . ' alt="' . $source . ' ' . $img_info . '">';
80
            $attachmentImage .= '</a>';
81
        } elseif (file_exists($image)) {
82
            $attachmentImage = '<img src="' . $image_url . '" alt="' . $source . ' ' . $img_info . '">';
83
        } else {
84
            $attachmentImage = '';
85
        }
86
87
        return $attachmentImage;
88
    }
89
90
    /**
91
     * @param $source
92
     * @param $thumb_width
93
     * @return bool
94
     */
95
    function sf_createThumbnail($source, $thumb_width)
96
    {
97
        /** @var Smartfaq\Helper $helper */
98
        $helper = Smartfaq\Helper::getInstance();
99
100
        $img_path   = XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments');
0 ignored issues
show
Bug introduced by
The constant XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
101
        $thumb_path = $img_path . '/thumbs';
102
        $src_file   = $img_path . '/' . $source;
103
        $new_file   = $thumb_path . '/' . $source;
104
        //$imageLibs = sf_getImageLibs();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
105
106
        if (!filesize($src_file) || !is_readable($src_file)) {
107
            return false;
108
        }
109
110
        if (!is_dir($thumb_path) || !is_writable($thumb_path)) {
111
            return false;
112
        }
113
114
        $imginfo = @getimagesize($src_file);
115
116
        if (null === $imginfo) {
117
            return false;
118
        }
119
        if ($imginfo[0] < $thumb_width) {
120
            return false;
121
        }
122
123
        $newWidth  = (int)min($imginfo[0], $thumb_width);
124
        $newHeight = (int)($imginfo[1] * $newWidth / $imginfo[0]);
125
126
        if (1 == $helper->getConfig('image_lib') or 0 == $helper->getConfig('image_lib')) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
127
            if (preg_match("#[A-Z]:|\\\\#Ai", __FILE__)) {
128
                $cur_dir     = __DIR__;
129
                $src_file_im = '"' . $cur_dir . '\\' . str_replace('/', '\\', $src_file) . '"';
130
                $new_file_im = '"' . $cur_dir . '\\' . str_replace('/', '\\', $new_file) . '"';
131
            } else {
132
                $src_file_im = @escapeshellarg($src_file);
133
                $new_file_im = @escapeshellarg($new_file);
134
            }
135
            $path           = empty($helper->getConfig('path_magick')) ? '' : $helper->getConfig('path_magick') . '/';
136
            $magick_command = $path . 'convert -quality 85 -antialias -sample ' . $newWidth . 'x' . $newHeight . ' ' . $src_file_im . ' +profile "*" ' . str_replace('\\', '/', $new_file_im) . '';
137
138
            @passthru($magick_command);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for passthru(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

138
            /** @scrutinizer ignore-unhandled */ @passthru($magick_command);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Bug introduced by
Are you sure the usage of passthru($magick_command) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
139
            if (file_exists($new_file)) {
140
                return true;
141
            }
142
        }
143
144
        if (2 == $helper->getConfig('image_lib') or 0 == $helper->getConfig('image_lib')) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
145
            $path = empty($helper->getConfig('path_netpbm')) ? '' : $helper->getConfig('path_netpbm') . '/';
146
            if (preg_match("/\.png/i", $source)) {
147
                $cmd = $path . "pngtopnm $src_file | " . $path . "pnmscale -xysize $newWidth $newHeight | " . $path . "pnmtopng > $new_file";
148
            } elseif (preg_match("/\.(jpg|jpeg)/i", $source)) {
149
                $cmd = $path . "jpegtopnm $src_file | " . $path . "pnmscale -xysize $newWidth $newHeight | " . $path . "ppmtojpeg -quality=90 > $new_file";
150
            } elseif (preg_match("/\.gif/i", $source)) {
151
                $cmd = $path . "giftopnm $src_file | " . $path . "pnmscale -xysize $newWidth $newHeight | ppmquant 256 | " . $path . "ppmtogif > $new_file";
152
            }
153
154
            @exec($cmd, $output, $retval);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for exec(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

154
            /** @scrutinizer ignore-unhandled */ @exec($cmd, $output, $retval);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Comprehensibility Best Practice introduced by
The variable $cmd does not seem to be defined for all execution paths leading up to this point.
Loading history...
155
            if (file_exists($new_file)) {
156
                return true;
157
            }
158
        }
159
160
        $type            = $imginfo[2];
161
        $supported_types = [];
162
163
        if (!extension_loaded('gd')) {
164
            return false;
165
        }
166
        if (function_exists('imagegif')) {
167
            $supported_types[] = 1;
168
        }
169
        if (function_exists('imagejpeg')) {
170
            $supported_types[] = 2;
171
        }
172
        if (function_exists('imagepng')) {
173
            $supported_types[] = 3;
174
        }
175
176
        $imageCreateFunction = function_exists('imagecreatetruecolor') ? 'imagecreatetruecolor' : 'imagecreate';
177
178
        if (in_array($type, $supported_types)) {
179
            switch ($type) {
180
                case 1:
181
                    if (!function_exists('imagecreatefromgif')) {
182
                        return false;
183
                    }
184
                    $im     = imagecreatefromgif($src_file);
185
                    $new_im = imagecreate($newWidth, $newHeight);
186
                    imagecopyresized($new_im, $im, 0, 0, 0, 0, $newWidth, $newHeight, $imginfo[0], $imginfo[1]);
187
                    imagegif($new_im, $new_file);
188
                    imagedestroy($im);
189
                    imagedestroy($new_im);
190
                    break;
191
                case 2:
192
                    $im     = imagecreatefromjpeg($src_file);
193
                    $new_im = $imageCreateFunction($newWidth, $newHeight);
194
                    imagecopyresized($new_im, $im, 0, 0, 0, 0, $newWidth, $newHeight, $imginfo[0], $imginfo[1]);
195
                    imagejpeg($new_im, $new_file, 90);
196
                    imagedestroy($im);
197
                    imagedestroy($new_im);
198
                    break;
199
                case 3:
200
                    $im     = imagecreatefrompng($src_file);
201
                    $new_im = $imageCreateFunction($newWidth, $newHeight);
202
                    imagecopyresized($new_im, $im, 0, 0, 0, 0, $newWidth, $newHeight, $imginfo[0], $imginfo[1]);
203
                    imagepng($new_im, $new_file);
204
                    imagedestroy($im);
205
                    imagedestroy($new_im);
206
                    break;
207
            }
208
        }
209
210
        if (file_exists($new_file)) {
211
            return true;
212
        } else {
213
            return false;
214
        }
215
    }
216
217
endif;
218