Blocksadmin::listBlocks()   F
last analyzed

Complexity

Conditions 23
Paths 6914

Size

Total Lines 169
Code Lines 122

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 23
eloc 122
nc 6914
nop 0
dl 0
loc 169
rs 0
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Newbb\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
16
 * @link            https://xoops.org
17
 * @license         GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
18
 */
19
20
use Xmf\Request;
21
use XoopsModules\Newbb\{
22
    Helper
23
};
24
25
//require_once __DIR__ . '/admin_header.php';
26
27
/**
28
 * class Blocksadmin
29
 */
30
final class Blocksadmin
31
{
32
    /**
33
     * @var \XoopsMySQLDatabase|null
34
     */
35
    public $db;
36
    /**
37
     * @var string
38
     */
39
    public string $moduleDirName;
40
    /**
41
     * @var string
42
     */
43
    public string $moduleDirNameUpper;
44
    /**
45
     * @var Helper
46
     */
47
    public Helper $helper;
48
49
    /**
50
     * Blocksadmin constructor.
51
     * @param \XoopsMySQLDatabase|null $db
52
     * @param Helper              $helper
53
     */
54
    public function __construct(?\XoopsMySQLDatabase $db, Helper $helper)
55
    {
56
        $this->helper = $helper;
57
        if (null == $db) {
58
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
59
        }
60
        $this->db                 = $db;
61
        assert($this->db instanceof \XoopsMySQLDatabase);
62
        $this->moduleDirName      = \basename(\dirname(__DIR__, 2));
63
        $this->moduleDirNameUpper = \mb_strtoupper($this->moduleDirName);
64
        \xoops_loadLanguage('admin', 'system');
65
        \xoops_loadLanguage('admin/blocksadmin', 'system');
66
        \xoops_loadLanguage('admin/groups', 'system');
67
        \xoops_loadLanguage('common', $this->moduleDirName);
68
        \xoops_loadLanguage('blocksadmin', $this->moduleDirName);
69
    }
70
71
    /**
72
     * @return void
73
     */
74
    public function listBlocks(): void
75
    {
76
        global $xoopsModule, $pathIcon16;
77
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
78
        //        xoops_loadLanguage('admin', 'system');
79
        //        xoops_loadLanguage('admin/blocksadmin', 'system');
80
        //        xoops_loadLanguage('admin/groups', 'system');
81
        //        xoops_loadLanguage('common', $moduleDirName);
82
        //        xoops_loadLanguage('blocks', $moduleDirName);
83
84
        /** @var \XoopsModuleHandler $moduleHandler */
85
        $moduleHandler = \xoops_getHandler('module');
86
        /** @var \XoopsMemberHandler $memberHandler */
87
        $memberHandler = \xoops_getHandler('member');
88
        /** @var \XoopsGroupPermHandler $grouppermHandler */
89
        $grouppermHandler = \xoops_getHandler('groupperm');
90
        $groups           = $memberHandler->getGroups();
91
        $criteria         = new \CriteriaCompo(new \Criteria('hasmain', '1'));
92
        $criteria->add(new \Criteria('isactive', '1'));
93
        $moduleList     = $moduleHandler->getList($criteria);
94
        $moduleList[-1] = \_AM_SYSTEM_BLOCKS_TOPPAGE;
95
        $moduleList[0]  = \_AM_SYSTEM_BLOCKS_ALLPAGES;
96
        \ksort($moduleList);
97
        echo "<h4 style='text-align:left;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</h4>';
98
        echo "<form action='" . $_SERVER['SCRIPT_NAME'] . "' name='blockadmin' method='post'>";
99
        echo $GLOBALS['xoopsSecurity']->getTokenHTML();
100
        echo "<table class='outer' style='padding: 4px; border-collapse: separate; border-spacing: 1px; width: 100%;'>
101
        <tr valign='middle'><th style='text-align:center;'>" . \_AM_SYSTEM_BLOCKS_TITLE . "</th><th style='text-align:center;' nowrap='nowrap'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'SIDE') . '<br>' . \_LEFT . '-' . \_CENTER . '-' . \_RIGHT . "</th>
102
        <th style='text-align:center;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'WEIGHT') . "</th>
103
        <th style='text-align:center;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLE') . "</th><th style='text-align:center;'>" . \_AM_SYSTEM_BLOCKS_VISIBLEIN . "</th>
104
        <th style='text-align:center;'>" . \_AM_SYSTEM_ADGS . "</th>
105
        <th style='text-align:center;'>" . \_AM_SYSTEM_BLOCKS_BCACHETIME . "</th>
106
        <th style='text-align:center;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'ACTION') . '</th>
107
        </tr>';
108
        $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

108
        $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...
109
        $blockCount = is_countable($blockArray) ? \count($blockArray) : 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $blockCount is dead and can be removed.
Loading history...
110
        $class      = 'even';
111
        $cachetimes = [
112
            0       => \_NOCACHE,
113
            30      => \sprintf(\_SECONDS, 30),
114
            60      => \_MINUTE,
115
            300     => \sprintf(\_MINUTES, 5),
116
            1800    => \sprintf(\_MINUTES, 30),
117
            3600    => \_HOUR,
118
            18000   => \sprintf(\_HOURS, 5),
119
            86400   => \_DAY,
120
            259200  => \sprintf(\_DAYS, 3),
121
            604800  => \_WEEK,
122
            2_592_000 => \_MONTH,
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Newbb\Common\2_592_000 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
123
        ];
124
        foreach ($blockArray as $i) {
125
            $modules = [];
126
            $groupsPermissions = $grouppermHandler->getGroupIds('block_read', $i->getVar('bid'));
127
            $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

127
            $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...
128
            $result            = $this->db->query($sql);
129
            if ($this->db->isResultSet($result)) {
130
                  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

130
                  while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
131
                    $modules[] = (int)$row['module_id'];
132
                }
133
            } else {
134
                \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
135
            }
136
            $cachetimeOptions = '';
137
            foreach ($cachetimes as $cachetime => $cachetimeName) {
138
                if ($i->getVar('bcachetime') == $cachetime) {
139
                    $cachetimeOptions .= "<option value='$cachetime' selected='selected'>$cachetimeName</option>\n";
140
                } else {
141
                    $cachetimeOptions .= "<option value='$cachetime'>$cachetimeName</option>\n";
142
                }
143
            }
144
145
            $ssel7 = '';
146
            $ssel6 = $ssel7;
147
            $ssel5 = $ssel6;
148
            $ssel4 = $ssel5;
149
            $ssel3 = $ssel4;
150
            $ssel2 = $ssel3;
151
            $ssel1 = $ssel2;
152
            $ssel0 = $ssel1;
153
            $sel1  = $ssel0;
154
            $sel0  = $sel1;
155
            if (1 === $i->getVar('visible')) {
156
                $sel1 = ' checked';
157
            } else {
158
                $sel0 = ' checked';
159
            }
160
            if (\XOOPS_SIDEBLOCK_LEFT === $i->getVar('side')) {
161
                $ssel0 = ' checked';
162
            } elseif (\XOOPS_SIDEBLOCK_RIGHT === $i->getVar('side')) {
163
                $ssel1 = ' checked';
164
            } elseif (\XOOPS_CENTERBLOCK_LEFT === $i->getVar('side')) {
165
                $ssel2 = ' checked';
166
            } elseif (\XOOPS_CENTERBLOCK_RIGHT === $i->getVar('side')) {
167
                $ssel4 = ' checked';
168
            } elseif (\XOOPS_CENTERBLOCK_CENTER === $i->getVar('side')) {
169
                $ssel3 = ' checked';
170
            } elseif (\XOOPS_CENTERBLOCK_BOTTOMLEFT === $i->getVar('side')) {
171
                $ssel5 = ' checked';
172
            } elseif (\XOOPS_CENTERBLOCK_BOTTOMRIGHT === $i->getVar('side')) {
173
                $ssel6 = ' checked';
174
            } elseif (\XOOPS_CENTERBLOCK_BOTTOM === $i->getVar('side')) {
175
                $ssel7 = ' checked';
176
            }
177
            $title = '' === $i->getVar('title') ? '&nbsp;' : $i->getVar('title');
178
            $name = $i->getVar('name');
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
179
            echo "<tr valign='top'><td class='$class' style='text-align:center;'><input type='text' name='title[" . $i->getVar('bid') . "]' value='" . $title . "'></td>
180
            <td class='$class' style='text-align:center;' nowrap='nowrap'><div style='text-align:center;' >
181
                    <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_LEFT . "'$ssel2>
182
                    <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_CENTER . "'$ssel3>
183
                    <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_RIGHT . "'$ssel4>
184
                    </div>
185
                    <div>
186
                        <span style='float:right;'><input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_SIDEBLOCK_RIGHT . "'$ssel1></span>
187
                    <div style='text-align:left;'><input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_SIDEBLOCK_LEFT . "'$ssel0></div>
188
                    </div>
189
                    <div style='text-align:center;'>
190
                    <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_BOTTOMLEFT . "'$ssel5>
191
                        <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_BOTTOM . "'$ssel7>
192
                    <input type='radio' name='side[" . $i->getVar('bid') . "]' value='" . \XOOPS_CENTERBLOCK_BOTTOMRIGHT . "'$ssel6>
193
                    </div>
194
                </td>
195
                <td class='$class' style='text-align:center;'><input type='text' name='weight[" . $i->getVar('bid') . "]' value='" . $i->getVar('weight') . "' size='5' maxlength='5'></td>
196
                <td class='$class' style='text-align:center;' nowrap><input type='radio' name='visible[" . $i->getVar('bid') . "]' value='1'$sel1>" . \_YES . "&nbsp;<input type='radio' name='visible[" . $i->getVar('bid') . "]' value='0'$sel0>" . \_NO . '</td>';
197
198
            echo "<td class='$class' style='text-align:center;'><select size='5' name='bmodule[" . $i->getVar('bid') . "][]' id='bmodule[" . $i->getVar('bid') . "][]' multiple='multiple'>";
199
            foreach ($moduleList as $k => $v) {
200
                echo "<option value='$k'" . (\in_array($k, $modules) ? " selected='selected'" : '') . ">$v</option>";
201
            }
202
            echo '</select></td>';
203
204
            echo "<td class='$class' style='text-align:center;'><select size='5' name='groups[" . $i->getVar('bid') . "][]' id='groups[" . $i->getVar('bid') . "][]' multiple='multiple'>";
205
            foreach ($groups as $grp) {
206
                echo "<option value='" . $grp->getVar('groupid') . "' " . (\in_array($grp->getVar('groupid'), $groupsPermissions) ? " selected='selected'" : '') . '>' . $grp->getVar('name') . '</option>';
207
            }
208
            echo '</select></td>';
209
210
            // Cache lifetime
211
            echo '<td class="' . $class . '" style="text-align:center;"> <select name="bcachetime[' . $i->getVar('bid') . ']  height:1px;">' . $cachetimeOptions . '</select>
212
                                    </td>';
213
214
            // Actions
215
216
            echo "<td class='$class' style='text-align:center;'>
217
                <a href='blocksadmin.php?op=edit&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/edit.png' . " alt='" . \_EDIT . "' title='" . \_EDIT . "'></a> 
218
                <a href='blocksadmin.php?op=clone&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/editcopy.png' . " alt='" . \_CLONE . "' title='" . \_CLONE . "'></a>";
219
            //            if ('S' !== $i->getVar('block_type') && 'M' !== $i->getVar('block_type')) {
220
            //                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 . "'>
221
            //                     </a>";
222
            //            }
223
224
            //            if ('S' !== $i->getVar('block_type') && 'M' !== $i->getVar('block_type')) {
225
            if (!\in_array($i->getVar('block_type'), ['M', 'S'])) {
226
                echo "&nbsp;
227
                <a href='blocksadmin.php?op=delete&amp;bid=" . $i->getVar('bid') . "'><img src=" . $pathIcon16 . '/delete.png' . " alt='" . \_DELETE . "' title='" . \_DELETE . "'>
228
                     </a>";
229
            }
230
            echo "
231
            <input type='hidden' name='oldtitle[" . $i->getVar('bid') . "]' value='" . $i->getVar('title') . "'>
232
            <input type='hidden' name='oldside[" . $i->getVar('bid') . "]' value='" . $i->getVar('side') . "'>
233
            <input type='hidden' name='oldweight[" . $i->getVar('bid') . "]' value='" . $i->getVar('weight') . "'>
234
            <input type='hidden' name='oldvisible[" . $i->getVar('bid') . "]' value='" . $i->getVar('visible') . "'>
235
            <input type='hidden' name='oldgroups[" . $i->getVar('groups') . "]' value='" . $i->getVar('groups') . "'>
236
            <input type='hidden' name='oldbcachetime[" . $i->getVar('bid') . "]' value='" . $i->getVar('bcachetime') . "'>
237
            <input type='hidden' name='bid[" . $i->getVar('bid') . "]' value='" . $i->getVar('bid') . "'>
238
            </td></tr>
239
            ";
240
            $class = ('even' === $class) ? 'odd' : 'even';
241
        }
242
        echo "<tr><td class='foot' style='text-align:center;' colspan='8'> <input type='hidden' name='op' value='order'>" . $GLOBALS['xoopsSecurity']->getTokenHTML() . "<input type='submit' name='submit' value='" . \_SUBMIT . "'></td></tr></table></form><br><br>";
243
    }
244
245
    /**
246
     * @param int $bid
247
     */
248
    public function deleteBlock(int $bid): void
249
    {
250
        //        \xoops_cp_header();
251
252
        \xoops_loadLanguage('admin', 'system');
253
        \xoops_loadLanguage('admin/blocksadmin', 'system');
254
        \xoops_loadLanguage('admin/groups', 'system');
255
256
        $myblock = new \XoopsBlock($bid);
0 ignored issues
show
Unused Code introduced by
The assignment to $myblock is dead and can be removed.
Loading history...
257
258
        $sql = \sprintf('DELETE FROM %s WHERE bid = %u', $this->db->prefix('newblocks'), $bid);
259
        $this->db->queryF($sql) || \trigger_error($GLOBALS['xoopsDB']->error());
260
        $sql = \sprintf('DELETE FROM %s WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
261
        $this->db->queryF($sql) || \trigger_error($GLOBALS['xoopsDB']->error());
262
263
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
264
    }
265
266
    /**
267
     * @param int $bid
268
     */
269
    public function cloneBlock(int $bid): void
270
    {
271
        //require_once __DIR__ . '/admin_header.php';
272
        //        \xoops_cp_header();
273
274
        \xoops_loadLanguage('admin', 'system');
275
        \xoops_loadLanguage('admin/blocksadmin', 'system');
276
        \xoops_loadLanguage('admin/groups', 'system');
277
278
        $modules = [];
279
        $myblock = new \XoopsBlock($bid);
280
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
281
        $result  = $this->db->query($sql);
282
        if ($this->db->isResultSet($result)) {
283
            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

283
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
284
                $modules[] = (int)$row['module_id'];
285
            }
286
        } else {
287
            \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
288
        }
289
290
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
291
        $block    = [
292
            'title'      => $myblock->getVar('title') . ' Clone',
293
            'form_title' => \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BLOCKS_CLONEBLOCK'),
294
            'name'       => $myblock->getVar('name'),
295
            'side'       => $myblock->getVar('side'),
296
            'weight'     => $myblock->getVar('weight'),
297
            'visible'    => $myblock->getVar('visible'),
298
            'content'    => $myblock->getVar('content', 'N'),
299
            'modules'    => $modules,
300
            'is_custom'  => $isCustom,
301
            'ctype'      => $myblock->getVar('c_type'),
302
            'bcachetime' => $myblock->getVar('bcachetime'),
303
            'op'         => 'clone_ok',
304
            'bid'        => $myblock->getVar('bid'),
305
            'edit_form'  => $myblock->getOptions(),
306
            'template'   => $myblock->getVar('template'),
307
            'options'    => $myblock->getVar('options'),
308
        ];
309
        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>';
310
        //        $form = new Blockform();
311
        //        $form->render();
312
313
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Newbb\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...
Bug introduced by
Are you sure $this->render($block) of type void can be used in echo? ( Ignorable by Annotation )

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

313
        echo /** @scrutinizer ignore-type */ $this->render($block);
Loading history...
314
        //        xoops_cp_footer();
315
        //        require_once __DIR__ . '/admin_footer.php';
316
        //        exit();
317
    }
318
319
    /**
320
     * @param int        $bid
321
     * @param string     $bside
322
     * @param string     $bweight
323
     * @param string     $bvisible
324
     * @param string     $bcachetime
325
     * @param array|null $bmodule
326
     * @param array|null $options
327
     * @param array|null $groups
328
     */
329
    public function isBlockCloned(int $bid, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
330
    {
331
        $newid = null;
332
        \xoops_loadLanguage('admin', 'system');
333
        \xoops_loadLanguage('admin/blocksadmin', 'system');
334
        \xoops_loadLanguage('admin/groups', 'system');
335
336
337
338
        $block = new \XoopsBlock($bid);
339
        $clone = $block->xoopsClone();
340
        assert($clone instanceof \XoopsObject);
341
        if (($bmodule === null || $bmodule === [])) {
342
            //            \xoops_cp_header();
343
            \xoops_error(\sprintf(_AM_NOTSELNG, _AM_VISIBLEIN));
344
            \xoops_cp_footer();
345
            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...
346
        }
347
        $clone->setVar('side', $bside);
348
        $clone->setVar('weight', $bweight);
349
        $clone->setVar('visible', $bvisible);
350
        //$clone->setVar('content', $_POST['bcontent']);
351
        $clone->setVar('title', Request::getString('btitle', '', 'POST'));
352
        $clone->setVar('bcachetime', $bcachetime);
353
        if (\is_array($options) && ($options !== [])) {
354
            $optionsImploded = \implode('|', $options);
355
            $clone->setVar('options', $optionsImploded);
356
        }
357
        $clone->setVar('bid', 0);
358
        if (\in_array($block->getVar('block_type'), ['C', 'E'])) {
359
            $clone->setVar('block_type', 'E');
360
        } else {
361
            $clone->setVar('block_type', 'D');
362
        }
363
        //        $newid = $clone->store(); //see https://github.com/XOOPS/XoopsCore25/issues/1105
364
        if ($clone->store()) {
0 ignored issues
show
Bug introduced by
The method store() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsBlock or XoopsComments or XoopsModules\Xoopspoll\Option or XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

364
        if ($clone->/** @scrutinizer ignore-call */ store()) {
Loading history...
365
            $newid = $clone->id();  //get the id of the cloned block
0 ignored issues
show
Bug introduced by
The method id() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsTplfile or XoopsModule or XoopsImageSet or XoopsGroup or XoopsConfigOption or XoopsBlock or XoopsComment or XoopsConfigCategory or XoopsAvatar or XoopsImagecategory or XoopsImage or XoopsConfigItem or XoopsNotification or XoopsUser or XoopsGroupPerm or XoopsPrivmessage or XoopsImagesetimg or XoopsTplset. ( Ignorable by Annotation )

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

365
            /** @scrutinizer ignore-call */ 
366
            $newid = $clone->id();  //get the id of the cloned block
Loading history...
366
        }
367
        if (!$newid) {
368
            //            \xoops_cp_header();
369
            $clone->getHtmlErrors();
370
            \xoops_cp_footer();
371
            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...
372
        }
373
        if ('' !== $clone->getVar('template')) {
374
            /** @var \XoopsTplfileHandler $tplfileHandler */
375
            $tplfileHandler = \xoops_getHandler('tplfile');
376
            $btemplate      = $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', (string)$bid);
377
            if ((is_countable($btemplate) ? \count($btemplate) : 0) > 0) {
378
                $tplclone = $btemplate[0]->xoopsClone();
379
                $tplclone->setVar('tpl_id', 0);
380
                $tplclone->setVar('tpl_refid', $newid);
381
                $tplfileHandler->insert($tplclone);
382
            }
383
        }
384
385
        foreach ($bmodule as $bmid) {
386
            $sql = 'INSERT INTO ' . $this->db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')';
387
            $this->db->query($sql);
388
        }
389
        //$groups = &$GLOBALS['xoopsUser']->getGroups();
390
        foreach ($groups as $iValue) {
391
            $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . ' (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (' . $iValue . ', ' . $newid . ", 1, 'block_read')";
392
            $this->db->query($sql);
393
        }
394
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
395
    }
396
397
    /**
398
     * @param string     $bid
399
     * @param string     $title
400
     * @param string     $weight
401
     * @param string     $visible
402
     * @param string     $side
403
     * @param string     $bcachetime
404
     * @param array|null $bmodule
405
     */
406
    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

406
    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...
407
    {
408
        $myblock = new \XoopsBlock($bid);
409
        $myblock->setVar('title', $title);
410
        $myblock->setVar('weight', $weight);
411
        $myblock->setVar('visible', $visible);
412
        $myblock->setVar('side', $side);
413
        $myblock->setVar('bcachetime', $bcachetime);
414
        $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

414
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
415
        //        /** @var \XoopsBlockHandler $blockHandler */
416
        //        $blockHandler = \xoops_getHandler('block');
417
        //        return $blockHandler->insert($myblock);
418
    }
419
420
    /**
421
     * @param int $bid
422
     * @return void
423
     */
424
    public function editBlock(int $bid): void
425
    {
426
        //        require_once \dirname(__DIR__,2) . '/admin/admin_header.php';
427
        //        \xoops_cp_header();
428
        \xoops_loadLanguage('admin', 'system');
429
        \xoops_loadLanguage('admin/blocksadmin', 'system');
430
        \xoops_loadLanguage('admin/groups', 'system');
431
        //        mpu_adm_menu();
432
        $myblock = new \XoopsBlock($bid);
433
        $modules = [];
434
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
435
        $result  = $this->db->query($sql);
436
        if ($this->db->isResultSet($result)) {
437
            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

437
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
438
                $modules[] = (int)$row['module_id'];
439
            }
440
        } else {
441
            \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
442
        }
443
444
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
445
        $block    = [
446
            'title'      => $myblock->getVar('title'),
447
            'form_title' => \_AM_SYSTEM_BLOCKS_EDITBLOCK,
448
            //        'name'       => $myblock->getVar('name'),
449
            'side'       => $myblock->getVar('side'),
450
            'weight'     => $myblock->getVar('weight'),
451
            'visible'    => $myblock->getVar('visible'),
452
            'content'    => $myblock->getVar('content', 'N'),
453
            'modules'    => $modules,
454
            'is_custom'  => $isCustom,
455
            'ctype'      => $myblock->getVar('c_type'),
456
            'bcachetime' => $myblock->getVar('bcachetime'),
457
            'op'         => 'edit_ok',
458
            'bid'        => $myblock->getVar('bid'),
459
            'edit_form'  => $myblock->getOptions(),
460
            'template'   => $myblock->getVar('template'),
461
            'options'    => $myblock->getVar('options'),
462
        ];
463
        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>';
464
465
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Newbb\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...
Bug introduced by
Are you sure $this->render($block) of type void can be used in echo? ( Ignorable by Annotation )

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

465
        echo /** @scrutinizer ignore-type */ $this->render($block);
Loading history...
466
    }
467
468
    /**
469
     * @param int        $bid
470
     * @param string     $btitle
471
     * @param string     $bside
472
     * @param string     $bweight
473
     * @param string     $bvisible
474
     * @param string     $bcachetime
475
     * @param array|null $bmodule
476
     * @param array|null $options
477
     * @param array|null $groups
478
     */
479
    public function updateBlock(int $bid, string $btitle, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
480
    {
481
        $myblock = new \XoopsBlock($bid);
482
        $myblock->setVar('title', $btitle);
483
        $myblock->setVar('weight', $bweight);
484
        $myblock->setVar('visible', $bvisible);
485
        $myblock->setVar('side', $bside);
486
        $myblock->setVar('bcachetime', $bcachetime);
487
        //update block options
488
        if (isset($options)) {
489
            $optionsCount = \count($options);
490
            if ($optionsCount > 0) {
491
                //Convert array values to comma-separated
492
                foreach ($options as $i => $iValue) {
493
                    if (\is_array($iValue)) {
494
                        $options[$i] = \implode(',', $iValue);
495
                    }
496
                }
497
                $optionsImploded = \implode('|', $options);
498
                $myblock->setVar('options', $optionsImploded);
499
            }
500
        }
501
        $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

501
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
502
        //        /** @var \XoopsBlockHandler $blockHandler */
503
        //        $blockHandler = \xoops_getHandler('block');
504
        //        $blockHandler->insert($myblock);
505
506
        if (($bmodule !== null && $bmodule !== []) && $bmodule !== []) {
507
            $sql = \sprintf('DELETE FROM `%s` WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
508
            $this->db->query($sql);
509
            if (\in_array(0, $bmodule)) {
510
                $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, 0);
511
                $this->db->query($sql);
512
            } else {
513
                foreach ($bmodule as $bmid) {
514
                    $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, (int)$bmid);
515
                    $this->db->query($sql);
516
                }
517
            }
518
        }
519
        $sql = \sprintf('DELETE FROM `%s` WHERE gperm_itemid = %u', $this->db->prefix('group_permission'), $bid);
520
        $this->db->query($sql);
521
        if (($groups !== null && $groups !== [])) {
522
            foreach ($groups as $grp) {
523
                $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);
524
                $this->db->query($sql);
525
            }
526
        }
527
        $this->helper->redirect('admin/blocksadmin.php', 1, \constant('CO_' . $this->moduleDirNameUpper . '_' . 'UPDATE_SUCCESS'));
528
    }
529
530
    /**
531
     * @param array $bid
532
     * @param array $oldtitle
533
     * @param array $oldside
534
     * @param array $oldweight
535
     * @param array $oldvisible
536
     * @param array $oldgroups
537
     * @param array $oldbcachetime
538
     * @param array $oldbmodule
539
     * @param array $title
540
     * @param array $weight
541
     * @param array $visible
542
     * @param array $side
543
     * @param array $bcachetime
544
     * @param array $groups
545
     * @param array $bmodule
546
     */
547
    public function orderBlock(
548
        array $bid, array $oldtitle, array $oldside, array $oldweight, array $oldvisible, array $oldgroups, array $oldbcachetime, array $oldbmodule, array $title, array $weight, array $visible, array $side, array $bcachetime, array $groups, array $bmodule
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

548
        array $bid, array $oldtitle, array $oldside, array $oldweight, array $oldvisible, /** @scrutinizer ignore-unused */ array $oldgroups, array $oldbcachetime, array $oldbmodule, array $title, array $weight, array $visible, array $side, array $bcachetime, array $groups, array $bmodule

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