Blocksadmin   F
last analyzed

Complexity

Total Complexity 80

Size/Duplication

Total Lines 701
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 80
eloc 460
c 1
b 0
f 1
dl 0
loc 701
rs 2

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 2
C orderBlock() 0 55 15
A editBlock() 0 39 3
A setOrder() 0 9 1
F listBlocks() 0 253 22
B updateBlock() 0 50 11
C render() 0 110 9
A deleteBlock() 0 17 3
A cloneBlock() 0 42 3
B isBlockCloned() 0 63 11

How to fix   Complexity   

Complex Class

Complex classes like Blocksadmin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Blocksadmin, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Smartfaq\Common;
6
7
/**
8
 * You may not change or alter any portion of this comment or credits
9
 * of supporting developers from this source code or any supporting source code
10
 * which is considered copyrighted (c) material of the original comment or credit authors.
11
 *
12
 *
13
 * @category        Module
14
 * @author          XOOPS Development Team
15
 * @copyright       XOOPS Project (https://xoops.org)
16
 * @license         GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
17
 */
18
19
use Xmf\Request;
20
use XoopsModules\Smartfaq\{
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 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, Helper $helper)
52
    {
53
        if (null === $db) {
54
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
55
        }
56
        $this->db                 = $db;
57
        $this->helper             = $helper;
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()
68
    : void
69
    {
70
        global $xoopsModule, $pathIcon16;
71
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
72
        //        xoops_loadLanguage('admin', 'system');
73
        //        xoops_loadLanguage('admin/blocksadmin', 'system');
74
        //        xoops_loadLanguage('admin/groups', 'system');
75
        //        xoops_loadLanguage('common', $moduleDirName);
76
        //        xoops_loadLanguage('blocks', $moduleDirName);
77
78
        /** @var \XoopsModuleHandler $moduleHandler */
79
        $moduleHandler = \xoops_getHandler('module');
80
        /** @var \XoopsMemberHandler $memberHandler */
81
        $memberHandler = \xoops_getHandler('member');
82
        /** @var \XoopsGroupPermHandler $grouppermHandler */
83
        $grouppermHandler = \xoops_getHandler('groupperm');
84
        $groups           = $memberHandler->getGroups();
85
        $criteria         = new \CriteriaCompo(new \Criteria('hasmain', '1'));
86
        $criteria->add(new \Criteria('isactive', '1'));
87
        $moduleList     = $moduleHandler->getList($criteria);
88
        $moduleList[-1] = \_AM_SYSTEM_BLOCKS_TOPPAGE;
89
        $moduleList[0]  = \_AM_SYSTEM_BLOCKS_ALLPAGES;
90
        \ksort($moduleList);
91
        echo "
92
        <h4 style='text-align:left;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</h4>';
93
        echo "<form action='" . $_SERVER['SCRIPT_NAME'] . "' name='blockadmin' method='post'>";
94
        echo $GLOBALS['xoopsSecurity']->getTokenHTML();
95
        echo "<table width='100%' class='outer' cellpadding='4' cellspacing='1'>
96
        <tr valign='middle'><th align='center'>"
97
             . \_AM_SYSTEM_BLOCKS_TITLE
98
             . "</th><th align='center' nowrap='nowrap'>"
99
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'SIDE')
100
             . '<br>'
101
             . \_LEFT
102
             . '-'
103
             . \_CENTER
104
             . '-'
105
             . \_RIGHT
106
             . "</th><th align='center'>"
107
             . \constant(
108
                 'CO_' . $this->moduleDirNameUpper . '_' . 'WEIGHT'
109
             )
110
             . "</th><th align='center'>"
111
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLE')
112
             . "</th><th align='center'>"
113
             . \_AM_SYSTEM_BLOCKS_VISIBLEIN
114
             . "</th><th align='center'>"
115
             . \_AM_SYSTEM_ADGS
116
             . "</th><th align='center'>"
117
             . \_AM_SYSTEM_BLOCKS_BCACHETIME
118
             . "</th><th align='center'>"
119
             . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'ACTION')
120
             . '</th></tr>
121
        ';
122
        $blockArray = \XoopsBlock::getByModule($xoopsModule->mid());
0 ignored issues
show
Deprecated Code introduced by
The function XoopsBlock::getByModule() has been deprecated: (This also appears, dead, in XoopsBlockHandler) ( Ignorable by Annotation )

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

122
        $blockArray = /** @scrutinizer ignore-deprecated */ \XoopsBlock::getByModule($xoopsModule->mid());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
123
        $blockCount = \count($blockArray);
0 ignored issues
show
Unused Code introduced by
The assignment to $blockCount is dead and can be removed.
Loading history...
124
        $class      = 'even';
125
        $cachetimes = [
126
            0       => \_NOCACHE,
127
            30      => \sprintf(\_SECONDS, 30),
128
            60      => \_MINUTE,
129
            300     => \sprintf(\_MINUTES, 5),
130
            1800    => \sprintf(\_MINUTES, 30),
131
            3600    => \_HOUR,
132
            18000   => \sprintf(\_HOURS, 5),
133
            86400   => \_DAY,
134
            259200  => \sprintf(\_DAYS, 3),
135
            604800  => \_WEEK,
136
            2592000 => \_MONTH,
137
        ];
138
        foreach ($blockArray as $i) {
139
            $groupsPermissions = $grouppermHandler->getGroupIds('block_read', $i->getVar('bid'));
140
            $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

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

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

358
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
359
                $modules[] = (int)$row['module_id'];
360
            }
361
        }
362
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
363
        $block    = [
364
            'title'      => $myblock->getVar('title') . ' Clone',
365
            'form_title' => \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BLOCKS_CLONEBLOCK'),
366
            'name'       => $myblock->getVar('name'),
367
            'side'       => $myblock->getVar('side'),
368
            'weight'     => $myblock->getVar('weight'),
369
            'visible'    => $myblock->getVar('visible'),
370
            'content'    => $myblock->getVar('content', 'N'),
371
            'modules'    => $modules,
372
            'is_custom'  => $isCustom,
373
            'ctype'      => $myblock->getVar('c_type'),
374
            'bcachetime' => $myblock->getVar('bcachetime'),
375
            'op'         => 'clone_ok',
376
            'bid'        => $myblock->getVar('bid'),
377
            'edit_form'  => $myblock->getOptions(),
378
            'template'   => $myblock->getVar('template'),
379
            'options'    => $myblock->getVar('options'),
380
        ];
381
        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>';
382
        //        $form = new Blockform();
383
        //        $form->render();
384
385
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Smartfaq\Common\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...
386
        //        xoops_cp_footer();
387
        //        require_once __DIR__ . '/admin_footer.php';
388
        //        exit();
389
    }
390
391
    public function isBlockCloned(int $bid, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
392
    {
393
        \xoops_loadLanguage('admin', 'system');
394
        \xoops_loadLanguage('admin/blocksadmin', 'system');
395
        \xoops_loadLanguage('admin/groups', 'system');
396
397
        $block = new \XoopsBlock($bid);
398
        $clone = $block->xoopsClone();
399
        if (empty($bmodule)) {
400
            //            \xoops_cp_header();
401
            \xoops_error(\sprintf(_AM_NOTSELNG, _AM_VISIBLEIN));
402
            \xoops_cp_footer();
403
            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...
404
        }
405
        $clone->setVar('side', $bside);
406
        $clone->setVar('weight', $bweight);
407
        $clone->setVar('visible', $bvisible);
408
        //$clone->setVar('content', $_POST['bcontent']);
409
        $clone->setVar('title', Request::getString('btitle', '', 'POST'));
410
        $clone->setVar('bcachetime', $bcachetime);
411
        if (\is_array($options) && (\count($options) > 0)) {
412
            $options = \implode('|', $options);
413
            $clone->setVar('options', $options);
414
        }
415
        $clone->setVar('bid', 0);
416
        if (\in_array($block->getVar('block_type'), ['C', 'E'])) {
417
            $clone->setVar('block_type', 'E');
418
        }
419
        else {
420
            $clone->setVar('block_type', 'D');
421
        }
422
        //        $newid = $clone->store(); //see https://github.com/XOOPS/XoopsCore25/issues/1105
423
        if ($clone->store()) {
424
            $newid = $clone->id();  //get the id of the cloned block
425
        }
426
        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...
427
            //            \xoops_cp_header();
428
            $clone->getHtmlErrors();
429
            \xoops_cp_footer();
430
            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...
431
        }
432
        if ('' !== $clone->getVar('template')) {
433
            /** @var \XoopsTplfileHandler $tplfileHandler */
434
            $tplfileHandler = \xoops_getHandler('tplfile');
435
            $btemplate      = $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', (string)$bid);
436
            if (\count($btemplate) > 0) {
437
                $tplclone = $btemplate[0]->xoopsClone();
438
                $tplclone->setVar('tpl_id', 0);
439
                $tplclone->setVar('tpl_refid', $newid);
440
                $tplfileHandler->insert($tplclone);
441
            }
442
        }
443
444
        foreach ($bmodule as $bmid) {
445
            $sql = 'INSERT INTO ' . $this->db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')';
446
            $this->db->query($sql);
447
        }
448
        //$groups = &$GLOBALS['xoopsUser']->getGroups();
449
        foreach ($groups as $iValue) {
450
            $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . ' (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (' . $iValue . ', ' . $newid . ", 1, 'block_read')";
451
            $this->db->query($sql);
452
        }
453
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
454
    }
455
456
    public function setOrder(string $bid, string $title, string $weight, string $visible, string $side, string $bcachetime, ?array $bmodule = null)
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

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

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...
457
    : void {
458
        $myblock = new \XoopsBlock($bid);
459
        $myblock->setVar('title', $title);
460
        $myblock->setVar('weight', $weight);
461
        $myblock->setVar('visible', $visible);
462
        $myblock->setVar('side', $side);
463
        $myblock->setVar('bcachetime', $bcachetime);
464
        $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

464
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
465
        //        /** @var \XoopsBlockHandler $blockHandler */
466
        //        $blockHandler = \xoops_getHandler('block');
467
        //        return $blockHandler->insert($myblock);
468
    }
469
470
    public function editBlock(int $bid)
471
    : void {
472
        //        require_once \dirname(__DIR__,2) . '/admin/admin_header.php';
473
        //        \xoops_cp_header();
474
        \xoops_loadLanguage('admin', 'system');
475
        \xoops_loadLanguage('admin/blocksadmin', 'system');
476
        \xoops_loadLanguage('admin/groups', 'system');
477
        //        mpu_adm_menu();
478
        $myblock = new \XoopsBlock($bid);
479
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
480
        $result  = $this->db->query($sql);
481
        $modules = [];
482
        if ($this->db->isResultSet($result)) {
483
            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

483
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
484
                $modules[] = (int)$row['module_id'];
485
            }
486
        }
487
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
488
        $block    = [
489
            'title'      => $myblock->getVar('title'),
490
            'form_title' => \_AM_SYSTEM_BLOCKS_EDITBLOCK,
491
            //        'name'       => $myblock->getVar('name'),
492
            'side'       => $myblock->getVar('side'),
493
            'weight'     => $myblock->getVar('weight'),
494
            'visible'    => $myblock->getVar('visible'),
495
            'content'    => $myblock->getVar('content', 'N'),
496
            'modules'    => $modules,
497
            'is_custom'  => $isCustom,
498
            'ctype'      => $myblock->getVar('c_type'),
499
            'bcachetime' => $myblock->getVar('bcachetime'),
500
            'op'         => 'edit_ok',
501
            'bid'        => $myblock->getVar('bid'),
502
            'edit_form'  => $myblock->getOptions(),
503
            'template'   => $myblock->getVar('template'),
504
            'options'    => $myblock->getVar('options'),
505
        ];
506
        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>';
507
508
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Smartfaq\Common\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...
509
    }
510
511
    public function updateBlock(int $bid, string $btitle, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups)
512
    : void {
513
        $myblock = new \XoopsBlock($bid);
514
        $myblock->setVar('title', $btitle);
515
        $myblock->setVar('weight', $bweight);
516
        $myblock->setVar('visible', $bvisible);
517
        $myblock->setVar('side', $bside);
518
        $myblock->setVar('bcachetime', $bcachetime);
519
        //update block options
520
        if (isset($options)) {
521
            $optionsCount = \count($options);
522
            if ($optionsCount > 0) {
523
                //Convert array values to comma-separated
524
                foreach ($options as $i => $iValue) {
525
                    if (\is_array($iValue)) {
526
                        $options[$i] = \implode(',', $iValue);
527
                    }
528
                }
529
                $options = \implode('|', $options);
530
                $myblock->setVar('options', $options);
531
            }
532
        }
533
        $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

533
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
534
        //        /** @var \XoopsBlockHandler $blockHandler */
535
        //        $blockHandler = \xoops_getHandler('block');
536
        //        $blockHandler->insert($myblock);
537
538
        if (!empty($bmodule) && \count($bmodule) > 0) {
539
            $sql = \sprintf('DELETE FROM `%s` WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
540
            $this->db->query($sql);
541
            if (\in_array(0, $bmodule)) {
542
                $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, 0);
543
                $this->db->query($sql);
544
            }
545
            else {
546
                foreach ($bmodule as $bmid) {
547
                    $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, (int)$bmid);
548
                    $this->db->query($sql);
549
                }
550
            }
551
        }
552
        $sql = \sprintf('DELETE FROM `%s` WHERE gperm_itemid = %u', $this->db->prefix('group_permission'), $bid);
553
        $this->db->query($sql);
554
        if (!empty($groups)) {
555
            foreach ($groups as $grp) {
556
                $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);
557
                $this->db->query($sql);
558
            }
559
        }
560
        $this->helper->redirect('admin/blocksadmin.php', 1, \constant('CO_' . $this->moduleDirNameUpper . '_' . 'UPDATE_SUCCESS'));
561
    }
562
563
    public function orderBlock(
564
        array $bid,
565
        array $oldtitle,
566
        array $oldside,
567
        array $oldweight,
568
        array $oldvisible,
569
        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

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