SystemBlock::getForm()   F
last analyzed

Complexity

Conditions 16
Paths 200

Size

Total Lines 166
Code Lines 128

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 128
nc 200
nop 1
dl 0
loc 166
rs 3.7866
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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:

1
<?php
2
/**
3
 * Block Class Manager
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright       (c) 2000-2025 XOOPS Project (https://xoops.org)
13
 * @license             GNU GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
14
 * @package             system
15
 */
16
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
17
18
require_once XOOPS_ROOT_PATH . '/kernel/block.php';
19
20
/**
21
 * System Block
22
 *
23
 * @copyright       (c) 2000-2025 XOOPS Project (https://xoops.org)
24
 * @package             system
25
 */
26
class SystemBlock extends XoopsBlock
27
{
28
    /**
29
     *
30
     */
31
    public function __construct()
32
    {
33
        parent::__construct();
34
    }
35
36
    /**
37
     * @param string $mode
38
     *
39
     * @return XoopsThemeForm
40
     */
41
    public function getForm($mode = 'edit')
42
    {
43
        if ($this->isNew()) {
44
            $title   = _AM_SYSTEM_BLOCKS_ADDBLOCK;
45
            $modules = [-1];
46
            $groups  = [XOOPS_GROUP_USERS, XOOPS_GROUP_ANONYMOUS, XOOPS_GROUP_ADMIN];
47
            $this->setVar('block_type', 'C');
48
            $this->setVar('visible', 1);
49
            $op = 'save';
50
        } else {
51
            // Search modules
52
            /** @var  SystemBlockLinkModuleHandler $blocklinkmodule_handler */
53
            $blocklinkmodule_handler = xoops_getModuleHandler('blocklinkmodule');
54
            $criteria                = new CriteriaCompo(new Criteria('block_id', $this->getVar('bid')));
55
            $blocklinkmodule         = $blocklinkmodule_handler->getObjects($criteria);
56
            foreach ($blocklinkmodule as $link) {
57
                /** @var  SystemBlockLinkModule $link */
58
                $modules[] = $link->getVar('module_id');
59
            }
60
            // Search perms
61
            /** @var XoopsGroupPermHandler $groupperm_handler */
62
            $groupperm_handler = xoops_getHandler('groupperm');
63
            $groups            = $groupperm_handler->getGroupIds('block_read', $this->getVar('bid'));
64
            switch ($mode) {
65
                case 'edit':
66
                    $title = _AM_SYSTEM_BLOCKS_EDITBLOCK;
67
                    break;
68
                case 'clone':
69
                    $title = _AM_SYSTEM_BLOCKS_CLONEBLOCK;
70
                    $this->setVar('bid', 0);
71
                    if ($this->isCustom()) {
72
                        $this->setVar('block_type', 'C');
73
                    } else {
74
                        $this->setVar('block_type', 'D');
75
                    }
76
                    break;
77
            }
78
            $op = 'save';
79
        }
80
        $form = new XoopsThemeForm($title, 'blockform', 'admin.php', 'post', true);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $title does not seem to be defined for all execution paths leading up to this point.
Loading history...
81
        if (!$this->isNew()) {
82
            $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_NAME, $this->getVar('name') . ' [' . $this->getVar('dirname') . ']'));
83
        }
84
        // Side position
85
        $side_select = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_TYPE, 'side', $this->getVar('side'));
86
        $side_select->addOptionArray(
87
            [
88
                0  => _AM_SYSTEM_BLOCKS_SBLEFT,
89
                1  => _AM_SYSTEM_BLOCKS_SBRIGHT,
90
                3  => _AM_SYSTEM_BLOCKS_CBLEFT,
91
                4  => _AM_SYSTEM_BLOCKS_CBRIGHT,
92
                5  => _AM_SYSTEM_BLOCKS_CBCENTER,
93
                7  => _AM_SYSTEM_BLOCKS_CBBOTTOMLEFT,
94
                8  => _AM_SYSTEM_BLOCKS_CBBOTTOMRIGHT,
95
                9  => _AM_SYSTEM_BLOCKS_CBBOTTOM,
96
                10 => _AM_SYSTEM_BLOCKS_CBFOOTERLEFT,
97
                11 => _AM_SYSTEM_BLOCKS_CBFOOTERRIGHT,
98
                12 => _AM_SYSTEM_BLOCKS_CBFOOTERCENTER,
99
            ],
100
        );
101
102
        $form->addElement($side_select);
103
        // Order
104
        $form->addElement(new XoopsFormText(_AM_SYSTEM_BLOCKS_WEIGHT, 'weight', 2, 5, $this->getVar('weight')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('weight') can also be of type array and array; however, parameter $value of XoopsFormText::__construct() does only seem to accept 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

104
        $form->addElement(new XoopsFormText(_AM_SYSTEM_BLOCKS_WEIGHT, 'weight', 2, 5, /** @scrutinizer ignore-type */ $this->getVar('weight')));
Loading history...
105
        // Display
106
        $form->addElement(new XoopsFormRadioYN(_AM_SYSTEM_BLOCKS_VISIBLE, 'visible', $this->getVar('visible')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('visible') can also be of type array and array; however, parameter $value of XoopsFormRadioYN::__construct() does only seem to accept 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

106
        $form->addElement(new XoopsFormRadioYN(_AM_SYSTEM_BLOCKS_VISIBLE, 'visible', /** @scrutinizer ignore-type */ $this->getVar('visible')));
Loading history...
107
        // Visible In
108
        $mod_select     = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_VISIBLEIN, 'modules', $modules, 5, true);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $modules does not seem to be defined for all execution paths leading up to this point.
Loading history...
109
        /** @var XoopsModuleHandler $module_handler */
110
        $module_handler = xoops_getHandler('module');
111
        $criteria       = new CriteriaCompo(new Criteria('hasmain', 1));
112
        $criteria->add(new Criteria('isactive', 1));
113
        $module_list     = $module_handler->getList($criteria);
114
        $module_list[-1] = _AM_SYSTEM_BLOCKS_TOPPAGE;
115
        $module_list[0]  = _AM_SYSTEM_BLOCKS_ALLPAGES;
116
        ksort($module_list);
117
        $mod_select->addOptionArray($module_list);
118
        $form->addElement($mod_select);
119
        // Title
120
        $form->addElement(new XoopsFormText(_AM_SYSTEM_BLOCKS_TITLE, 'title', 50, 255, $this->getVar('title')), false);
121
        if ($this->isNew() || $this->isCustom()) {
122
            $editor_configs           = [];
123
            $editor_configs['name']   = 'content_block';
124
            $editor_configs['value']  = $this->getVar('content', 'e');
125
            $editor_configs['rows']   = 20;
126
            $editor_configs['cols']   = 100;
127
            $editor_configs['width']  = '100%';
128
            $editor_configs['height'] = '400px';
129
            $editor_configs['editor'] = xoops_getModuleOption('blocks_editor', 'system');
0 ignored issues
show
Deprecated Code introduced by
The function xoops_getModuleOption() has been deprecated. ( Ignorable by Annotation )

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

129
            $editor_configs['editor'] = /** @scrutinizer ignore-deprecated */ xoops_getModuleOption('blocks_editor', 'system');
Loading history...
130
            $form->addElement(new XoopsFormEditor(_AM_SYSTEM_BLOCKS_CONTENT, 'content_block', $editor_configs), true);
131
            if (in_array($editor_configs['editor'], ['dhtmltextarea', 'textarea'])) {
132
                $ctype_select = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_CTYPE, 'c_type', $this->getVar('c_type'));
133
                $ctype_select->addOptionArray(
134
                    [
135
                        'H' => _AM_SYSTEM_BLOCKS_HTML,
136
                        'P' => _AM_SYSTEM_BLOCKS_PHP,
137
                        'S' => _AM_SYSTEM_BLOCKS_AFWSMILE,
138
                        'T' => _AM_SYSTEM_BLOCKS_AFNOSMILE,
139
                    ],
140
                );
141
                $form->addElement($ctype_select);
142
            } else {
143
                $form->addElement(new XoopsFormHidden('c_type', 'H'));
144
            }
145
        } else {
146
            if ($this->getVar('template') !== '') {
147
                $tplfile_handler = xoops_getHandler('tplfile');
148
                $btemplate       = $tplfile_handler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $this->getVar('bid'));
0 ignored issues
show
Bug introduced by
The method find() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsTplfileHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

148
                /** @scrutinizer ignore-call */ 
149
                $btemplate       = $tplfile_handler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $this->getVar('bid'));
Loading history...
149
                if (count($btemplate) > 0) {
150
                    $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_CONTENT, '<a href="' . XOOPS_URL . '/modules/system/admin.php?fct=tplsets&amp;op=edittpl&amp;id=' . $btemplate[0]->getVar('tpl_id') . '">' . _AM_SYSTEM_BLOCKS_EDITTPL . '</a>'));
151
                } else {
152
                    $btemplate2 = $tplfile_handler->find('default', 'block', $this->getVar('bid'));
153
                    if (count($btemplate2) > 0) {
154
                        $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_CONTENT, '<a href="' . XOOPS_URL . '/modules/system/admin.php?fct=tplsets&amp;op=edittpl&amp;id=' . $btemplate2[0]->getVar('tpl_id') . '" rel="external">' . _AM_SYSTEM_BLOCKS_EDITTPL . '</a>'));
155
                    }
156
                }
157
            }
158
            if ($this->getOptions() !== false) {
159
                $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_OPTIONS, $this->getOptions()));
0 ignored issues
show
Bug introduced by
It seems like $this->getOptions() can also be of type true; however, parameter $value of XoopsFormLabel::__construct() does only seem to accept 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

159
                $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_OPTIONS, /** @scrutinizer ignore-type */ $this->getOptions()));
Loading history...
160
            } else {
161
                $form->addElement(new XoopsFormHidden('options', $this->getVar('options')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('options') can also be of type array and array; however, parameter $value of XoopsFormHidden::__construct() does only seem to accept 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

161
                $form->addElement(new XoopsFormHidden('options', /** @scrutinizer ignore-type */ $this->getVar('options')));
Loading history...
162
            }
163
            $form->addElement(new XoopsFormHidden('c_type', 'H'));
164
        }
165
        $cache_select = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_BCACHETIME, 'bcachetime', $this->getVar('bcachetime'));
166
        $cache_select->addOptionArray(
167
            [
168
                '0'       => _NOCACHE,
169
                '30'      => sprintf(_SECONDS, 30),
170
                '60'      => _MINUTE,
171
                '300'     => sprintf(_MINUTES, 5),
172
                '1800'    => sprintf(_MINUTES, 30),
173
                '3600'    => _HOUR,
174
                '18000'   => sprintf(_HOURS, 5),
175
                '86400'   => _DAY,
176
                '259200'  => sprintf(_DAYS, 3),
177
                '604800'  => _WEEK,
178
                '2592000' => _MONTH,
179
            ],
180
        );
181
        $form->addElement($cache_select);
182
        // Groups
183
        $form->addElement(new XoopsFormSelectGroup(_AM_SYSTEM_BLOCKS_GROUP, 'groups', true, $groups, 5, true));
184
185
        $form->addElement(new XoopsFormHidden('block_type', $this->getVar('block_type')));
186
        $form->addElement(new XoopsFormHidden('mid', $this->getVar('mid')));
187
        $form->addElement(new XoopsFormHidden('func_num', $this->getVar('func_num')));
188
        $form->addElement(new XoopsFormHidden('func_file', $this->getVar('func_file')));
189
        $form->addElement(new XoopsFormHidden('show_func', $this->getVar('show_func')));
190
        $form->addElement(new XoopsFormHidden('edit_func', $this->getVar('edit_func')));
191
        $form->addElement(new XoopsFormHidden('template', $this->getVar('template')));
192
        $form->addElement(new XoopsFormHidden('dirname', $this->getVar('dirname')));
193
        $form->addElement(new XoopsFormHidden('name', $this->getVar('name')));
194
        $form->addElement(new XoopsFormHidden('bid', $this->getVar('bid')));
195
        $form->addElement(new XoopsFormHidden('op', $op));
196
        $form->addElement(new XoopsFormHidden('fct', 'blocksadmin'));
197
        $button_tray = new XoopsFormElementTray('', '&nbsp;');
198
        if ($this->isNew() || $this->isCustom()) {
199
            $preview = new XoopsFormButton('', 'previewblock', _PREVIEW, 'preview');
200
            $preview->setExtra("onclick=\"blocks_preview();\"");
201
            $button_tray->addElement($preview);
202
        }
203
        $button_tray->addElement(new XoopsFormButton('', 'submitblock', _SUBMIT, 'submit'));
204
        $form->addElement($button_tray);
205
206
        return $form;
207
    }
208
209
    /**
210
     * XoopsBlock::getOptions()
211
     *
212
     * @return bool|string
213
     */
214
    public function getOptions()
215
    {
216
        global $xoopsConfig;
217
        if (!$this->isCustom()) {
218
            $edit_func = $this->getVar('edit_func');
219
            if (!$edit_func) {
220
                return false;
221
            }
222
            if (file_exists($GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/blocks/' . $this->getVar('func_file')))) {
223
                if (file_exists($file = $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/blocks.php'))) {
224
                    include_once $file;
225
                } elseif (file_exists($file = $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/language/english/blocks.php'))) {
226
                    include_once $file;
227
                }
228
                include_once $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/blocks/' . $this->getVar('func_file'));
229
                $options   = explode('|', (string) $this->getVar('options'));
230
                $edit_form = $edit_func($options);
231
                if (!$edit_form) {
232
                    return false;
233
                }
234
235
                return $edit_form;
236
            } else {
237
                return false;
238
            }
239
        } else {
240
            return false;
241
        }
242
    }
243
244
    /**
245
     * @return bool
246
     */
247
    public function isCustom()
248
    {
249
        return $this->getVar('block_type') === 'C';
250
    }
251
252
    /**
253
     * do stripslashes/htmlspecialchars according to the needed output
254
     *
255
     * @param string $format output use: S for Show and E for Edit
256
     * @param string $c_type type of block content
257
     *
258
     * @returns string
259
     */
260
    public function getContent($format = 's', $c_type = 'T')
261
    {
262
        $format = strtolower($format);
263
        $c_type = strtoupper($c_type);
264
        switch ($format) {
265
            case 's':
266
                // check the type of content
267
                // H : custom HTML block
268
                // P : custom PHP block
269
                // S : use text sanitizater (smilies enabled)
270
                // T : use text sanitizater (smilies disabled)
271
                if ($c_type === 'H') {
272
                    return str_replace('{X_SITEURL}', XOOPS_URL . '/', (string) $this->getVar('content', 'n'));
273
                } elseif ($c_type === 'P') {
274
                    ob_start();
275
                    echo eval($this->getVar('content', 'n'));
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
276
                    $content = ob_get_contents();
277
                    ob_end_clean();
278
279
                    return str_replace('{X_SITEURL}', XOOPS_URL . '/', $content);
280
                } elseif ($c_type === 'S') {
281
                    $myts    = \MyTextSanitizer::getInstance();
282
                    $content = str_replace('{X_SITEURL}', XOOPS_URL . '/', (string) $this->getVar('content', 'n'));
283
284
                    return $myts->displayTarea($content, 1, 1);
285
                } else {
286
                    $myts    = \MyTextSanitizer::getInstance();
287
                    $content = str_replace('{X_SITEURL}', XOOPS_URL . '/', (string) $this->getVar('content', 'n'));
288
289
                    return $myts->displayTarea($content, 1, 0);
290
                }
291
                break;
292
            case 'e':
293
                return $this->getVar('content', 'e');
294
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
295
            default:
296
                return $this->getVar('content', 'n');
297
                break;
298
        }
299
    }
300
}
301
302
/**
303
 * System block handler class.
304
 *
305
 * This class is responsible for providing data access mechanisms to the data source
306
 * of XOOPS block class objects.
307
 *
308
 * @copyright       (c) 2000-2025 XOOPS Project (https://xoops.org)
309
 * @package             system
310
 * @subpackage          blocks
311
 */
312
class SystemBlockHandler extends XoopsPersistableObjectHandler
313
{
314
    /**
315
     * @param null|XoopsDatabase $db
316
     */
317
    public function __construct(XoopsDatabase $db)
318
    {
319
        parent::__construct($db, 'newblocks', 'SystemBlock', 'bid', 'title');
320
    }
321
322
    /**
323
     * @param XoopsObject|SystemBlock $obj
324
     *
325
     * @return int|bool object id on success, otherwise false
326
     */
327
    public function insert(XoopsObject $obj, $force = true)
328
    {
329
        if (!($obj instanceof $this->className)) {
330
            return false;
331
        }
332
        $obj->setVar('last_modified', time());
333
334
        return parent::insert($obj, $force);
335
    }
336
337
    /**
338
     * retrieve array of {@link XoopsBlock}s meeting certain conditions
339
     *
340
     * @param CriteriaElement|CriteriaCompo $criteria {@link CriteriaElement} with conditions for the blocks
341
     * @param bool $id_as_key           should the blocks' bid be the key for the returned array?
342
     * @param bool $as_object           return an array of objects
343
     *
344
     * @return array {@link XoopsBlock}s matching the conditions
345
     **/
346
    public function &getObjects(?CriteriaElement $criteria = null, $id_as_key = false, $as_object = true)
347
    {
348
        $ret   = [];
349
        $limit = $start = 0;
350
        $sql   = 'SELECT DISTINCT(b.bid), b.* FROM ' . $this->db->prefix('newblocks') . ' b LEFT JOIN ' . $this->db->prefix('block_module_link') . ' l ON b.bid=l.block_id';
351
        if (isset($criteria) && \method_exists($criteria, 'renderWhere')) {
352
            $sql .= ' ' . $criteria->renderWhere();
353
            $limit = $criteria->getLimit();
354
            $start = $criteria->getStart();
355
        }
356
        $result = $this->db->query($sql, $limit, $start);
0 ignored issues
show
Bug introduced by
The method query() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

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

356
        /** @scrutinizer ignore-call */ 
357
        $result = $this->db->query($sql, $limit, $start);
Loading history...
357
        if (!$this->db->isResultSet($result)) {
358
            return $ret;
359
        }
360
361
        if ($as_object) {
362
            /** @var array $myrow */
363
            while (false !== ($myrow = $this->db->fetchArray($result))) {
0 ignored issues
show
Bug introduced by
The method fetchArray() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

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

363
            while (false !== ($myrow = $this->db->/** @scrutinizer ignore-call */ fetchArray($result))) {
Loading history...
364
                $object = $this->create(false);
365
                $object->assignVars($myrow);
366
                if ($id_as_key) {
367
                    $ret[$myrow[$this->keyName]] = $object;
368
                } else {
369
                    $ret[] = $object;
370
                }
371
                unset($object);
372
            }
373
        } else {
374
            $object = $this->create(false);
375
            /** @var array $myrow */
376
            while (false !== ($myrow = $this->db->fetchArray($result))) {
377
                $object->assignVars($myrow);
378
                if ($id_as_key) {
379
                    $ret[$myrow[$this->keyName]] = $object->getValues(array_keys($myrow));
380
                } else {
381
                    $ret[] = $object->getValues(array_keys($myrow));
382
                }
383
            }
384
            unset($object);
385
        }
386
387
        return $ret;
388
    }
389
390
    /**
391
     * get all the blocks that match the supplied parameters
392
     *
393
     * @param int|int[] $groupid  groupid (can be an array)
394
     * @param bool $asobject
395
     * @param int|string $side
396
     *                            0: sideblock - left
397
     *                            1: sideblock - right
398
     *                            2: sideblock - left and right
399
     *                            3: centerblock - left
400
     *                            4: centerblock - right
401
     *                            5: centerblock - center
402
     *                            6: centerblock - left, right, center
403
     * @param           $visible  0: not visible 1: visible
0 ignored issues
show
Documentation Bug introduced by
The doc comment 0: not at position 0 could not be parsed: Unknown type name '0' at position 0 in 0: not.
Loading history...
404
     * @param string $orderby     order of the blocks
405
     * @param int $isactive
406
     *
407
     * @return array of block objects
408
     */
409
    public function getAllBlocksByGroup($groupid, $asobject = true, $side = null, $visible = null, $orderby = 'b.weight,b.bid', $isactive = 1)
410
    {
411
        /** @var XoopsMySQLDatabase $db */
412
        $db  = XoopsDatabaseFactory::getDatabaseConnection();
413
        $ret = [];
414
        $sql = 'SELECT b.* ';
415
        if (!$asobject) {
416
            $sql = 'SELECT b.bid ';
417
        }
418
        $sql .= 'FROM ' . $db->prefix('newblocks') . ' b LEFT JOIN ' . $db->prefix('group_permission') . " l ON l.gperm_itemid=b.bid WHERE gperm_name = 'block_read' AND gperm_modid = 1";
419
        if (is_array($groupid)) {
420
            $sql .= ' AND (l.gperm_groupid=' . $groupid[0] . '';
421
            $size = count($groupid);
422
            if ($size > 1) {
423
                for ($i = 1; $i < $size; ++$i) {
424
                    $sql .= ' OR l.gperm_groupid=' . $groupid[$i] . '';
425
                }
426
            }
427
            $sql .= ')';
428
        } else {
429
            $sql .= ' AND l.gperm_groupid=' . $groupid . '';
430
        }
431
        $sql .= ' AND b.isactive=' . $isactive;
432
        if (isset($side)) {
433
            // get both sides in sidebox? (some themes need this)
434
            if ($side === XOOPS_SIDEBLOCK_BOTH) {
435
                $side = '(b.side=0 OR b.side=1)';
436
            } elseif ($side === XOOPS_CENTERBLOCK_ALL) {
437
                $side = '(b.side=3 OR b.side=4 OR b.side=5 OR b.side=7 OR b.side=8 OR b.side=9 )';
438
            } elseif ($side === XOOPS_FOOTERBLOCK_ALL) {
439
                $side = '(b.side=10 OR b.side=11 OR b.side=12 )';
440
            } else {
441
                $side = 'b.side=' . $side;
442
            }
443
            $sql .= ' AND ' . $side;
444
        }
445
        if (isset($visible)) {
446
            $sql .= " AND b.visible=$visible";
447
        }
448
        $sql .= " ORDER BY $orderby";
449
        $result = $db->query($sql);
450
        if (!$db->isResultSet($result)) {
451
            throw new \RuntimeException(
452
                \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
453
                E_USER_ERROR,
454
            );
455
        }
456
        $added  = [];
457
        while (false !== ($myrow = $db->fetchArray($result))) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, 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

457
        while (false !== ($myrow = $db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
458
            if (!in_array($myrow['bid'], $added)) {
459
                if (!$asobject) {
460
                    $ret[] = $myrow['bid'];
461
                } else {
462
                    $ret[] = new XoopsBlock($myrow);
463
                }
464
                $added[] = $myrow['bid'];
465
            }
466
        }
467
468
        return $ret;
469
    }
470
471
    /**
472
     * @param $groupid
473
     *
474
     * @return array
475
     */
476
    public function getBlockByPerm($groupid)
477
    {
478
        if (isset($groupid)) {
479
            $sql = 'SELECT DISTINCT gperm_itemid FROM ' . $this->db->prefix('group_permission') . " WHERE gperm_name = 'block_read' AND gperm_modid = 1";
480
            if (is_array($groupid)) {
481
                $sql .= ' AND gperm_groupid IN (' . implode(',', $groupid) . ')';
482
            } else {
483
                if ((int) $groupid > 0) {
484
                    $sql .= ' AND gperm_groupid=' . (int) $groupid;
485
                }
486
            }
487
            $result = $this->db->query($sql);
488
            if (!$this->db->isResultSet($result)) {
489
                throw new \RuntimeException(
490
                    \sprintf(_DB_QUERY_ERROR, $sql) . $this->db->error(),
0 ignored issues
show
Bug introduced by
The method error() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

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

490
                    \sprintf(_DB_QUERY_ERROR, $sql) . $this->db->/** @scrutinizer ignore-call */ error(),
Loading history...
491
                    E_USER_ERROR,
492
                );
493
            }
494
            $blockids = [];
495
            /** @var array $myrow */
496
            while (false !== ($myrow = $this->db->fetchArray($result))) {
497
                $blockids[] = $myrow['gperm_itemid'];
498
            }
499
            if (empty($blockids)) {
500
                return $blockids;
501
            }
502
503
            return $blockids;
504
        }
505
506
        return null;
507
    }
508
509
    /**
510
     * @param        $groupid
511
     * @param int $module_id
512
     * @param bool $toponlyblock
513
     * @param null $visible
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $visible is correct as it would always require null to be passed?
Loading history...
514
     * @param string $orderby
515
     * @param int $isactive
516
     *
517
     * @return array
518
     */
519
    public function getAllByGroupModule($groupid, $module_id = 0, $toponlyblock = false, $visible = null, $orderby = 'b.weight, m.block_id', $isactive = 1)
520
    {
521
        $isactive = (int) $isactive;
522
        $db       = $GLOBALS['xoopsDB'];
523
        $ret      = [];
524
        if (isset($groupid)) {
525
            $sql = 'SELECT DISTINCT gperm_itemid FROM ' . $db->prefix('group_permission') . " WHERE gperm_name = 'block_read' AND gperm_modid = 1";
526
            if (is_array($groupid)) {
527
                $sql .= ' AND gperm_groupid IN (' . implode(',', $groupid) . ')';
528
            } else {
529
                if ((int) $groupid > 0) {
530
                    $sql .= ' AND gperm_groupid=' . (int) $groupid;
531
                }
532
            }
533
            $result = $db->query($sql);
534
            if (!$db->isResultSet($result)) {
535
                throw new \RuntimeException(
536
                    \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
537
                    E_USER_ERROR,
538
                );
539
            }
540
            $blockids = [];
541
            while (false !== ($myrow = $db->fetchArray($result))) {
542
                $blockids[] = $myrow['gperm_itemid'];
543
            }
544
            if (empty($blockids)) {
545
                return $blockids;
546
            }
547
        }
548
        $sql = 'SELECT b.* FROM ' . $db->prefix('newblocks') . ' b, ' . $db->prefix('block_module_link') . ' m WHERE m.block_id=b.bid';
549
        $sql .= ' AND b.isactive=' . $isactive;
550
        if (isset($visible)) {
551
            $sql .= ' AND b.visible=' . (int) $visible;
552
        }
553
        if (!isset($module_id)) {
554
        } elseif (!empty($module_id)) {
555
            $sql .= ' AND m.module_id IN (0,' . (int) $module_id;
556
            if ($toponlyblock) {
557
                $sql .= ',-1';
558
            }
559
            $sql .= ')';
560
        } else {
561
            if ($toponlyblock) {
562
                $sql .= ' AND m.module_id IN (0,-1)';
563
            } else {
564
                $sql .= ' AND m.module_id=0';
565
            }
566
        }
567
        if (!empty($blockids)) {
568
            $sql .= ' AND b.bid IN (' . implode(',', $blockids) . ')';
569
        }
570
        $sql .= ' ORDER BY ' . $orderby;
571
        $result = $db->query($sql);
572
        if (!$db->isResultSet($result)) {
573
            throw new \RuntimeException(
574
                \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
575
                E_USER_ERROR,
576
            );
577
        }
578
        while (false !== ($myrow = $db->fetchArray($result))) {
579
            $block              = new XoopsBlock($myrow);
580
            $ret[$myrow['bid']] = & $block;
581
            unset($block);
582
        }
583
584
        return $ret;
585
    }
586
587
    /**
588
     * @param int $module_id
589
     * @param bool $toponlyblock
590
     * @param null $visible
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $visible is correct as it would always require null to be passed?
Loading history...
591
     * @param string $orderby
592
     * @param int $isactive
593
     *
594
     * @return array
595
     */
596
    public function getNonGroupedBlocks($module_id = 0, $toponlyblock = false, $visible = null, $orderby = 'b.weight, m.block_id', $isactive = 1)
597
    {
598
        $db   = $GLOBALS['xoopsDB'];
599
        $ret  = [];
600
        $bids = [];
601
        $sql  = 'SELECT DISTINCT(bid) from ' . $db->prefix('newblocks');
602
        $result = $db->query($sql);
603
        if ($db->isResultSet($result)) {
604
            while (false !== ($myrow = $db->fetchArray($result))) {
605
                $bids[] = $myrow['bid'];
606
            }
607
        }
608
609
        $sql     = 'SELECT DISTINCT(p.gperm_itemid) from ' . $db->prefix('group_permission') . ' p, ' . $db->prefix('groups') . " g WHERE g.groupid=p.gperm_groupid AND p.gperm_name='block_read'";
610
        $grouped = [];
611
        $result = $db->query($sql);
612
        if ($db->isResultSet($result)) {
613
            while (false !== ($myrow = $db->fetchArray($result))) {
614
                $grouped[] = $myrow['gperm_itemid'];
615
            }
616
        }
617
618
        $non_grouped = array_diff($bids, $grouped);
619
        if (!empty($non_grouped)) {
620
            $sql = 'SELECT b.* FROM ' . $db->prefix('newblocks') . ' b, ' . $db->prefix('block_module_link') . ' m WHERE m.block_id=b.bid';
621
            $sql .= ' AND b.isactive=' . (int) $isactive;
622
            if (isset($visible)) {
623
                $sql .= ' AND b.visible=' . (int) $visible;
624
            }
625
            if (!isset($module_id)) {
626
            } elseif (!empty($module_id)) {
627
                $sql .= ' AND m.module_id IN (0,' . (int) $module_id;
628
                if ($toponlyblock) {
629
                    $sql .= ',-1';
630
                }
631
                $sql .= ')';
632
            } else {
633
                if ($toponlyblock) {
634
                    $sql .= ' AND m.module_id IN (0,-1)';
635
                } else {
636
                    $sql .= ' AND m.module_id=0';
637
                }
638
            }
639
            $sql .= ' AND b.bid IN (' . implode(',', $non_grouped) . ')';
640
            $sql .= ' ORDER BY ' . $orderby;
641
            $result = $db->query($sql);
642
            if (!$db->isResultSet($result)) {
643
                throw new \RuntimeException(
644
                    \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
645
                    E_USER_ERROR,
646
                );
647
            }
648
            while (false !== ($myrow = $db->fetchArray($result))) {
649
                $block              = new XoopsBlock($myrow);
650
                $ret[$myrow['bid']] = & $block;
651
                unset($block);
652
            }
653
        }
654
655
        return $ret;
656
    }
657
658
    /**
659
     * XoopsBlock::countSimilarBlocks()
660
     *
661
     * @param  mixed $moduleId
662
     * @param  mixed $funcNum
663
     * @param  mixed $showFunc
664
     * @return int
665
     */
666
    public function countSimilarBlocks($moduleId, $funcNum, $showFunc = null)
667
    {
668
        $funcNum  = (int) $funcNum;
669
        $moduleId = (int) $moduleId;
670
        if ($funcNum < 1 || $moduleId < 1) {
671
            // invalid query
672
            return 0;
673
        }
674
        /** @var XoopsMySQLDatabase $db */
675
        $db = XoopsDatabaseFactory::getDatabaseConnection();
676
        if (isset($showFunc)) {
677
            // showFunc is set for more strict comparison
678
            $sql = sprintf('SELECT COUNT(*) FROM %s WHERE mid = %d AND func_num = %d AND show_func = %s', $db->prefix('newblocks'), $moduleId, $funcNum, $db->quoteString(trim((string) $showFunc)));
679
        } else {
680
            $sql = sprintf('SELECT COUNT(*) FROM %s WHERE mid = %d AND func_num = %d', $db->prefix('newblocks'), $moduleId, $funcNum);
681
        }
682
        $result = $db->query($sql);
683
        if (!$db->isResultSet($result)) {
684
            // throw new \RuntimeException(
685
            //       \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(), E_USER_ERROR
686
            // );
687
            return 0;
688
        }
689
        [$count] = $db->fetchRow($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchRow() does only seem to accept mysqli_result, 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

689
        [$count] = $db->fetchRow(/** @scrutinizer ignore-type */ $result);
Loading history...
690
691
        return (int) $count;
692
    }
693
}
694