Passed
Push — master ( 827974...c305a5 )
by Michael
04:03
created

PicturesHandler::renderFormSubmit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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

175
        $sql = \sprintf('DELETE FROM `%s` WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), /** @scrutinizer ignore-type */ $adslightPictures->getVar('cod_img'));
Loading history...
176
        if ($force) {
177
            $result = $this->db->queryF($sql);
178
        } else {
179
            $result = $this->db->query($sql);
180
        }
181
        if (!$result) {
182
            return false;
183
        }
184
185
        return true;
186
    }
187
188
    /**
189
     * retrieve Pictures object(s) from the database
190
     *
191
     * @param \CriteriaCompo|\CriteriaElement|null $criteria  {@link \CriteriaElement} conditions to be met
192
     * @param bool                  $id_as_key use the UID as key for the array?
193
     * @return array  array of {@link Pictures} objects
194
     */
195
    public function &getObjects(\CriteriaElement $criteria = null, $id_as_key = false, $as_object = true) //&getObjects(?\CriteriaElement $criteria = null, $id_as_key = false): array
196
    {
197
        $ret   = [];
198
        $limit = $start = 0;
199
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
200
        if (isset($criteria) && $criteria instanceof \CriteriaElement) {
201
            $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

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