Passed
Pull Request — master (#1270)
by Michael
04:44
created

SystemBlockHandler::countSimilarBlocks()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 5
nop 3
dl 0
loc 24
rs 9.4888
c 0
b 0
f 0
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
            \trigger_error("Query Failed! SQL: $sql- Error: " . $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

349
            \trigger_error("Query Failed! SQL: $sql- Error: " . $this->db->/** @scrutinizer ignore-call */ error(), E_USER_ERROR);
Loading history...
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
            \trigger_error("Query Failed! SQL: $sql- Error: " . $db->error(), E_USER_ERROR);
441
        }
442
        $added  = array();
443
        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

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

662
        list($count) = $db->fetchRow(/** @scrutinizer ignore-type */ $result);
Loading history...
663
664
        return $count;
665
    }
666
}
667