Blocksadmin::orderBlock()   C
last analyzed

Complexity

Conditions 15
Paths 38

Size

Total Lines 53
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 15
eloc 27
c 1
b 0
f 1
nc 38
nop 15
dl 0
loc 53
rs 5.9166

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Publisher\Common;
4
5
/**
6
 * You may not change or alter any portion of this comment or credits
7
 * of supporting developers from this source code or any supporting source code
8
 * which is considered copyrighted (c) material of the original comment or credit authors.
9
 *
10
 *
11
 * @category        Module
12
 * @author          XOOPS Development Team
13
 * @copyright       XOOPS Project
14
 * @link            https://xoops.org
15
 * @license         GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
16
 */
17
18
use Xmf\Request;
19
20
//use XoopsModules\Tag\{
21
//    Helper
22
//};
23
24
//require __DIR__ . '/admin_header.php';
25
26
/**
27
 * class Blocksadmin
28
 */
29
class Blocksadmin
30
{
31
    /**
32
     * @var \XoopsMySQLDatabase|null
33
     */
34
    public $db;
35
    /**
36
     * @var \XoopsModules\Tag\Helper
37
     */
38
    public $helper;
39
    /**
40
     * @var string
41
     */
42
    public $moduleDirName;
43
    /**
44
     * @var string
45
     */
46
    public $moduleDirNameUpper;
47
48
    /**
49
     * Blocksadmin constructor.
50
     */
51
    public function __construct(?\XoopsDatabase $db, \Xmf\Module\Helper $helper)
52
    {
53
        if (null === $db) {
54
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
55
        }
56
        $this->db                 = $db;
57
        $this->helper             = $helper;
0 ignored issues
show
Documentation Bug introduced by
$helper is of type Xmf\Module\Helper, but the property $helper was declared to be of type XoopsModules\Tag\Helper. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
58
        $this->moduleDirName      = \basename(\dirname(__DIR__, 2));
59
        $this->moduleDirNameUpper = \mb_strtoupper($this->moduleDirName);
60
        \xoops_loadLanguage('admin', 'system');
61
        \xoops_loadLanguage('admin/blocksadmin', 'system');
62
        \xoops_loadLanguage('admin/groups', 'system');
63
        \xoops_loadLanguage('common', $this->moduleDirName);
64
        \xoops_loadLanguage('blocksadmin', $this->moduleDirName);
65
    }
66
67
    public function listBlocks(): void
68
    {
69
        global $xoopsModule, $pathIcon16;
70
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
71
        //        xoops_loadLanguage('admin', 'system');
72
        //        xoops_loadLanguage('admin/blocksadmin', 'system');
73
        //        xoops_loadLanguage('admin/groups', 'system');
74
        //        xoops_loadLanguage('common', $moduleDirName);
75
        //        xoops_loadLanguage('blocks', $moduleDirName);
76
77
        /** @var \XoopsModuleHandler $moduleHandler */
78
        $moduleHandler = \xoops_getHandler('module');
79
        /** @var \XoopsMemberHandler $memberHandler */
80
        $memberHandler = \xoops_getHandler('member');
81
        /** @var \XoopsGroupPermHandler $grouppermHandler */
82
        $grouppermHandler = \xoops_getHandler('groupperm');
83
        $groups           = $memberHandler->getGroups();
84
        $criteria         = new \CriteriaCompo(new \Criteria('hasmain', '1'));
85
        $criteria->add(new \Criteria('isactive', '1'));
86
        $moduleList     = $moduleHandler->getList($criteria);
87
        $moduleList[-1] = \_AM_SYSTEM_BLOCKS_TOPPAGE;
88
        $moduleList[0]  = \_AM_SYSTEM_BLOCKS_ALLPAGES;
89
        \ksort($moduleList);
90
        echo "
91
        <h4 style='text-align:left;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</h4>';
92
        echo "<form action='" . $_SERVER['SCRIPT_NAME'] . "' name='blockadmin' method='post'>";
93
        echo $GLOBALS['xoopsSecurity']->getTokenHTML();
94
        echo "<table width='100%' class='outer' cellpadding='4' cellspacing='1'>
95
        <tr valign='middle'><th align='center'>"
96
             . \_AM_SYSTEM_BLOCKS_TITLE
97
             . "</th><th align='center' nowrap='nowrap'>"
98
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'SIDE')
99
             . '<br>'
100
             . _LEFT
101
             . '-'
102
             . _CENTER
103
             . '-'
104
             . _RIGHT
105
             . "</th><th align='center'>"
106
             . \constant(
107
                 'CO_' . $this->moduleDirNameUpper . '_' . 'WEIGHT'
108
             )
109
             . "</th><th align='center'>"
110
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLE')
111
             . "</th><th align='center'>"
112
             . \_AM_SYSTEM_BLOCKS_VISIBLEIN
113
             . "</th><th align='center'>"
114
             . \_AM_SYSTEM_ADGS
115
             . "</th><th align='center'>"
116
             . \_AM_SYSTEM_BLOCKS_BCACHETIME
117
             . "</th><th align='center'>"
118
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'ACTION')
119
             . '</th></tr>
120
        ';
121
        $blockArray = \XoopsBlock::getByModule($xoopsModule->mid());
122
        $blockCount = \count($blockArray);
0 ignored issues
show
Unused Code introduced by
The assignment to $blockCount is dead and can be removed.
Loading history...
123
        $class      = 'even';
124
        $cachetimes = [
125
            0       => _NOCACHE,
126
            30      => \sprintf(_SECONDS, 30),
127
            60      => _MINUTE,
128
            300     => \sprintf(_MINUTES, 5),
129
            1800    => \sprintf(_MINUTES, 30),
130
            3600    => _HOUR,
131
            18000   => \sprintf(_HOURS, 5),
132
            86400   => _DAY,
133
            259200  => \sprintf(_DAYS, 3),
134
            604800  => _WEEK,
135
            2592000 => _MONTH,
136
        ];
137
        foreach ($blockArray as $i) {
138
            $groupsPermissions = $grouppermHandler->getGroupIds('block_read', $i->getVar('bid'));
139
            $sql               = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $i->getVar('bid');
0 ignored issues
show
Bug introduced by
The method prefix() does not exist on null. ( Ignorable by Annotation )

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

139
            $sql               = 'SELECT module_id FROM ' . $this->db->/** @scrutinizer ignore-call */ prefix('block_module_link') . ' WHERE block_id=' . $i->getVar('bid');

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...
140
            $result            = $this->db->query($sql);
141
            $modules           = [];
142
            if (!$this->db->isResultSet($result)) {
143
                \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
144
            }
145
            while (false !== ($row = $this->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

145
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
146
                $modules[] = (int)$row['module_id'];
147
            }
148
149
            $cachetimeOptions = '';
150
            foreach ($cachetimes as $cachetime => $cachetimeName) {
151
                if ($i->getVar('bcachetime') == $cachetime) {
152
                    $cachetimeOptions .= "<option value='$cachetime' selected='selected'>$cachetimeName</option>\n";
153
                } else {
154
                    $cachetimeOptions .= "<option value='$cachetime'>$cachetimeName</option>\n";
155
                }
156
            }
157
158
            $ssel7 = '';
159
            $ssel6 = $ssel7;
160
            $ssel5 = $ssel6;
161
            $ssel4 = $ssel5;
162
            $ssel3 = $ssel4;
163
            $ssel2 = $ssel3;
164
            $ssel1 = $ssel2;
165
            $ssel0 = $ssel1;
166
            $sel1  = $ssel0;
167
            $sel0  = $sel1;
168
            if (1 === $i->getVar('visible')) {
169
                $sel1 = ' checked';
170
            } else {
171
                $sel0 = ' checked';
172
            }
173
            if (\XOOPS_SIDEBLOCK_LEFT === $i->getVar('side')) {
174
                $ssel0 = ' checked';
175
            } elseif (\XOOPS_SIDEBLOCK_RIGHT === $i->getVar('side')) {
176
                $ssel1 = ' checked';
177
            } elseif (\XOOPS_CENTERBLOCK_LEFT === $i->getVar('side')) {
178
                $ssel2 = ' checked';
179
            } elseif (\XOOPS_CENTERBLOCK_RIGHT === $i->getVar('side')) {
180
                $ssel4 = ' checked';
181
            } elseif (\XOOPS_CENTERBLOCK_CENTER === $i->getVar('side')) {
182
                $ssel3 = ' checked';
183
            } elseif (\XOOPS_CENTERBLOCK_BOTTOMLEFT === $i->getVar('side')) {
184
                $ssel5 = ' checked';
185
            } elseif (\XOOPS_CENTERBLOCK_BOTTOMRIGHT === $i->getVar('side')) {
186
                $ssel6 = ' checked';
187
            } elseif (\XOOPS_CENTERBLOCK_BOTTOM === $i->getVar('side')) {
188
                $ssel7 = ' checked';
189
            }
190
            if ('' === $i->getVar('title')) {
191
                $title = '&nbsp;';
192
            } else {
193
                $title = $i->getVar('title');
194
            }
195
            $name = $i->getVar('name');
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
196
            echo "<tr valign='top'><td class='$class' align='center'><input type='text' name='title["
197
                 . $i->getVar('bid')
198
                 . "]' value='"
199
                 . $title
200
                 . "'></td><td class='$class' align='center' nowrap='nowrap'>
201
                    <div align='center' >
202
                    <input type='radio' name='side["
203
                 . $i->getVar('bid')
204
                 . "]' value='"
205
                 . \XOOPS_CENTERBLOCK_LEFT
206
                 . "'$ssel2>
207
                        <input type='radio' name='side["
208
                 . $i->getVar('bid')
209
                 . "]' value='"
210
                 . \XOOPS_CENTERBLOCK_CENTER
211
                 . "'$ssel3>
212
                    <input type='radio' name='side["
213
                 . $i->getVar('bid')
214
                 . "]' value='"
215
                 . \XOOPS_CENTERBLOCK_RIGHT
216
                 . "'$ssel4>
217
                    </div>
218
                    <div>
219
                        <span style='float:right;'><input type='radio' name='side["
220
                 . $i->getVar('bid')
221
                 . "]' value='"
222
                 . \XOOPS_SIDEBLOCK_RIGHT
223
                 . "'$ssel1></span>
224
                    <div align='left'><input type='radio' name='side["
225
                 . $i->getVar('bid')
226
                 . "]' value='"
227
                 . \XOOPS_SIDEBLOCK_LEFT
228
                 . "'$ssel0></div>
229
                    </div>
230
                    <div align='center'>
231
                    <input type='radio' name='side["
232
                 . $i->getVar('bid')
233
                 . "]' value='"
234
                 . \XOOPS_CENTERBLOCK_BOTTOMLEFT
235
                 . "'$ssel5>
236
                        <input type='radio' name='side["
237
                 . $i->getVar('bid')
238
                 . "]' value='"
239
                 . \XOOPS_CENTERBLOCK_BOTTOM
240
                 . "'$ssel7>
241
                    <input type='radio' name='side["
242
                 . $i->getVar('bid')
243
                 . "]' value='"
244
                 . \XOOPS_CENTERBLOCK_BOTTOMRIGHT
245
                 . "'$ssel6>
246
                    </div>
247
                </td><td class='$class' align='center'><input type='text' name='weight["
248
                 . $i->getVar('bid')
249
                 . "]' value='"
250
                 . $i->getVar('weight')
251
                 . "' size='5' maxlength='5'></td><td class='$class' align='center' nowrap><input type='radio' name='visible["
252
                 . $i->getVar('bid')
253
                 . "]' value='1'$sel1>"
254
                 . _YES
255
                 . "&nbsp;<input type='radio' name='visible["
256
                 . $i->getVar('bid')
257
                 . "]' value='0'$sel0>"
258
                 . _NO
259
                 . '</td>';
260
261
            echo "<td class='$class' align='center'><select size='5' name='bmodule[" . $i->getVar('bid') . "][]' id='bmodule[" . $i->getVar('bid') . "][]' multiple='multiple'>";
262
            foreach ($moduleList as $k => $v) {
263
                echo "<option value='$k'" . (\in_array($k, $modules) ? " selected='selected'" : '') . ">$v</option>";
264
            }
265
            echo '</select></td>';
266
267
            echo "<td class='$class' align='center'><select size='5' name='groups[" . $i->getVar('bid') . "][]' id='groups[" . $i->getVar('bid') . "][]' multiple='multiple'>";
268
            foreach ($groups as $grp) {
269
                echo "<option value='" . $grp->getVar('groupid') . "' " . (\in_array($grp->getVar('groupid'), $groupsPermissions) ? " selected='selected'" : '') . '>' . $grp->getVar('name') . '</option>';
270
            }
271
            echo '</select></td>';
272
273
            // Cache lifetime
274
            echo '<td class="' . $class . '" align="center"> <select name="bcachetime[' . $i->getVar('bid') . ']" size="1">' . $cachetimeOptions . '</select>
275
                                    </td>';
276
277
            // Actions
278
279
            echo "<td class='$class' align='center'>
280
                <a href='blocksadmin.php?op=edit&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/edit.png' . " alt='" . _EDIT . "' title='" . _EDIT . "'></a> 
281
                <a href='blocksadmin.php?op=clone&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/editcopy.png' . " alt='" . _CLONE . "' title='" . _CLONE . "'></a>";
282
            //            if ('S' !== $i->getVar('block_type') && 'M' !== $i->getVar('block_type')) {
283
            //                echo "&nbsp;<a href='" . XOOPS_URL . '/modules/system/admin.php?fct=blocksadmin&amp;op=delete&amp;bid=' . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/delete.png' . " alt='" . _DELETE . "' title='" . _DELETE . "'>
284
            //                     </a>";
285
            //            }
286
287
            //            if ('S' !== $i->getVar('block_type') && 'M' !== $i->getVar('block_type')) {
288
            if (!\in_array($i->getVar('block_type'), ['M', 'S'])) {
289
                echo "&nbsp;
290
                <a href='blocksadmin.php?op=delete&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/delete.png' . " alt='" . _DELETE . "' title='" . _DELETE . "'>
291
                     </a>";
292
            }
293
            echo "
294
            <input type='hidden' name='oldtitle[" . $i->getVar('bid') . "]' value='" . $i->getVar('title') . "'>
295
            <input type='hidden' name='oldside[" . $i->getVar('bid') . "]' value='" . $i->getVar('side') . "'>
296
            <input type='hidden' name='oldweight[" . $i->getVar('bid') . "]' value='" . $i->getVar('weight') . "'>
297
            <input type='hidden' name='oldvisible[" . $i->getVar('bid') . "]' value='" . $i->getVar('visible') . "'>
298
            <input type='hidden' name='oldgroups[" . $i->getVar('groups') . "]' value='" . $i->getVar('groups') . "'>
299
            <input type='hidden' name='oldbcachetime[" . $i->getVar('bid') . "]' value='" . $i->getVar('bcachetime') . "'>
300
            <input type='hidden' name='bid[" . $i->getVar('bid') . "]' value='" . $i->getVar('bid') . "'>
301
            </td></tr>
302
            ";
303
            $class = ('even' === $class) ? 'odd' : 'even';
304
        }
305
        echo "<tr><td class='foot' align='center' colspan='8'>
306
        <input type='hidden' name='op' value='order'>
307
        " . $GLOBALS['xoopsSecurity']->getTokenHTML() . "
308
        <input type='submit' name='submit' value='" . _SUBMIT . "'>
309
        </td></tr></table>
310
        </form>
311
        <br><br>";
312
    }
313
314
    public function deleteBlock(int $bid): void
315
    {
316
        //        \xoops_cp_header();
317
318
        \xoops_loadLanguage('admin', 'system');
319
        \xoops_loadLanguage('admin/blocksadmin', 'system');
320
        \xoops_loadLanguage('admin/groups', 'system');
321
322
        $myblock = new \XoopsBlock($bid);
0 ignored issues
show
Unused Code introduced by
The assignment to $myblock is dead and can be removed.
Loading history...
323
324
        $sql = \sprintf('DELETE FROM %s WHERE bid = %u', $this->db->prefix('newblocks'), $bid);
325
        $this->db->queryF($sql) or \trigger_error($GLOBALS['xoopsDB']->error());
326
327
        $sql = \sprintf('DELETE FROM %s WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
328
        $this->db->queryF($sql) or \trigger_error($GLOBALS['xoopsDB']->error());
329
330
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
331
    }
332
333
    public function cloneBlock(int $bid): void
334
    {
335
        //require __DIR__ . '/admin_header.php';
336
        //        \xoops_cp_header();
337
338
        \xoops_loadLanguage('admin', 'system');
339
        \xoops_loadLanguage('admin/blocksadmin', 'system');
340
        \xoops_loadLanguage('admin/groups', 'system');
341
342
        $myblock = new \XoopsBlock($bid);
343
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
344
        $result  = $this->db->query($sql);
345
        $modules = [];
346
        if ($this->db->isResultSet($result)) {
347
            while (false !== ($row = $this->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

347
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
348
                $modules[] = (int)$row['module_id'];
349
            }
350
        }
351
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
352
        $block    = [
353
            'title'      => $myblock->getVar('title') . ' Clone',
354
            'form_title' => \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BLOCKS_CLONEBLOCK'),
355
            'name'       => $myblock->getVar('name'),
356
            'side'       => $myblock->getVar('side'),
357
            'weight'     => $myblock->getVar('weight'),
358
            'visible'    => $myblock->getVar('visible'),
359
            'content'    => $myblock->getVar('content', 'N'),
360
            'modules'    => $modules,
361
            'is_custom'  => $isCustom,
362
            'ctype'      => $myblock->getVar('c_type'),
363
            'bcachetime' => $myblock->getVar('bcachetime'),
364
            'op'         => 'clone_ok',
365
            'bid'        => $myblock->getVar('bid'),
366
            'edit_form'  => $myblock->getOptions(),
367
            'template'   => $myblock->getVar('template'),
368
            'options'    => $myblock->getVar('options'),
369
        ];
370
        echo '<a href="blocksadmin.php">' . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;' . \_AM_SYSTEM_BLOCKS_CLONEBLOCK . '<br><br>';
371
        //        $form = new Blockform();
372
        //        $form->render();
373
374
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Publisher\C...n\Blocksadmin::render() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
375
        //        xoops_cp_footer();
376
        //        require_once __DIR__ . '/admin_footer.php';
377
        //        exit();
378
    }
379
380
    public function isBlockCloned(int $bid, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
381
    {
382
        \xoops_loadLanguage('admin', 'system');
383
        \xoops_loadLanguage('admin/blocksadmin', 'system');
384
        \xoops_loadLanguage('admin/groups', 'system');
385
386
        $block = new \XoopsBlock($bid);
387
        /** @var \XoopsBlock $clone */
388
        $clone = $block->xoopsClone();
389
        if (empty($bmodule)) {
390
            //            \xoops_cp_header();
391
            \xoops_error(\sprintf(_AM_NOTSELNG, _AM_VISIBLEIN));
392
            \xoops_cp_footer();
393
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
394
        }
395
        $clone->setVar('side', $bside);
396
        $clone->setVar('weight', $bweight);
397
        $clone->setVar('visible', $bvisible);
398
        //$clone->setVar('content', $_POST['bcontent']);
399
        $clone->setVar('title', Request::getString('btitle', '', 'POST'));
400
        $clone->setVar('bcachetime', $bcachetime);
401
        if (\is_array($options) && (\count($options) > 0)) {
402
            $options = \implode('|', $options);
403
            $clone->setVar('options', $options);
404
        }
405
        $clone->setVar('bid', 0);
406
        if (\in_array($block->getVar('block_type'), ['C', 'E'])) {
407
            $clone->setVar('block_type', 'E');
408
        } else {
409
            $clone->setVar('block_type', 'D');
410
        }
411
        //        $newid = $clone->store(); //see https://github.com/XOOPS/XoopsCore25/issues/1105
412
        if ($clone->store()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $clone->store() of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
Deprecated Code introduced by
The function XoopsBlock::store() 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

412
        if (/** @scrutinizer ignore-deprecated */ $clone->store()) {
Loading history...
413
            $newid = $clone->id();  //get the id of the cloned block
414
        }
415
        if (!$newid) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $newid does not seem to be defined for all execution paths leading up to this point.
Loading history...
416
            //            \xoops_cp_header();
417
            $clone->getHtmlErrors();
418
            \xoops_cp_footer();
419
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
420
        }
421
        if ('' !== $clone->getVar('template')) {
422
            /** @var \XoopsTplfileHandler $tplfileHandler */
423
            $tplfileHandler = \xoops_getHandler('tplfile');
424
            $btemplate      = $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', (string)$bid);
425
            if (\count($btemplate) > 0) {
426
                $tplclone = $btemplate[0]->xoopsClone();
427
                $tplclone->setVar('tpl_id', 0);
428
                $tplclone->setVar('tpl_refid', $newid);
429
                $tplfileHandler->insert($tplclone);
430
            }
431
        }
432
433
        foreach ($bmodule as $bmid) {
434
            $sql = 'INSERT INTO ' . $this->db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')';
435
            $this->db->query($sql);
436
        }
437
        //$groups = &$GLOBALS['xoopsUser']->getGroups();
438
        foreach ($groups as $iValue) {
439
            $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . ' (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (' . $iValue . ', ' . $newid . ", 1, 'block_read')";
440
            $this->db->query($sql);
441
        }
442
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
443
    }
444
445
    public function setOrder(string $bid, string $title, string $weight, string $visible, string $side, string $bcachetime, ?array $bmodule = null): void
0 ignored issues
show
Unused Code introduced by
The parameter $bmodule is not used and could be removed. ( Ignorable by Annotation )

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

445
    public function setOrder(string $bid, string $title, string $weight, string $visible, string $side, string $bcachetime, /** @scrutinizer ignore-unused */ ?array $bmodule = null): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
446
    {
447
        $myblock = new \XoopsBlock($bid);
448
        $myblock->setVar('title', $title);
449
        $myblock->setVar('weight', $weight);
450
        $myblock->setVar('visible', $visible);
451
        $myblock->setVar('side', $side);
452
        $myblock->setVar('bcachetime', $bcachetime);
453
        $myblock->store();
0 ignored issues
show
Deprecated Code introduced by
The function XoopsBlock::store() 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

453
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
454
        //        /** @var \XoopsBlockHandler $blockHandler */
455
        //        $blockHandler = \xoops_getHandler('block');
456
        //        return $blockHandler->insert($myblock);
457
    }
458
459
    public function editBlock(int $bid): void
460
    {
461
        //        require_once \dirname(__DIR__,2) . '/admin/admin_header.php';
462
        //        \xoops_cp_header();
463
        \xoops_loadLanguage('admin', 'system');
464
        \xoops_loadLanguage('admin/blocksadmin', 'system');
465
        \xoops_loadLanguage('admin/groups', 'system');
466
        //        mpu_adm_menu();
467
        $myblock = new \XoopsBlock($bid);
468
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
469
        $result  = $this->db->query($sql);
470
        $modules = [];
471
        if ($this->db->isResultSet($result)) {
472
            while (false !== ($row = $this->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

472
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
473
                $modules[] = (int)$row['module_id'];
474
            }
475
        }
476
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
477
        $block    = [
478
            'title'      => $myblock->getVar('title'),
479
            'form_title' => \_AM_SYSTEM_BLOCKS_EDITBLOCK,
480
            //        'name'       => $myblock->getVar('name'),
481
            'side'       => $myblock->getVar('side'),
482
            'weight'     => $myblock->getVar('weight'),
483
            'visible'    => $myblock->getVar('visible'),
484
            'content'    => $myblock->getVar('content', 'N'),
485
            'modules'    => $modules,
486
            'is_custom'  => $isCustom,
487
            'ctype'      => $myblock->getVar('c_type'),
488
            'bcachetime' => $myblock->getVar('bcachetime'),
489
            'op'         => 'edit_ok',
490
            'bid'        => $myblock->getVar('bid'),
491
            'edit_form'  => $myblock->getOptions(),
492
            'template'   => $myblock->getVar('template'),
493
            'options'    => $myblock->getVar('options'),
494
        ];
495
        echo '<a href="blocksadmin.php">' . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;' . \_AM_SYSTEM_BLOCKS_EDITBLOCK . '<br><br>';
496
497
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Publisher\C...n\Blocksadmin::render() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
498
    }
499
500
    public function updateBlock(int $bid, string $btitle, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
501
    {
502
        $myblock = new \XoopsBlock($bid);
503
        $myblock->setVar('title', $btitle);
504
        $myblock->setVar('weight', $bweight);
505
        $myblock->setVar('visible', $bvisible);
506
        $myblock->setVar('side', $bside);
507
        $myblock->setVar('bcachetime', $bcachetime);
508
        //update block options
509
        if (isset($options)) {
510
            $optionsCount = \count($options);
511
            if ($optionsCount > 0) {
512
                //Convert array values to comma-separated
513
                foreach ($options as $i => $iValue) {
514
                    if (\is_array($iValue)) {
515
                        $options[$i] = \implode(',', $iValue);
516
                    }
517
                }
518
                $options = \implode('|', $options);
519
                $myblock->setVar('options', $options);
520
            }
521
        }
522
        $myblock->store();
0 ignored issues
show
Deprecated Code introduced by
The function XoopsBlock::store() 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

522
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
523
        //        /** @var \XoopsBlockHandler $blockHandler */
524
        //        $blockHandler = \xoops_getHandler('block');
525
        //        $blockHandler->insert($myblock);
526
527
        if (!empty($bmodule) && \count($bmodule) > 0) {
528
            $sql = \sprintf('DELETE FROM `%s` WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
529
            $this->db->query($sql);
530
            if (\in_array(0, $bmodule)) {
531
                $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, 0);
532
                $this->db->query($sql);
533
            } else {
534
                foreach ($bmodule as $bmid) {
535
                    $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, (int)$bmid);
536
                    $this->db->query($sql);
537
                }
538
            }
539
        }
540
        $sql = \sprintf('DELETE FROM `%s` WHERE gperm_itemid = %u', $this->db->prefix('group_permission'), $bid);
541
        $this->db->query($sql);
542
        if (!empty($groups)) {
543
            foreach ($groups as $grp) {
544
                $sql = \sprintf("INSERT INTO `%s` (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (%u, %u, 1, 'block_read')", $this->db->prefix('group_permission'), $grp, $bid);
545
                $this->db->query($sql);
546
            }
547
        }
548
        $this->helper->redirect('admin/blocksadmin.php', 1, \constant('CO_' . $this->moduleDirNameUpper . '_' . 'UPDATE_SUCCESS'));
549
    }
550
551
    public function orderBlock(
552
        array $bid,
553
        array $oldtitle,
554
        array $oldside,
555
        array $oldweight,
556
        array $oldvisible,
557
        array $oldgroups,
0 ignored issues
show
Unused Code introduced by
The parameter $oldgroups is not used and could be removed. ( Ignorable by Annotation )

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

557
        /** @scrutinizer ignore-unused */ array $oldgroups,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
558
        array $oldbcachetime,
559
        array $oldbmodule,
560
        array $title,
561
        array $weight,
562
        array $visible,
563
        array $side,
564
        array $bcachetime,
565
        array $groups,
566
        array $bmodule
567
    ): void {
568
        if (!$GLOBALS['xoopsSecurity']->check()) {
569
            \redirect_header($_SERVER['SCRIPT_NAME'], 3, \implode('<br>', $GLOBALS['xoopsSecurity']->getErrors()));
570
        }
571
        foreach (\array_keys($bid) as $i) {
572
            if ($oldtitle[$i] !== $title[$i]
573
                || $oldweight[$i] !== $weight[$i]
574
                || $oldvisible[$i] !== $visible[$i]
575
                || $oldside[$i] !== $side[$i]
576
                || $oldbcachetime[$i] !== $bcachetime[$i]
577
                || $oldbmodule[$i] !== $bmodule[$i]) {
578
                $this->setOrder($bid[$i], $title[$i], $weight[$i], $visible[$i], $side[$i], $bcachetime[$i], $bmodule[$i]);
579
            }
580
            if (!empty($bmodule[$i]) && \count($bmodule[$i]) > 0) {
581
                $sql = \sprintf('DELETE FROM `%s` WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid[$i]);
582
                $this->db->query($sql);
583
                if (\in_array(0, $bmodule[$i], true)) {
584
                    $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid[$i], 0);
585
                    $this->db->query($sql);
586
                } else {
587
                    foreach ($bmodule[$i] as $bmid) {
588
                        $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid[$i], (int)$bmid);
589
                        $this->db->query($sql);
590
                    }
591
                }
592
            }
593
            $sql = \sprintf('DELETE FROM `%s` WHERE gperm_itemid = %u', $this->db->prefix('group_permission'), $bid[$i]);
594
            $this->db->query($sql);
595
            if (!empty($groups[$i])) {
596
                foreach ($groups[$i] as $grp) {
597
                    $sql = \sprintf("INSERT INTO `%s` (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (%u, %u, 1, 'block_read')", $this->db->prefix('group_permission'), $grp, $bid[$i]);
598
                    $this->db->query($sql);
599
                }
600
            }
601
        }
602
603
        $this->helper->redirect('admin/blocksadmin.php', 1, \constant('CO_' . $this->moduleDirNameUpper . '_' . 'UPDATE_SUCCESS'));
604
    }
605
606
    public function render(?array $block = null)
607
    {
608
        \xoops_load('XoopsFormLoader');
609
        \xoops_loadLanguage('common', $this->moduleDirNameUpper);
610
611
        $form = new \XoopsThemeForm($block['form_title'], 'blockform', 'blocksadmin.php', 'post', true);
612
        if (isset($block['name'])) {
613
            $form->addElement(new \XoopsFormLabel(\_AM_SYSTEM_BLOCKS_NAME, $block['name']));
614
        }
615
        $sideSelect = new \XoopsFormSelect(\_AM_SYSTEM_BLOCKS_TYPE, 'bside', $block['side']);
616
        $sideSelect->addOptionArray([
617
                                        0 => \_AM_SYSTEM_BLOCKS_SBLEFT,
618
                                        1 => \_AM_SYSTEM_BLOCKS_SBRIGHT,
619
                                        3 => \_AM_SYSTEM_BLOCKS_CBLEFT,
620
                                        4 => \_AM_SYSTEM_BLOCKS_CBRIGHT,
621
                                        5 => \_AM_SYSTEM_BLOCKS_CBCENTER,
622
                                        7 => \_AM_SYSTEM_BLOCKS_CBBOTTOMLEFT,
623
                                        8 => \_AM_SYSTEM_BLOCKS_CBBOTTOMRIGHT,
624
                                        9 => \_AM_SYSTEM_BLOCKS_CBBOTTOM,
625
                                    ]);
626
        $form->addElement($sideSelect);
627
        $form->addElement(new \XoopsFormText(\constant('CO_' . $this->moduleDirNameUpper . '_' . 'WEIGHT'), 'bweight', 2, 5, $block['weight']));
628
        $form->addElement(new \XoopsFormRadioYN(\constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLE'), 'bvisible', $block['visible']));
629
        $modSelect = new \XoopsFormSelect(\constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLEIN'), 'bmodule', $block['modules'], 5, true);
630
        /** @var \XoopsModuleHandler $moduleHandler */
631
        $moduleHandler = \xoops_getHandler('module');
632
        $criteria      = new \CriteriaCompo(new \Criteria('hasmain', '1'));
633
        $criteria->add(new \Criteria('isactive', '1'));
634
        $moduleList     = $moduleHandler->getList($criteria);
635
        $moduleList[-1] = \_AM_SYSTEM_BLOCKS_TOPPAGE;
636
        $moduleList[0]  = \_AM_SYSTEM_BLOCKS_ALLPAGES;
637
        \ksort($moduleList);
638
        $modSelect->addOptionArray($moduleList);
639
        $form->addElement($modSelect);
640
        $form->addElement(new \XoopsFormText(\_AM_SYSTEM_BLOCKS_TITLE, 'btitle', 50, 255, $block['title']), false);
641
        if ($block['is_custom']) {
642
            $textarea = new \XoopsFormDhtmlTextArea(\_AM_SYSTEM_BLOCKS_CONTENT, 'bcontent', $block['content'], 15, 70);
643
            $textarea->setDescription('<span style="font-size:x-small;font-weight:bold;">' . \_AM_SYSTEM_BLOCKS_USEFULTAGS . '</span><br><span style="font-size:x-small;font-weight:normal;">' . \sprintf(_AM_BLOCKTAG1, '{X_SITEURL}', XOOPS_URL . '/') . '</span>');
644
            $form->addElement($textarea, true);
645
            $ctypeSelect = new \XoopsFormSelect(\_AM_SYSTEM_BLOCKS_CTYPE, 'bctype', $block['ctype']);
646
            $ctypeSelect->addOptionArray([
647
                                             'H' => \_AM_SYSTEM_BLOCKS_HTML,
648
                                             'P' => \_AM_SYSTEM_BLOCKS_PHP,
649
                                             'S' => \_AM_SYSTEM_BLOCKS_AFWSMILE,
650
                                             'T' => \_AM_SYSTEM_BLOCKS_AFNOSMILE,
651
                                         ]);
652
            $form->addElement($ctypeSelect);
653
        } else {
654
            if ('' !== $block['template']) {
655
                /** @var \XoopsTplfileHandler $tplfileHandler */
656
                $tplfileHandler = \xoops_getHandler('tplfile');
657
                $btemplate      = $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $block['bid']);
658
                if (\count($btemplate) > 0) {
659
                    $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>'));
660
                } else {
661
                    $btemplate2 = $tplfileHandler->find('default', 'block', $block['bid']);
662
                    if (\count($btemplate2) > 0) {
663
                        $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') . '" target="_blank">' . \_AM_SYSTEM_BLOCKS_EDITTPL . '</a>'));
664
                    }
665
                }
666
            }
667
            if (false !== $block['edit_form']) {
668
                $form->addElement(new \XoopsFormLabel(\_AM_SYSTEM_BLOCKS_OPTIONS, $block['edit_form']));
669
            }
670
        }
671
        $cache_select = new \XoopsFormSelect(\_AM_SYSTEM_BLOCKS_BCACHETIME, 'bcachetime', $block['bcachetime']);
672
        $cache_select->addOptionArray([
673
                                          0       => _NOCACHE,
674
                                          30      => \sprintf(_SECONDS, 30),
675
                                          60      => _MINUTE,
676
                                          300     => \sprintf(_MINUTES, 5),
677
                                          1800    => \sprintf(_MINUTES, 30),
678
                                          3600    => _HOUR,
679
                                          18000   => \sprintf(_HOURS, 5),
680
                                          86400   => _DAY,
681
                                          259200  => \sprintf(_DAYS, 3),
682
                                          604800  => _WEEK,
683
                                          2592000 => _MONTH,
684
                                      ]);
685
        $form->addElement($cache_select);
686
687
        /** @var \XoopsGroupPermHandler $grouppermHandler */
688
        $grouppermHandler = \xoops_getHandler('groupperm');
689
        $groups           = $grouppermHandler->getGroupIds('block_read', $block['bid']);
690
691
        $form->addElement(new \XoopsFormSelectGroup(\_AM_SYSTEM_BLOCKS_GROUP, 'groups', true, $groups, 5, true));
692
693
        if (isset($block['bid'])) {
694
            $form->addElement(new \XoopsFormHidden('bid', $block['bid']));
695
        }
696
        $form->addElement(new \XoopsFormHidden('op', $block['op']));
697
        $form->addElement(new \XoopsFormHidden('fct', 'blocksadmin'));
698
        $buttonTray = new \XoopsFormElementTray('', '&nbsp;');
699
        if ($block['is_custom']) {
700
            $buttonTray->addElement(new \XoopsFormButton('', 'previewblock', _PREVIEW, 'submit'));
701
        }
702
703
        //Submit buttons
704
        $buttonTray   = new \XoopsFormElementTray('', '');
705
        $submitButton = new \XoopsFormButton('', 'submitblock', _SUBMIT, 'submit');
706
        $buttonTray->addElement($submitButton);
707
708
        $cancelButton = new \XoopsFormButton('', '', _CANCEL, 'button');
709
        $cancelButton->setExtra('onclick="history.go(-1)"');
710
        $buttonTray->addElement($cancelButton);
711
712
        $form->addElement($buttonTray);
713
        $form->display();
714
    }
715
}
716