ImageHandler   F
last analyzed

Complexity

Total Complexity 61

Size/Duplication

Total Lines 633
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 61
eloc 329
c 2
b 0
f 0
dl 0
loc 633
rs 3.52

15 Methods

Rating   Name   Duplication   Size   Complexity  
B getObjects() 0 31 7
A renderFormEdit() 0 22 1
A delete() 0 21 4
A create() 0 14 2
B resizeImage() 0 65 7
A getLastPictures() 0 19 2
B insert2() 0 67 9
A deleteAll() 0 13 4
A receivePicture() 0 67 3
A getLastPicturesForBlock() 0 47 5
A getCount() 0 13 4
A renderFormSubmit() 0 18 1
B makeAvatar() 0 63 7
A get2() 0 15 3
A __construct() 0 12 2

How to fix   Complexity   

Complex Class

Complex classes like ImageHandler 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.

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 ImageHandler, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Suico;
6
7
/*
8
 You may not change or alter any portion of this comment or credits
9
 of supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit authors.
11
12
 This program is distributed in the hope that it will be useful,
13
 but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
*/
16
17
use CriteriaElement;
18
use Xmf\Request;
19
use XoopsDatabase;
20
use XoopsFormButton;
21
use XoopsFormFile;
22
use XoopsFormHidden;
23
use XoopsFormLabel;
24
use XoopsFormText;
25
use XoopsMediaUploader;
26
use XoopsObject;
27
use XoopsPersistableObjectHandler;
28
use XoopsThemeForm;
29
30
/**
31
 * @category        Module
32
 * @package         suico
33
 * @copyright       {@link https://xoops.org/ XOOPS Project}
34
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
35
 * @author          Marcello Brandão aka  Suico, Mamba, LioMJ  <https://xoops.org>
36
 */
37
38
/**
39
 * Includes of form objects and uploader
40
 */
41
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
42
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
43
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
44
45
/**
46
 * suico_imageshandler class.
47
 * This class provides simple mechanism for Image object and generate forms for inclusion etc
48
 */
49
class ImageHandler extends XoopsPersistableObjectHandler
50
{
51
    public $helper;
52
    public $isAdmin;
53
54
    /**
55
     * Constructor
56
     * @param \XoopsDatabase|null             $xoopsDatabase
57
     * @param \XoopsModules\Suico\Helper|null $helper
58
     */
59
    public function __construct(
60
        ?XoopsDatabase $xoopsDatabase = null,
61
        $helper = null
62
    ) {
63
        /** @var \XoopsModules\Suico\Helper $this->helper */
64
        if (null === $helper) {
65
            $this->helper = Helper::getInstance();
66
        } else {
67
            $this->helper = $helper;
68
        }
69
        $isAdmin = $this->helper->isUserAdmin();
0 ignored issues
show
Unused Code introduced by
The assignment to $isAdmin is dead and can be removed.
Loading history...
70
        parent::__construct($xoopsDatabase, 'suico_images', Image::class, 'image_id', 'title', 'caption');
0 ignored issues
show
Unused Code introduced by
The call to XoopsPersistableObjectHandler::__construct() has too many arguments starting with 'caption'. ( Ignorable by Annotation )

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

70
        parent::/** @scrutinizer ignore-call */ 
71
                __construct($xoopsDatabase, 'suico_images', Image::class, 'image_id', 'title', 'caption');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
71
    }
72
73
    /**
74
     * create a new Groups
75
     *
76
     * @param bool $isNew flag the new objects as "new"?
77
     * @return \XoopsObject Groups
78
     */
79
    public function create(
80
        $isNew = true
81
    ) {
82
        $obj = parent::create($isNew);
83
        //        if ($isNew) {
84
        //            $obj->setDefaultPermissions();
85
        //        }
86
        if ($isNew) {
87
            $obj->setNew();
88
        } else {
89
            $obj->unsetNew();
90
        }
91
        $obj->helper = $this->helper;
92
        return $obj;
93
    }
94
95
    /**
96
     * retrieve a Image
97
     *
98
     * @param int|null $id of the Image
99
     * @param null $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
100
     * @return mixed reference to the {@link Image} object, FALSE if failed
101
     */
102
    public function get2(
103
        $id = null,
104
        $fields = null
0 ignored issues
show
Unused Code introduced by
The parameter $fields is not used and could be removed. ( Ignorable by Annotation )

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

104
        /** @scrutinizer ignore-unused */ $fields = null

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
105
    ) {
106
        $sql = 'SELECT * FROM ' . $this->db->prefix('suico_images') . ' WHERE image_id=' . $id;
107
        if (!$result = $this->db->query($sql)) {
108
            return false;
109
        }
110
        $numrows = $this->db->getRowsNum($result);
111
        if (1 === $numrows) {
112
            $image = new Image();
113
            $image->assignVars($this->db->fetchArray($result));
114
            return $image;
115
        }
116
        return false;
117
    }
118
119
    /**
120
     * insert a new Image in the database
121
     *
122
     * @param \XoopsObject $xoopsObject reference to the {@link Image} object
123
     * @param bool         $force
124
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
125
     */
126
    public function insert2(
127
        XoopsObject $xoopsObject,
128
        $force = false
129
    ) {
130
        global $xoopsConfig;
131
        if (!$xoopsObject instanceof Image) {
132
            return false;
133
        }
134
        if (!$xoopsObject->isDirty()) {
135
            return true;
136
        }
137
        if (!$xoopsObject->cleanVars()) {
138
            return false;
139
        }
140
        $image_id = '';
141
        foreach ($xoopsObject->cleanVars as $k => $v) {
142
            ${$k} = $v;
143
        }
144
        //        $now = 'date_add(now(), interval ' . $xoopsConfig['server_TZ'] . ' hour)';
145
        if ($xoopsObject->isNew()) {
146
            // ajout/modification d'un Image
147
            $xoopsObject = new Image();
148
            $format      = 'INSERT INTO %s (image_id, title, caption, date_created, date_updated, uid_owner, filename, private)';
149
            $format      .= 'VALUES (%u, %s, %s, %s, %s, %s, %s, 0)';
150
            $sql         = \sprintf(
151
                $format,
152
                $this->db->prefix('suico_images'),
153
                $image_id,
154
                $this->db->quoteString($title),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $title seems to be never defined.
Loading history...
155
                $this->db->quoteString($caption),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $caption seems to be never defined.
Loading history...
156
                \time(),//$now,
157
                \time(),//$now,
158
                $this->db->quoteString($uid_owner),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $uid_owner seems to be never defined.
Loading history...
159
                $this->db->quoteString($filename)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filename seems to be never defined.
Loading history...
160
            );
161
            $force       = true;
162
        } else {
163
            $format = 'UPDATE %s SET ';
164
            $format .= 'image_id=%u, title=%s, caption=%s, date_created=%s, date_updated=%s, uid_owner=%s, filename=%s, private=%s';
165
            $format .= ' WHERE image_id = %u';
166
            $sql    = \sprintf(
167
                $format,
168
                $this->db->prefix('suico_images'),
169
                $image_id,
170
                $this->db->quoteString($title),
171
                $this->db->quoteString($caption),
172
                $xoopsObject->getVar('date_created'), // $now,
0 ignored issues
show
Bug introduced by
It seems like $xoopsObject->getVar('date_created') 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

172
                /** @scrutinizer ignore-type */ $xoopsObject->getVar('date_created'), // $now,
Loading history...
173
                $xoopsObject->getVar('date_updated'), // $now,
174
                $this->db->quoteString($uid_owner),
175
                $this->db->quoteString($filename),
176
                $this->db->quoteString($private),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $private seems to be never defined.
Loading history...
177
                $image_id
178
            );
179
        }
180
        if ($force) {
181
            $result = $this->db->queryF($sql);
182
        } else {
183
            $result = $this->db->query($sql);
184
        }
185
        if (!$result) {
186
            return false;
187
        }
188
        if (empty($image_id)) {
0 ignored issues
show
introduced by
The condition empty($image_id) is always true.
Loading history...
189
            $image_id = $this->db->getInsertId();
190
        }
191
        $xoopsObject->assignVar('image_id', $image_id);
192
        return true;
193
    }
194
195
    /**
196
     * delete a Image from the database
197
     *
198
     * @param \XoopsObject $xoopsObject reference to the Image to delete
199
     * @param bool         $force
200
     * @return bool FALSE if failed.
201
     */
202
    public function delete(
203
        XoopsObject $xoopsObject,
204
        $force = false
205
    ) {
206
        if (!$xoopsObject instanceof Image) {
207
            return false;
208
        }
209
        $sql = \sprintf(
210
            'DELETE FROM %s WHERE image_id = %u',
211
            $this->db->prefix('suico_images'),
212
            $xoopsObject->getVar('image_id')
0 ignored issues
show
Bug introduced by
It seems like $xoopsObject->getVar('image_id') 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

212
            /** @scrutinizer ignore-type */ $xoopsObject->getVar('image_id')
Loading history...
213
        );
214
        if ($force) {
215
            $result = $this->db->queryF($sql);
216
        } else {
217
            $result = $this->db->query($sql);
218
        }
219
        if (!$result) {
220
            return false;
221
        }
222
        return true;
223
    }
224
225
    /**
226
     * retrieve suico_imagess from the database
227
     *
228
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement} conditions to be met
229
     * @param bool                                 $id_as_key       use the UID as key for the array?
230
     * @param bool                                 $as_object
231
     * @return array array of {@link Image} objects
232
     */
233
    public function &getObjects(
234
        ?CriteriaElement $criteriaElement = null,
235
        $id_as_key = false,
236
        $as_object = true
237
    ) {
238
        $ret   = [];
239
        $limit = $start = 0;
240
        $sql   = 'SELECT * FROM ' . $this->db->prefix('suico_images');
241
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
242
            $sql .= ' ' . $criteriaElement->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

242
            $sql .= ' ' . $criteriaElement->/** @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...
243
            if ('' !== $criteriaElement->getSort()) {
244
                $sql .= ' ORDER BY ' . $criteriaElement->getSort() . ' ' . $criteriaElement->getOrder();
245
            }
246
            $limit = $criteriaElement->getLimit();
247
            $start = $criteriaElement->getStart();
248
        }
249
        $result = $this->db->query($sql, $limit, $start);
250
        if (!$result) {
251
            return $ret;
252
        }
253
        while (false !== ($myrow = $this->db->fetchArray($result))) {
254
            $image = new Image();
255
            $image->assignVars($myrow);
256
            if ($id_as_key) {
257
                $ret[$myrow['image_id']] = &$image;
258
            } else {
259
                $ret[] = &$image;
260
            }
261
            unset($image);
262
        }
263
        return $ret;
264
    }
265
266
    /**
267
     * count suico_imagess matching a condition
268
     *
269
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement} to match
270
     * @return int count of suico_imagess
271
     */
272
    public function getCount(
273
        ?CriteriaElement $criteriaElement = null
274
    ) {
275
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('suico_images');
276
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
277
            $sql .= ' ' . $criteriaElement->renderWhere();
278
        }
279
        $result = $this->db->query($sql);
280
        if (!$result) {
281
            return 0;
282
        }
283
        [$count] = $this->db->fetchRow($result);
284
        return (int)$count;
285
    }
286
287
    /**
288
     * delete suico_imagess matching a set of conditions
289
     *
290
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement}
291
     * @param bool                                 $force
292
     * @param bool                                 $asObject
293
     * @return bool FALSE if deletion failed
294
     */
295
    public function deleteAll(
296
        ?CriteriaElement $criteriaElement = null,
297
        $force = true,
298
        $asObject = false
299
    ) {
300
        $sql = 'DELETE FROM ' . $this->db->prefix('suico_images');
301
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
302
            $sql .= ' ' . $criteriaElement->renderWhere();
303
        }
304
        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...
305
            return false;
306
        }
307
        return true;
308
    }
309
310
    /**
311
     * Render a form to send pictures
312
     *
313
     * @param int       $maxbytes the maximum size of a picture
314
     * @param \XoopsTpl $xoopsTpl the one in which the form will be rendered
315
     * @return bool TRUE
316
     *
317
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
318
     */
319
    public function renderFormSubmit(
320
        $maxbytes,
321
        $xoopsTpl
322
    ) {
323
        $form          = new XoopsThemeForm(\_MD_SUICO_SUBMIT_PIC_TITLE, 'form_picture', 'submitImage.php', 'post', true);
324
        $field_url     = new XoopsFormFile(\_MD_SUICO_SELECT_PHOTO, 'sel_photo', 2000000);
325
        $field_title   = new XoopsFormText(\_MD_SUICO_PHOTOTITLE, 'title', 35, 55);
326
        $field_caption = new XoopsFormText(\_MD_SUICO_CAPTION, 'caption', 35, 55);
327
        $form->setExtra('enctype="multipart/form-data"');
328
        $buttonSend    = new XoopsFormButton('', 'submit_button', \_MD_SUICO_UPLOADPICTURE, 'submit');
329
        $field_warning = new XoopsFormLabel(\sprintf(\_MD_SUICO_YOU_CAN_UPLOAD, $maxbytes / 1024));
330
        $form->addElement($field_warning);
331
        $form->addElement($field_url, true);
332
        $form->addElement($field_title);
333
        $form->addElement($field_caption);
334
        $form->addElement($buttonSend);
335
        $form->assign($xoopsTpl); //If your server is php 5
336
        return true;
337
    }
338
339
    /**
340
     * Render a form to edit the description of the pictures
341
     *
342
     * @param        $title
343
     * @param string $caption  The description of the picture
344
     * @param int    $image_id the id of the image in database
345
     * @param string $filename the url to the thumb of the image so it can be displayed
346
     * @return bool TRUE
347
     */
348
    public function renderFormEdit(
349
        $title,
350
        $caption,
351
        $image_id,
352
        $filename
353
    ) {
354
        $form          = new XoopsThemeForm(\_MD_SUICO_EDIT_PICTURE, 'form_picture', 'editpicture.php', 'post', true);
355
        $field_title   = new XoopsFormText($title, 'title', 35, 55);
356
        $field_caption = new XoopsFormText($caption, 'caption', 35, 55);
357
        $form->setExtra('enctype="multipart/form-data"');
358
        $buttonSend     = new XoopsFormButton('', 'submit_button', \_MD_SUICO_SUBMIT, 'submit');
359
        $field_warning  = new XoopsFormLabel("<img src='" . $filename . "' alt='thumb'>");
360
        $field_image_id = new XoopsFormHidden('image_id', $image_id);
361
        $field_marker   = new XoopsFormHidden('marker', 1);
362
        $form->addElement($field_warning);
363
        $form->addElement($field_title);
364
        $form->addElement($field_caption);
365
        $form->addElement($field_image_id);
366
        $form->addElement($field_marker);
367
        $form->addElement($buttonSend);
368
        $form->display();
369
        return true;
370
    }
371
372
    /**
373
     * Upload the file and Save into database
374
     *
375
     * @param string $title         A litle title of the file
376
     * @param string $caption       A litle description of the file
377
     * @param string $pathUpload    The path to where the file should be uploaded
378
     * @param int    $thumbwidth    the width in pixels that the thumbnail will have
379
     * @param int    $thumbheight   the height in pixels that the thumbnail will have
380
     * @param int    $pictwidth     the width in pixels that the pic will have
381
     * @param int    $pictheight    the height in pixels that the pic will have
382
     * @param int    $maxfilebytes  the maximum size a file can have to be uploaded in bytes
383
     * @param int    $maxfilewidth  the maximum width in pixels that a pic can have
384
     * @param int    $maxfileheight the maximum height in pixels that a pic can have
385
     * @return bool FALSE if upload fails or database fails
386
     */
387
    public function receivePicture(
388
        $title,
389
        $caption,
390
        $pathUpload,
391
        $thumbwidth,
392
        $thumbheight,
393
        $pictwidth,
394
        $pictheight,
395
        $maxfilebytes,
396
        $maxfilewidth,
397
        $maxfileheight
398
    ) {
399
        global $xoopsUser, $xoopsDB;
400
        //search logged user id
401
        $uid = $xoopsUser->getVar('uid');
402
        //create a hash so it does not erase another file
403
        //$hash1 = date();
404
        //$hash = substr($hash1,0,4);
405
        // mimetypes and settings put this in admin part later
406
        $allowed_mimetypes = Helper::getInstance()->getConfig(
407
            'mimetypes'
408
        );
409
        $maxfilesize       = $maxfilebytes;
410
        //        $uploadDir = \XOOPS_UPLOAD_PATH . '/suico/images/';
411
        // create the object to upload
412
        $uploader = new XoopsMediaUploader(
413
            $pathUpload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight
414
        );
415
        // fetch the media
416
        if ($uploader->fetchMedia(Request::getArray('xoops_upload_file', '', 'POST')[0])) {
417
            //lets create a name for it
418
            $uploader->setPrefix('pic_' . $uid . '_');
419
            //now let s upload the file
420
            if (!$uploader->upload()) {
421
                // if there are errors lets return them
422
                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>';
423
                return false;
424
            }
425
            // now let s create a new object picture and set its variables
426
            $picture  = $this->create();
427
            $filename = $uploader->getSavedFileName();
428
            $picture->setVar('filename', $filename);
429
            $picture->setVar('title', $title);
430
            $picture->setVar('caption', $caption);
431
            $picture->setVar('date_created', \time());
432
            $picture->setVar('date_updated', \time());
433
            $picture->setVar('private', 0);
434
            $uid = $xoopsUser->getVar('uid');
435
            $picture->setVar('uid_owner', $uid);
436
            $this->insert($picture);
437
            $saved_destination = $uploader->getSavedDestination();
438
            //print_r($_FILES);
439
            //$this->resizeImage($saved_destination,false, $thumbwidth, $thumbheight, $pictwidth, $pictheight,$pathUpload);
440
            //$this->resizeImage($saved_destination,true, $thumbwidth, $thumbheight, $pictwidth, $pictheight,$pathUpload);
441
            $this->resizeImage(
442
                $saved_destination,
443
                $thumbwidth,
444
                $thumbheight,
445
                $pictwidth,
446
                $pictheight,
447
                $pathUpload
448
            );
449
        } else {
450
            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>';
451
            return false;
452
        }
453
        return true;
454
    }
455
456
    /**
457
     * Resize a picture and save it to $pathUpload
458
     *
459
     * @param string $img         the path to the file
460
     * @param int    $thumbwidth  the width in pixels that the thumbnail will have
461
     * @param int    $thumbheight the height in pixels that the thumbnail will have
462
     * @param int    $pictwidth   the width in pixels that the pic will have
463
     * @param int    $pictheight  the height in pixels that the pic will have
464
     * @param string $pathUpload  The path to where the files should be saved after resizing
465
     */
466
    public function resizeImage(
467
        $img,
468
        $thumbwidth,
469
        $thumbheight,
470
        $pictwidth,
471
        $pictheight,
472
        $pathUpload
473
    ) {
474
        $img2   = $img;
475
        $path   = \pathinfo($img);
476
        $img    = \imagecreatefromjpeg($img);
477
        $xratio = $thumbwidth / \imagesx($img);
478
        $yratio = $thumbheight / \imagesy($img);
479
        if ($xratio < 1 || $yratio < 1) {
480
            if ($xratio < $yratio) {
481
                $resized = \imagecreatetruecolor($thumbwidth, (int)\floor(\imagesy($img) * $xratio));
482
            } else {
483
                $resized = \imagecreatetruecolor((int)\floor(\imagesx($img) * $yratio), $thumbheight);
484
            }
485
            \imagecopyresampled(
486
                $resized,
487
                $img,
488
                0,
489
                0,
490
                0,
491
                0,
492
                \imagesx($resized) + 1,
493
                \imagesy($resized) + 1,
494
                \imagesx($img),
495
                \imagesy($img)
496
            );
497
            \imagejpeg($resized, $pathUpload . '/thumb_' . $path['basename']);
498
            \imagedestroy($resized);
499
        } else {
500
            \imagejpeg($img, $pathUpload . '/thumb_' . $path['basename']);
501
        }
502
        \imagedestroy($img);
503
        $path2   = \pathinfo($img2);
504
        $img2    = \imagecreatefromjpeg($img2);
505
        $xratio2 = $pictwidth / \imagesx($img2);
506
        $yratio2 = $pictheight / \imagesy($img2);
507
        if ($xratio2 < 1 || $yratio2 < 1) {
508
            if ($xratio2 < $yratio2) {
509
                $resized2 = \imagecreatetruecolor($pictwidth, (int)\floor(\imagesy($img2) * $xratio2));
510
            } else {
511
                $resized2 = \imagecreatetruecolor((int)\floor(\imagesx($img2) * $yratio2), $pictheight);
512
            }
513
            \imagecopyresampled(
514
                $resized2,
515
                $img2,
516
                0,
517
                0,
518
                0,
519
                0,
520
                \imagesx($resized2) + 1,
521
                \imagesy($resized2) + 1,
522
                \imagesx($img2),
523
                \imagesy($img2)
524
            );
525
            \imagejpeg($resized2, $pathUpload . '/resized_' . $path2['basename']);
526
            \imagedestroy($resized2);
527
        } else {
528
            \imagejpeg($img2, $pathUpload . '/resized_' . $path2['basename']);
529
        }
530
        \imagedestroy($img2);
531
    }
532
533
    /**
534
     * @param $limit
535
     * @return array
536
     */
537
    public function getLastPictures($limit)
538
    {
539
        $ret    = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
540
        $sql    = 'SELECT uname, t.uid_owner, t.filename FROM ' . $this->db->prefix(
541
                'suico_images'
542
            ) . ' AS t, ' . $this->db->prefix(
543
                'users'
544
            );
545
        $sql    .= ' WHERE uid_owner = uid AND private=0 ORDER BY image_id DESC';
546
        $result = $this->db->query($sql, $limit, 0);
547
        $vetor  = [];
548
        $i      = 0;
549
        while (false !== ($myrow = $this->db->fetchArray($result))) {
550
            $vetor[$i]['uid_owner']    = $myrow['uid_owner'];
551
            $vetor[$i]['uname']        = $myrow['uname'];
552
            $vetor[$i]['img_filename'] = $myrow['filename'];
553
            $i++;
554
        }
555
        return $vetor;
556
    }
557
558
    /**
559
     * @param $limit
560
     * @return array
561
     */
562
    public function getLastPicturesForBlock($limit)
563
    {
564
        global $xoopsUser, $xoopsDB;
565
        if (\is_object($xoopsUser)) {
566
            $uid = $xoopsUser->getVar('uid');
567
        }
568
569
        $controller = new PhotosController($xoopsDB, $xoopsUser);
570
571
        $isUser      = $controller->isUser;
572
        $isAnonymous = $controller->isAnonym;
573
574
        if (1 == $isAnonymous) {
575
            $sql = 'SELECT uname, t.uid_owner, t.filename, t.title, t.caption, t.date_created, t.date_updated  FROM ' . $this->db->prefix('suico_images') . ' AS t';
576
            $sql .= ' INNER JOIN ' . $this->db->prefix('users') . ' u ON t.uid_owner=u.uid';
577
            $sql .= ' INNER JOIN ' . $this->db->prefix('suico_configs') . ' c on t.uid_owner=c.config_uid';
578
            $sql .= ' WHERE private=0 AND c.pictures < 2 ';
579
            $sql .= ' ORDER BY image_id DESC';
580
        }
581
        if (1 == $isUser) {
582
            $sql0 = 'SELECT f.friend2_uid FROM ' . $this->db->prefix('suico_friendships') . ' AS f';
583
            $sql0 .= ' WHERE f.friend1_uid = '. $uid ;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $uid does not seem to be defined for all execution paths leading up to this point.
Loading history...
584
            $sql = 'SELECT uname, t.uid_owner, t.filename, t.title, t.caption, t.date_created, t.date_updated  FROM ' . $this->db->prefix('suico_images') . ' AS t';
585
            $sql .= ' INNER JOIN ' . $this->db->prefix('users') . ' u ON t.uid_owner=u.uid';
586
            $sql .= ' INNER JOIN ' . $this->db->prefix('suico_configs') . ' c on t.uid_owner=c.config_uid';
587
            $sql .= ' WHERE (private=0 AND c.pictures < 3 )'; //all pictures visible to members
588
            $sql .= ' OR ( private=0 AND c.pictures = 3 AND c.config_uid IN ( '. $sql0 .')) '; //pictures visible to friends
589
            $sql .= ' OR ( c.config_uid = '. $uid .' ) '; //my private pictures
590
            $sql .= ' ORDER BY image_id DESC';
591
        }
592
593
        $result = $this->db->query($sql, $limit, 0);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.
Loading history...
594
595
596
        $vetor  = [];
597
        $i      = 0;
598
        while (false !== ($myrow = $this->db->fetchArray($result))) {
599
            $vetor[$i]['uid_owner']    = $myrow['uid_owner'];
600
            $vetor[$i]['uname']        = $myrow['uname'];
601
            $vetor[$i]['img_filename'] = $myrow['filename'];
602
            $vetor[$i]['title']        = $myrow['title'];
603
            $vetor[$i]['caption']      = $myrow['caption'];
604
            $vetor[$i]['date_created'] = \formatTimestamp($myrow['date_created']);
605
            $vetor[$i]['date_updated'] = \formatTimestamp($myrow['date_updated']);
606
            $i++;
607
        }
608
        return $vetor;
609
    }
610
611
    /**
612
     * Resize a picture and save it to $pathUpload
613
     *
614
     * @param string $img        the path to the file
615
     * @param        $width
616
     * @param        $height
617
     * @param string $pathUpload The path to where the files should be saved after resizing
618
     */
619
    public function makeAvatar(
620
        $img,
621
        $width,
0 ignored issues
show
Unused Code introduced by
The parameter $width is not used and could be removed. ( Ignorable by Annotation )

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

621
        /** @scrutinizer ignore-unused */ $width,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
622
        $height,
0 ignored issues
show
Unused Code introduced by
The parameter $height is not used and could be removed. ( Ignorable by Annotation )

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

622
        /** @scrutinizer ignore-unused */ $height,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
623
        $pathUpload
624
    ) {
625
        $img2   = $img;
626
        $path   = \pathinfo($img);
627
        $img    = \imagecreatefromjpeg($img);
628
        $xratio = $thumbwidth / \imagesx($img);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $thumbwidth seems to be never defined.
Loading history...
629
        $yratio = $thumbheight / \imagesy($img);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $thumbheight does not exist. Did you maybe mean $height?
Loading history...
630
        if ($xratio < 1 || $yratio < 1) {
631
            if ($xratio < $yratio) {
632
                $resized = \imagecreatetruecolor($thumbwidth, (int)\floor(\imagesy($img) * $xratio));
633
            } else {
634
                $resized = \imagecreatetruecolor((int)\floor(\imagesx($img) * $yratio), $thumbheight);
635
            }
636
            \imagecopyresampled(
637
                $resized,
638
                $img,
639
                0,
640
                0,
641
                0,
642
                0,
643
                \imagesx($resized) + 1,
644
                \imagesy($resized) + 1,
645
                \imagesx($img),
646
                \imagesy($img)
647
            );
648
            \imagejpeg($resized, $pathUpload . '/thumb_' . $path['basename']);
649
            \imagedestroy($resized);
650
        } else {
651
            \imagejpeg($img, $pathUpload . '/thumb_' . $path['basename']);
652
        }
653
        \imagedestroy($img);
654
        $path2   = \pathinfo($img2);
655
        $img2    = \imagecreatefromjpeg($img2);
656
        $xratio2 = $pictwidth / \imagesx($img2);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pictwidth seems to be never defined.
Loading history...
657
        $yratio2 = $pictheight / \imagesy($img2);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pictheight does not exist. Did you maybe mean $height?
Loading history...
658
        if ($xratio2 < 1 || $yratio2 < 1) {
659
            if ($xratio2 < $yratio2) {
660
                $resized2 = \imagecreatetruecolor($pictwidth, (int)\floor(\imagesy($img2) * $xratio2));
661
            } else {
662
                $resized2 = \imagecreatetruecolor((int)\floor(\imagesx($img2) * $yratio2), $pictheight);
663
            }
664
            \imagecopyresampled(
665
                $resized2,
666
                $img2,
667
                0,
668
                0,
669
                0,
670
                0,
671
                \imagesx($resized2) + 1,
672
                \imagesy($resized2) + 1,
673
                \imagesx($img2),
674
                \imagesy($img2)
675
            );
676
            \imagejpeg($resized2, $pathUpload . '/resized_' . $path2['basename']);
677
            \imagedestroy($resized2);
678
        } else {
679
            \imagejpeg($img2, $pathUpload . '/resized_' . $path2['basename']);
680
        }
681
        \imagedestroy($img2);
682
    }
683
}
684
685