MyBlocksAdmin::form_edit()   F
last analyzed

Complexity

Conditions 12
Paths 384

Size

Total Lines 144

Duplication

Lines 47
Ratio 32.64 %

Importance

Changes 0
Metric Value
cc 12
nc 384
nop 2
dl 47
loc 144
rs 3.0666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
// $Id: MyBlocksAdmin.class.php ,ver 0.0.7.1 2011/02/15 02:55:00 domifara Exp $
3
4
/**
5
 * Class MyBlocksAdmin
6
 */
7
class MyBlocksAdmin
8
{
9
    public $db;
10
11
    public $lang;
12
13
    public $cachetime_options = [];
14
15
    public $ctype_options = [];
16
17
    public $type_options = [];
18
19
    public $target_mid = 0;
20
21
    public $target_dirname = '';
22
23
    public $target_mname = '';
24
25
    public $block_configs = [];
26
27
    public $preview_request = [];
28
29
    public function MyBlocksAadmin()
30
    {
31
    }
32
33
    public function construct()
34
    {
35
        $this->db = XoopsDatabaseFactory::getDatabaseConnection();
36
37
        $this->lang = @$GLOBALS['xoopsConfig']['language'];
38
39
        $this->cachetime_options = [
40
            0 => _NOCACHE,
41
            30 => sprintf(_SECONDS, 30),
42
            60 => _MINUTE,
43
            300 => sprintf(_MINUTES, 5),
44
            1800 => sprintf(_MINUTES, 30),
45
            3600 => _HOUR,
46
            18000 => sprintf(_HOURS, 5),
47
            86400 => _DAY,
48
            259200 => sprintf(_DAYS, 3),
49
            604800 => _WEEK,
50
            2592000 => _MONTH,
51
        ];
52
53
        $this->ctype_options = [
54
            'H' => _MD_A_MYBLOCKSADMIN_CTYPE_HTML,
55
            'T' => _MD_A_MYBLOCKSADMIN_CTYPE_NOSMILE,
56
            'S' => _MD_A_MYBLOCKSADMIN_CTYPE_SMILE,
57
            'P' => _MD_A_MYBLOCKSADMIN_CTYPE_PHP,
58
        ];
59
60
        $this->type_options = [
61
            'C' => 'custom block',
62
            'E' => 'cloned custom block',
63
            'M' => 'module\'s block',
64
            'D' => 'cloned module\'s block',
65
            'S' => 'system block',
66
        ];
67
    }
68
69
    //HACK by domifara for php5.3+
70
71
    //function getInstance()
72
73
    /**
74
     * @return \MyBlocksAdmin
75
     */
76
77
    public static function getInstance()
78
    {
79
        static $instance;
80
81
        if (!isset($instance)) {
82
            $instance = new self();
83
84
            $instance->construct();
85
        }
86
87
        return $instance;
88
    }
89
90
    // virtual
91
92
    public function checkPermission()
93
    {
94
        // only groups have 'module_admin' of 'altsys' can do that.
95
96
        $moduleHandler = xoops_getHandler('module');
97
98
        $module = $moduleHandler->getByDirname('altsys');
99
100
        $moduleperm_handler = xoops_getHandler('groupperm');
101
102 View Code Duplication
        if (!is_object(@$GLOBALS['xoopsUser']) || !$moduleperm_handler->checkRight('module_admin', $module->getVar('mid'), $GLOBALS['xoopsUser']->getGroups())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
            die('only admin of altsys can access this area');
104
        }
105
    }
106
107
    /**
108
     * @param $xoopsModule
109
     */
110
111
    public function init($xoopsModule)
112
    {
113
        // altsys "module" MODE
114
115
        if ('altsys' == $xoopsModule->getVar('dirname')) {
116
            // set target_module if specified by $_GET['dirname']
117
118
            $moduleHandler = xoops_getHandler('module');
119
120
         if (! empty($_GET['dirname'])) {
121
                $dirname = preg_replace('/[^0-9a-zA-Z_-]/', '', \Xmf\Request::getString('dirname', '', 'GET'));
122
123
                $target_module = $moduleHandler->getByDirname($dirname);
124
            }
125
126
            if (is_object(@$target_module)) {
127
                // module's blocks
128
129
                $this->target_mid = $target_module->getVar('mid');
0 ignored issues
show
Bug introduced by
The variable $target_module does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
130
131
                $this->target_mname = $target_module->getVar('name') . '&nbsp;' . sprintf('(%2.2f)', $target_module->getVar('version') / 100.0);
132
133
                $this->target_dirname = $target_module->getVar('dirname');
134
135
                $modinfo = $target_module->getInfo();
0 ignored issues
show
Unused Code introduced by
$modinfo is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
136
137
                // breadcrumbs
138
139
                $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
140
141
                $breadcrumbsObj->appendPath(XOOPS_URL . '/modules/altsys/admin/index.php?mode=admin&amp;lib=altsys&amp;page=myblocksadmin', '_MI_ALTSYS_MENU_MYBLOCKSADMIN');
142
143
                $breadcrumbsObj->appendPath(XOOPS_URL . '/modules/altsys/admin/index.php?mode=admin&amp;lib=altsys&amp;page=myblocksadmin&amp;dirname=' . $this->target_dirname, $this->target_mname);
144
            } else {
145
                // custom blocks
146
147
                $this->target_mid = 0;
148
149
                $this->target_mname = _MI_ALTSYS_MENU_CUSTOMBLOCKS;
150
151
                $this->target_dirname = '__CustomBlocks__';
152
153
                // breadcrumbs
154
155
                $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
156
157
                $breadcrumbsObj->appendPath(XOOPS_URL . '/modules/altsys/admin/index.php?mode=admin&amp;lib=altsys&amp;page=myblocksadmin', '_MI_ALTSYS_MENU_MYBLOCKSADMIN');
158
159
                $breadcrumbsObj->appendPath(XOOPS_URL . '/modules/altsys/admin/index.php?mode=admin&amp;lib=altsys&amp;page=myblocksadmin&amp;dirname=' . $this->target_dirname, '_MI_ALTSYS_MENU_CUSTOMBLOCKS');
160
            }
161
        } else {
162
            // myblocksadmin as a library
163
164
            $this->target_mid = $xoopsModule->getVar('mid');
165
166
            $this->target_mname = $xoopsModule->getVar('name') . '&nbsp;' . sprintf('(%2.2f)', $xoopsModule->getVar('version') / 100.0);
167
168
            $this->target_dirname = $xoopsModule->getVar('dirname');
169
170
            $mod_url = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname');
171
172
            $modinfo = $xoopsModule->getInfo();
173
174
            $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
175
176
            $breadcrumbsObj->appendPath($mod_url . '/' . @$modinfo['adminindex'], $this->target_mname);
177
178
            $breadcrumbsObj->appendPath($mod_url . '/admin/index.php?mode=admin&amp;lib=altsys&amp;page=myblocksadmin', _MD_A_MYBLOCKSADMIN_BLOCKADMIN);
179
        }
180
181
        // read xoops_version.php of the target
182
183
        $this->block_configs = $this->get_block_configs();
184
    }
185
186
    // virtual
187
188
    /**
189
     * @param $block
190
     * @return bool
191
     */
192
193
    public function canEdit($block)
0 ignored issues
show
Unused Code introduced by
The parameter $block is not used and could be removed.

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

Loading history...
194
    {
195
        return true;
196
    }
197
198
    // virtual
199
200
    /**
201
     * @param $block
202
     * @return bool
203
     */
204
205
    public function canDelete($block)
206
    {
207
        // can delete if it is a cloned block
208
209
        if ('D' == $block->getVar('block_type') || 'C' == $block->getVar('block_type')) {
210
            return true;
211
        }
212
213
        return false;
214
    }
215
216
    // virtual
217
218
    // ret 0 : cannot
219
220
    // ret 1 : forced by altsys or system
221
222
    // ret 2 : can_clone
223
224
    /**
225
     * @param $block
226
     * @return int
227
     */
228
229
    public function canClone($block)
230
    {
231
        // can clone link if it is marked as cloneable block
232
233
        if ('D' == $block->getVar('block_type') || 'C' == $block->getVar('block_type')) {
234
            return 2;
235
        }
236
237
        // $modversion['blocks'][n]['can_clone']
238
239
        foreach ($this->block_configs as $bconf) {
240
            if ($block->getVar('show_func') == @$bconf['show_func'] && $block->getVar('func_file') == @$bconf['file'] && (empty($bconf['template']) || $block->getVar('template') == @$bconf['template'])) {
241
                if (!empty($bconf['can_clone'])) {
242
                    return 2;
243
                }
244
            }
245
        }
246
247
        if (!empty($GLOBALS['altsysModuleConfig']['enable_force_clone'])) {
248
            return 1;
249
        }
250
251
        return 0;
252
    }
253
254
    // virtual
255
256
    // options
257
258
    /**
259
     * @param $block_data
260
     * @return bool|string
261
     */
262
263
    public function renderCell4BlockOptions($block_data)
264
    {
265
        $bid = (int)$block_data['bid'];
266
267
        //HACK by domifara
268
269 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
            $handler = xoops_getHandler('block');
271
272
            $block = $handler->create(false);
273
274
            $block->load($bid);
275
        } else {
276
            $block = new XoopsBlock($bid);
277
        }
278
279
        return $block->getOptions();
280
    }
281
282
    // virtual
283
284
    // link blocks - modules
285
286
    /**
287
     * @param $block_data
288
     * @return string
289
     */
290
291
    public function renderCell4BlockModuleLink($block_data)
292
    {
293
        $bid = (int)$block_data['bid'];
294
295
        // get selected targets
296
297
        if (is_array(@$block_data['bmodule'])) {
298
            // bmodule origined from request (preview etc.)
299
300
            $selected_mids = $block_data['bmodule'];
301
        } else {
302
            // origined from the table of `block_module_link`
303
304
            $result = $this->db->query('SELECT module_id FROM ' . $this->db->prefix('block_module_link') . " WHERE block_id='$bid'");
305
306
            $selected_mids = [];
307
308
            while (list($selected_mid) = $this->db->fetchRow($result)) {
309
                $selected_mids[] = (int)$selected_mid;
310
            }
311
312
            if (empty($selected_mids)) {
313
                $selected_mids = [0];
314
            } // all pages
315
        }
316
317
        // get all targets
318
319
        $moduleHandler = xoops_getHandler('module');
320
321
        $criteria = new CriteriaCompo(new Criteria('hasmain', 1));
322
323
        $criteria->add(new Criteria('isactive', 1));
324
325
        $module_list = $moduleHandler->getList($criteria);
326
327
        $module_list = [-1 => _MD_A_MYBLOCKSADMIN_TOPPAGE, 0 => _MD_A_MYBLOCKSADMIN_ALLPAGES] + $module_list;
328
329
        // build options
330
331
        $module_options = '';
332
333
        foreach ($module_list as $mid => $mname) {
334
            $mname = htmlspecialchars($mname, ENT_QUOTES | ENT_HTML5);
335
336
            if (in_array($mid, $selected_mids, true)) {
337
                $module_options .= "<option value='$mid' selected='selected'>$mname</option>\n";
338
            } else {
339
                $module_options .= "<option value='$mid'>$mname</option>\n";
340
            }
341
        }
342
343
        $ret = "
344
                <select name='bmodules[$bid][]' size='5' multiple='multiple'>
345
                    $module_options
346
                </select>";
347
348
        return $ret;
349
    }
350
351
    // virtual
352
353
    // group_permission - 'block_read'
354
355
    /**
356
     * @param $block_data
357
     * @return string
358
     */
359
360
    public function renderCell4BlockReadGroupPerm($block_data)
361
    {
362
        $bid = (int)$block_data['bid'];
363
364
        // get selected targets
365
366
        if (is_array(@$block_data['bgroup'])) {
367
            // bgroup origined from request (preview etc.)
368
369
            $selected_gids = $block_data['bgroup'];
370
        } else {
371
            // origined from the table of `group_perm`
372
373
            $result = $this->db->query('SELECT gperm_groupid FROM ' . $this->db->prefix('group_permission') . " WHERE gperm_itemid='$bid' AND gperm_name='block_read'");
374
375
            $selected_gids = [];
376
377
            while (list($selected_gid) = $this->db->fetchRow($result)) {
378
                $selected_gids[] = (int)$selected_gid;
379
            }
380
381
            if (0 == $bid && empty($selected_gids)) {
382
                $selected_gids = $GLOBALS['xoopsUser']->getGroups();
383
            }
384
        }
385
386
        // get all targets
387
388
        $group_handler = xoops_getHandler('group');
389
390
        $groups = $group_handler->getObjects();
391
392
        // build options
393
394
        $group_options = '';
395
396
        foreach ($groups as $group) {
397
            $gid = $group->getVar('groupid');
398
399
            $gname = $group->getVar('name', 's');
400
401
            if (in_array($gid, $selected_gids, true)) {
402
                $group_options .= "<option value='$gid' selected='selected'>$gname</option>\n";
403
            } else {
404
                $group_options .= "<option value='$gid'>$gname</option>\n";
405
            }
406
        }
407
408
        $ret = "
409
                <select name='bgroups[$bid][]' size='5' multiple='multiple'>
410
                    $group_options
411
                </select>";
412
413
        return $ret;
414
    }
415
416
    // virtual
417
418
    // visible and side
419
420
    /**
421
     * @param $block_data
422
     * @return string
423
     */
424
425
    public function renderCell4BlockPosition($block_data)
426
    {
427
        $bid = (int)$block_data['bid'];
428
429
        $side = (int)$block_data['side'];
430
431
        $visible = (int)$block_data['visible'];
432
433
        $sseln = $ssel0 = $ssel1 = $ssel2 = $ssel3 = $ssel4 = '';
434
435
        $scoln = $scol0 = $scol1 = $scol2 = $scol3 = $scol4 = 'unselected';
436
437
        $stextbox = 'unselected';
438
439
        $value4extra_side = '';
440
441
        if (1 != $visible) {
442
            $sseln = " checked='checked'";
443
444
            $scoln = 'disabled';
445
        } else {
446
            switch ($side) {
447
                case XOOPS_SIDEBLOCK_LEFT:
448
                    $ssel0 = " checked='checked'";
449
                    $scol0 = 'selected';
450
                    break;
451
                case XOOPS_SIDEBLOCK_RIGHT:
452
                    $ssel1 = " checked='checked'";
453
                    $scol1 = 'selected';
454
                    break;
455
                case XOOPS_CENTERBLOCK_LEFT:
456
                    $ssel2 = " checked='checked'";
457
                    $scol2 = 'selected';
458
                    break;
459
                case XOOPS_CENTERBLOCK_RIGHT:
460
                    $ssel4 = " checked='checked'";
461
                    $scol4 = 'selected';
462
                    break;
463
                case XOOPS_CENTERBLOCK_CENTER:
464
                    $ssel3 = " checked='checked'";
465
                    $scol3 = 'selected';
466
                    break;
467
                default:
468
                    $value4extra_side = $side;
469
                    $stextbox = 'selected';
470
                    break;
471
            }
472
        }
473
474
        return "
475
                <div class='blockposition $scol0'>
476
                    <input type='radio' name='sides[$bid]' value='" . XOOPS_SIDEBLOCK_LEFT . "' class='blockposition' $ssel0 onclick='document.getElementById(\"extra_side_$bid\").value=" . XOOPS_SIDEBLOCK_LEFT . ";' />
477
                </div>
478
                <div style='float:" . _GLOBAL_LEFT . ";'>-</div>
479
                <div class='blockposition $scol2'>
480
                    <input type='radio' name='sides[$bid]' value='" . XOOPS_CENTERBLOCK_LEFT . "' class='blockposition' $ssel2 onclick='document.getElementById(\"extra_side_$bid\").value=" . XOOPS_CENTERBLOCK_LEFT . ";' />
481
                </div>
482
                <div class='blockposition $scol3'>
483
                    <input type='radio' name='sides[$bid]' value='" . XOOPS_CENTERBLOCK_CENTER . "' class='blockposition' $ssel3 onclick='document.getElementById(\"extra_side_$bid\").value=" . XOOPS_CENTERBLOCK_CENTER . ";' />
484
                </div>
485
                <div class='blockposition $scol4'>
486
                    <input type='radio' name='sides[$bid]' value='" . XOOPS_CENTERBLOCK_RIGHT . "' class='blockposition' $ssel4 onclick='document.getElementById(\"extra_side_$bid\").value=" . XOOPS_CENTERBLOCK_RIGHT . ";' />
487
                </div>
488
                <div style='float:" . _GLOBAL_LEFT . ";'>-</div>
489
                <div class='blockposition $scol1'>
490
                    <input type='radio' name='sides[$bid]' value='" . XOOPS_SIDEBLOCK_RIGHT . "' class='blockposition' $ssel1 onclick='document.getElementById(\"extra_side_$bid\").value=" . XOOPS_SIDEBLOCK_RIGHT . ";' />
491
                </div>
492
                <br />
493
                <br />
494
                <div style='float:" . _GLOBAL_LEFT . ";width:50px;' class='$stextbox'>
495
                    <input type='text' name='extra_sides[$bid]' value='" . $value4extra_side . "' style='width:20px;' id='extra_side_$bid' />
496
                </div>
497
                <div class='blockposition $scoln'>
498
                    <input type='radio' name='sides[$bid]' value='-1' class='blockposition' $sseln onclick='document.getElementById(\"extra_side_$bid\").value=-1;' />
499
                </div>
500
                <div style='float:" . _GLOBAL_LEFT . ";'>" . _NONE . '</div>
501
    ';
502
    }
503
504
    // public
505
506
    public function list_blocks()
507
    {
508
        global $xoopsGTicket;
509
510
        // main query
511
512
        $sql = 'SELECT * FROM ' . $this->db->prefix('newblocks') . " WHERE mid='$this->target_mid' ORDER BY visible DESC,side,weight";
513
514
        $result = $this->db->query($sql);
515
516
        $block_arr = [];
517
518
        //HACK by domifara
519
520
        if (defined('XOOPS_CUBE_LEGACY')) {
521
            $handler = xoops_getHandler('block'); //add
522
        }
523
524 View Code Duplication
        while (false !== ($myrow = $this->db->fetchArray($result))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
525
            //HACK by domifara
526
527
            if (defined('XOOPS_CUBE_LEGACY')) {
528
                $block_one = $handler->create(false);
0 ignored issues
show
Bug introduced by
The variable $handler does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
529
530
                $block_one->assignVars($myrow);
531
532
                $block_arr[] = &$block_one;
533
            } else {
534
                $block_arr[] = new XoopsBlock($myrow);
535
            }
536
        }
537
538
        if (empty($block_arr)) {
539
            return;
540
        }
541
542
        // blocks rendering loop
543
544
        $blocks4assign = [];
545
546
        foreach ($block_arr as $i => $block) {
547
            $block_data = [
548
                'bid' => (int)$block->getVar('bid'),
549
                'name' => $block->getVar('name', 'n'),
550
                'title' => $block->getVar('title', 'n'),
551
                'weight' => (int)$block->getVar('weight'),
552
                'bcachetime' => (int)$block->getVar('bcachetime'),
553
                'side' => (int)$block->getVar('side'),
554
                'visible' => (int)$block->getVar('visible'),
555
                'can_edit' => $this->canEdit($block),
556
                'can_delete' => $this->canDelete($block),
557
                'can_clone' => $this->canClone($block),
558
            ];
559
560
            $blocks4assign[] = [
561
                                   'name_raw' => $block_data['name'],
562
                                   'title_raw' => $block_data['title'],
563
                                   'cell_position' => $this->renderCell4BlockPosition($block_data),
564
                                   'cell_module_link' => $this->renderCell4BlockModuleLink($block_data),
565
                                   'cell_group_perm' => $this->renderCell4BlockReadGroupPerm($block_data),
566
                               ] + $block_data;
567
        }
568
569
        // display
570
571
        require_once XOOPS_TRUST_PATH . '/libs/altsys/class/D3Tpl.class.php';
572
573
        $tpl = new D3Tpl();
574
575
        $tpl->assign([
576
                         'target_mid' => $this->target_mid,
577
                         'target_dirname' => $this->target_dirname,
578
                         'target_mname' => $this->target_mname,
579
                         'language' => $this->lang,
580
                         'cachetime_options' => $this->cachetime_options,
581
                         'blocks' => $blocks4assign,
582
                         'gticket_hidden' => $xoopsGTicket->getTicketHtml(__LINE__, 1800, 'myblocksadmin'),
583
                     ]);
584
585
        $tpl->display('db:altsys_main_myblocksadmin_list.tpl');
586
    }
587
588
    /**
589
     * @return array
590
     */
591
592
    public function get_block_configs()
593
    {
594
        if ($this->target_mid <= 0) {
595
            return [];
596
        }
597
598
        include XOOPS_ROOT_PATH . '/modules/' . $this->target_dirname . '/xoops_version.php';
599
600
        if (empty($modversion['blocks'])) {
0 ignored issues
show
Bug introduced by
The variable $modversion seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
601
            return [];
602
        }
603
604
        return $modversion['blocks'];
605
    }
606
607
    public function list_groups()
608
    {
609
        // query for getting blocks
610
611
        $sql = 'SELECT * FROM ' . $this->db->prefix('newblocks') . " WHERE mid='$this->target_mid' ORDER BY visible DESC,side,weight";
612
613
        $result = $this->db->query($sql);
614
615
        $block_arr = [];
616
617
        //HACK by domifara
618
619
        if (defined('XOOPS_CUBE_LEGACY')) {
620
            $handler = xoops_getHandler('block'); //add
621
        }
622
623 View Code Duplication
        while (false !== ($myrow = $this->db->fetchArray($result))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
624
            //HACK by domifara
625
626
            if (defined('XOOPS_CUBE_LEGACY')) {
627
                $block_one = $handler->create(false);
0 ignored issues
show
Bug introduced by
The variable $handler does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
628
629
                $block_one->assignVars($myrow);
630
631
                $block_arr[] = &$block_one;
632
            } else {
633
                $block_arr[] = new XoopsBlock($myrow);
634
            }
635
        }
636
637
        $item_list = [];
638
639
        foreach (array_keys($block_arr) as $i) {
640
            $item_list[$block_arr[$i]->getVar('bid')] = $block_arr[$i]->getVar('title');
641
        }
642
643
        $form = new MyXoopsGroupPermForm(_MD_A_MYBLOCKSADMIN_PERMFORM, 1, 'block_read', '');
644
645
        // skip system (TODO)
646
647
        if ($this->target_mid > 1) {
648
            $form->addAppendix('module_admin', $this->target_mid, $this->target_mname . ' ' . _MD_A_MYBLOCKSADMIN_PERM_MADMIN);
649
650
            $form->addAppendix('module_read', $this->target_mid, $this->target_mname . ' ' . _MD_A_MYBLOCKSADMIN_PERM_MREAD);
651
        }
652
653
        foreach ($item_list as $item_id => $item_name) {
654
            $form->addItem($item_id, $item_name);
655
        }
656
657
        echo $form->render();
658
    }
659
660
    /**
661
     * @param       $bid
662
     * @param       $bside
663
     * @param       $bweight
664
     * @param       $bvisible
665
     * @param       $btitle
666
     * @param       $bcontent
667
     * @param       $bctype
668
     * @param       $bcachetime
669
     * @param array $options
670
     * @return string
671
     */
672
673
    public function update_block($bid, $bside, $bweight, $bvisible, $btitle, $bcontent, $bctype, $bcachetime, $options = [])
674
    {
675
        global $xoopsConfig;
676
677
        //HACK by domifara
678
679 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
680
            $handler = xoops_getHandler('block');
681
682
            $block = $handler->create(false);
683
684
            $block->load($bid);
685
        } else {
686
            $block = new XoopsBlock($bid);
687
        }
688
689
        if ($bside >= 0) {
690
            $block->setVar('side', $bside);
691
        }
692
693
        $block->setVar('weight', $bweight);
694
695
        $block->setVar('visible', $bvisible);
696
697
        $block->setVar('title', $btitle);
698
699
        if (isset($bcontent)) {
700
            $block->setVar('content', $bcontent);
701
        }
702
703
        if (isset($bctype)) {
704
            $block->setVar('c_type', $bctype);
705
        }
706
707
        $block->setVar('bcachetime', $bcachetime);
708
709
        if ($options && is_array($options)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $options of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
710
            $block->setVar('options', implode('|', $options));
711
        }
712
713
        if ('C' == $block->getVar('block_type')) {
714
            $name = $this->get_blockname_from_ctype($block->getVar('c_type'));
715
716
            $block->setVar('name', $name);
717
        }
718
719
        $msg = _MD_A_MYBLOCKSADMIN_DBUPDATED;
720
721
        if (false != $block->store()) {
722
            include_once XOOPS_ROOT_PATH . '/class/template.php';
723
724
            $xoopsTpl = new XoopsTpl();
725
726
            $xoopsTpl->xoops_setCaching(2);
727
728
            if ('' != $block->getVar('template')) {
729 View Code Duplication
                if ($xoopsTpl->is_cached('db:' . $block->getVar('template'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
730
                    if (!$xoopsTpl->clear_cache('db:' . $block->getVar('template'))) {
731
                        $msg = 'Unable to clear cache for block ID' . $bid;
732
                    }
733
                }
734 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
735
                if ($xoopsTpl->is_cached('db:system_dummy.tpl', 'blk_' . $bid)) {
736
                    if (!$xoopsTpl->clear_cache('db:system_dummy.tpl', 'blk_' . $bid)) {
737
                        $msg = 'Unable to clear cache for block ID' . $bid;
738
                    }
739
                }
740
            }
741
        } else {
742
            $msg = 'Failed update of block. ID:' . $bid;
743
        }
744
745
        return $msg;
746
    }
747
748
    // virtual
749
750
    /**
751
     * @param int               $bid
752
     * @param $bmodules
753
     */
754
755
    public function updateBlockModuleLink($bid, $bmodules)
756
    {
757
        $bid = (int)$bid;
758
759
        $table = $this->db->prefix('block_module_link');
760
761
        $sql = "DELETE FROM `$table` WHERE `block_id`=$bid";
762
763
        $this->db->query($sql);
764
765
        foreach ($bmodules as $mid) {
766
            $mid = (int)$mid;
767
768
            $sql = "INSERT INTO `$table` (`block_id`,`module_id`) VALUES ($bid,$mid)";
769
770
            $this->db->query($sql);
771
        }
772
    }
773
774
    // virtual
775
776
    /**
777
     * @param int               $bid
778
     * @param $req_gids
779
     */
780
781
    public function updateBlockReadGroupPerm($bid, $req_gids)
782
    {
783
        $bid = (int)$bid;
784
785
        $table = $this->db->prefix('group_permission');
786
787
        $req_gids = array_map('intval', $req_gids);
788
789
        sort($req_gids);
790
791
        // compare group ids from request and the records.
792
793
        $sql = "SELECT `gperm_groupid` FROM `$table` WHERE gperm_name='block_read' AND `gperm_itemid`=$bid";
794
795
        $result = $this->db->query($sql);
796
797
        $db_gids = [];
798
799
        while (list($gid) = $this->db->fetchRow($result)) {
800
            $db_gids[] = $gid;
801
        }
802
803
        $db_gids = array_map('intval', $db_gids);
804
805
        sort($db_gids);
806
807
        // if they are identical, just return (prevent increase of gperm_id)
808
809
        if (serialize($req_gids) == serialize($db_gids)) {
810
            return;
811
        }
812
813
        $sql = "DELETE FROM `$table` WHERE gperm_name='block_read' AND `gperm_itemid`=$bid";
814
815
        $this->db->query($sql);
816
817
        foreach ($req_gids as $gid) {
818
            $gid = (int)$gid;
819
820
            $sql = "INSERT INTO `$table` (`gperm_groupid`,`gperm_itemid`,`gperm_modid`,`gperm_name`) VALUES ($gid,$bid,1,'block_read')";
821
822
            $this->db->query($sql);
823
        }
824
    }
825
826
    /**
827
     * @return string
828
     */
829
830
    public function do_order()
831
    {
832
        $sides = is_array(@$_POST['sides']) ? $_POST['sides'] : [];
833
834
        foreach (array_keys($sides) as $bid) {
835
            $request = $this->fetchRequest4Block($bid);
836
837
            // update the block
838
839
            $this->update_block($request['bid'], $request['side'], $request['weight'], $request['visible'], $request['title'], null, null, $request['bcachetime'], []);
840
841
            // block_module_link update
842
843
            $this->updateBlockModuleLink($bid, $request['bmodule']);
844
845
            // group_permission update
846
847
            $this->updateBlockReadGroupPerm($bid, $request['bgroup']);
848
        }
849
850
        return _MD_A_MYBLOCKSADMIN_DBUPDATED;
851
    }
852
853
    /**
854
     * @param int               $bid
855
     * @return array
856
     */
857
858 View Code Duplication
    public function fetchRequest4Block($bid)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
859
    {
860
        $bid = (int)$bid;
861
862
        (method_exists('MyTextSanitizer', 'sGetInstance') and $myts = MyTextSanitizer::sGetInstance()) || $myts = MyTextSanitizer::getInstance();
863
864
        if (@$_POST['extra_sides'][$bid] > 0) {
865
            $_POST['sides'][$bid] = \Xmf\Request::getInt('extra_sides', 0, 'POST')[$bid];
866
        }
867
868
        if (@$_POST['sides'][$bid] < 0) {
869
            $visible = 0;
870
871
            $_POST['sides'][$bid] = -1;
872
        } else {
873
            $visible = 1;
874
        }
875
876
        return [
877
            'bid' => $bid,
878
            'side' => (int)(@$_POST['sides'][$bid]),
879
            'weight' => (int)(@$_POST['weights'][$bid]),
880
            'visible' => $visible,
881
            'title' => (@$_POST['titles'][$bid]),
882
            'content' => (@$_POST['contents'][$bid]),
883
            'ctype' => preg_replace('/[^A-Z]/', '', @$_POST['ctypes'][$bid]),
884
            'bcachetime' => (int)(@$_POST['bcachetimes'][$bid]),
885
            'bmodule' => is_array(@$_POST['bmodules'][$bid]) ? $_POST['bmodules'][$bid] : [0],
886
            'bgroup' => is_array(@$_POST['bgroups'][$bid]) ? $_POST['bgroups'][$bid] : [],
887
            'options' => is_array(@$_POST['options'][$bid]) ? $_POST['options'][$bid] : [],
888
        ];
889
    }
890
891
    /**
892
     * @param int               $bid
893
     * @return string
894
     */
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
895
896
    public function do_delete($bid)
897
    {
898
        $bid = (int)$bid;
899
900
        //HACK by domifara
901
902 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
903
            $handler = xoops_getHandler('block');
904
905
            $block = $handler->create(false);
906
907
            $block->load($bid);
908
        } else {
909
            $block = new XoopsBlock($bid);
910
        }
911
912
        if (!is_object($block)) {
913
            die('Invalid bid');
914
        }
915
916
        if (!$this->canDelete($block)) {
917
            die('Cannot delete this block');
918
        }
919
920
        $this->do_deleteBlockReadGroupPerm($bid); //HACK add by domifara
921
922
        $block->delete();
923
924
        return _MD_A_MYBLOCKSADMIN_DBUPDATED;
925
    }
926
927
    //HACK add by domifara
928
929
    /**
930
     * @param int               $bid
931
     */
932
933
    public function do_deleteBlockReadGroupPerm($bid)
934
    {
935
        $bid = (int)$bid;
936
937
        $table = $this->db->prefix('group_permission');
938
939
        $sql = "DELETE FROM `$table` WHERE gperm_name='block_read' AND `gperm_itemid`=$bid";
940
941
        $this->db->query($sql);
942
    }
943
944
    /**
945
     * @param int               $bid
946
     */
947
948
    public function form_delete($bid)
949
    {
950
        $bid = (int)$bid;
951
952
        //HACK by domifara
953
954
        //HACK by domifara
955
956 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
957
            $handler = xoops_getHandler('block');
958
959
            $block = $handler->create(false);
960
961
            $block->load($bid);
962
        } else {
963
            $block = new XoopsBlock($bid);
964
        }
965
966
        if (!is_object($block)) {
967
            die('Invalid bid');
968
        }
969
970
        if (!$this->canDelete($block)) {
971
            die('Cannot delete this block');
972
        }
973
974
        // breadcrumbs
975
976
        $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
977
978
        $breadcrumbsObj->appendPath('', _DELETE);
979
980
        xoops_confirm(['op' => 'delete_ok'] + $GLOBALS['xoopsGTicket']->getTicketArray(__LINE__, 1800, 'myblocksadmin'), "?mode=admin&amp;lib=altsys&amp;page=myblocksadmin&amp;dirname=$this->target_dirname&amp;bid=$bid", sprintf(_MD_A_MYBLOCKSADMIN_FMT_REMOVEBLOCK, $block->getVar('title')));
981
    }
982
983
    /**
984
     * @param int               $bid
985
     * @return string
986
     */
987
988
    public function do_clone($bid)
989
    {
990
        $bid = (int)$bid;
991
992
        $request = $this->fetchRequest4Block($bid);
993
994
        //HACK by domifara
995
996 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
997
            $handler = xoops_getHandler('block');
998
999
            $block = $handler->create(false);
1000
1001
            $block->load($bid);
1002
        } else {
1003
            $block = new XoopsBlock($bid);
1004
        }
1005
1006
        if (!$block->getVar('bid')) {
1007
            die('Invalid bid');
1008
        }
1009
1010
        if (!$this->canClone($block)) {
1011
            die('Invalid block_type');
1012
        }
1013
1014
        if (empty($_POST['options'])) {
1015
            $options = [];
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1016
        } elseif (is_array($_POST['options'])) {
1017
            $options = $_POST['options'];
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1018
        } else {
1019
            $options = explode('|', $_POST['options']);
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1020
        }
1021
1022
        // for backward compatibility
1023
1024
        // $cblock =& $block->clone(); or $cblock =& $block->xoopsClone();
1025
1026
        //HACK by domifara
1027
1028
        if (defined('XOOPS_CUBE_LEGACY')) {
1029
            $cblock = $handler->create(false);
0 ignored issues
show
Bug introduced by
The variable $handler does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1030
        } else {
1031
            $cblock = new XoopsBlock();
1032
        }
1033
1034
        foreach ($block->vars as $k => $v) {
1035
            $cblock->assignVar($k, $v['value']);
1036
        }
1037
1038
        $cblock->setNew();
1039
1040
        $cblock->setVar('bid', 0);
1041
1042
        $cblock->setVar('block_type', 'C' == $block->getVar('block_type') ? 'C' : 'D');
1043
1044
        $cblock->setVar('func_num', $this->find_func_num_vacancy($block->getVar('mid')));
1045
1046
        // store the block into DB as a new one
1047
1048
        $newbid = $cblock->store();
1049
1050
        if (!$newbid) {
1051
            return $cblock->getHtmlErrors();
1052
        }
1053
1054
        // update the block by the request
1055
1056
        $this->update_block($newbid, $request['side'], $request['weight'], $request['visible'], $request['title'], $request['content'], $request['ctype'], $request['bcachetime'], is_array(@$_POST['options']) ? $_POST['options'] : []);
1057
1058
        // block_module_link update
1059
1060
        $this->updateBlockModuleLink($newbid, $request['bmodule']);
1061
1062
        // group_permission update
1063
1064
        $this->updateBlockReadGroupPerm($newbid, $request['bgroup']);
1065
1066
        return _MD_A_MYBLOCKSADMIN_DBUPDATED;
1067
    }
1068
1069
    /**
1070
     * @param $mid
1071
     * @return int
1072
     */
1073
1074
    public function find_func_num_vacancy($mid)
1075
    {
1076
        $func_num = 256;
1077
1078
        do {
1079
            $func_num--;
1080
1081
            list($count) = $this->db->fetchRow($this->db->query('SELECT COUNT(*) FROM ' . $this->db->prefix('newblocks') . ' WHERE mid=' . (int)$mid . ' AND func_num=' . $func_num));
1082
        } while ($count > 0);
1083
1084
        return $func_num > 128 ? $func_num : 255;
1085
    }
1086
1087
    /**
1088
     * @param int               $bid
1089
     * @return string
1090
     */
1091
1092
    public function do_edit($bid)
1093
    {
1094
        $bid = (int)$bid;
1095
1096
        if ($bid <= 0) {
1097
            // new custom block
1098
1099
            //HACK by domifara
1100
1101 View Code Duplication
            if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1102
                $handler = xoops_getHandler('block');
1103
1104
                $new_block = $handler->create(false);
1105
            } else {
1106
                $new_block = new XoopsBlock();
1107
            }
1108
1109
            $new_block->setNew();
1110
1111
            $new_block->setVar('name', $this->get_blockname_from_ctype('C'));
1112
1113
            $new_block->setVar('block_type', 'C');
1114
1115
            $new_block->setVar('func_num', 0);
1116
1117
            $bid = $new_block->store();
1118
1119
            $request = $this->fetchRequest4Block(0);
1120
1121
            // permission copy
1122
1123
            foreach ($GLOBALS['xoopsUser']->getGroups() as $gid) {
1124
                $sql = 'INSERT INTO ' . $this->db->prefix('group_permission') . " (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES ($gid, $bid, 1, 'block_read')";
1125
1126
                $this->db->query($sql);
1127
            }
1128
        } else {
1129
            $request = $this->fetchRequest4Block($bid);
1130
        }
1131
1132
        // update the block by the request
1133
1134
        $msg = $this->update_block($bid, $request['side'], $request['weight'], $request['visible'], $request['title'], $request['content'], $request['ctype'], $request['bcachetime'], is_array(@$_POST['options']) ? $_POST['options'] : []);
1135
1136
        // block_module_link update
1137
1138
        $this->updateBlockModuleLink($bid, $request['bmodule']);
1139
1140
        // group_permission update
1141
1142
        $this->updateBlockReadGroupPerm($bid, $request['bgroup']);
1143
1144
        return $msg;
1145
    }
1146
1147
    /**
1148
     * @param        $bid
1149
     * @param string $mode
1150
     */
1151
1152
    public function form_edit($bid, $mode = 'edit')
1153
    {
1154
        $bid = (int)$bid;
1155
1156
        //HACK by domifara
1157
1158 View Code Duplication
        if (defined('XOOPS_CUBE_LEGACY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1159
            $handler = xoops_getHandler('block');
1160
1161
            $block = $handler->create(false);
1162
1163
            $block->load($bid);
1164
        } else {
1165
            $block = new XoopsBlock($bid);
1166
        }
1167
1168 View Code Duplication
        if (!$block->getVar('bid')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1169
            // new defaults
1170
1171
            $bid = 0;
1172
1173
            $mode = 'new';
1174
1175
            $block->setVar('mid', 0);
1176
1177
            $block->setVar('block_type', 'C');
1178
        }
1179
1180 View Code Duplication
        switch ($mode) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1181
            case 'clone':
1182
                $form_title = _MD_A_MYBLOCKSADMIN_CLONEFORM;
1183
                $button_value = _MD_A_MYBLOCKSADMIN_BTN_CLONE;
1184
                $next_op = 'clone_ok';
1185
                // breadcrumbs
1186
                $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
1187
                $breadcrumbsObj->appendPath('', _MD_A_MYBLOCKSADMIN_CLONEFORM);
1188
                break;
1189
            case 'new':
1190
                $form_title = _MD_A_MYBLOCKSADMIN_NEWFORM;
1191
                $button_value = _MD_A_MYBLOCKSADMIN_BTN_NEW;
1192
                $next_op = 'new_ok';
1193
                // breadcrumbs
1194
                $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
1195
                $breadcrumbsObj->appendPath('', _MD_A_MYBLOCKSADMIN_NEWFORM);
1196
                break;
1197
            case 'edit':
1198
            default:
1199
                $form_title = _MD_A_MYBLOCKSADMIN_EDITFORM;
1200
                $button_value = _MD_A_MYBLOCKSADMIN_BTN_EDIT;
1201
                $next_op = 'edit_ok';
1202
                // breadcrumbs
1203
                $breadcrumbsObj = AltsysBreadcrumbs::getInstance();
1204
                $breadcrumbsObj->appendPath('', _MD_A_MYBLOCKSADMIN_EDITFORM);
1205
                break;
1206
        }
1207
1208
        $is_custom = in_array($block->getVar('block_type'), ['C', 'E'], true) ? true : false;
1209
1210
        $block_template = $block->getVar('template', 'n');
1211
1212
        $block_template_tplset = '';
1213
1214 View Code Duplication
        if (!$is_custom && $block_template) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1215
            // find template of the block
1216
1217
            $tplfile_handler = xoops_getHandler('tplfile');
1218
1219
            $found_templates = $tplfile_handler->find($GLOBALS['xoopsConfig']['template_set'], 'block', null, null, $block_template);
1220
1221
            $block_template_tplset = count($found_templates) > 0 ? $GLOBALS['xoopsConfig']['template_set'] : 'default';
1222
        }
1223
1224
        //HACK by domifara
1225
1226
        /*
1227
            if ( !($block->getVar('c_type')) ){
1228
                $block->setVar('c_type','S');
1229
            }
1230
        */
1231
1232
        $block_data = $this->preview_request + [
1233
                'bid' => $bid,
1234
                'name' => $block->getVar('name', 'n'),
1235
                'title' => $block->getVar('title', 'n'),
1236
                'weight' => (int)$block->getVar('weight'),
1237
                'bcachetime' => (int)$block->getVar('bcachetime'),
1238
                'side' => (int)$block->getVar('side'),
1239
                'visible' => (int)$block->getVar('visible'),
1240
                'template' => $block_template,
1241
                'template_tplset' => $block_template_tplset,
1242
                'options' => $block->getVar('options'),
1243
                'content' => $block->getVar('content', 'n'),
1244
                'is_custom' => $is_custom,
1245
                'type' => $block->getVar('block_type'),
1246
                'ctype' => $block->getVar('c_type'),
1247
            ];
1248
1249
        $block4assign = [
1250
                            'name_raw' => $block_data['name'],
1251
                            'title_raw' => $block_data['title'],
1252
                            'content_raw' => $block_data['content'],
1253
                            'cell_position' => $this->renderCell4BlockPosition($block_data),
1254
                            'cell_module_link' => $this->renderCell4BlockModuleLink($block_data),
1255
                            'cell_group_perm' => $this->renderCell4BlockReadGroupPerm($block_data),
1256
                            'cell_options' => $this->renderCell4BlockOptions($block_data),
1257
                            'content_preview' => $this->previewContent($block_data),
1258
                        ] + $block_data;
1259
1260
        // display
1261
1262
        require_once XOOPS_TRUST_PATH . '/libs/altsys/class/D3Tpl.class.php';
1263
1264
        $tpl = new D3Tpl();
1265
1266
        //HACK by domifara
1267
1268
        if (defined('XOOPS_CUBE_LEGACY')) {
1269
            $tpl->assign('xoops_cube_legacy', true);
1270
1271
            include_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
1272
        } else {
1273
            $tpl->assign('xoops_cube_legacy', false);
1274
        }
1275
1276
        $tpl->assign([
1277
                         'target_dirname' => $this->target_dirname,
1278
                         'target_mname' => $this->target_mname,
1279
                         'language' => $this->lang,
1280
                         'cachetime_options' => $this->cachetime_options,
1281
                         'ctype_options' => $this->ctype_options,
1282
                         'block' => $block4assign,
1283
                         'op' => $next_op,
1284
                         'form_title' => $form_title,
1285
                         'submit_button' => $button_value,
1286
                         'common_fck_installed' => $this->checkFck(),
1287
                         'gticket_hidden' => $GLOBALS['xoopsSecurity']->getTokenHTML('myblocksadmin'),
1288
                     ]);
1289
1290
        if (defined('XOOPS_CUBE_LEGACY')) {
1291
            $tpl->display('db:altsys_main_myblocksadmin_edit_4legacy.tpl');
1292
        } else {
1293
            $tpl->display('db:altsys_main_myblocksadmin_edit.tpl');
1294
        }
1295
    }
1296
1297
    /**
1298
     * @return bool
1299
     */
1300
1301
    public function checkFck()
1302
    {
1303
        return file_exists(XOOPS_ROOT_PATH . '/common/fckeditor/fckeditor.js');
1304
    }
1305
1306
    /**
1307
     * @param $block_data
1308
     * @return string
1309
     */
1310
1311
    public function previewContent($block_data)
1312
    {
1313
        $bid = (int)$block_data['bid'];
1314
1315
        if (!$block_data['is_custom']) {
1316
            return '';
1317
        }
1318
1319
        if (empty($this->preview_request)) {
1320
            return '';
1321
        }
1322
1323
        //HACK by domifara
1324
1325
        //TODO : need no hook block at this
1326
1327
        $block = new XoopsBlock($bid);
1328
1329
        /*
1330
            $handler = xoops_getHandler('block');
1331
            $block =& $handler->create(false) ;
1332
            $block->load($bid) ;
1333
        */
1334
1335
        if ($block->getVar('mid')) {
1336
            return '';
1337
        }
1338
1339
        $block->setVar('title', $block_data['title']);
1340
1341
        $block->setVar('content', $block_data['content']);
1342
1343
        restore_error_handler();
1344
1345
        $original_level = error_reporting(E_ALL);
1346
1347
        $ret = $block->getContent('S', $block_data['ctype']);
1348
1349
        error_reporting($original_level);
1350
1351
        return $ret;
1352
    }
1353
1354
    /**
1355
     * @param $bctype
1356
     * @return mixed|string
1357
     */
1358
1359
    public function get_blockname_from_ctype($bctype)
1360
    {
1361
        $ctypes = [
1362
            'H' => _MD_A_MYBLOCKSADMIN_CTYPE_HTML,
1363
            'S' => _MD_A_MYBLOCKSADMIN_CTYPE_SMILE,
1364
            'N' => _MD_A_MYBLOCKSADMIN_CTYPE_NOSMILE,
1365
            'P' => _MD_A_MYBLOCKSADMIN_CTYPE_PHP,
1366
        ];
1367
1368
        return isset($ctypes[$bctype]) ? $ctypes[$bctype] : _MD_A_MYBLOCKSADMIN_CTYPE_SMILE;
1369
    }
1370
1371
    public function processPost()
1372
    {
1373
        // Ticket Check
1374
1375
        if (!$GLOBALS['xoopsSecurity']->check(true, 'myblocksadmin')) {
1376
            redirect_header(XOOPS_URL . '/', 3, $GLOBALS['xoopsSecurity']->getErrors());
1377
        }
1378
1379
        $msg = '';
1380
1381
        $bid = (int)(@$_GET['bid']);
1382
1383
        if (! empty($_POST['preview'])) {
1384
            // preview
1385
1386
            $this->preview_request = $this->fetchRequest4Block($bid);
1387
1388
            $_GET['op'] = str_replace('_ok', '', @$_POST['op']);
1389
1390
            return; // continue ;
1391
        } elseif ('order' == @$_POST['op']) {
1392
            // order ok
1393
1394
            $msg = $this->do_order();
1395
        } elseif ('delete_ok' == @$_POST['op']) {
1396
            // delete ok
1397
1398
            $msg = $this->do_delete($bid);
1399
        } elseif ('clone_ok' == @$_POST['op']) {
1400
            // clone ok
1401
1402
            $msg = $this->do_clone($bid);
1403
        } elseif ('edit_ok' == @$_POST['op'] || 'new_ok' == @$_POST['op']) {
1404
            // edit ok
1405
1406
            $msg = $this->do_edit($bid);
1407
        } elseif (!empty($_POST['submit'])) {
1408
            // update module_admin,module_read,block_read
1409
1410
            include dirname(__DIR__) . '/include/mygroupperm.php';
1411
1412
            $msg = _MD_A_MYBLOCKSADMIN_PERMUPDATED;
1413
        }
1414
1415
        redirect_header('?mode=admin&lib=altsys&page=myblocksadmin&dirname=' . $this->target_dirname, 1, $msg);
1416
1417
        exit;
1418
    }
1419
1420
    public function processGet()
1421
    {
1422
        $bid = (int)(@$_GET['bid']);
1423
1424
        switch (@$_GET['op']) {
1425
            case 'clone':
1426
                $this->form_edit($bid, 'clone');
1427
                break;
1428
            case 'new':
1429
            case 'edit':
1430
                $this->form_edit($bid, 'edit');
1431
                break;
1432
            case 'delete':
1433
                $this->form_delete($bid);
1434
                break;
1435
            case 'list':
1436
            default:
1437
                // the first form (blocks)
1438
                $this->list_blocks();
1439
                // the second form (groups)
1440
                $this->list_groups();
1441
                break;
1442
        }
1443
    }
1444
}
1445