getFormUploadImage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 21
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 31
rs 9.584
1
<?php
2
3
declare(strict_types=1);
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
 * wg Image Editor for xoops
17
 *
18
 * @copyright      xoops
19
 * @license        GPL 2.0 or later
20
 * @package        general
21
 * @author         Wedega - Email:<[email protected]> - Website:<https://wedega.com>
22
 * @version        1.1 image_editor.php XOOPS Project (www.xoops.org) $
23
 */
24
25
use Xmf\Request;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Request. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
26
use XoopsModules\Wgevents;
27
use XoopsModules\Wgevents\{
28
    Constants,
29
    Utility,
30
    Common\Resizer
31
};
32
33
include __DIR__ . '/header.php';
34
$GLOBALS['xoopsOption']['template_main'] = 'wgevents_image_editor.tpl';
35
36
require_once \XOOPS_ROOT_PATH . '/header.php';
37
38
$utility = new \XoopsModules\Wgevents\Utility();
39
40
$op         = Request::getString('op', 'list');
41
$sourceId   = Request::getInt('id', Request::getInt('imageIdCrop'));
42
$origin     = Request::getString('imageOrigin');
43
$start      = Request::getInt('start');
44
$limit      = Request::getInt('limit', $helper->getConfig('userpager'));
45
$img_resize = Request::getInt('img_resize');
46
47
$uid = $xoopsUser instanceof \XoopsUser ? $xoopsUser->id() : 0;
48
49
// get all objects/classes/vars needed for image editor
50
$imageClass = 0; //identifier for different image classes; currently not used
51
$imgCurrent = [];
52
53
//if ($imageClass === Constants::IMAGECLASS_MEMBER) {
54
    $imageId      = $sourceId;
55
    $imageHandler = $eventHandler;
56
    $imageObj     = $eventHandler->get($sourceId);
57
    $imageOrigin  = 'id';
58
    $imgName  = \mb_substr(\str_replace(' ', '', $imageObj->getVar('name')), 0, 20) . '.jpg';
59
    $imageDir = '/uploads/wgevents/events/logos/' . $imageObj->getVar('submitter') . '/';
60
    $imgPath  = \XOOPS_ROOT_PATH . $imageDir;
61
    $imgUrl   = \XOOPS_URL . $imageDir;
62
    $imgFinal = $imgPath . $imgName;
63
    $imgTemp  = \WGEVENTS_UPLOAD_PATH . '/temp/' . $imgName;
64
    $redir    = 'event.php?op=list&amp;start=' . $start . '&amp;limit=' . $limit;
65
    $nameObj  = 'title';
66
    $fieldObj = 'logo';
67
    $submObj  = 'submitter';
68
/*
69
} else {
70
    // only used if image editor is used for different source
71
    // TODO: maybe for categories
72
}
73
*/
74
75
$imgCurrent['img_name'] = $imageObj->getVar($fieldObj);
76
$imgCurrent['src'] = $imgUrl . $imageObj->getVar($fieldObj);
77
$imgCurrent['origin'] = $imageClass;
78
$images = [];
79
80
$image_array = \XoopsLists::getImgListAsArray($imgPath);
81
$i = 0;
82
foreach ($image_array as $image_img) {
83
    if ('blank.gif' !== $image_img) {
84
        $i++;
85
        $images[$i]['id'] = 'imageSelect'.$i;
86
        $images[$i]['name'] = $image_img;
87
        $images[$i]['title'] = $image_img;
88
        $images[$i]['origin'] = 0; //identifier for different image classes; currently not used
89
        if ($imgCurrent['img_name'] === $image_img) {
90
            $images[$i]['selected'] = 1;
91
        }
92
        $images[$i]['src'] = $imgUrl . $image_img;
93
    }
94
}
95
// var_dump($images);
96
$GLOBALS['xoopsTpl']->assign('images', $images);
97
unset($images);
98
// end: get all objects/classes/vars needed for image editor
99
100
// Define Stylesheet
101
$GLOBALS['xoTheme']->addStylesheet(\WGEVENTS_URL . '/assets/css/style.css');
102
$GLOBALS['xoTheme']->addStylesheet(\WGEVENTS_URL . '/assets/css/cropper/imageeditor.css');
103
104
// add scripts
105
//$GLOBALS['xoTheme']->addScript(\XOOPS_URL . '/modules/wgevents/assets/js/admin.js');
106
107
// assign vars
108
$GLOBALS['xoopsTpl']->assign('wgevents_url', \WGEVENTS_URL);
109
$GLOBALS['xoopsTpl']->assign('wgevents_icon_url_16', \WGEVENTS_ICONS_URL . '/16');
110
$GLOBALS['xoopsTpl']->assign('wgevents_icon_url_32', \WGEVENTS_ICONS_URL . '/32');
111
$GLOBALS['xoopsTpl']->assign('wgevents_upload_url', \WGEVENTS_UPLOAD_URL);
112
$GLOBALS['xoopsTpl']->assign('wgevents_upload_path', \WGEVENTS_UPLOAD_PATH);
113
$GLOBALS['xoopsTpl']->assign('wgevents_image_editor', \WGEVENTS_URL);
114
$GLOBALS['xoopsTpl']->assign('wgevents_upload_image_url', $imgUrl);
115
$GLOBALS['xoopsTpl']->assign('gridtarget', $imgName);
116
$GLOBALS['xoopsTpl']->assign('imgCurrent', $imgCurrent);
117
$GLOBALS['xoopsTpl']->assign('imageId', $imageId);
118
$GLOBALS['xoopsTpl']->assign('imageOrigin', $imageOrigin);
119
$GLOBALS['xoopsTpl']->assign('start', $start);
120
$GLOBALS['xoopsTpl']->assign('limit', $limit);
121
122
// Breadcrumbs
123
$xoBreadcrumbs[] = ['title' => \_MA_WGEVENTS_INDEX, 'link' => 'index.php'];
124
$xoBreadcrumbs[] = ['title' => $imageObj->getVar('name'), 'link' => 'event.php?op=show&amp;id=' . $imageObj->getVar('id')];
125
$xoBreadcrumbs[] = ['title' => \_MA_WGEVENTS_IMG_EDITOR];
126
127
// get config for images
128
$maxwidth  = $helper->getConfig('maxwidth_image');
129
$maxheight = $helper->getConfig('maxheight_image');
130
$maxsize   = $helper->getConfig('maxsize_image');
131
$mimetypes = $helper->getConfig('mimetypes_image');
132
133
switch ($op) {
134
135
    case 'creategrid':
136
        // create an image grid based on given sources
137
        $type   = Request::getInt('type', 4);
138
        $src[1] = Request::getString('src1');
139
        $src[2] = Request::getString('src2');
140
        $src[3] = Request::getString('src3');
141
        $src[4] = Request::getString('src4');
142
        $src[5] = Request::getString('src5');
143
        $src[6] = Request::getString('src6');
144
        $target = Request::getString('target');
145
146
        $images = [];
147
        for ($i = 1; $i <= 6; $i++) {
148
            if ('' !== $src[$i]) {
149
                $file       = \str_replace(\XOOPS_URL, \XOOPS_ROOT_PATH, $src[$i]);
150
                $images[$i] = ['file' => $file, 'mimetype' => \mime_content_type($file)];
151
            }
152
        }
153
154
        // create basic image
155
        $tmp   = \imagecreatetruecolor($maxwidth, $maxheight);
156
        $imgBg = imagecolorallocate($tmp, 0, 0, 0);
157
        imagefilledrectangle($tmp, 0, 0, $maxwidth, $maxheight, $imgBg);
158
159
        $final = XOOPS_UPLOAD_PATH . '/wgevents/temp/' . $target;
160
        \unlink($final);
161
        \imagejpeg($tmp, $final);
162
        \imagedestroy($tmp);
163
164
        $imgTemp = XOOPS_UPLOAD_PATH . '/wgevents/temp/' . $uid . 'imgTemp';
165
166
        $imgHandler = new Resizer();
167
        if (4 === $type) {
168
            for ($i = 1; $i <= 4; $i++) {
169
                \unlink($imgTemp . $i . '.jpg');
170
                $imgHandler->sourceFile    = $images[$i]['file'];
171
                $imgHandler->endFile       = $imgTemp . $i . '.jpg';
172
                $imgHandler->imageMimetype = $images[$i]['mimetype'];
173
                $imgHandler->maxWidth      = (int)\round($maxwidth / 2 - 1);
174
                $imgHandler->maxHeight     = (int)\round($maxheight / 2 - 1);
175
                $imgHandler->jpgQuality    = 90;
176
                $imgHandler->resizeAndCrop();
177
            }
178
            $imgHandler->mergeType = 4;
179
            $imgHandler->endFile   = $final;
180
            $imgHandler->maxWidth  = $maxwidth;
181
            $imgHandler->maxHeight = $maxheight;
182
            for ($i = 1; $i <= 4; $i++) {
183
                $imgHandler->sourceFile = $imgTemp . $i . '.jpg';
184
                $imgHandler->mergePos   = $i;
185
                $imgHandler->mergeImage();
186
                \unlink($imgTemp . $i . '.jpg');
187
            }
188
        }
189
        if (6 === $type) {
190
            for ($i = 1; $i <= 6; $i++) {
191
                $imgHandler->sourceFile    = $images[$i]['file'];
192
                $imgHandler->endFile       = $imgTemp . $i . '.jpg';
193
                $imgHandler->imageMimetype = $images[$i]['mimetype'];
194
                $imgHandler->maxWidth      = (int)\round($maxwidth / 3 - 1);
195
                $imgHandler->maxHeight     = (int)\round($maxheight / 2 - 1);
196
                $imgHandler->resizeAndCrop();
197
            }
198
            $imgHandler->mergeType = 6;
199
            $imgHandler->endFile   = $final;
200
            $imgHandler->maxWidth  = $maxwidth;
201
            $imgHandler->maxHeight = $maxheight;
202
            for ($i = 1; $i <= 6; $i++) {
203
                $imgHandler->sourceFile = $imgTemp . $i . '.jpg';
204
                $imgHandler->mergePos   = $i;
205
                $imgHandler->mergeImage();
206
                \unlink($imgTemp . $i . '.jpg');
207
            }
208
        }
209
        break;
210
211
    case 'cropimage':
212
        // save base64_image and resize to maxwidth/maxheight
213
        $base64_image_content = Request::getString('croppedImage');
214
        if (\preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
215
            $type = $result[2];
216
            \file_put_contents($imgTemp, base64_decode(\str_replace($result[1], '', $base64_image_content), true));
217
        }
218
219
        $imgHandler                = new Resizer();
220
        $imgHandler->sourceFile    = $imgTemp;
221
        $imgHandler->endFile       = $imgTemp;
222
        $imgHandler->imageMimetype = 'image/jpeg';
223
        $imgHandler->maxWidth      = $maxwidth;
224
        $imgHandler->maxHeight     = $maxheight;
225
        $ret                       = $imgHandler->resizeImage();
226
227
        //\unlink($imgFinal);
228
        break;
229
    case 'saveImageSelected':
230
        // save image selected from list of available images in upload folder
231
        // Set Vars
232
        $image_id = Request::getString('image_id');
233
        // remove '_image' from id
234
        $image_id = \substr($image_id, 0, -6);
235
        $imageObj->setVar($fieldObj, $image_id);
236
        //$imageObj->setVar($submObj, $uid); // do not change submitter of event
237
        // Insert Data
238
        if ($imageHandler->insert($imageObj)) {
239
            \redirect_header($redir, 2, _MA_WGEVENTS_FORM_OK);
240
        }
241
        $GLOBALS['xoopsTpl']->assign('error', $imageObj->getHtmlErrors());
242
        break;
243
244
    case 'saveGrid':
245
        // save before created grid image
246
        $imgTempGrid = Request::getString('gridImgFinal');
247
        $ret = \rename($imgTempGrid, $imgFinal);
248
        // Set Vars
249
        $imageObj->setVar($fieldObj, $imgName);
250
        //$imageObj->setVar($submObj, $uid); // do not change submitter of event
251
        // Insert Data
252
        if ($imageHandler->insert($imageObj)) {
253
            \redirect_header($redir, 2, _MA_WGEVENTS_FORM_OK);
254
        }
255
        $GLOBALS['xoopsTpl']->assign('error', $imageObj->getHtmlErrors());
256
257
        break;
258
    case 'saveCrop':
259
        // save before created cropped image
260
        \unlink($imgFinal);
261
        $ret = \rename($imgTemp, $imgFinal);
262
        // Set Vars
263
        $imageObj->setVar($fieldObj, $imgName);
264
        //$imageObj->setVar($submObj, $uid); // do not change submitter of event
265
        // Insert Data
266
        if ($imageHandler->insert($imageObj, true)) {
267
            \redirect_header($redir, 2, _MA_WGEVENTS_FORM_OK);
268
        }
269
        $GLOBALS['xoopsTpl']->assign('error', $imageObj->getHtmlErrors());
270
271
        break;
272
    case 'uploadImage':
273
        // Security Check
274
        if (!$GLOBALS['xoopsSecurity']->check()) {
275
            \redirect_header($redir, 3, \implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
276
        }
277
        // Set Vars
278
        require_once \XOOPS_ROOT_PATH . '/class/uploader.php';
279
        $fileName       = $_FILES['attachedfile']['name'];
280
        $imageMimetype  = $_FILES['attachedfile']['type'];
281
        $uploaderErrors = '';
282
        $uploader       = new \XoopsMediaUploader($imgPath, $mimetypes, $maxsize, null, null);
283
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
284
            $extension = \preg_replace('/^.+\.([^.]+)$/sU', '', $fileName);
285
            $imgName   .= '.' . $extension;
286
            $uploader->setPrefix($imgName);
287
            $uploader->fetchMedia($_POST['xoops_upload_file'][0]);
288
            if (!$uploader->upload()) {
289
                $uploaderErrors = $uploader->getErrors();
290
            } else {
291
                $savedFilename = $uploader->getSavedFileName();
292
                $imageObj->setVar($fieldObj, $savedFilename);
293
                // resize image
294
                if (1 == $img_resize) {
295
                    $imgHandler                = new Resizer();
296
                    $imgHandler->sourceFile    = $imgPath . $savedFilename;
297
                    $imgHandler->endFile       = $imgPath . $savedFilename;
298
                    $imgHandler->imageMimetype = $imageMimetype;
299
                    $imgHandler->maxWidth      = $maxwidth;
300
                    $imgHandler->maxHeight     = $maxheight;
301
                    $result                    = $imgHandler->resizeImage();
302
                }
303
304
                $imageObj->setVar($fieldObj, $savedFilename);
305
                //$imageObj->setVar($submObj, $uid); // do not change submitter of event
306
            }
307
        } elseif ($fileName > '') {
308
            $uploaderErrors = $uploader->getErrors();
309
        }
310
        if ('' !== $uploaderErrors) {
311
            \redirect_header($redir, 5, $uploaderErrors);
312
        }
313
        // Insert Data
314
        if ($imageHandler->insert($imageObj)) {
315
            \redirect_header($redir, 2, _MA_WGEVENTS_FORM_OK);
316
        }
317
        // Get Form
318
        $GLOBALS['xoopsTpl']->assign('error', $imageObj->getHtmlErrors());
319
        $form = $imageObj->getFormUploadImage($imageOrigin, $imageId);
320
        $GLOBALS['xoopsTpl']->assign('form', $form->render());
321
        break;
322
323
    case 'imghandler':
324
    default:
325
        $GLOBALS['xoTheme']->addStylesheet(\WGEVENTS_URL . '/assets/css/cropper/cropper.min.css');
326
        $GLOBALS['xoTheme']->addScript(\WGEVENTS_URL . '/assets/js/cropper/cropper.min.js');
327
        $GLOBALS['xoTheme']->addScript(\WGEVENTS_URL . '/assets/js/cropper/cropper-main.js');
328
329
        $GLOBALS['xoopsTpl']->assign('nbModals', [1, 2, 3, 4, 5, 6]);
330
331
        // get form for upload album image
332
        $currImage = (string)$imageObj->getVar($fieldObj);
333
        if ('' === $currImage) {
334
            $currImage = 'blank.gif';
335
        }
336
        $image_path = $imgPath . $currImage;
337
        $width = 0;
338
        $height= 0;
339
        if (\file_exists($image_path)) {
340
            // get size of current album image
341
            list($width, $height, $type, $attr) = \getimagesize($image_path);
342
        }
343
        $GLOBALS['xoopsTpl']->assign('image_path', $image_path);
344
        $GLOBALS['xoopsTpl']->assign('albimage_width', $width);
345
        $GLOBALS['xoopsTpl']->assign('albimage_height', $height);
346
347
        $form = getFormUploadImage($imageOrigin, $imageId);
348
        $GLOBALS['xoopsTpl']->assign('form_uploadimage', $form->render());
349
350
        $GLOBALS['xoopsTpl']->assign('btn_style', 'btn-primary');
351
352
        break;
353
}
354
355
$GLOBALS['xoopsTpl']->assign('panel_type', $helper->getConfig('panel_type'));
356
357
include __DIR__ . '/footer.php';
358
359
/**
360
 * @public function getFormUploadImage:
361
 * provide form for uploading a new image
362
 * @param $imageOrigin
363
 * @param $imageId
364
 * @return \XoopsThemeForm
365
 */
366
function getFormUploadImage($imageOrigin, $imageId)
367
{
368
    $helper = \XoopsModules\Wgevents\Helper::getInstance();
369
    // Get Theme Form
370
    \xoops_load('XoopsFormLoader');
371
    $form = new \XoopsThemeForm('', 'formuploadimage', 'image_editor.php', 'post', true);
372
    $form->setExtra('enctype="multipart/form-data"');
373
    // upload new image
374
    $imageTray1      = new \XoopsFormElementTray(\_MA_WGEVENTS_FORM_UPLOAD_IMG, '<br>');
375
    $imageFileSelect = new \XoopsFormFile('', 'attachedfile', $helper->getConfig('maxsize'));
376
    $imageTray1->addElement($imageFileSelect);
377
    $form->addElement($imageTray1);
378
379
    $cond = \_MA_WGEVENTS_IMG_MAXSIZE . ': ' . ($helper->getConfig('maxsize_image') / 1048576) . ' ' . \_MA_WGEVENTS_SIZE_MB . '<br>';
380
    //$cond .= \_MI_WGEVENTS_MAXWIDTH . ': ' . $helper->getConfig('maxwidth') . ' px<br>';
381
    //$cond .= \_MI_WGEVENTS_MAXHEIGHT . ': ' . $helper->getConfig('maxheight') . ' px<br>';
382
    $cond .= \_MA_WGEVENTS_IMG_MIMETYPES . ': ' . \implode(', ', $helper->getConfig('mimetypes_image')) . '<br>';
0 ignored issues
show
Bug introduced by
It seems like $helper->getConfig('mimetypes_image') can also be of type null; however, parameter $pieces of implode() does only seem to accept 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

382
    $cond .= \_MA_WGEVENTS_IMG_MIMETYPES . ': ' . \implode(', ', /** @scrutinizer ignore-type */ $helper->getConfig('mimetypes_image')) . '<br>';
Loading history...
383
    $form->addElement(new \XoopsFormLabel(\_MA_WGEVENTS_IMG_EDITOR_UPLOAD, $cond));
384
385
    $imageTray3      = new \XoopsFormElementTray(\_MA_WGEVENTS_IMG_EDITOR_RESIZE, '');
386
    $resizeinfo = \str_replace('%w', (string)$helper->getConfig('maxwidth_image'), \_MA_WGEVENTS_IMG_EDITOR_RESIZE_DESC);
387
    $resizeinfo = \str_replace('%h', (string)$helper->getConfig('maxheight_image'), $resizeinfo);
388
    $imageTray3->addElement(new \XoopsFormLabel($resizeinfo, ''));
389
    $imageTray3->addElement(new \XoopsFormRadioYN('', 'img_resize', 1));
390
    $form->addElement($imageTray3);
391
392
    $form->addElement(new \XoopsFormHidden($imageOrigin, $imageId));
393
    $form->addElement(new \XoopsFormHidden('op', 'uploadImage'));
394
    $form->addElement(new \XoopsFormButtonTray('', \_SUBMIT, 'submit', '', false));
395
396
    return $form;
397
}
398