Blocksadmin::updateBlock()   B
last analyzed

Complexity

Conditions 11
Paths 18

Size

Total Lines 49
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 11
eloc 32
c 2
b 0
f 0
nc 18
nop 9
dl 0
loc 49
rs 7.3166

How to fix   Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

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

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\News\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\News\{
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 Helper
38
     */
39
    public Helper $helper;
40
    /**
41
     * @var string
42
     */
43
    public string $moduleDirName;
44
    /**
45
     * @var string
46
     */
47
    public $moduleDirNameUpper;
48
49
    /**
50
     * Blocksadmin constructor.
51
     * @param \XoopsDatabase|null $db
52
     * @param Helper              $helper
53
     */
54
    public function __construct(?\XoopsDatabase $db, Helper $helper)
55
    {
56
        if (null === $db) {
57
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
58
        }
59
        $this->db                 = $db;
60
        $this->helper             = $helper;
61
        $this->moduleDirName      = \basename(\dirname(__DIR__, 2));
62
        $this->moduleDirNameUpper = \mb_strtoupper($this->moduleDirName);
63
        \xoops_loadLanguage('admin', 'system');
64
        \xoops_loadLanguage('admin/blocksadmin', 'system');
65
        \xoops_loadLanguage('admin/groups', 'system');
66
        \xoops_loadLanguage('common', $this->moduleDirName);
67
        \xoops_loadLanguage('blocksadmin', $this->moduleDirName);
68
    }
69
70
    /**
71
     * @return void
72
     */
73
    public function listBlocks(): void
74
    {
75
        global $xoopsModule, $pathIcon16;
76
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
77
        //        xoops_loadLanguage('admin', 'system');
78
        //        xoops_loadLanguage('admin/blocksadmin', 'system');
79
        //        xoops_loadLanguage('admin/groups', 'system');
80
        //        xoops_loadLanguage('common', $moduleDirName);
81
        //        xoops_loadLanguage('blocks', $moduleDirName);
82
83
        /** @var \XoopsModuleHandler $moduleHandler */
84
        $moduleHandler = \xoops_getHandler('module');
85
        /** @var \XoopsMemberHandler $memberHandler */
86
        $memberHandler = \xoops_getHandler('member');
87
        /** @var \XoopsGroupPermHandler $grouppermHandler */
88
        $grouppermHandler = \xoops_getHandler('groupperm');
89
        $groups           = $memberHandler->getGroups();
90
        $criteria         = new \CriteriaCompo(new \Criteria('hasmain', '1'));
91
        $criteria->add(new \Criteria('isactive', '1'));
92
        $moduleList     = $moduleHandler->getList($criteria);
93
        $moduleList[-1] = \_AM_SYSTEM_BLOCKS_TOPPAGE;
94
        $moduleList[0]  = \_AM_SYSTEM_BLOCKS_ALLPAGES;
95
        \ksort($moduleList);
96
        echo "<h4 style='text-align:left;'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BADMIN') . '</h4>';
97
        echo "<form action='" . $_SERVER['SCRIPT_NAME'] . "' name='blockadmin' method='post'>";
98
        echo $GLOBALS['xoopsSecurity']->getTokenHTML();
99
        echo "<table width='100%' class='outer' cellpadding='4' cellspacing='1'>
100
        <tr valign='middle'><th align='center'>" . \_AM_SYSTEM_BLOCKS_TITLE . "</th><th align='center' nowrap='nowrap'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'SIDE') . '<br>' . \_LEFT . '-' . \_CENTER . '-' . \_RIGHT . "</th>
101
        <th align='center'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'WEIGHT') . "</th>
102
        <th align='center'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'VISIBLE') . "</th><th align='center'>" . \_AM_SYSTEM_BLOCKS_VISIBLEIN . "</th>
103
        <th align='center'>" . \_AM_SYSTEM_ADGS . "</th>
104
        <th align='center'>" . \_AM_SYSTEM_BLOCKS_BCACHETIME . "</th>
105
        <th align='center'>" . \constant('CO_' . $this->moduleDirNameUpper . '_' . 'ACTION') . '</th>
106
        </tr>';
107
        $blockArray = \XoopsBlock::getByModule($xoopsModule->mid());
108
        $blockCount = \count($blockArray);
0 ignored issues
show
Unused Code introduced by
The assignment to $blockCount is dead and can be removed.
Loading history...
109
        $class      = 'even';
110
        $cachetimes = [
111
            0       => \_NOCACHE,
112
            30      => \sprintf(\_SECONDS, 30),
113
            60      => \_MINUTE,
114
            300     => \sprintf(\_MINUTES, 5),
115
            1800    => \sprintf(\_MINUTES, 30),
116
            3600    => \_HOUR,
117
            18000   => \sprintf(\_HOURS, 5),
118
            86400   => \_DAY,
119
            259200  => \sprintf(\_DAYS, 3),
120
            604800  => \_WEEK,
121
            2592000 => \_MONTH,
122
        ];
123
        foreach ($blockArray as $i) {
124
            $modules = [];
125
            $groupsPermissions = $grouppermHandler->getGroupIds('block_read', $i->getVar('bid'));
126
            $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

126
            $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...
127
            $result            = $this->db->query($sql);
128
            if (!$this->db->isResultSet($result)) {
129
                \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
130
            } else {
131
                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

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

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

312
        echo /** @scrutinizer ignore-type */ $this->render($block);
Loading history...
313
        //        xoops_cp_footer();
314
        //        require_once __DIR__ . '/admin_footer.php';
315
        //        exit();
316
    }
317
318
    /**
319
     * @param int        $bid
320
     * @param string     $bside
321
     * @param string     $bweight
322
     * @param string     $bvisible
323
     * @param string     $bcachetime
324
     * @param array|null $bmodule
325
     * @param array|null $options
326
     * @param array|null $groups
327
     */
328
    public function isBlockCloned(int $bid, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
329
    {
330
        \xoops_loadLanguage('admin', 'system');
331
        \xoops_loadLanguage('admin/blocksadmin', 'system');
332
        \xoops_loadLanguage('admin/groups', 'system');
333
334
        $block = new \XoopsBlock($bid);
335
        $clone = $block->xoopsClone();
336
        if (empty($bmodule)) {
337
            //            \xoops_cp_header();
338
            \xoops_error(\sprintf(_AM_NOTSELNG, _AM_VISIBLEIN));
339
            \xoops_cp_footer();
340
            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...
341
        }
342
        $clone->setVar('side', $bside);
343
        $clone->setVar('weight', $bweight);
344
        $clone->setVar('visible', $bvisible);
345
        //$clone->setVar('content', $_POST['bcontent']);
346
        $clone->setVar('title', Request::getString('btitle', '', 'POST'));
347
        $clone->setVar('bcachetime', $bcachetime);
348
        if (\is_array($options) && ($options !== [])) {
349
            $optionsImploded = \implode('|', $options);
350
            $clone->setVar('options', $optionsImploded);
351
        }
352
        $clone->setVar('bid', 0);
353
        if (\in_array($block->getVar('block_type'), ['C', 'E'])) {
354
            $clone->setVar('block_type', 'E');
355
        } else {
356
            $clone->setVar('block_type', 'D');
357
        }
358
        //        $newid = $clone->store(); //see https://github.com/XOOPS/XoopsCore25/issues/1105
359
        if ($clone->store()) {
360
            $newid = $clone->id();  //get the id of the cloned block
361
        }
362
        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...
363
            //            \xoops_cp_header();
364
            $clone->getHtmlErrors();
365
            \xoops_cp_footer();
366
            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...
367
        }
368
        if ('' !== $clone->getVar('template')) {
369
            /** @var \XoopsTplfileHandler $tplfileHandler */
370
            $tplfileHandler = \xoops_getHandler('tplfile');
371
            $btemplate      = $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', (string)$bid);
372
            if (\count($btemplate) > 0) {
373
                $tplclone = $btemplate[0]->xoopsClone();
374
                $tplclone->setVar('tpl_id', 0);
375
                $tplclone->setVar('tpl_refid', $newid);
376
                $tplfileHandler->insert($tplclone);
377
            }
378
        }
379
380
        foreach ($bmodule as $bmid) {
381
            $sql = 'INSERT INTO ' . $this->db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')';
382
            $this->db->query($sql);
383
        }
384
        //$groups = &$GLOBALS['xoopsUser']->getGroups();
385
        foreach ($groups as $iValue) {
386
            $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . ' (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (' . $iValue . ', ' . $newid . ", 1, 'block_read')";
387
            $this->db->query($sql);
388
        }
389
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
390
    }
391
392
    /**
393
     * @param string     $bid
394
     * @param string     $title
395
     * @param string     $weight
396
     * @param string     $visible
397
     * @param string     $side
398
     * @param string     $bcachetime
399
     * @param array|null $bmodule
400
     */
401
    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

401
    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...
402
    {
403
        $myblock = new \XoopsBlock($bid);
404
        $myblock->setVar('title', $title);
405
        $myblock->setVar('weight', $weight);
406
        $myblock->setVar('visible', $visible);
407
        $myblock->setVar('side', $side);
408
        $myblock->setVar('bcachetime', $bcachetime);
409
        $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

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

434
            while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
435
                $modules[] = (int)$row['module_id'];
436
            }
437
        }
438
439
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
440
        $block    = [
441
            'title'      => $myblock->getVar('title'),
442
            'form_title' => \_AM_SYSTEM_BLOCKS_EDITBLOCK,
443
            //        'name'       => $myblock->getVar('name'),
444
            'side'       => $myblock->getVar('side'),
445
            'weight'     => $myblock->getVar('weight'),
446
            'visible'    => $myblock->getVar('visible'),
447
            'content'    => $myblock->getVar('content', 'N'),
448
            'modules'    => $modules,
449
            'is_custom'  => $isCustom,
450
            'ctype'      => $myblock->getVar('c_type'),
451
            'bcachetime' => $myblock->getVar('bcachetime'),
452
            'op'         => 'edit_ok',
453
            'bid'        => $myblock->getVar('bid'),
454
            'edit_form'  => $myblock->getOptions(),
455
            'template'   => $myblock->getVar('template'),
456
            'options'    => $myblock->getVar('options'),
457
        ];
458
        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>';
459
460
        echo $this->render($block);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\News\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

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

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

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