Completed
Pull Request — master (#8)
by Michael
02:48
created

MyXoopsGroupFormCheckBox::setOptionTree()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 51 and the first side effect is on line 33.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
// $Id: mygrouppermform.php 8112 2011-11-06 13:41:14Z beckmi $
3
//  ------------------------------------------------------------------------ //
4
//                XOOPS - PHP Content Management System                      //
5
//                    Copyright (c) 2000-2003 XOOPS.org                           //
6
//                       <http://www.xoops.org/>                             //
7
//  ------------------------------------------------------------------------ //
8
//  This program is free software; you can redistribute it and/or modify     //
9
//  it under the terms of the GNU General Public License as published by     //
10
//  the Free Software Foundation; either version 2 of the License, or        //
11
//  (at your option) any later version.                                      //
12
//                                                                           //
13
//  You may not change or alter any portion of this comment or credits       //
14
//  of supporting developers from this source code or any supporting         //
15
//  source code which is considered copyrighted (c) material of the          //
16
//  original comment or credit authors.                                      //
17
//                                                                           //
18
//  This program is distributed in the hope that it will be useful,          //
19
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
20
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
21
//  GNU General Public License for more details.                             //
22
//                                                                           //
23
//  You should have received a copy of the GNU General Public License        //
24
//  along with this program; if not, write to the Free Software              //
25
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
26
//  ------------------------------------------------------------------------ //
27
// Author: Kazumi Ono (AKA onokazu)                                          //
28
// URL: http://www.myweb.ne.jp/, http://www.xoops.org/, http://jp.xoops.org/ //
29
// Project: The XOOPS Project                                                //
30
// ------------------------------------------------------------------------- //
31
32
if (!defined('XOOPS_ROOT_PATH')) {
33
    exit;
34
}
35
36
require_once XOOPS_ROOT_PATH . '/class/xoopsform/formelement.php';
37
require_once XOOPS_ROOT_PATH . '/class/xoopsform/formhidden.php';
38
require_once XOOPS_ROOT_PATH . '/class/xoopsform/formbutton.php';
39
require_once XOOPS_ROOT_PATH . '/class/xoopsform/formelementtray.php';
40
require_once XOOPS_ROOT_PATH . '/class/xoopsform/form.php';
41
42
/**
43
 * Renders a form for setting module specific group permissions
44
 *
45
 * @author      Kazumi Ono  <[email protected]>
46
 * @copyright   copyright (c) 2000-2003 XOOPS.org
47
 *
48
 * @package     kernel
49
 * @subpackage  form
50
 */
51
class MyXoopsGroupPermForm extends XoopsForm
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
52
{
53
54
    /**
55
     * Module ID
56
     * @var int
57
     */
58
    public $_modid;
59
    /**
60
     * Tree structure of items
61
     * @var array
62
     */
63
    public $_itemTree = array();
64
    /**
65
     * Name of permission
66
     * @var string
67
     */
68
    public $_permName;
69
    /**
70
     * Description of permission
71
     * @var string
72
     */
73
    public $_permDesc;
74
    /**
75
     * Appendix
76
     * @var array ('permname'=>,'itemid'=>,'itemname'=>,'selected'=>)
77
     */
78
    public $_appendix = array();
79
80
    /**
81
     * Constructor
82
     * @param string $title
83
     * @param string $modid
84
     * @param string $permname
85
     * @param string $permdesc
86
     */
87
    public function __construct($title, $modid, $permname, $permdesc)
88
    {
89
        //        parent::__construct($title, 'groupperm_form', XOOPS_URL.'/modules/system/admin/groupperm.php', 'post'); GIJ
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
90
        parent::__construct($title, 'groupperm_form', '', 'post');
91
        $this->_modid    = (int)$modid;
92
        $this->_permName = $permname;
93
        $this->_permDesc = $permdesc;
94
        $this->addElement(new XoopsFormHidden('modid', $this->_modid));
95
    }
96
97
    /**
98
     * Adds an item to which permission will be assigned
99
     *
100
     * @param string $itemName
101
     * @param int    $itemId
102
     * @param int    $itemParent
103
     * @access public
104
     */
105
    public function addItem($itemId, $itemName, $itemParent = 0)
106
    {
107
        $this->_itemTree[$itemParent]['children'][] = $itemId;
108
        $this->_itemTree[$itemId]['parent']         = $itemParent;
109
        $this->_itemTree[$itemId]['name']           = $itemName;
110
        $this->_itemTree[$itemId]['id']             = $itemId;
111
    }
112
113
    /**
114
     * Add appendix
115
     *
116
     * @access public
117
     * @param $permName
118
     * @param $itemId
119
     * @param $itemName
120
     */
121
    public function addAppendix($permName, $itemId, $itemName)
122
    {
123
        $this->_appendix[] = array(
124
            'permname' => $permName,
125
            'itemid'   => $itemId,
126
            'itemname' => $itemName,
127
            'selected' => false
128
        );
129
    }
130
131
    /**
132
     * Loads all child ids for an item to be used in javascript
133
     *
134
     * @param int   $itemId
135
     * @param array $childIds
136
     * @access private
137
     */
138
    public function _loadAllChildItemIds($itemId, &$childIds)
139
    {
140
        if (!empty($this->_itemTree[$itemId]['children'])) {
141
            $first_child = $this->_itemTree[$itemId]['children'];
142
            foreach ($first_child as $fcid) {
143
                array_push($childIds, $fcid);
144
                if (!empty($this->_itemTree[$fcid]['children'])) {
145
                    foreach ($this->_itemTree[$fcid]['children'] as $_fcid) {
146
                        array_push($childIds, $_fcid);
147
                        $this->_loadAllChildItemIds($_fcid, $childIds);
148
                    }
149
                }
150
            }
151
        }
152
    }
153
154
    /**
155
     * Renders the form
156
     *
157
     * @return string
158
     * @access public
159
     */
160
    public function render()
161
    {
162
        global $xoopsGTicket;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
163
164
        // load all child ids for javascript codes
165
        foreach (array_keys($this->_itemTree) as $item_id) {
166
            $this->_itemTree[$item_id]['allchild'] = array();
167
            $this->_loadAllChildItemIds($item_id, $this->_itemTree[$item_id]['allchild']);
168
        }
169
        $gpermHandler  = xoops_getHandler('groupperm');
170
        $memberHandler = xoops_getHandler('member');
171
        $glist          = $memberHandler->getGroupList();
172
        foreach (array_keys($glist) as $i) {
173
            // get selected item id(s) for each group
174
            $selected = $gpermHandler->getItemIds($this->_permName, $i, $this->_modid);
175
            $ele      = new MyXoopsGroupFormCheckBox($glist[$i], 'perms[' . $this->_permName . ']', $i, $selected);
176
            $ele->setOptionTree($this->_itemTree);
177
178
            foreach ($this->_appendix as $key => $append) {
179
                $this->_appendix[$key]['selected'] = $gpermHandler->checkRight($append['permname'], $append['itemid'], $i, $this->_modid);
180
            }
181
            $ele->setAppendix($this->_appendix);
182
            $this->addElement($ele);
183
            unset($ele);
184
        }
185
186
        // GIJ start
187
        $jstray          = new XoopsFormElementTray(' &nbsp; ');
188
        $jsuncheckbutton = new XoopsFormButton('', 'none', _NONE, 'button');
189
        $jsuncheckbutton->setExtra("onclick=\"with(document.groupperm_form){for(i=0;i<length;i++){if(elements[i].type=='checkbox'){elements[i].checked=false;}}}\"");
190
        $jscheckbutton = new XoopsFormButton('', 'all', _ALL, 'button');
191
        $jscheckbutton->setExtra("onclick=\"with(document.groupperm_form){for(i=0;i<length;i++){if(elements[i].type=='checkbox' && (elements[i].name.indexOf('module_admin')<0 || elements[i].name.indexOf('[groups][1]')>=0)){elements[i].checked=true;}}}\"");
192
        $jstray->addElement($jsuncheckbutton);
193
        $jstray->addElement($jscheckbutton);
194
        $this->addElement($jstray);
195
        // GIJ end
196
197
        $tray = new XoopsFormElementTray('');
198
        $tray->addElement(new XoopsFormButton('', 'reset', _CANCEL, 'reset'));
199
        $tray->addElement(new XoopsFormButton('', 'submit', _SUBMIT, 'submit'));
200
        $this->addElement($tray);
201
202
        $ret = '<h4>' . $this->getTitle() . '</h4>' . $this->_permDesc . '<br>';
203
        $ret .= "<form name='" . $this->getName() . "' id='" . $this->getName() . "' action='" . $this->getAction() . "' method='" . $this->getMethod() . "'" . $this->getExtra() . ">\n<table style='width: 100% margin: 1px;' class='outer'>\n";
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
204
        $elements =& $this->getElements();
205
        foreach (array_keys($elements) as $i) {
206
            if (!is_object($elements[$i])) {
207
                $ret .= $elements[$i];
208
            } elseif (!$elements[$i]->isHidden()) {
209
                $ret .= "<tr style='vertical-align: top; text-align: left;'><td class='head'>" . $elements[$i]->getCaption();
210
                if ($elements[$i]->getDescription() != '') {
211
                    $ret .= '<br><br><span style="font-weight: normal;">' . $elements[$i]->getDescription() . '</span>';
212
                }
213
                $ret .= "</td>\n<td class='even'>\n" . $elements[$i]->render() . "\n</td></tr>\n";
214
            } else {
215
                $ret .= $elements[$i]->render();
216
            }
217
        }
218
        $ret .= '</table>' . $xoopsGTicket->getTicketHtml(__LINE__, 1800, 'myblocksadmin') . '</form>';
219
220
        return $ret;
221
    }
222
}
223
224
/**
225
 * Renders checkbox options for a group permission form
226
 *
227
 * @author      Kazumi Ono  <[email protected]>
228
 * @copyright   copyright (c) 2000-2003 XOOPS.org
229
 *
230
 * @package     kernel
231
 * @subpackage  form
232
 */
233
class MyXoopsGroupFormCheckBox extends XoopsFormElement
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
234
{
235
236
    /**
237
     * Pre-selected value(s)
238
     * @var array;
239
     */
240
    public $_value;
241
    /**
242
     * Group ID
243
     * @var int
244
     */
245
    public $_groupId;
246
    /**
247
     * Option tree
248
     * @var array
249
     */
250
    public $_optionTree;
251
    /**
252
     * Appendix
253
     * @var array ('permname'=>,'itemid'=>,'itemname'=>,'selected'=>)
254
     */
255
    public $_appendix = array();
256
257
    /**
258
     * Constructor
259
     * @param      $caption
260
     * @param      $name
261
     * @param      $groupId
262
     * @param null $values
263
     */
264
    public function __construct($caption, $name, $groupId, $values = null)
265
    {
266
        $this->setCaption($caption);
267
        $this->setName($name);
268
        if (isset($values)) {
269
            $this->setValue($values);
270
        }
271
        $this->_groupId = $groupId;
272
    }
273
274
    /**
275
     * Sets pre-selected values
276
     *
277
     * @param mixed $value A group ID or an array of group IDs
278
     * @access public
279
     */
280
    public function setValue($value)
281
    {
282
        if (is_array($value)) {
283
            foreach ($value as $v) {
284
                $this->setValue($v);
285
            }
286
        } else {
287
            $this->_value[] = $value;
288
        }
289
    }
290
291
    /**
292
     * Sets the tree structure of items
293
     *
294
     * @param array $optionTree
295
     * @access public
296
     */
297
    public function setOptionTree(&$optionTree)
298
    {
299
        $this->_optionTree = $optionTree;
300
    }
301
302
    /**
303
     * Sets appendix of checkboxes
304
     *
305
     * @access public
306
     * @param $appendix
307
     */
308
    public function setAppendix($appendix)
309
    {
310
        $this->_appendix = $appendix;
311
    }
312
313
    /**
314
     * Renders checkbox options for this group
315
     *
316
     * @return string
317
     * @access public
318
     */
319
    public function render()
320
    {
321
        $ret = '';
322
323
        if (count($this->_appendix) > 0) {
324
            $ret .= '<table class="outer"><tr>';
325
            $cols = 1;
326
            foreach ($this->_appendix as $append) {
327
                if ($cols > 4) {
328
                    $ret .= '</tr><tr>';
329
                    $cols = 1;
330
                }
331
                $checked = $append['selected'] ? 'checked="checked"' : '';
332
                $name    = 'perms[' . $append['permname'] . ']';
333
                $itemid  = $append['itemid'];
0 ignored issues
show
Unused Code introduced by
$itemid 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...
334
                $itemid  = $append['itemid'];
335
                $ret .= "<td class=\"odd\"><input type=\"checkbox\" name=\"{$name}[groups][$this->_groupId][$itemid]\" id=\"{$name}[groups][$this->_groupId][$itemid]\" value=\"1\" $checked>{$append['itemname']}<input type=\"hidden\" name=\"{$name}[parents][$itemid]\" value=\"\"><input type=\"hidden\" name=\"{$name}[itemname][$itemid]\" value=\"{$append['itemname']}\"><br></td>";
336
                $cols++;
337
            }
338
            $ret .= '</tr></table>';
339
        }
340
341
        $ret .= '<table class="outer"><tr>';
342
        $cols = 1;
343
        if (!empty($this->_optionTree[0]['children'])) {
344
            foreach ($this->_optionTree[0]['children'] as $topitem) {
345
                if ($cols > 4) {
346
                    $ret .= '</tr><tr>';
347
                    $cols = 1;
348
                }
349
                $tree   = '<td class="odd">';
350
                $prefix = '';
351
                $this->_renderOptionTree($tree, $this->_optionTree[$topitem], $prefix);
352
                $ret .= "{$tree}</td>";
353
                $cols++;
354
            }
355
        }
356
        $ret .= '</tr></table>';
357
358
        return $ret;
359
    }
360
361
    /**
362
     * Renders checkbox options for an item tree
363
     *
364
     * @param string $tree
365
     * @param array  $option
366
     * @param string $prefix
367
     * @param array  $parentIds
368
     * @access private
369
     */
370
    public function _renderOptionTree(&$tree, $option, $prefix, $parentIds = array())
371
    {
372
        $tree .= $prefix . "<input type=\"checkbox\" name=\"" . $this->getName() . '[groups][' . $this->_groupId . '][' . $option['id'] . "]\" id=\"" . $this->getName() . '[groups][' . $this->_groupId . '][' . $option['id'] . "]\" onclick=\"";
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
373
        // If there are parent elements, add javascript that will
374
        // make them selecteded when this element is checked to make
375
        // sure permissions to parent items are added as well.
376
        foreach ($parentIds as $pid) {
377
            $parent_ele = $this->getName() . '[groups][' . $this->_groupId . '][' . $pid . ']';
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
378
            $tree .= "var ele = xoopsGetElementById('" . $parent_ele . "'); if(ele.checked != true) {ele.checked = this.checked;}";
379
        }
380
        // If there are child elements, add javascript that will
381
        // make them unchecked when this element is unchecked to make
382
        // sure permissions to child items are not added when there
383
        // is no permission to this item.
384
        foreach ($option['allchild'] as $cid) {
385
            $child_ele = $this->getName() . '[groups][' . $this->_groupId . '][' . $cid . ']';
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
386
            $tree .= "var ele = xoopsGetElementById('" . $child_ele . "'); if(this.checked != true) {ele.checked = false;}";
387
        }
388
        $tree .= '" value="1"';
389
        if (isset($this->_value) && in_array($option['id'], $this->_value)) {
390
            $tree .= " checked='checked'";
391
        }
392
        $tree .= '>' . $option['name'] . "<input type=\"hidden\" name=\"" . $this->getName() . '[parents][' . $option['id'] . "]\" value=\"" . implode(':', $parentIds) . "\"><input type=\"hidden\" name=\"" . $this->getName() . '[itemname][' . $option['id'] . "]\" value=\""
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
393
                 . htmlspecialchars($option['name']) . "\"><br>\n";
394
        if (isset($option['children'])) {
395
            foreach ($option['children'] as $child) {
396
                array_push($parentIds, $option['id']);
397
                $this->_renderOptionTree($tree, $this->_optionTree[$child], $prefix . '&nbsp;-', $parentIds);
398
            }
399
        }
400
    }
401
}
402