Issues (621)

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.

class/SwUploadHandler.php (10 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
namespace XoopsModules\Smallworld;
4
5
/**
6
 * You may not change or alter any portion of this comment or credits
7
 * of supporting developers from this source code or any supporting source code
8
 * which is considered copyrighted (c) material of the original comment or credit authors.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
/**
16
 * SmallWorld
17
 *
18
 * @copyright    The XOOPS Project (https://xoops.org)
19
 * @copyright    2011 Culex
20
 * @license      GNU GPL (http://www.gnu.org/licenses/gpl-2.0.html/)
21
 * @package      SmallWorld
22
 * @since        1.0
23
 * @author       Michael Albertsen (http://culex.dk) <[email protected]>
24
 */
25
class SwUploadHandler
26
{
27
    private $upload_dir;
28
    private $upload_url;
29
    private $thumbnails_dir;
30
    private $thumbnails_url;
31
    private $thumbnail_max_width;
32
    private $thumbnail_max_height;
33
    private $field_name;
34
35
    /**
36
     * SwUploadHandler constructor.
37
     * @param $options
38
     */
39 View Code Duplication
    public function __construct($options)
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...
40
    {
41
        $this->upload_dir           = $options['upload_dir'];
42
        $this->upload_url           = $options['upload_url'];
43
        $this->thumbnails_dir       = $options['thumbnails_dir'];
44
        $this->thumbnails_url       = $options['thumbnails_url'];
45
        $this->thumbnail_max_width  = $options['thumbnail_max_width'];
46
        $this->thumbnail_max_height = $options['thumbnail_max_height'];
47
        $this->field_name           = $options['field_name'];
48
    }
49
50
    /**
51
     * @param $file_name
52
     * @return null|\stdClass
53
     */
54 View Code Duplication
    private function get_file_object($file_name)
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...
55
    {
56
        $file_path = $this->upload_dir . $file_name;
57
        if (is_file($file_path) && '.' !== $file_name[0] && 'index.html' !== $file_name && 'Thumbs.db' !== $file_name) {
58
            $file            = new \stdClass();
59
            $file->name      = $file_name;
60
            $file->size      = filesize($file_path);
61
            $file->url       = $this->upload_url . rawurlencode($file->name);
62
            $file->thumbnail = is_file($this->thumbnails_dir . $file_name) ? $this->thumbnails_url . rawurlencode($file->name) : null;
63
64
            return $file;
65
        }
66
67
        return null;
68
    }
69
70
    /**
71
     * @param $file_name
72
     * @return bool
73
     */
74 View Code Duplication
    private function create_thumbnail($file_name)
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...
75
    {
76
        $file_path      = $this->upload_dir . $file_name;
77
        $thumbnail_path = $this->thumbnails_dir . $file_name;
78
        list($img_width, $img_height) = @getimagesize($file_path);
79
        if (!$img_width || !$img_height) {
80
            return false;
81
        }
82
        $scale = min($this->thumbnail_max_width / $img_width, $this->thumbnail_max_height / $img_height);
83
        if ($scale > 1) {
84
            $scale = 1;
85
        }
86
        $thumbnail_width  = $img_width * $scale;
87
        $thumbnail_height = $img_height * $scale;
88
        $thumbnail_img    = @imagecreatetruecolor($thumbnail_width, $thumbnail_height);
89
        switch (mb_strtolower(mb_substr(mb_strrchr($file_name, '.'), 1))) {
90
            case 'jpg':
91
            case 'jpeg':
92
                $src_img         = @imagecreatefromjpeg($file_path);
93
                $write_thumbnail = 'imagejpeg';
94
                break;
95
            case 'gif':
96
                $src_img         = @imagecreatefromgif($file_path);
97
                $write_thumbnail = 'imagegif';
98
                break;
99
            case 'png':
100
                $src_img         = @imagecreatefrompng($file_path);
101
                $write_thumbnail = 'imagepng';
102
                break;
103
            default:
104
                $src_img = $write_thumbnail = null;
105
        }
106
        $success = $src_img && @imagecopyresampled($thumbnail_img, $src_img, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $img_width, $img_height)
107
                   && $write_thumbnail($thumbnail_img, $thumbnail_path);
108
        // Free up memory (imagedestroy does not delete files):
109
        @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...
110
        @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...
111
112
        return $success;
113
    }
114
115
    //function to return file extension from a path or file name
116
117
    /**
118
     * @param $path
119
     * @return mixed
120
     */
121
    public function getFileExtension($path)
122
    {
123
        $parts = pathinfo($path);
124
125
        return $parts['extension'];
126
    }
127
128
    /**
129
     * @param $uploaded_file
130
     * @param $name
131
     * @param $size
132
     * @param $type
133
     * @param $error
134
     * @return \stdClass|bool  false if not XOOPS user
135
     */
136
    private function handle_file_upload($uploaded_file, $name, $size, $type, $error)
137
    {
138
        $file   = new \stdClass();
139
        $swDB   = new SwDatabase();
140
        $userid = ($GLOBALS['xoopsUser'] && ($GLOBALS['xoopsUser'] instanceof \XoopsUser)) ? $GLOBALS['xoopsUser']->uid() : 0;
0 ignored issues
show
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
141
142
        if (0 == $userid) {
143
            return false;
144
        }
145
        // Generate new name for file
146
        //$file->name = basename(stripslashes($name));
147
        $file->name = time() . mt_rand(0, 99999) . '.' . $this->getFileExtension($name);
148
        $file->size = (int)$size;
149
        $file->type = $type;
150
        $img        = XOOPS_URL . '/uploads/albums_smallworld/' . $userid . '/' . $file->name;
151
152
        // Save to database for later use
153
        $swDB->saveImage("null, '" . $userid . "', '" . $file->name . "', '" . addslashes($img) . "', '" . time() . "', ''");
154
155 View Code Duplication
        if (!$error && $file->name) {
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...
156
            if ('.' === $file->name[0]) {
157
                $file->name = mb_substr($file->name, 1);
158
            }
159
            $file_path   = $this->upload_dir . $file->name;
160
            $append_file = is_file($file_path) && $file->size > filesize($file_path);
161
            clearstatcache();
162
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
163
                // multipart/formdata uploads (POST method uploads)
164
                if ($append_file) {
165
                    file_put_contents($file_path, fopen($uploaded_file, 'rb'), FILE_APPEND);
166
                } else {
167
                    move_uploaded_file($uploaded_file, $file_path);
168
                }
169
            } else {
170
                // Non-multipart uploads (PUT method support)
171
                file_put_contents($file_path, fopen('php://input', 'rb'), $append_file ? FILE_APPEND : 0);
172
            }
173
            $file_size = filesize($file_path);
174
            if ($file_size === $file->size) {
175
                $file->url       = $this->upload_url . rawurlencode($file->name);
176
                $file->thumbnail = $this->create_thumbnail($file->name) ? $this->thumbnails_url . rawurlencode($file->name) : null;
177
            }
178
            $file->size = $file_size;
179
        } else {
180
            $file->error = $error;
181
        }
182
183
        return $file;
184
    }
185
186 View Code Duplication
    public function get()
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...
187
    {
188
        $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
189
        if (null !== $file_name) {
190
            $info = $this->get_file_object($file_name);
191
        } else {
192
            $info = array_values(array_filter(array_map([$this, 'get_file_object'], scandir($this->upload_dir, SCANDIR_SORT_NONE))));
193
        }
194
        header('Cache-Control: no-cache, must-revalidate');
195
        header('Content-type: application/json');
196
        echo json_encode($info);
197
    }
198
199 View Code Duplication
    public function post()
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...
200
    {
201
        $upload = isset($_FILES[$this->field_name]) ? $_FILES[$this->field_name] : [
202
            'tmp_name' => null,
203
            'name'     => null,
204
            'size'     => null,
205
            'type'     => null,
206
            'error'    => null,
207
        ];
208
        if (is_array($upload['tmp_name']) && count($upload['tmp_name']) > 1) {
209
            $info = [];
210
            foreach ($upload['tmp_name'] as $index => $value) {
211
                $info[] = $this->handle_file_upload($upload['tmp_name'][$index], $upload['name'][$index], $upload['size'][$index], $upload['type'][$index], $upload['error'][$index]);
212
            }
213
        } else {
214
            if (is_array($upload['tmp_name'])) {
215
                $upload = [
216
                    'tmp_name' => $upload['tmp_name'][0],
217
                    'name'     => $upload['name'][0],
218
                    'size'     => $upload['size'][0],
219
                    'type'     => $upload['type'][0],
220
                    'error'    => $upload['error'][0],
221
                ];
222
            }
223
            $info = $this->handle_file_upload(
224
                $upload['tmp_name'],
225
                isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
226
                isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
227
                isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
228
                $upload['error']
229
            );
230
        }
231
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' === $_SERVER['HTTP_X_REQUESTED_WITH']) {
232
            header('Content-type: application/json');
233
        } else {
234
            header('Content-type: text/plain');
235
        }
236
        echo json_encode($info);
237
    }
238
239
    public function delete()
240
    {
241
        $userid = ($GLOBALS['xoopsUser'] && ($GLOBALS['xoopsUser'] instanceof \XoopsUser)) ? $GLOBALS['xoopsUser']->uid() : 0;
0 ignored issues
show
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
242
243
        if (0 == $userid) {
244
            return false;
245
        }
246
        $swDB      = new SwDatabase();
247
        $file_name = isset($_REQUEST['file']) ? basename(stripslashes($_REQUEST['file'])) : null;
248
        $file_path = $this->upload_dir . $file_name;
249
        //$img       = XOOPS_URL . '/uploads/albums_smallworld/' . $userid . '/' . $file_name;
250
251
        // Delete file based on user and filename
252
        $swDB->deleteImage($userid, $file_name);
253
        $swDB->deleteImage($userid, 'Thumbs.db');
254
        $thumbnail_path = $this->thumbnails_dir . $file_name;
255
        $success        = is_file($file_path) && '.' !== $file_name[0] && unlink($file_path);
256
        if ($success && is_file($thumbnail_path)) {
257
            unlink($thumbnail_path);
258
        }
259
        header('Content-type: application/json');
260
        echo json_encode($success);
261
    }
262
}
263