PicturesHandler::receivePicture()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 56
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 29
c 0
b 0
f 0
dl 0
loc 56
rs 9.456
cc 3
nc 3
nop 9

How to fix   Long Method    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Adslight;
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
 * @copyright    XOOPS Project (https://xoops.org)
17
 * @license      GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
18
 * @author       XOOPS Development Team
19
 * @author       Pascal Le Boustouller: original author ([email protected])
20
 * @author       Luc Bizet (www.frxoops.org)
21
 * @author       jlm69 (www.jlmzone.com)
22
 * @author       mamba (www.xoops.org)
23
 */
24
25
use Xmf\Request;
26
27
/**
28
 * Protection against inclusion outside the site
29
 */
30
31
/**
32
 * Includes of form objects and uploader
33
 */
34
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
35
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
36
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
37
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
38
39
// -------------------------------------------------------------------------
40
// ------------------light_pictures user handler class -------------------
41
// -------------------------------------------------------------------------
42
43
/**
44
 * PicturesHandler class definition
45
 *
46
 * This class provides simple mechanism to manage {@see Pictures} objects
47
 * and generate forms for inclusion
48
 *
49
 * @todo change this to a XoopsPersistableObjectHandler and remove 'most' method overloads
50
 */
51
class PicturesHandler extends \XoopsPersistableObjectHandler
52
{
53
    private const TABLE      = 'adslight_pictures';
54
    private const ENTITY     = Pictures::class;
55
    private const ENTITYNAME = 'Pictures';
56
    private const KEYNAME    = 'cod_img';
57
    private const IDENTIFIER = 'title';
58
59
    /**
60
     * Class constructor
61
     * @param \XoopsDatabase|null $db
62
     */
63
    public function __construct(\XoopsDatabase $db)
64
    {
65
        $this->db = $db;
66
        parent::__construct($db, static::TABLE, static::ENTITY, static::KEYNAME, static::IDENTIFIER);
67
    }
68
69
    /**
70
     * create a new light_pictures
71
     *
72
     * @param bool $isNew flag the new objects as "new"?
73
     *
74
     * @return \XoopsObject
75
     */
76
    public function create($isNew = true)
77
    {
78
        $adslightPictures = new Pictures();
79
        if ($isNew) {
80
            $adslightPictures->setNew();
81
        } else {
82
            $adslightPictures->unsetNew();
83
        }
84
85
        return $adslightPictures;
86
    }
87
88
    /**
89
     * retrieve a light_pictures
90
     *
91
     * @param int|null   $id of the light_pictures
92
     * @param array|null $fields
93
     * @return false|\XoopsModules\Adslight\Pictures reference to the {@link light_pictures} object, FALSE if failed
94
     */
95
    public function get($id = null, $fields = null)
96
    {
97
        //        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' AND lid=' . $lid . ' ';
98
        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' ';
99
        $result = $this->db->query($sql);
100
        if (!$this->db->isResultSet($result)) {
101
//            \trigger_error("Query Failed! SQL: $sql- Error: " . $this->db->error(), E_USER_ERROR);
102
            return false;
103
        }
104
        $numrows = $this->db->getRowsNum($result);
105
        if (1 === $numrows) {
106
            $adslightPictures = new Pictures();
107
            $adslightPictures->assignVars($this->db->fetchArray($result));
108
109
            return $adslightPictures;
110
        }
111
112
        return false;
113
    }
114
115
    /**
116
     * insert a new AdslightPicture object into the database
117
     *
118
     * @param bool $force
119
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
120
     */
121
    public function insert(\XoopsObject $object, $force = false): bool
122
    {
123
        global $lid;
124
        if (!$object instanceof Pictures) {
125
            return false;
126
        }
127
        if (!$object->isDirty()) {
128
            return true;
129
        }
130
        if (!$object->cleanVars()) {
131
            return false;
132
        }
133
        foreach ($object->cleanVars as $k => $v) {
134
            ${$k} = $v;
135
        }
136
        $now = \time();
137
        if ($object->isNew()) {
138
            // add/modify of Pictures
139
            $object = new Pictures();
140
141
            $format = 'INSERT INTO `%s` (cod_img, title, date_created, date_updated, lid, uid_owner, url)';
142
            $format .= 'VALUES (%u, %s, %s, %s, %s, %s, %s)';
143
            $sql    = \sprintf($format, $this->db->prefix('adslight_pictures'), $cod_img, $this->db->quoteString($title), $now, $now, $this->db->quoteString($lid), $this->db->quoteString($uid_owner), $this->db->quoteString($url));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $url seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $title seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $uid_owner seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $cod_img seems to be never defined.
Loading history...
144
            $force  = true;
145
        } else {
146
            $format = 'UPDATE `%s` SET ';
147
            $format .= 'cod_img=%u, title=%s, date_created=%s, date_updated=%s, lid=%s, uid_owner=%s, url=%s';
148
            $format .= ' WHERE cod_img = %u';
149
            $sql    = \sprintf($format, $this->db->prefix('adslight_pictures'), $cod_img, $this->db->quoteString($title), $now, $now, $this->db->quoteString($lid), $this->db->quoteString($uid_owner), $this->db->quoteString($url), $cod_img);
150
        }
151
        if ($force) {
152
            $result = $this->db->queryF($sql);
153
        } else {
154
            $result = $this->db->query($sql);
155
        }
156
        if (!$result) {
157
            return false;
158
        }
159
        if (empty($cod_img)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cod_img seems to never exist and therefore empty should always be true.
Loading history...
160
            $cod_img = $this->db->getInsertId();
161
        }
162
        $object->assignVars([
163
                                'cod_img' => $cod_img,
164
                                'lid'     => $lid,
165
                                'url'     => $url,
166
                            ]);
167
168
        return true;
169
    }
170
171
    /**
172
     * delete Pictures object from the database
173
     *
174
     * @param \XoopsObject $object reference to the Pictures to delete
175
     * @param bool         $force
176
     * @return bool        FALSE if failed.
177
     */
178
    public function delete(\XoopsObject $object, $force = false): bool
179
    {
180
        if (!$object instanceof Pictures) {
181
            return false;
182
        }
183
        $sql = \sprintf('DELETE FROM `%s` WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), $object->getVar('cod_img'));
0 ignored issues
show
Bug introduced by
It seems like $object->getVar('cod_img') can also be of type array and array; however, parameter $values of sprintf() does only seem to accept double|integer|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

183
        $sql = \sprintf('DELETE FROM `%s` WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), /** @scrutinizer ignore-type */ $object->getVar('cod_img'));
Loading history...
184
        if ($force) {
185
            $result = $this->db->queryF($sql);
186
        } else {
187
            $result = $this->db->query($sql);
188
        }
189
        if (!$result) {
190
            return false;
191
        }
192
193
        return true;
194
    }
195
196
    /**
197
     * retrieve Pictures object(s) from the database
198
     *
199
     * @param \CriteriaCompo|\CriteriaElement|null $criteria  {@link \CriteriaElement} conditions to be met
200
     * @param bool                                 $id_as_key use the UID as key for the array?
201
     * @param mixed                                $as_object
202
     * @return array  array of {@link Pictures} objects
203
     */
204
    public function &getObjects($criteria = null, $id_as_key = false, $as_object = true) //&getObjects(?\CriteriaElement $criteria = null, $id_as_key = false): array
205
    {
206
        $ret   = [];
207
        $limit = $start = 0;
208
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
209
        if (\is_object($criteria) && \is_subclass_of($criteria, \CriteriaElement::class)) {
210
            $sql .= ' ' . $criteria->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

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

210
            $sql .= ' ' . $criteria->/** @scrutinizer ignore-call */ renderWhere();

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...
211
            if ('' !== $criteria->getSort()) {
212
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
213
            }
214
            $limit = $criteria->getLimit();
215
            $start = $criteria->getStart();
216
        }
217
        $result = $this->db->query($sql, $limit, $start);
218
        if (!$this->db->isResultSet($result)) {
219
//            \trigger_error("Query Failed! SQL: $sql- Error: " . $this->db->error(), E_USER_ERROR);
220
            return $ret;
221
        }
222
        while (false !== ($myrow = $this->db->fetchArray($result))) {
223
            $adslightPictures = new Pictures();
224
            $adslightPictures->assignVars($myrow);
225
            if ($id_as_key) {
226
                $ret[$myrow['cod_img']] = $adslightPictures;
227
            } else {
228
                $ret[] = $adslightPictures;
229
            }
230
            unset($adslightPictures);
231
        }
232
233
        return $ret;
234
    }
235
236
    /**
237
     * count Pictures matching a condition
238
     *
239
     * @param \CriteriaElement|null $criteria {@link \CriteriaElement} to match
240
     * @return int    count of Pictures
241
     */
242
    public function getCount(?\CriteriaElement $criteria = null): int
243
    {
244
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('adslight_pictures');
245
         if (\is_object($criteria) && \is_subclass_of($criteria, \CriteriaElement::class)) {
246
            $sql .= ' ' . $criteria->renderWhere();
247
        }
248
        $result = $this->db->query($sql);
249
        if (!$this->db->isResultSet($result)) {
250
            return 0;
251
        }
252
        [$count] = $this->db->fetchRow($result);
253
254
        return (int)$count;
255
    }
256
257
    /**
258
     * delete Pictures matching a set of conditions
259
     *
260
     * @param \CriteriaCompo|\CriteriaElement|null $criteria {@link \CriteriaElement}
261
     * @param mixed                                $force
262
     * @param mixed                                $asObject
263
     * @return bool   FALSE if deletion failed
264
     */
265
    //    public function deleteAll(?\CriteriaElement $criteria = null): bool
266
    public function deleteAll(\CriteriaElement $criteria = null, $force = true, $asObject = false)
267
    {
268
        $sql = 'DELETE FROM ' . $this->db->prefix('adslight_pictures');
269
         if (\is_object($criteria) && \is_subclass_of($criteria, \CriteriaElement::class)) {
270
            $sql .= ' ' . $criteria->renderWhere();
271
        }
272
        if (!$result = $this->db->query($sql)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
273
            return false;
274
        }
275
276
        return true;
277
    }
278
279
    /**
280
     * Render a form to send pictures
281
     *
282
     * @param int       $uid
283
     * @param int       $lid
284
     * @param int       $maxbytes the maximum size of a picture
285
     * @param \XoopsTpl $xoopsTpl the one in which the form will be rendered
286
     * @return bool   TRUE
287
     *
288
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
289
     */
290
    public function renderFormSubmit(
291
        $uid,
292
        $lid,
293
        $maxbytes,
294
        $xoopsTpl
295
    ): bool {
296
        global $xoopsUser;
297
        $uid        = (int)$uid;
298
        $lid        = (int)$lid;
299
        $form       = new \XoopsThemeForm(\_ADSLIGHT_SUBMIT_PIC_TITLE, 'form_picture', XOOPS_URL . "/modules/adslight/add_photo.php?lid={$lid}&uid=" . $xoopsUser->getVar('uid'), 'post', true);
300
        $field_url  = new \XoopsFormFile(\_ADSLIGHT_SELECT_PHOTO, 'sel_photo', 2000000);
301
        $field_desc = new \XoopsFormText(\_ADSLIGHT_CAPTION, 'caption', 35, 55);
302
303
        $form->setExtra('enctype="multipart/form-data"');
304
        $button_send   = new \XoopsFormButton('', 'submit_button', \_ADSLIGHT_UPLOADPICTURE, 'submit');
305
        $field_warning = new \XoopsFormLabel(\sprintf(\_ADSLIGHT_YOUCANUPLOAD, $maxbytes / 1024));
306
        $field_lid     = new \XoopsFormHidden('lid', $lid);
307
        $field_uid     = new \XoopsFormHidden('uid', $uid);
308
309
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
310
311
        $form->addElement($field_warning);
312
        $form->addElement($field_url, true);
313
        $form->addElement($field_desc, true);
314
        $form->addElement($field_lid, true);
315
        $form->addElement($field_uid, true);
316
317
        $form->addElement($field_token, true);
318
319
        $form->addElement($button_send);
320
        if (\str_replace('.', '', \PHP_VERSION) > 499) {
321
            $form->assign($xoopsTpl);
322
        } else {
323
            $form->display();
324
        }
325
326
        return true;
327
    }
328
329
    /**
330
     * Render a form to edit the description of the pictures
331
     *
332
     * @param string $caption  The description of the picture
333
     * @param int    $cod_img  the id of the image in database
334
     * @param string $filename the url to the thumb of the image so it can be displayed
335
     * @return bool   TRUE
336
     */
337
    public function renderFormEdit(
338
        $caption,
339
        $cod_img,
340
        $filename
341
    ): bool {
342
        $form       = new \XoopsThemeForm(\_ADSLIGHT_EDIT_CAPTION, 'form_picture', 'editdesc.php', 'post', true);
343
        $field_desc = new \XoopsFormText($caption, 'caption', 35, 55);
344
        $form->setExtra('enctype="multipart/form-data"');
345
        $button_send = new \XoopsFormButton(\_ADSLIGHT_EDIT, 'submit_button', \_SUBMIT, 'submit');
346
        //@todo - replace alt with language string
347
        $field_warning = new \XoopsFormLabel("<img src='{$filename}' alt='sssss'>");
348
        $field_cod_img = new \XoopsFormHidden('cod_img', $cod_img);
349
        //    $field_lid = new \XoopsFormHidden('lid', $lid);
350
        $field_marker = new \XoopsFormHidden('marker', 1);
351
352
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
353
354
        $form->addElement($field_warning);
355
        $form->addElement($field_desc);
356
        $form->addElement($field_cod_img);
357
        $form->addElement($field_marker);
358
        $form->addElement($field_token);
359
        $form->addElement($button_send);
360
        $form->display();
361
362
        return true;
363
    }
364
365
    /**
366
     * Upload the file and Save into database
367
     *
368
     * @param string $title         A litle description of the file
369
     * @param string $pathUpload    The path to where the file should be uploaded
370
     * @param int    $thumbwidth    the width in pixels that the thumbnail will have
371
     * @param int    $thumbheight   the height in pixels that the thumbnail will have
372
     * @param int    $pictwidth     the width in pixels that the pic will have
373
     * @param int    $pictheight    the height in pixels that the pic will have
374
     * @param int    $maxfilebytes  the maximum size a file can have to be uploaded in bytes
375
     * @param int    $maxfilewidth  the maximum width in pixels that a pic can have
376
     * @param int    $maxfileheight the maximum height in pixels that a pic can have
377
     * @return bool FALSE if upload fails or database fails
378
     */
379
    public function receivePicture(
380
        $title,
381
        $pathUpload,
382
        $thumbwidth,
383
        $thumbheight,
384
        $pictwidth,
385
        $pictheight,
386
        $maxfilebytes,
387
        $maxfilewidth,
388
        $maxfileheight
389
    ): bool {
390
        global $lid;
391
        //busca id do user logado
392
        $uid = $GLOBALS['xoopsUser']->getVar('uid');
0 ignored issues
show
Unused Code introduced by
The assignment to $uid is dead and can be removed.
Loading history...
393
        $lid = Request::getInt('lid', 0, 'POST');
394
        //create a hash so it does not erase another file
395
        $hash1 = \time();
396
        $hash  = \mb_substr((string)$hash1, 0, 4);
0 ignored issues
show
Unused Code introduced by
The assignment to $hash is dead and can be removed.
Loading history...
397
        // mimetypes and settings put this in admin part later
398
        $allowed_mimetypes = [
399
            'image/jpeg',
400
            'image/gif',
401
        ];
402
        $maxfilesize       = $maxfilebytes;
403
        // create the object to upload
404
        $uploader = new \XoopsMediaUploader($pathUpload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
405
        // fetch the media
406
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
407
            //let'screate a name for it
408
            $uploader->setPrefix("pic_{$lid}_");
409
            //now let s upload the file
410
            if (!$uploader->upload()) {
411
                // if there are errors let'sreturn them
412
                echo '<div style="color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;"><p>' . $uploader->getErrors() . '</p></div>';
413
414
                return false;
415
            }
416
            // now let s create a new object picture and set its variables
417
            $picture = $this->create();
418
            $url     = $uploader->getSavedFileName();
419
            $picture->setVar('url', $url);
420
            $picture->setVar('title', $title);
421
            $uid = $GLOBALS['xoopsUser']->getVar('uid');
422
            //            $lid = $lid;
423
            $picture->setVar('lid', $lid);
424
            $picture->setVar('uid_owner', $uid);
425
            $this->insert($picture);
426
            $saved_destination = $uploader->getSavedDestination();
427
            $this->resizeImage($saved_destination, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $pathUpload);
428
        } else {
429
            echo '<div style="color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;"><p>' . $uploader->getErrors() . '</p></div>';
430
431
            return false;
432
        }
433
434
        return true;
435
    }
436
437
    /**
438
     * Resize a picture and save it to $pathUpload
439
     *
440
     * @param string $img         the path to the file
441
     * @param int    $thumbwidth  the width in pixels that the thumbnail will have
442
     * @param int    $thumbheight the height in pixels that the thumbnail will have
443
     * @param int    $pictwidth   the width in pixels that the pic will have
444
     * @param int    $pictheight  the height in pixels that the pic will have
445
     * @param string $pathUpload  The path to where the files should be saved after resizing
446
     */
447
    public function resizeImage(
448
        $img,
449
        $thumbwidth,
450
        $thumbheight,
451
        $pictwidth,
452
        $pictheight,
453
        $pathUpload
454
    ): void {
455
        $img2   = $img;
456
        $path   = \pathinfo($img);
457
        $img    = \imagecreatefromjpeg($img);
458
        $xratio = $thumbwidth / \imagesx($img);
459
        $yratio = $thumbheight / \imagesy($img);
460
        if ($xratio < 1 || $yratio < 1) {
461
            if ($xratio < $yratio) {
462
                $resized = \imagecreatetruecolor((int)$thumbwidth, (int)\floor(\imagesy($img) * $xratio));
463
            } else {
464
                $resized = \imagecreatetruecolor((int)\floor(\imagesx($img) * $yratio), $thumbheight);
465
            }
466
            \imagecopyresampled($resized, $img, 0, 0, 0, 0, \imagesx($resized) + 1, \imagesy($resized) + 1, \imagesx($img), \imagesy($img));
467
            \imagejpeg($resized, "{$pathUpload}/thumbs/thumb_{$path['basename']}");
468
            \imagedestroy($resized);
469
        } else {
470
            \imagejpeg($img, "{$pathUpload}/thumbs/thumb_{$path['basename']}");
471
        }
472
        \imagedestroy($img);
473
        $path2   = \pathinfo($img2);
474
        $img2    = \imagecreatefromjpeg($img2);
475
        $xratio2 = $pictwidth / \imagesx($img2);
476
        $yratio2 = $pictheight / \imagesy($img2);
477
        if ($xratio2 < 1 || $yratio2 < 1) {
478
            if ($xratio2 < $yratio2) {
479
                $resized2 = \imagecreatetruecolor((int)$pictwidth, (int)\floor(\imagesy($img2) * $xratio2));
480
            } else {
481
                $resized2 = \imagecreatetruecolor((int)\floor(\imagesx($img2) * $yratio2), (int)$pictheight);
482
            }
483
            \imagecopyresampled($resized2, $img2, 0, 0, 0, 0, \imagesx($resized2) + 1, \imagesy($resized2) + 1, \imagesx($img2), \imagesy($img2));
484
            \imagejpeg($resized2, "{$pathUpload}/midsize/resized_{$path2['basename']}");
485
            \imagedestroy($resized2);
486
        } else {
487
            \imagejpeg($img2, "{$pathUpload}/midsize/resized_{$path2['basename']}");
488
        }
489
        \imagedestroy($img2);
490
    }
491
}
492