Passed
Push — master ( 123af7...b40d59 )
by Michael
16:33
created

Blocksadmin::cloneBlock()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 47
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

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

134
            $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...
135
            $result            = $this->db->query($sql);
136
            if (!$this->db->isResultSet($result)) {
137
//                \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
138
                $errorMsg = \sprintf(_DB_QUERY_ERROR, $sql) . $this->db->error();
139
                $logger   = \XoopsLogger::getInstance();
140
                $logger->handleError(E_USER_WARNING, $errorMsg, __FILE__, __LINE__);
141
                $this->helper->redirect('admin/blocksadmin.php', 3, $errorMsg);
142
            }
143
            $modules           = [];
144
            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

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

316
        while (false !== ($row = $this->db->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
317
            $modules[] = (int)$row['module_id'];
318
        }
319
320
        $isCustom = \in_array($myblock->getVar('block_type'), ['C', 'E']);
321
        $block    = [
322
            'title'      => $myblock->getVar('title') . ' Clone',
323
            'form_title' => \constant('CO_' . $this->moduleDirNameUpper . '_' . 'BLOCKS_CLONEBLOCK'),
324
            'name'       => $myblock->getVar('name'),
325
            'side'       => $myblock->getVar('side'),
326
            'weight'     => $myblock->getVar('weight'),
327
            'visible'    => $myblock->getVar('visible'),
328
            'content'    => $myblock->getVar('content', 'N'),
329
            'modules'    => $modules,
330
            'is_custom'  => $isCustom,
331
            'ctype'      => $myblock->getVar('c_type'),
332
            'bcachetime' => $myblock->getVar('bcachetime'),
333
            'op'         => 'clone_ok',
334
            'bid'        => $myblock->getVar('bid'),
335
            'edit_form'  => $myblock->getOptions(),
336
            'template'   => $myblock->getVar('template'),
337
            'options'    => $myblock->getVar('options'),
338
        ];
339
        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>';
340
        //        $form = new Blockform();
341
        //        $form->render();
342
343
        echo $this->render($block);
0 ignored issues
show
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

343
        echo /** @scrutinizer ignore-type */ $this->render($block);
Loading history...
Bug introduced by
Are you sure the usage of $this->render($block) targeting XoopsModules\Adslight\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...
344
        //        xoops_cp_footer();
345
        //        require_once __DIR__ . '/admin_footer.php';
346
        //        exit();
347
    }
348
349
    /**
350
     * @param int        $bid
351
     * @param string     $bside
352
     * @param string     $bweight
353
     * @param string     $bvisible
354
     * @param string     $bcachetime
355
     * @param array|null $bmodule
356
     * @param array|null $options
357
     * @param array|null $groups
358
     */
359
    public function isBlockCloned(int $bid, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void
360
    {
361
        \xoops_loadLanguage('admin', 'system');
362
        \xoops_loadLanguage('admin/blocksadmin', 'system');
363
        \xoops_loadLanguage('admin/groups', 'system');
364
365
        $block = new \XoopsBlock($bid);
366
        /** @var \XoopsBlock $clone */
367
        $clone = $block->xoopsClone();
368
        if (empty($bmodule)) {
369
            //            \xoops_cp_header();
370
            \xoops_error(\sprintf(_AM_NOTSELNG, _AM_VISIBLEIN));
371
            \xoops_cp_footer();
372
            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...
373
        }
374
        $clone->setVar('side', $bside);
375
        $clone->setVar('weight', $bweight);
376
        $clone->setVar('visible', $bvisible);
377
        //$clone->setVar('content', $_POST['bcontent']);
378
        $clone->setVar('title', Request::getString('btitle', '', 'POST'));
379
        $clone->setVar('bcachetime', $bcachetime);
380
        if (\is_array($options) && (\count($options) > 0)) {
381
            $options = \implode('|', $options);
382
            $clone->setVar('options', $options);
383
        }
384
        $clone->setVar('bid', 0);
385
        if (\in_array($block->getVar('block_type'), ['C', 'E'])) {
386
            $clone->setVar('block_type', 'E');
387
        } else {
388
            $clone->setVar('block_type', 'D');
389
        }
390
        //        $newid = $clone->store(); //see https://github.com/XOOPS/XoopsCore25/issues/1105
391
        if ($clone->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

391
        if (/** @scrutinizer ignore-deprecated */ $clone->store()) {
Loading history...
Bug Best Practice introduced by
The expression $clone->store() of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
392
            $newid = $clone->id();  //get the id of the cloned block
393
        }
394
        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...
395
            //            \xoops_cp_header();
396
            $clone->getHtmlErrors();
397
            \xoops_cp_footer();
398
            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...
399
        }
400
        if ('' !== $clone->getVar('template')) {
401
            /** @var \XoopsTplfileHandler $tplfileHandler */
402
            $tplfileHandler = \xoops_getHandler('tplfile');
403
            $configHandler = xoops_getHandler('config');
404
            $xoopsConfig = $configHandler->getConfigsByCat(XOOPS_CONF);
0 ignored issues
show
Bug introduced by
The method getConfigsByCat() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

404
            /** @scrutinizer ignore-call */ 
405
            $xoopsConfig = $configHandler->getConfigsByCat(XOOPS_CONF);
Loading history...
405
            $btemplate      = $tplfileHandler->find($xoopsConfig['template_set'], 'block', (string)$bid);
406
            if (\count($btemplate) > 0) {
407
                $tplclone = $btemplate[0]->xoopsClone();
408
                $tplclone->setVar('tpl_id', 0);
409
                $tplclone->setVar('tpl_refid', $newid);
410
                $tplfileHandler->insert($tplclone);
411
            }
412
        }
413
414
        foreach ($bmodule as $bmid) {
415
            $sql = 'INSERT INTO ' . $this->db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')';
416
            $this->db->query($sql);
417
        }
418
        //$groups = &$this->xoopsUser->getGroups();
419
        foreach ($groups as $iValue) {
420
            $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . ' (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (' . $iValue . ', ' . $newid . ", 1, 'block_read')";
421
            $this->db->query($sql);
422
        }
423
        $this->helper->redirect('admin/blocksadmin.php?op=list', 1, _AM_DBUPDATED);
424
    }
425
426
    /**
427
     * @param string     $bid
428
     * @param string     $title
429
     * @param string     $weight
430
     * @param string     $visible
431
     * @param string     $side
432
     * @param string     $bcachetime
433
     * @param array|null $bmodule
434
     */
435
    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

435
    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...
436
    {
437
        $myblock = new \XoopsBlock($bid);
438
        $myblock->setVar('title', $title);
439
        $myblock->setVar('weight', $weight);
440
        $myblock->setVar('visible', $visible);
441
        $myblock->setVar('side', $side);
442
        $myblock->setVar('bcachetime', $bcachetime);
443
        $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

443
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
444
        //        /** @var \XoopsBlockHandler $blockHandler */
445
        //        $blockHandler = \xoops_getHandler('block');
446
        //        return $blockHandler->insert($myblock);
447
    }
448
449
    /**
450
     * @param int $bid
451
     * @return void
452
     */
453
    public function editBlock(int $bid): void
454
    {
455
        //        require_once \dirname(__DIR__,2) . '/admin/admin_header.php';
456
        //        \xoops_cp_header();
457
        \xoops_loadLanguage('admin', 'system');
458
        \xoops_loadLanguage('admin/blocksadmin', 'system');
459
        \xoops_loadLanguage('admin/groups', 'system');
460
        //        mpu_adm_menu();
461
        $myblock = new \XoopsBlock($bid);
462
        $sql     = 'SELECT module_id FROM ' . $this->db->prefix('block_module_link') . ' WHERE block_id=' . $bid;
463
        $result  = $this->db->query($sql);
464
        if (!$this->db->isResultSet($result)) {
465
            //            \trigger_error("Query Failed! SQL: $sql Error: " . $this->db->error(), \E_USER_ERROR);
466
            $errorMsg = \sprintf(_DB_QUERY_ERROR, $sql) . $this->db->error();
467
            $logger   = \XoopsLogger::getInstance();
468
            $logger->handleError(E_USER_WARNING, $errorMsg, __FILE__, __LINE__);
469
            $this->helper->redirect('admin/blocksadmin.php', 3, $errorMsg);
470
        }
471
        $modules = [];
472
            while (false !== ($row = $this->db->fetchArray($result))) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

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

497
        echo /** @scrutinizer ignore-type */ $this->render($block);
Loading history...
498
    }
499
500
    /**
501
     * @param int        $bid
502
     * @param string     $btitle
503
     * @param string     $bside
504
     * @param string     $bweight
505
     * @param string     $bvisible
506
     * @param string     $bcachetime
507
     * @param array|null $bmodule
508
     * @param array|null $options
509
     * @param array|null $groups
510
     */
511
    public function updateBlock(int $bid, string $btitle, string $bside, string $bweight, string $bvisible, string $bcachetime, ?array $bmodule, ?array $options, ?array $groups): void 
512
    {
513
        $myblock = new \XoopsBlock($bid);
514
        $myblock->setVar('title', $btitle);
515
        $myblock->setVar('weight', $bweight);
516
        $myblock->setVar('visible', $bvisible);
517
        $myblock->setVar('side', $bside);
518
        $myblock->setVar('bcachetime', $bcachetime);
519
        //update block options
520
        if (isset($options)) {
521
            $optionsCount = \count($options);
522
            if ($optionsCount > 0) {
523
                //Convert array values to comma-separated
524
                foreach ($options as $i => $iValue) {
525
                    if (\is_array($iValue)) {
526
                        $options[$i] = \implode(',', $iValue);
527
                    }
528
                }
529
                $options = \implode('|', $options);
530
                $myblock->setVar('options', $options);
531
            }
532
        }
533
        $myblock->store();
0 ignored issues
show
Deprecated Code introduced by
The function XoopsBlock::store() has been deprecated. ( Ignorable by Annotation )

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

533
        /** @scrutinizer ignore-deprecated */ $myblock->store();
Loading history...
534
        //        /** @var \XoopsBlockHandler $blockHandler */
535
        //        $blockHandler = \xoops_getHandler('block');
536
        //        $blockHandler->insert($myblock);
537
538
        if (!empty($bmodule) && \count($bmodule) > 0) {
539
            $sql = \sprintf('DELETE FROM `%s` WHERE block_id = %u', $this->db->prefix('block_module_link'), $bid);
540
            $this->db->query($sql);
541
            if (\in_array(0, $bmodule)) {
542
                $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, 0);
543
                $this->db->query($sql);
544
            } else {
545
                foreach ($bmodule as $bmid) {
546
                    $sql = \sprintf('INSERT INTO `%s` (block_id, module_id) VALUES (%u, %d)', $this->db->prefix('block_module_link'), $bid, (int)$bmid);
547
                    $this->db->query($sql);
548
                }
549
            }
550
        }
551
        $sql = \sprintf('DELETE FROM `%s` WHERE gperm_itemid = %u', $this->db->prefix('group_permission'), $bid);
552
        $this->db->query($sql);
553
        if (!empty($groups)) {
554
            foreach ($groups as $grp) {
555
                $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);
556
                $this->db->query($sql);
557
            }
558
        }
559
        $this->helper->redirect('admin/blocksadmin.php', 1, \constant('CO_' . $this->moduleDirNameUpper . '_' . 'UPDATE_SUCCESS'));
560
    }
561
562
    /**
563
     * @param array $bid
564
     * @param array $oldtitle
565
     * @param array $oldside
566
     * @param array $oldweight
567
     * @param array $oldvisible
568
     * @param array $oldgroups
569
     * @param array $oldbcachetime
570
     * @param array $oldbmodule
571
     * @param array $title
572
     * @param array $weight
573
     * @param array $visible
574
     * @param array $side
575
     * @param array $bcachetime
576
     * @param array $groups
577
     * @param array $bmodule
578
     */
579
    public function orderBlock(
580
        array $bid,
581
        array $oldtitle,
582
        array $oldside,
583
        array $oldweight,
584
        array $oldvisible,
585
        array $oldgroups,
0 ignored issues
show
Unused Code introduced by
The parameter $oldgroups is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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