Completed
Pull Request — master (#5)
by Michael
02:20
created

SwUploadHandler   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 228
Duplicated Lines 4.82 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 11
loc 228
rs 8.48
c 0
b 0
f 0
wmc 49
lcom 1
cbo 1

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A get_file_object() 0 13 6
B create_thumbnail() 0 39 10
A getFileExtension() 0 5 1
B handle_file_upload() 11 46 11
A get() 0 12 3
B post() 0 39 11
B delete() 0 20 6

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SwUploadHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SwUploadHandler, and based on these observations, apply Extract Interface, too.

1
<?php namespace XoopsModules\Smallworld;
2
3
/**
4
 * You may not change or alter any portion of this comment or credits
5
 * of supporting developers from this source code or any supporting source code
6
 * which is considered copyrighted (c) material of the original comment or credit authors.
7
 *
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 */
12
13
/**
14
 * SmallWorld
15
 *
16
 * @copyright    The XOOPS Project (https://xoops.org)
17
 * @copyright    2011 Culex
18
 * @license      GNU GPL (http://www.gnu.org/licenses/gpl-2.0.html/)
19
 * @package      SmallWorld
20
 * @since        1.0
21
 * @author       Michael Albertsen (http://culex.dk) <[email protected]>
22
 */
23
class SwUploadHandler
24
{
25
    private $upload_dir;
26
    private $upload_url;
27
    private $thumbnails_dir;
28
    private $thumbnails_url;
29
    private $thumbnail_max_width;
30
    private $thumbnail_max_height;
31
    private $field_name;
32
33
    /**
34
     * SwUploadHandler constructor.
35
     * @param $options
36
     */
37
    public function __construct($options)
38
    {
39
        $this->upload_dir           = $options['upload_dir'];
40
        $this->upload_url           = $options['upload_url'];
41
        $this->thumbnails_dir       = $options['thumbnails_dir'];
42
        $this->thumbnails_url       = $options['thumbnails_url'];
43
        $this->thumbnail_max_width  = $options['thumbnail_max_width'];
44
        $this->thumbnail_max_height = $options['thumbnail_max_height'];
45
        $this->field_name           = $options['field_name'];
46
    }
47
48
    /**
49
     * @param $file_name
50
     * @return null|\stdClass
51
     */
52
    private function get_file_object($file_name)
53
    {
54
        $file_path = $this->upload_dir . $file_name;
55
        if (is_file($file_path) && '.' !== $file_name[0] && 'index.html' !== $file_name && 'Thumbs.db' !== $file_name) {
56
            $file            = new \stdClass();
57
            $file->name      = $file_name;
58
            $file->size      = filesize($file_path);
59
            $file->url       = $this->upload_url . rawurlencode($file->name);
60
            $file->thumbnail = is_file($this->thumbnails_dir . $file_name) ? $this->thumbnails_url . rawurlencode($file->name) : null;
61
            return $file;
62
        }
63
        return null;
64
    }
65
66
    /**
67
     * @param $file_name
68
     * @return bool
69
     */
70
    private function create_thumbnail($file_name)
71
    {
72
        $file_path      = $this->upload_dir . $file_name;
73
        $thumbnail_path = $this->thumbnails_dir . $file_name;
74
        list($img_width, $img_height) = @getimagesize($file_path);
75
        if (!$img_width || !$img_height) {
76
            return false;
77
        }
78
        $scale = min($this->thumbnail_max_width / $img_width, $this->thumbnail_max_height / $img_height);
79
        if ($scale > 1) {
80
            $scale = 1;
81
        }
82
        $thumbnail_width  = $img_width * $scale;
83
        $thumbnail_height = $img_height * $scale;
84
        $thumbnail_img    = @imagecreatetruecolor($thumbnail_width, $thumbnail_height);
85
        switch (strtolower(substr(strrchr($file_name, '.'), 1))) {
86
            case 'jpg':
87
            case 'jpeg':
88
                $src_img         = @imagecreatefromjpeg($file_path);
89
                $write_thumbnail = 'imagejpeg';
90
                break;
91
            case 'gif':
92
                $src_img         = @imagecreatefromgif($file_path);
93
                $write_thumbnail = 'imagegif';
94
                break;
95
            case 'png':
96
                $src_img         = @imagecreatefrompng($file_path);
97
                $write_thumbnail = 'imagepng';
98
                break;
99
            default:
100
                $src_img = $write_thumbnail = null;
101
        }
102
        $success = $src_img && @imagecopyresampled($thumbnail_img, $src_img, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $img_width, $img_height)
103
                   && $write_thumbnail($thumbnail_img, $thumbnail_path);
104
        // Free up memory (imagedestroy does not delete files):
105
        @imagedestroy($src_img);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
106
        @imagedestroy($thumbnail_img);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
107
        return $success;
108
    }
109
110
    //function to return file extension from a path or file name
111
112
    /**
113
     * @param $path
114
     * @return mixed
115
     */
116
    public function getFileExtension($path)
117
    {
118
        $parts = pathinfo($path);
119
        return $parts['extension'];
120
    }
121
122
    /**
123
     * @param $uploaded_file
124
     * @param $name
125
     * @param $size
126
     * @param $type
127
     * @param $error
128
     * @return \XoopsModules\Smallworld|\stdClass
129
     */
130
    private function handle_file_upload($uploaded_file, $name, $size, $type, $error)
131
    {
132
        global $xoopsUser;
133
        $file   = new \stdClass();
134
        $db     = new SwDatabase();
135
        $userid = $xoopsUser->getVar('uid');
136
137
        // Generate new name for file
138
        //$file->name = basename(stripslashes($name));
139
        $file->name = time() . mt_rand(0, 99999) . '.' . $this->getFileExtension($name);
140
        $file->size = (int)$size;
141
        $file->type = $type;
142
        $img        = XOOPS_URL . '/uploads/albums_smallworld/' . $userid . '/' . $file->name;
143
144
        // Save to database for later use
145
        $db->saveImage("'', '" . $userid . "', '" . $file->name . "', '" . addslashes($img) . "', '" . time() . "', ''");
146
147
        if (!$error && $file->name) {
148
            if ('.' === $file->name[0]) {
149
                $file->name = substr($file->name, 1);
150
            }
151
            $file_path   = $this->upload_dir . $file->name;
152
            $append_file = is_file($file_path) && $file->size > filesize($file_path);
153
            clearstatcache();
154 View Code Duplication
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
0 ignored issues
show
Duplication introduced by
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...
155
                // multipart/formdata uploads (POST method uploads)
156
                if ($append_file) {
157
                    file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
158
                } else {
159
                    move_uploaded_file($uploaded_file, $file_path);
160
                }
161
            } else {
162
                // Non-multipart uploads (PUT method support)
163
                file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
164
            }
165
            $file_size = filesize($file_path);
166
            if ($file_size === $file->size) {
167
                $file->url       = $this->upload_url . rawurlencode($file->name);
168
                $file->thumbnail = $this->create_thumbnail($file->name) ? $this->thumbnails_url . rawurlencode($file->name) : null;
169
            }
170
            $file->size = $file_size;
171
        } else {
172
            $file->error = $error;
173
        }
174
        return $file;
175
    }
176
177
    public function get()
178
    {
179
        $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
180
        if (null !== $file_name) {
181
            $info = $this->get_file_object($file_name);
182
        } else {
183
            $info = array_values(array_filter(array_map([$this, 'get_file_object'], scandir($this->upload_dir, SCANDIR_SORT_NONE))));
184
        }
185
        header('Cache-Control: no-cache, must-revalidate');
186
        header('Content-type: application/json');
187
        echo json_encode($info);
188
    }
189
190
    public function post()
191
    {
192
        $upload = isset($_FILES[$this->field_name]) ? $_FILES[$this->field_name] : [
193
            'tmp_name' => null,
194
            'name'     => null,
195
            'size'     => null,
196
            'type'     => null,
197
            'error'    => null,
198
        ];
199
        if (is_array($upload['tmp_name']) && count($upload['tmp_name']) > 1) {
200
            $info = [];
201
            foreach ($upload['tmp_name'] as $index => $value) {
202
                $info[] = $this->handle_file_upload($upload['tmp_name'][$index], $upload['name'][$index], $upload['size'][$index], $upload['type'][$index], $upload['error'][$index]);
203
            }
204
        } else {
205
            if (is_array($upload['tmp_name'])) {
206
                $upload = [
207
                    'tmp_name' => $upload['tmp_name'][0],
208
                    'name'     => $upload['name'][0],
209
                    'size'     => $upload['size'][0],
210
                    'type'     => $upload['type'][0],
211
                    'error'    => $upload['error'][0],
212
                ];
213
            }
214
            $info = $this->handle_file_upload(
215
                $upload['tmp_name'],
216
                isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
217
                isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
218
                isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
219
                $upload['error']
220
            );
221
        }
222
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' === $_SERVER['HTTP_X_REQUESTED_WITH']) {
223
            header('Content-type: application/json');
224
        } else {
225
            header('Content-type: text/plain');
226
        }
227
        echo json_encode($info);
228
    }
229
230
    public function delete()
231
    {
232
        global $xoopsUser;
233
        $userid    = $xoopsUser->getVar('uid');
234
        $db        = new SwDatabase();
235
        $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
236
        $file_path = $this->upload_dir . $file_name;
237
        $img       = XOOPS_URL . '/uploads/albums_smallworld/' . $userid . '/' . $file_name;
0 ignored issues
show
Unused Code introduced by
$img is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
238
239
        // Delete file based on user and filename
240
        $db->DeleteImage($userid, $file_name);
241
        $db->DeleteImage($userid, 'Thumbs.db');
242
        $thumbnail_path = $this->thumbnails_dir . $file_name;
243
        $success        = is_file($file_path) && '.' !== $file_name[0] && unlink($file_path);
244
        if ($success && is_file($thumbnail_path)) {
245
            unlink($thumbnail_path);
246
        }
247
        header('Content-type: application/json');
248
        echo json_encode($success);
249
    }
250
}
251