FineimpuploadHandler::storeUploadedFile()   C
last analyzed

Complexity

Conditions 16
Paths 157

Size

Total Lines 81
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 16
eloc 53
nc 157
nop 3
dl 0
loc 81
rs 5.0916
c 1
b 0
f 0

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
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Tdmdownloads\Common;
6
7
use XoopsModules\Tdmdownloads\{
8
    Helper,
9
    Utility
10
};
11
12
/**
13
 * SystemFineImUploadHandler class to work with ajaxfineupload.php endpoint
14
 * to facilitate uploads for the system image manager
15
 *
16
 * Do not use or reference this directly from your client-side code.
17
 * Instead, this should be required via the endpoint.php or endpoint-cors.php
18
 * file(s).
19
 *
20
 * @license   MIT License (MIT)
21
 * @copyright Copyright (c) 2015-present, Widen Enterprises, Inc.
22
 * @link      https://github.com/FineUploader/php-traditional-server
23
 *
24
 * The MIT License (MIT)
25
 *
26
 * Copyright (c) 2015-present, Widen Enterprises, Inc.
27
 *
28
 * Permission is hereby granted, free of charge, to any person obtaining a copy
29
 * of this software and associated documentation files (the "Software"), to deal
30
 * in the Software without restriction, including without limitation the rights
31
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32
 * copies of the Software, and to permit persons to whom the Software is
33
 * furnished to do so, subject to the following conditions:
34
 *
35
 * The above copyright notice and this permission notice shall be included in all
36
 * copies or substantial portions of the Software.
37
 *
38
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44
 * SOFTWARE.
45
 */
46
//class FineImpUploadHandler extends \SystemFineUploadHandler
47
48
/**
49
 * Class FineimpuploadHandler
50
 * @package XoopsModules\Tdmdownloads\Common
51
 */
52
class FineimpuploadHandler extends \SystemFineUploadHandler
53
{
54
    /**
55
     * @var int
56
     */
57
    private $permUseralbum = 0;
58
    /**
59
     * @var int
60
     */
61
    private $imageId = 0;
62
    /**
63
     * @var string
64
     */
65
    private $imageName = null;
66
    /**
67
     * @var string
68
     */
69
    private $imageNameLarge = null;
70
    /**
71
     * @var string
72
     */
73
    private $imageNicename = null;
74
    /**
75
     * @var string
76
     */
77
    private $imagePath = null;
78
    /**
79
     * @var string
80
     */
81
    private $imageNameOrig = null;
82
    /**
83
     * @var string
84
     */
85
    private $imageMimetype = null;
86
    /**
87
     * @var int
88
     */
89
    private $imageSize = 0;
90
    /**
91
     * @var int
92
     */
93
    private $imageWidth = 0;
94
    /**
95
     * @var int
96
     */
97
    private $imageHeight = 0;
98
    /**
99
     * @var string
100
     */
101
    private $pathUpload = null;
102
103
    /**
104
     * XoopsFineImUploadHandler constructor.
105
     * @param \stdClass $claims claims passed in JWT header
106
     */
107
    public function __construct(\stdClass $claims)
108
    {
109
        parent::__construct($claims);
110
        $this->allowedMimeTypes  = ['image/gif', 'image/jpeg', 'image/png', 'application/zip'];
111
        $this->allowedExtensions = ['gif', 'jpeg', 'jpg', 'png', 'zip'];
112
    }
113
114
    /**
115
     * @param $target
116
     * @param $mimeType
117
     * @param $uid
118
     * @return array|bool
119
     */
120
    protected function storeUploadedFile($target, $mimeType, $uid)
121
    {
122
        $moduleDirName      = \basename(\dirname(__DIR__, 2));
123
        $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
124
        require_once XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/header.php';
125
        $this->pathUpload = \constant($moduleDirNameUpper . '_' . 'UPLOAD_IMAGE_PATH');
126
        $utility          = new Utility();
127
        $helper = Helper::getInstance();
128
        //        if ( WGGALLERY_PERM_SUBMITAPPR === $permissionsHandler->permGlobalSubmit()) {
129
        //            $this->permUseralbum = WGGALLERY_STATE_APPROVAL_VAL;
130
        //        } else {
131
        //            $this->permUseralbum = WGGALLERY_STATE_ONLINE_VAL;
132
        //        }
133
        $this->permUseralbum  = 1; //TODO: handle an option, whether images should be online immediately or not
134
        $pathParts            = \pathinfo($this->getName());
0 ignored issues
show
Bug introduced by
It seems like $this->getName() can also be of type array and null; however, parameter $path of pathinfo() does only seem to accept string, 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

134
        $pathParts            = \pathinfo(/** @scrutinizer ignore-type */ $this->getName());
Loading history...
135
        $this->imageName      = \uniqid('img', true) . '.' . \mb_strtolower($pathParts['extension']);
136
        $this->imageNicename  = \str_replace(['_', '-'], ' ', $pathParts['filename']);
137
        $this->imageNameLarge = \uniqid('imgl', true) . '.' . \mb_strtolower($pathParts['extension']);
138
        $this->imagePath      = $this->pathUpload . '/large/' . $this->imageNameLarge;
139
        if (!\move_uploaded_file($_FILES[$this->inputName]['tmp_name'], $this->imagePath)) {
140
            return false;
141
        }
142
        $this->imageNameOrig = $_FILES[$this->inputName]['name'];
143
        $this->imageMimetype = $_FILES[$this->inputName]['type'];
144
        $this->imageSize     = $_FILES[$this->inputName]['size'];
145
        $ret                 = $this->handleImageDB();
146
        if (!$ret) {
147
            return [
148
                'error' => \sprintf(\_FAILSAVEIMG, $this->imageNicename),
149
            ];
150
        }
151
        // load watermark settings
152
        $albumObj  = $albumsHandler->get($this->claims->cat);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $albumsHandler seems to be never defined.
Loading history...
153
        $wmId      = $albumObj->getVar('alb_wmid');
154
        $wmTargetM = false;
155
        $wmTargetL = false;
156
        if ($wmId > 0) {
157
            $watermarksObj = $watermarksHandler->get($wmId);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $watermarksHandler does not exist. Did you maybe mean $watermarksObj?
Loading history...
158
            $wmTarget      = $watermarksObj->getVar('wm_target');
159
            if (\constant($moduleDirNameUpper . '_' . 'WATERMARK_TARGET_A') === $wmTarget || \constant($moduleDirNameUpper . '_' . 'WATERMARK_TARGET_M') === $wmTarget) {
160
                $wmTargetM = true;
161
            }
162
            if (\constant($moduleDirNameUpper . '_' . 'WATERMARK_TARGET_A') === $wmTarget || \constant($moduleDirNameUpper . '_' . 'WATERMARK_TARGET_L') === $wmTarget) {
163
                $wmTargetL = true;
164
            }
165
        }
166
        // create medium image
167
        // $ret = $this->resizeImage($this->pathUpload . '/medium/' . $this->imageName, $helper->getConfig('maxwidth_medium'), $helper->getConfig('maxheight_medium'));
168
        $ret = $utility->resizeImage($this->imagePath, $this->pathUpload . '/medium/' . $this->imageName, $helper->getConfig('maxwidth_medium'), $helper->getConfig('maxheight_medium'), $this->imageMimetype);
0 ignored issues
show
Bug introduced by
The method resizeImage() does not exist on XoopsModules\Tdmdownloads\Utility. ( Ignorable by Annotation )

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

168
        /** @scrutinizer ignore-call */ 
169
        $ret = $utility->resizeImage($this->imagePath, $this->pathUpload . '/medium/' . $this->imageName, $helper->getConfig('maxwidth_medium'), $helper->getConfig('maxheight_medium'), $this->imageMimetype);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
169
        if (false === $ret) {
170
            return ['error' => \sprintf(\constant($moduleDirNameUpper . '_' . 'FAILSAVEIMG_MEDIUM'), $this->imageNicename)];
171
        }
172
        if ('copy' === $ret) {
173
            \copy($this->pathUpload . '/large/' . $this->imageNameLarge, $this->pathUpload . '/medium/' . $this->imageName);
174
        }
175
        // create thumb
176
        // $ret = $this->resizeImage($this->pathUpload . '/thumbs/' . $this->imageName, $helper->getConfig('maxwidth_thumbs'), $helper->getConfig('maxheight_thumbs'));
177
        $ret = $utility->resizeImage($this->imagePath, $this->pathUpload . '/thumbs/' . $this->imageName, $helper->getConfig('maxwidth_thumbs'), $helper->getConfig('maxheight_thumbs'), $this->imageMimetype);
178
        if (false === $ret) {
179
            return ['error' => \sprintf(\constant($moduleDirNameUpper . '_' . 'FAILSAVEIMG_THUMBS'), $this->imageNicename)];
180
        }
181
        if ('copy' === $ret) {
182
            \copy($this->pathUpload . '/large/' . $this->imageNameLarge, $this->pathUpload . '/thumbs/' . $this->imageName);
183
        }
184
        // add watermark to large image
185
        if ($wmTargetL) {
186
            $imgWm = $this->pathUpload . '/large/' . $this->imageNameLarge;
187
            $resWm = $watermarksHandler->watermarkImage($wmId, $imgWm, $imgWm);
188
            if (true !== $resWm) {
189
                return ['error' => \sprintf(\constant($moduleDirNameUpper . '_' . 'FAILSAVEWM_LARGE'), $this->imageNicename, $resWm)];
190
            }
191
        }
192
        // add watermark to medium image
193
        if ($wmTargetM) {
194
            $imgWm = $this->pathUpload . '/medium/' . $this->imageName;
195
            $resWm = $watermarksHandler->watermarkImage($wmId, $imgWm, $imgWm);
196
            if (true !== $resWm) {
197
                return ['error' => \sprintf(\constant($moduleDirNameUpper . '_' . 'FAILSAVEWM_MEDIUM'), $this->imageNicename, $resWm)];
198
            }
199
        }
200
        return ['success' => true, 'uuid' => $uuid];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $uuid does not exist. Did you maybe mean $uid?
Loading history...
201
    }
202
203
    /**
204
     * @return bool
205
     */
206
    private function handleImageDB()
207
    {
208
        $moduleDirName = \basename(\dirname(__DIR__, 2));
209
        require_once XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/header.php';
210
        global $xoopsUser;
211
        $this->getImageDim();
212
        $helper        = Helper::getInstance();
213
        /** @var \XoopsModules\Tdmdownloads\Common\ImagesHandler $imagesHandler */
214
        $imagesHandler = $helper->getHandler('Images');
215
        //        $imagesHandler = new \XoopsModules\Tdmdownloads\Common\ImagesHandler();
216
        $imagesObj = $imagesHandler->create();
217
        // Set Vars
218
        $imagesObj->setVar('img_title', $this->imageNicename);
219
        $imagesObj->setVar('img_desc', '');
220
        $imagesObj->setVar('img_name', $this->imageName);
221
        $imagesObj->setVar('img_namelarge', $this->imageNameLarge);
222
        $imagesObj->setVar('img_nameorig', $this->imageNameOrig);
223
        $imagesObj->setVar('img_mimetype', $this->imageMimetype);
224
        $imagesObj->setVar('img_size', $this->imageSize);
225
        $imagesObj->setVar('img_resx', $this->imageWidth);
226
        $imagesObj->setVar('img_resy', $this->imageHeight);
227
        $imagesObj->setVar('img_albid', $this->claims->cat);
228
        $imagesObj->setVar('img_state', $this->permUseralbum);
229
        $imagesObj->setVar('img_date', \time());
230
        $imagesObj->setVar('img_submitter', $xoopsUser->id());
231
        $imagesObj->setVar('img_ip', $_SERVER['REMOTE_ADDR']);
232
        // Insert Data
233
        if ($imagesHandler->insert($imagesObj)) {
234
            $this->imageId = $imagesHandler->getInsertId();
235
            return true;
236
        }
237
        return false;
238
    }
239
240
    /**
241
     * @return bool|string
242
     */
243
    private function getImageDim()
244
    {
245
        switch ($this->imageMimetype) {
246
            case 'image/png':
247
                $img = \imagecreatefrompng($this->imagePath);
248
                break;
249
            case 'image/jpeg':
250
                $img = \imagecreatefromjpeg($this->imagePath);
251
                break;
252
            case 'image/gif':
253
                $img = \imagecreatefromgif($this->imagePath);
254
                break;
255
            case 'application/zip':
256
                $this->imageWidth  = 0;
257
                $this->imageHeight = 0;
258
                //                $img = imagecreatefromgif($this->imagePath);
259
                break;
260
            default:
261
                $this->imageWidth  = 0;
262
                $this->imageHeight = 0;
263
                return 'Unsupported format';
264
        }
265
        $this->imageWidth  = \imagesx($img);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $img does not seem to be defined for all execution paths leading up to this point.
Loading history...
266
        $this->imageHeight = \imagesy($img);
267
        \imagedestroy($img);
268
        return true;
269
    }
270
}
271