Passed
Push — master ( 05faca...9c86bf )
by Richard
08:39 queued 13s
created

SystemBlockHandler::getAllByGroupModule()   D

Complexity

Conditions 15
Paths 246

Size

Total Lines 64
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 46
nc 246
nop 6
dl 0
loc 64
rs 4.5083
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-2016 XOOPS Project (www.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-2016 XOOPS Project (www.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 = array(-1);
46
            $groups  = array(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')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('bid') can also be of type array and array; however, parameter $value of Criteria::__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

54
            $criteria                = new CriteriaCompo(new Criteria('block_id', /** @scrutinizer ignore-type */ $this->getVar('bid')));
Loading history...
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(array(
87
                                         0  => _AM_SYSTEM_BLOCKS_SBLEFT,
88
                                         1  => _AM_SYSTEM_BLOCKS_SBRIGHT,
89
                                         3  => _AM_SYSTEM_BLOCKS_CBLEFT,
90
                                         4  => _AM_SYSTEM_BLOCKS_CBRIGHT,
91
                                         5  => _AM_SYSTEM_BLOCKS_CBCENTER,
92
                                         7  => _AM_SYSTEM_BLOCKS_CBBOTTOMLEFT,
93
                                         8  => _AM_SYSTEM_BLOCKS_CBBOTTOMRIGHT,
94
                                         9  => _AM_SYSTEM_BLOCKS_CBBOTTOM,
95
                                         10 => _AM_SYSTEM_BLOCKS_CBFOOTERLEFT,
96
                                         11 => _AM_SYSTEM_BLOCKS_CBFOOTERRIGHT,
97
                                         12 => _AM_SYSTEM_BLOCKS_CBFOOTERCENTER));
98
99
        $form->addElement($side_select);
100
        // Order
101
        $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

101
        $form->addElement(new XoopsFormText(_AM_SYSTEM_BLOCKS_WEIGHT, 'weight', 2, 5, /** @scrutinizer ignore-type */ $this->getVar('weight')));
Loading history...
102
        // Display
103
        $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

103
        $form->addElement(new XoopsFormRadioYN(_AM_SYSTEM_BLOCKS_VISIBLE, 'visible', /** @scrutinizer ignore-type */ $this->getVar('visible')));
Loading history...
104
        // Visible In
105
        $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...
106
        /* @var XoopsModuleHandler $module_handler */
107
        $module_handler = xoops_getHandler('module');
108
        $criteria       = new CriteriaCompo(new Criteria('hasmain', 1));
109
        $criteria->add(new Criteria('isactive', 1));
110
        $module_list     = $module_handler->getList($criteria);
111
        $module_list[-1] = _AM_SYSTEM_BLOCKS_TOPPAGE;
112
        $module_list[0]  = _AM_SYSTEM_BLOCKS_ALLPAGES;
113
        ksort($module_list);
114
        $mod_select->addOptionArray($module_list);
115
        $form->addElement($mod_select);
116
        // Title
117
        $form->addElement(new XoopsFormText(_AM_SYSTEM_BLOCKS_TITLE, 'title', 50, 255, $this->getVar('title')), false);
118
        if ($this->isNew() || $this->isCustom()) {
119
            $editor_configs           = array();
120
            $editor_configs['name']   = 'content_block';
121
            $editor_configs['value']  = $this->getVar('content', 'e');
122
            $editor_configs['rows']   = 20;
123
            $editor_configs['cols']   = 100;
124
            $editor_configs['width']  = '100%';
125
            $editor_configs['height'] = '400px';
126
            $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

126
            $editor_configs['editor'] = /** @scrutinizer ignore-deprecated */ xoops_getModuleOption('blocks_editor', 'system');
Loading history...
127
            $form->addElement(new XoopsFormEditor(_AM_SYSTEM_BLOCKS_CONTENT, 'content_block', $editor_configs), true);
128
            if (in_array($editor_configs['editor'], array('dhtmltextarea', 'textarea'))) {
129
                $ctype_select = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_CTYPE, 'c_type', $this->getVar('c_type'));
130
                $ctype_select->addOptionArray(array(
131
                                                  'H' => _AM_SYSTEM_BLOCKS_HTML,
132
                                                  'P' => _AM_SYSTEM_BLOCKS_PHP,
133
                                                  'S' => _AM_SYSTEM_BLOCKS_AFWSMILE,
134
                                                  'T' => _AM_SYSTEM_BLOCKS_AFNOSMILE));
135
                $form->addElement($ctype_select);
136
            } else {
137
                $form->addElement(new XoopsFormHidden('c_type', 'H'));
138
            }
139
        } else {
140
            if ($this->getVar('template') !== '') {
141
                $tplfile_handler = xoops_getHandler('tplfile');
142
                $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

142
                /** @scrutinizer ignore-call */ 
143
                $btemplate       = $tplfile_handler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $this->getVar('bid'));
Loading history...
143
                if (count($btemplate) > 0) {
144
                    $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>'));
145
                } else {
146
                    $btemplate2 = $tplfile_handler->find('default', 'block', $this->getVar('bid'));
147
                    if (count($btemplate2) > 0) {
148
                        $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>'));
149
                    }
150
                }
151
            }
152
            if ($this->getOptions() !== false) {
153
                $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

153
                $form->addElement(new XoopsFormLabel(_AM_SYSTEM_BLOCKS_OPTIONS, /** @scrutinizer ignore-type */ $this->getOptions()));
Loading history...
154
            } else {
155
                $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

155
                $form->addElement(new XoopsFormHidden('options', /** @scrutinizer ignore-type */ $this->getVar('options')));
Loading history...
156
            }
157
            $form->addElement(new XoopsFormHidden('c_type', 'H'));
158
        }
159
        $cache_select = new XoopsFormSelect(_AM_SYSTEM_BLOCKS_BCACHETIME, 'bcachetime', $this->getVar('bcachetime'));
160
        $cache_select->addOptionArray(array(
161
                                          '0'       => _NOCACHE,
162
                                          '30'      => sprintf(_SECONDS, 30),
163
                                          '60'      => _MINUTE,
164
                                          '300'     => sprintf(_MINUTES, 5),
165
                                          '1800'    => sprintf(_MINUTES, 30),
166
                                          '3600'    => _HOUR,
167
                                          '18000'   => sprintf(_HOURS, 5),
168
                                          '86400'   => _DAY,
169
                                          '259200'  => sprintf(_DAYS, 3),
170
                                          '604800'  => _WEEK,
171
                                          '2592000' => _MONTH));
172
        $form->addElement($cache_select);
173
        // Groups
174
        $form->addElement(new XoopsFormSelectGroup(_AM_SYSTEM_BLOCKS_GROUP, 'groups', true, $groups, 5, true));
175
176
        $form->addElement(new XoopsFormHidden('block_type', $this->getVar('block_type')));
177
        $form->addElement(new XoopsFormHidden('mid', $this->getVar('mid')));
178
        $form->addElement(new XoopsFormHidden('func_num', $this->getVar('func_num')));
179
        $form->addElement(new XoopsFormHidden('func_file', $this->getVar('func_file')));
180
        $form->addElement(new XoopsFormHidden('show_func', $this->getVar('show_func')));
181
        $form->addElement(new XoopsFormHidden('edit_func', $this->getVar('edit_func')));
182
        $form->addElement(new XoopsFormHidden('template', $this->getVar('template')));
183
        $form->addElement(new XoopsFormHidden('dirname', $this->getVar('dirname')));
184
        $form->addElement(new XoopsFormHidden('name', $this->getVar('name')));
185
        $form->addElement(new XoopsFormHidden('bid', $this->getVar('bid')));
186
        $form->addElement(new XoopsFormHidden('op', $op));
187
        $form->addElement(new XoopsFormHidden('fct', 'blocksadmin'));
188
        $button_tray = new XoopsFormElementTray('', '&nbsp;');
189
        if ($this->isNew() || $this->isCustom()) {
190
            $preview = new XoopsFormButton('', 'previewblock', _PREVIEW, 'preview');
191
            $preview->setExtra("onclick=\"blocks_preview();\"");
192
            $button_tray->addElement($preview);
193
        }
194
        $button_tray->addElement(new XoopsFormButton('', 'submitblock', _SUBMIT, 'submit'));
195
        $form->addElement($button_tray);
196
197
        return $form;
198
    }
199
200
    /**
201
     * XoopsBlock::getOptions()
202
     *
203
     * @return bool|string
204
     */
205
    public function getOptions()
206
    {
207
        global $xoopsConfig;
208
        if (!$this->isCustom()) {
209
            $edit_func = $this->getVar('edit_func');
210
            if (!$edit_func) {
211
                return false;
212
            }
213
            if (file_exists($GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/blocks/' . $this->getVar('func_file')))) {
214
                if (file_exists($file = $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/blocks.php'))) {
215
                    include_once $file;
216
                } elseif (file_exists($file = $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/language/english/blocks.php'))) {
217
                    include_once $file;
218
                }
219
                include_once $GLOBALS['xoops']->path('modules/' . $this->getVar('dirname') . '/blocks/' . $this->getVar('func_file'));
220
                $options   = explode('|', $this->getVar('options'));
221
                $edit_form = $edit_func($options);
222
                if (!$edit_form) {
223
                    return false;
224
                }
225
226
                return $edit_form;
227
            } else {
228
                return false;
229
            }
230
        } else {
231
            return false;
232
        }
233
    }
234
235
    /**
236
     * @return bool
237
     */
238
    public function isCustom()
239
    {
240
        return $this->getVar('block_type') === 'C';
241
    }
242
243
    /**
244
     * do stripslashes/htmlspecialchars according to the needed output
245
     *
246
     * @param string $format output use: S for Show and E for Edit
247
     * @param string $c_type type of block content
248
     *
249
     * @returns string
250
     */
251
    public function getContent($format = 's', $c_type = 'T')
252
    {
253
        $format = strtolower($format);
254
        $c_type = strtoupper($c_type);
255
        switch ($format) {
256
            case 's':
257
                // check the type of content
258
                // H : custom HTML block
259
                // P : custom PHP block
260
                // S : use text sanitizater (smilies enabled)
261
                // T : use text sanitizater (smilies disabled)
262
                if ($c_type === 'H') {
263
                    return str_replace('{X_SITEURL}', XOOPS_URL . '/', $this->getVar('content', 'n'));
264
                } elseif ($c_type === 'P') {
265
                    ob_start();
266
                    echo eval($this->getVar('content', 'n'));
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
267
                    $content = ob_get_contents();
268
                    ob_end_clean();
269
270
                    return str_replace('{X_SITEURL}', XOOPS_URL . '/', $content);
271
                } elseif ($c_type === 'S') {
272
                    $myts    = \MyTextSanitizer::getInstance();
273
                    $content = str_replace('{X_SITEURL}', XOOPS_URL . '/', $this->getVar('content', 'n'));
274
275
                    return $myts->displayTarea($content, 1, 1);
276
                } else {
277
                    $myts    = \MyTextSanitizer::getInstance();
278
                    $content = str_replace('{X_SITEURL}', XOOPS_URL . '/', $this->getVar('content', 'n'));
279
280
                    return $myts->displayTarea($content, 1, 0);
281
                }
282
                break;
283
            case 'e':
284
                return $this->getVar('content', 'e');
285
                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...
286
            default:
287
                return $this->getVar('content', 'n');
288
                break;
289
        }
290
    }
291
}
292
293
/**
294
 * System block handler class.
295
 *
296
 * This class is responsible for providing data access mechanisms to the data source
297
 * of XOOPS block class objects.
298
 *
299
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
300
 * @package             system
301
 * @subpackage          blocks
302
 */
303
class SystemBlockHandler extends XoopsPersistableObjectHandler
304
{
305
    /**
306
     * @param null|XoopsDatabase $db
307
     */
308
    public function __construct(XoopsDatabase $db)
309
    {
310
        parent::__construct($db, 'newblocks', 'SystemBlock', 'bid', 'title');
311
    }
312
313
    /**
314
     * @param XoopsObject|SystemBlock $obj
315
     *
316
     * @return int|bool object id on success, otherwise false
317
     */
318
    public function insert(XoopsObject $obj, $force = true)
319
    {
320
        if (!($obj instanceof $this->className)) {
321
            return false;
322
        }
323
        $obj->setVar('last_modified', time());
324
325
        return parent::insert($obj, $force);
326
    }
327
328
    /**
329
     * retrieve array of {@link XoopsBlock}s meeting certain conditions
330
     *
331
     * @param CriteriaElement|CriteriaCompo $criteria {@link CriteriaElement} with conditions for the blocks
332
     * @param bool $id_as_key           should the blocks' bid be the key for the returned array?
333
     * @param bool $as_object           return an array of objects
334
     *
335
     * @return array {@link XoopsBlock}s matching the conditions
336
     **/
337
    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false, $as_object = true)
338
    {
339
        $ret   = array();
340
        $limit = $start = 0;
341
        $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';
342
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
343
            $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

343
            $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...
344
            $limit = $criteria->getLimit();
345
            $start = $criteria->getStart();
346
        }
347
        $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

347
        /** @scrutinizer ignore-call */ 
348
        $result = $this->db->query($sql, $limit, $start);
Loading history...
348
        if (!$this->db->isResultSet($result)) {
349
            return $ret;
350
        }
351
352
        if ($as_object) {
353
            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

353
            while (false !== ($myrow = $this->db->/** @scrutinizer ignore-call */ fetchArray($result))) {
Loading history...
354
                $object = $this->create(false);
355
                $object->assignVars($myrow);
356
                if ($id_as_key) {
357
                    $ret[$myrow[$this->keyName]] = $object;
358
                } else {
359
                    $ret[] = $object;
360
                }
361
                unset($object);
362
            }
363
        } else {
364
            $object = $this->create(false);
365
            while (false !== ($myrow = $this->db->fetchArray($result))) {
366
                $object->assignVars($myrow);
367
                if ($id_as_key) {
368
                    $ret[$myrow[$this->keyName]] = $object->getValues(array_keys($myrow));
369
                } else {
370
                    $ret[] = $object->getValues(array_keys($myrow));
371
                }
372
            }
373
            unset($object);
374
        }
375
376
        return $ret;
377
    }
378
379
    /**
380
     * get all the blocks that match the supplied parameters
381
     *
382
     * @param int|int[] $groupid  groupid (can be an array)
383
     * @param bool $asobject
384
     * @param int|string $side
385
     *                            0: sideblock - left
386
     *                            1: sideblock - right
387
     *                            2: sideblock - left and right
388
     *                            3: centerblock - left
389
     *                            4: centerblock - right
390
     *                            5: centerblock - center
391
     *                            6: centerblock - left, right, center
392
     * @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...
393
     * @param string $orderby     order of the blocks
394
     * @param int $isactive
395
     *
396
     * @return array of block objects
397
     */
398
    public function getAllBlocksByGroup($groupid, $asobject = true, $side = null, $visible = null, $orderby = 'b.weight,b.bid', $isactive = 1)
399
    {
400
        /* @var XoopsMySQLDatabase $db */
401
        $db  = XoopsDatabaseFactory::getDatabaseConnection();
402
        $ret = array();
403
        $sql = 'SELECT b.* ';
404
        if (!$asobject) {
405
            $sql = 'SELECT b.bid ';
406
        }
407
        $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";
408
        if (is_array($groupid)) {
409
            $sql .= ' AND (l.gperm_groupid=' . $groupid[0] . '';
410
            $size = count($groupid);
411
            if ($size > 1) {
412
                for ($i = 1; $i < $size; ++$i) {
413
                    $sql .= ' OR l.gperm_groupid=' . $groupid[$i] . '';
414
                }
415
            }
416
            $sql .= ')';
417
        } else {
418
            $sql .= ' AND l.gperm_groupid=' . $groupid . '';
419
        }
420
        $sql .= ' AND b.isactive=' . $isactive;
421
        if (isset($side)) {
422
            // get both sides in sidebox? (some themes need this)
423
            if ($side === XOOPS_SIDEBLOCK_BOTH) {
424
                $side = '(b.side=0 OR b.side=1)';
425
            } elseif ($side === XOOPS_CENTERBLOCK_ALL) {
426
                $side = '(b.side=3 OR b.side=4 OR b.side=5 OR b.side=7 OR b.side=8 OR b.side=9 )';
427
            } elseif ($side === XOOPS_FOOTERBLOCK_ALL) {
428
                $side = '(b.side=10 OR b.side=11 OR b.side=12 )';
429
            } else {
430
                $side = 'b.side=' . $side;
431
            }
432
            $sql .= ' AND ' . $side;
433
        }
434
        if (isset($visible)) {
435
            $sql .= " AND b.visible=$visible";
436
        }
437
        $sql .= " ORDER BY $orderby";
438
        $result = $db->query($sql);
439
        if (!$db->isResultSet($result)) {
440
            throw new \RuntimeException(
441
                \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(), E_USER_ERROR
442
            );
443
        }
444
        $added  = array();
445
        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

445
        while (false !== ($myrow = $db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
446
            if (!in_array($myrow['bid'], $added)) {
447
                if (!$asobject) {
448
                    $ret[] = $myrow['bid'];
449
                } else {
450
                    $ret[] = new XoopsBlock($myrow);
451
                }
452
                $added[] = $myrow['bid'];
453
            }
454
        }
455
456
        return $ret;
457
    }
458
459
    /**
460
     * @param $groupid
461
     *
462
     * @return array
463
     */
464
    public function getBlockByPerm($groupid)
465
    {
466
        if (isset($groupid)) {
467
            $sql = 'SELECT DISTINCT gperm_itemid FROM ' . $this->db->prefix('group_permission') . " WHERE gperm_name = 'block_read' AND gperm_modid = 1";
468
            if (is_array($groupid)) {
469
                $sql .= ' AND gperm_groupid IN (' . implode(',', $groupid) . ')';
470
            } else {
471
                if ((int)$groupid > 0) {
472
                    $sql .= ' AND gperm_groupid=' . (int)$groupid;
473
                }
474
            }
475
            $result = $this->db->query($sql);
476
            if (!$this->db->isResultSet($result)) {
477
                throw new \RuntimeException(
478
                    \sprintf(_DB_QUERY_ERROR, $sql) . $this->db->error(), E_USER_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

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

672
        list($count) = $db->fetchRow(/** @scrutinizer ignore-type */ $result);
Loading history...
673
674
        return (int)$count;
675
    }
676
}
677