Passed
Pull Request — master (#81)
by Michael
02:53
created

class/GroupsHandler.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Yogurt;
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
 * Module: Yogurt
19
 *
20
 * @category        Module
21
 * @package         yogurt
22
 * @author          Marcello Brandão aka  Suico, Mamba, LioMJ  <https://xoops.org>
23
 * @copyright       {@link https://xoops.org/ XOOPS Project}
24
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
25
 */
26
27
use CriteriaElement;
28
use XoopsDatabase;
29
use XoopsFormButton;
30
use XoopsFormFile;
31
use XoopsFormHidden;
32
use XoopsFormLabel;
33
use XoopsFormText;
34
use XoopsFormTextArea;
35
use XoopsMediaUploader;
36
use XoopsObject;
37
use XoopsPersistableObjectHandler;
38
use XoopsThemeForm;
39
40
/**
41
 * Protection against inclusion outside the site
42
 */
43
if (!\defined('XOOPS_ROOT_PATH')) {
44
    die('XOOPS root path not defined');
45
}
46
47
// -------------------------------------------------------------------------
48
// ------------------Groups user handler class -------------------
49
// -------------------------------------------------------------------------
50
51
/**
52
 * yogurt_groupshandler class.
53
 * This class provides simple mecanisme for Groups object
54
 */
55
class GroupsHandler extends XoopsPersistableObjectHandler
56
{
57
    public $helper;
58
59
    public $isAdmin;
60
61
    /**
62
     * Constructor
63
     * @param \XoopsDatabase|null              $xoopsDatabase
64
     * @param \XoopsModules\Yogurt\Helper|null $helper
65
     */
66
    public function __construct(
67
        ?XoopsDatabase $xoopsDatabase = null,
68
        $helper = null
69
    ) {
70
        /** @var \XoopsModules\Yogurt\Helper $this ->helper */
71
        if (null === $helper) {
72
            $this->helper = Helper::getInstance();
73
        } else {
74
            $this->helper = $helper;
75
        }
76
        $isAdmin = $this->helper->isUserAdmin();
77
        parent::__construct($xoopsDatabase, 'yogurt_groups', Groups::class, 'group_id', 'group_title');
78
    }
79
80
    /**
81
     * create a new Groups
82
     *
83
     * @param bool $isNew flag the new objects as "new"?
84
     * @return \XoopsObject Groups
85
     */
86
    public function create(
87
        $isNew = true
88
    ) {
89
        $obj = parent::create($isNew);
90
        if ($isNew) {
91
            $obj->setNew();
92
        } else {
93
            $obj->unsetNew();
94
        }
95
        $obj->helper = $this->helper;
96
97
        return $obj;
98
    }
99
100
    /**
101
     * retrieve a Groups
102
     *
103
     * @param int  $id of the Groups
104
     * @param null $fields
105
     * @return mixed reference to the {@link Groups} object, FALSE if failed
106
     */
107
    public function get2(
108
        $id = null,
109
        $fields = null
110
    ) {
111
        $sql = 'SELECT * FROM ' . $this->db->prefix('yogurt_groups') . ' WHERE group_id=' . $id;
112
        if (!$result = $this->db->query($sql)) {
113
            return false;
114
        }
115
        $numrows = $this->db->getRowsNum($result);
116
        if (1 === $numrows) {
117
            $yogurt_groups = new Groups();
118
            $yogurt_groups->assignVars($this->db->fetchArray($result));
119
120
            return $yogurt_groups;
121
        }
122
123
        return false;
124
    }
125
126
    /**
127
     * insert a new Groups in the database
128
     *
129
     * @param \XoopsObject $xoopsObject   reference to the {@link Groups}
130
     *                                    object
131
     * @param bool         $force
132
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
133
     */
134
    public function insert2(
135
        XoopsObject $xoopsObject,
136
        $force = false
137
    ) {
138
        global $xoopsConfig;
139
        if (!$xoopsObject instanceof Groups) {
140
            return false;
141
        }
142
        if (!$xoopsObject->isDirty()) {
143
            return true;
144
        }
145
        if (!$xoopsObject->cleanVars()) {
146
            return false;
147
        }
148
        foreach ($xoopsObject->cleanVars as $k => $v) {
149
            ${$k} = $v;
150
        }
151
        //        $now = 'date_add(now(), interval ' . $xoopsConfig['server_TZ'] . ' hour)';
152
        if ($xoopsObject->isNew()) {
153
            // ajout/modification d'un Groups
154
            $xoopsObject = new Groups();
155
            $format      = 'INSERT INTO %s (group_id, owner_uid, group_title, group_desc, group_img)';
156
            $format      .= 'VALUES (%u, %u, %s, %s, %s)';
157
            $sql         = \sprintf(
158
                $format,
159
                $this->db->prefix('yogurt_groups'),
160
                $group_id,
161
                $owner_uid,
162
                $this->db->quoteString($group_title),
163
                $this->db->quoteString($group_desc),
164
                $this->db->quoteString($group_img)
165
            );
166
            $force       = true;
167
        } else {
168
            $format = 'UPDATE %s SET ';
169
            $format .= 'group_id=%u, owner_uid=%u, group_title=%s, group_desc=%s, group_img=%s';
170
            $format .= ' WHERE group_id = %u';
171
            $sql    = \sprintf(
172
                $format,
173
                $this->db->prefix('yogurt_groups'),
174
                $group_id,
175
                $owner_uid,
176
                $this->db->quoteString($group_title),
177
                $this->db->quoteString($group_desc),
178
                $this->db->quoteString($group_img),
179
                $group_id
180
            );
181
        }
182
        if ($force) {
183
            $result = $this->db->queryF($sql);
184
        } else {
185
            $result = $this->db->query($sql);
186
        }
187
        if (!$result) {
188
            return false;
189
        }
190
        if (empty($group_id)) {
191
            $group_id = $this->db->getInsertId();
192
        }
193
        $xoopsObject->assignVar('group_id', $group_id);
194
195
        return true;
196
    }
197
198
    /**
199
     * delete a Groups from the database
200
     *
201
     * @param \XoopsObject $xoopsObject reference to the Groups to delete
202
     * @param bool         $force
203
     * @return bool FALSE if failed.
204
     */
205
    public function delete(
206
        XoopsObject $xoopsObject,
207
        $force = false
208
    ) {
209
        if (!$xoopsObject instanceof Groups) {
210
            return false;
211
        }
212
        $sql = \sprintf(
213
            'DELETE FROM %s WHERE group_id = %u',
214
            $this->db->prefix('yogurt_groups'),
215
            $xoopsObject->getVar('group_id')
216
        );
217
        if ($force) {
218
            $result = $this->db->queryF($sql);
219
        } else {
220
            $result = $this->db->query($sql);
221
        }
222
        if (!$result) {
223
            return false;
224
        }
225
226
        return true;
227
    }
228
229
    /**
230
     * retrieve yogurt_groupss from the database
231
     *
232
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement} conditions to be met
233
     * @param bool                                 $id_as_key       use the UID as key for the array?
234
     * @param bool                                 $as_object
235
     * @return array array of {@link Groups} objects
236
     */
237
    public function &getObjects(
238
        ?CriteriaElement $criteriaElement = null,
239
        $id_as_key = false,
240
        $as_object = true
241
    ) {
242
        $ret   = [];
243
        $limit = $start = 0;
244
        $sql   = 'SELECT * FROM ' . $this->db->prefix('yogurt_groups');
245
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
246
            $sql .= ' ' . $criteriaElement->renderWhere();
247
            if ('' !== $criteriaElement->getSort()) {
248
                $sql .= ' ORDER BY ' . $criteriaElement->getSort() . ' ' . $criteriaElement->getOrder();
249
            }
250
            $limit = $criteriaElement->getLimit();
251
            $start = $criteriaElement->getStart();
252
        }
253
        $result = $this->db->query($sql, $limit, $start);
254
        if (!$result) {
255
            return $ret;
256
        }
257
        while (false !== ($myrow = $this->db->fetchArray($result))) {
258
            $yogurt_groups = new Groups();
259
            $yogurt_groups->assignVars($myrow);
260
            if (!$id_as_key) {
261
                $ret[] = &$yogurt_groups;
262
            } else {
263
                $ret[$myrow['group_id']] = &$yogurt_groups;
264
            }
265
            unset($yogurt_groups);
266
        }
267
268
        return $ret;
269
    }
270
271
    /**
272
     * retrieve yogurt_groupss from the database
273
     *
274
     * @param \CriteriaElement|\CriteriaCompo|null $criteria  {@link \CriteriaElement} conditions to be met
275
     * @param bool                                 $id_as_key use the UID as key for the array?
276
     * @return array array of {@link Groups} objects
277
     */
278
    public function getGroups(
279
        $criteria = null,
280
        $id_as_key = false
281
    ) {
282
        $ret   = [];
283
        $limit = $start = 0;
284
        $sql   = 'SELECT * FROM ' . $this->db->prefix('yogurt_groups');
285
        if (isset($criteria) && $criteria instanceof CriteriaElement) {
286
            $sql .= ' ' . $criteria->renderWhere();
287
            if ('' !== $criteria->getSort()) {
288
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
289
            }
290
            $limit = $criteria->getLimit();
291
            $start = $criteria->getStart();
292
        }
293
        $result = $this->db->query($sql, $limit, $start);
294
        if (!$result) {
295
            return $ret;
296
        }
297
298
        $i = 0;
299
        while (false !== ($myrow = $this->db->fetchArray($result))) {
300
            $ret[$i]['id']                = $myrow['group_id'];
301
            $ret[$i]['title']             = $myrow['group_title'];
302
            $ret[$i]['img']               = $myrow['group_img'];
303
            $ret[$i]['desc']              = $myrow['group_desc'];
304
            $ret[$i]['uid']               = $myrow['owner_uid'];
305
            $groupid                      = $myrow['group_id'];
306
            $query                        = 'SELECT COUNT(rel_id) AS grouptotalmembers FROM ' . $GLOBALS['xoopsDB']->prefix('yogurt_relgroupuser') . ' WHERE rel_group_id=' . $groupid . '';
307
            $queryresult                  = $GLOBALS['xoopsDB']->query($query);
308
            $row                          = $GLOBALS['xoopsDB']->fetchArray($queryresult);
309
            $grouptotalmembers            = $row['grouptotalmembers'];
310
            $ret[$i]['grouptotalmembers'] = $grouptotalmembers . ' ' . \_MD_YOGURT_GROUPMEMBERS;
311
            $i++;
312
        }
313
314
        return $ret;
315
    }
316
317
    /**
318
     * count yogurt_groupss matching a condition
319
     *
320
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement} to match
321
     * @return int count of yogurt_groupss
322
     */
323
    public function getCount(
324
        ?CriteriaElement $criteriaElement = null
325
    ) {
326
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('yogurt_groups');
327
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
328
            $sql .= ' ' . $criteriaElement->renderWhere();
329
        }
330
        $result = $this->db->query($sql);
331
        if (!$result) {
332
            return 0;
333
        }
334
        [$count] = $this->db->fetchRow($result);
335
336
        return $count;
337
    }
338
339
    /**
340
     * delete yogurt_groupss matching a set of conditions
341
     *
342
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement}
343
     * @param bool                                 $force
344
     * @param bool                                 $asObject
345
     * @return bool FALSE if deletion failed
346
     */
347
    public function deleteAll(
348
        ?CriteriaElement $criteriaElement = null,
349
        $force = true,
350
        $asObject = false
351
    ) {
352
        $sql = 'DELETE FROM ' . $this->db->prefix('yogurt_groups');
353
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
354
            $sql .= ' ' . $criteriaElement->renderWhere();
355
        }
356
        if (!$result = $this->db->query($sql)) {
357
            return false;
358
        }
359
360
        return true;
361
    }
362
363
    /**
364
     * @param $maxbytes
365
     * @param $xoopsTpl
366
     * @return bool
367
     */
368
    public function renderFormSubmit(
369
        $maxbytes,
370
        $xoopsTpl
371
    ) {
372
        $form = new XoopsThemeForm(\_MD_YOGURT_SUBMIT_GROUP, 'form_group', 'submitGroup.php', 'post', true);
373
        $form->setExtra('enctype="multipart/form-data"');
374
375
        $field_url     = new XoopsFormFile(\_MD_YOGURT_GROUP_IMAGE, 'group_img', $maxbytes);
376
        $field_title   = new XoopsFormText(\_MD_YOGURT_GROUP_TITLE, 'group_title', 35, 55);
377
        $field_desc    = new XoopsFormText(\_MD_YOGURT_GROUP_DESC, 'group_desc', 35, 55);
378
        $field_marker  = new XoopsFormHidden('marker', '1');
379
        $buttonSend    = new XoopsFormButton('', 'submit_button', \_MD_YOGURT_UPLOADGROUP, 'submit');
380
        $field_warning = new XoopsFormLabel(\sprintf(\_MD_YOGURT_YOU_CAN_UPLOAD, $maxbytes / 1024));
381
382
        $form->addElement($field_warning);
383
        $form->addElement($field_url, true);
384
385
        $form->addElement($field_title);
386
        $form->addElement($field_desc);
387
        $form->addElement($field_marker);
388
        $form->addElement($buttonSend);
389
        $form->display();
390
391
        return true;
392
    }
393
394
    /**
395
     * @param $group
396
     * @param $maxbytes
397
     * @return bool
398
     */
399
    public function renderFormEdit(
400
        $group,
401
        $maxbytes
402
    ) {
403
        $form = new XoopsThemeForm(\_MD_YOGURT_EDIT_GROUP, 'form_editgroup', 'editgroup.php', 'post', true);
404
        $form->setExtra('enctype="multipart/form-data"');
405
        $field_groupid = new XoopsFormHidden('group_id', $group->getVar('group_id'));
406
        $field_url     = new XoopsFormFile(\_MD_YOGURT_GROUP_IMAGE, 'img', $maxbytes);
407
        $field_url->setExtra('style="visibility:hidden;"');
408
        $field_title   = new XoopsFormText(\_MD_YOGURT_GROUP_TITLE, 'title', 35, 55, $group->getVar('group_title'));
409
        $field_desc    = new XoopsFormTextArea(\_MD_YOGURT_GROUP_DESC, 'desc', $group->getVar('group_desc'));
410
        $field_marker  = new XoopsFormHidden('marker', '1');
411
        $buttonSend    = new XoopsFormButton('', 'submit_button', \_MD_YOGURT_UPLOADGROUP, 'submit');
412
        $field_warning = new XoopsFormLabel(\sprintf(\_MD_YOGURT_YOU_CAN_UPLOAD, $maxbytes / 1024));
413
414
        $field_oldpicture = new XoopsFormLabel(
415
            \_MD_YOGURT_GROUP_IMAGE, '<img src="' . \XOOPS_UPLOAD_URL . '/' . $group->getVar(
416
                                       'group_img'
417
                                   ) . '">'
418
        );
419
420
        $field_maintainimage = new XoopsFormLabel(
421
            \_MD_YOGURT_MAINTAIN_OLD_IMAGE, "<input type='checkbox' value='1' id='flag_oldimg' name='flag_oldimg' onclick=\"groupImgSwitch(img)\"  checked>"
422
        );
423
424
        $form->addElement($field_oldpicture);
425
        $form->addElement($field_maintainimage);
426
        $form->addElement($field_warning);
427
        $form->addElement($field_url);
428
        $form->addElement($field_groupid);
429
        $form->addElement($field_title);
430
        $form->addElement($field_desc);
431
        $form->addElement($field_marker);
432
        $form->addElement($buttonSend);
433
        $form->display();
434
        echo "
435
        <!-- Start Form Validation JavaScript //-->
436
<script type='text/javascript'>
437
<!--//
438
function groupImgSwitch(img) {
439
440
var elestyle = xoopsGetElementById(img).style;
441
442
    if (elestyle.visibility == \"hidden\") {
443
        elestyle.visibility = \"visible\";
444
    } else {
445
        elestyle.visibility = \"hidden\";
446
    }
447
448
449
}
450
//--></script>
451
<!-- End Form Validation JavaScript //-->
452
        ";
453
454
        return true;
455
    }
456
457
    /**
458
     * @param string $group_title
459
     * @param string $group_desc
460
     * @param string $group_img
461
     * @param string $path_upload
462
     * @param int    $maxfilebytes
463
     * @param int    $maxfilewidth
464
     * @param int    $maxfileheight
465
     * @param int    $change_img
466
     * @param string $group
467
     * @return bool
468
     */
469
    public function receiveGroup(
470
        $group_title,
471
        $group_desc,
472
        $group_img,
473
        $path_upload,
474
        $maxfilebytes,
475
        $maxfilewidth,
476
        $maxfileheight,
477
        $change_img = 1,
478
        $group = ''
479
        //        $pictwidth,
480
        //        $pictheight,
481
        //        $thumbwidth,
482
        //        $thumbheight
483
    )
484
    {
485
        global $xoopsUser, $xoopsDB, $_POST, $_FILES;
486
        //search logged user id
487
        $uid = $xoopsUser->getVar('uid');
488
        if ('' === $group || \get_class($group) !== Groups::class) {
489
            $group = $this->create();
490
        } else {
491
            $group->unsetNew();
492
        }
493
494
        $helper      = Helper::getInstance();
495
        $pictwidth   = $helper->getConfig('resized_width');
496
        $pictheight  = $helper->getConfig('resized_height');
497
        $thumbwidth  = $helper->getConfig('thumb_width');
498
        $thumbheight = $helper->getConfig('thumb_height');
499
500
        if (1 === $change_img) {
501
            // mimetypes and settings put this in admin part later
502
            $allowed_mimetypes = Helper::getInstance()->getConfig(
503
                'mimetypes'
504
            );
505
            $maxfilesize       = $maxfilebytes;
506
507
            $uploadDir = \XOOPS_UPLOAD_PATH . '/yogurt/groups/';
508
            // create the object to upload
509
            $uploader = new XoopsMediaUploader(
510
                $uploadDir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight
511
            );
512
            // fetch the media
513
            if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
514
                //lets create a name for it
515
                $uploader->setPrefix('group_' . $uid . '_');
516
                //now let s upload the file
517
518
                if (!$uploader->upload()) {
519
                    // if there are errors lets return them
520
521
                    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>';
522
523
                    return false;
524
                }
525
                // now let s create a new object picture and set its variables
526
                $savedFilename = $uploader->getSavedFileName();
527
                $group->setVar('group_img', $savedFilename);
528
                $imageMimetype = $uploader->getMediaType();
529
                $group->setVar('group_img', $savedFilename);
530
                $maxWidth_grouplogo     = Helper::getInstance()->getConfig('groupslogo_width');
531
                $maxHeight_grouplogo    = Helper::getInstance()->getConfig('groupslogo_height');
532
                $resizer                = new Common\Resizer();
533
                $resizer->sourceFile    = $uploadDir . $savedFilename;
534
                $resizer->endFile       = $uploadDir . $savedFilename;
535
                $resizer->imageMimetype = $imageMimetype;
536
                $resizer->maxWidth      = $maxWidth_grouplogo;
537
                $resizer->maxHeight     = $maxHeight_grouplogo;
538
                $result                 = $resizer->resizeImage();
539
540
                $maxWidth_grouplogo  = Helper::getInstance()->getConfig('thumb_width');
541
                $maxHeight_grouplogo = Helper::getInstance()->getConfig('thumb_height');
542
543
                $resizer->endFile       = $uploadDir . '/thumb_' . $savedFilename;
544
                $resizer->imageMimetype = $imageMimetype;
545
                $resizer->maxWidth      = $maxWidth_grouplogo;
546
                $resizer->maxHeight     = $maxHeight_grouplogo;
547
                $result                 = $resizer->resizeImage();
548
549
                $maxWidth_grouplogo  = Helper::getInstance()->getConfig('resized_width');
550
                $maxHeight_grouplogo = Helper::getInstance()->getConfig('resized_height');
551
552
                $resizer->endFile       = $uploadDir . '/resized_' . $savedFilename;
553
                $resizer->imageMimetype = $imageMimetype;
554
                $resizer->maxWidth      = $maxWidth_grouplogo;
555
                $resizer->maxHeight     = $maxHeight_grouplogo;
556
                $result                 = $resizer->resizeImage();
557
            } else {
558
                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>';
559
560
                return false;
561
            }
562
        }
563
564
        $group->setVar('group_title', $group_title);
565
        $group->setVar('group_desc', $group_desc);
566
        $group->setVar('owner_uid', $uid);
567
568
        $this->insert2($group);
0 ignored issues
show
It seems like $group can also be of type string; however, parameter $xoopsObject of XoopsModules\Yogurt\GroupsHandler::insert2() does only seem to accept XoopsObject, 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

568
        $this->insert2(/** @scrutinizer ignore-type */ $group);
Loading history...
569
570
        return true;
571
    }
572
}
573