PermissionHandler   F
last analyzed

Complexity

Total Complexity 62

Size/Duplication

Total Lines 398
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 154
dl 0
loc 398
rs 3.44
c 0
b 0
f 0
wmc 62

20 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteByForum() 0 6 1
A getCategories() 0 5 1
C createPermData() 0 48 13
A getPermissionTable() 0 6 1
A validateRight() 0 20 5
B deleteRight() 0 30 7
A getForums() 0 5 1
A setTemplate() 0 5 1
B getAllowedItems() 0 27 8
A getTemplate() 0 6 1
A myCheckRight() 0 23 5
A getGroups() 0 7 2
A __construct() 0 6 1
A applyTemplate() 0 6 1
A deleteByCategory() 0 6 1
B getPermission() 0 21 7
A setCategoryPermission() 0 6 1
A loadPermData() 0 7 2
A loadHandler() 0 9 2
A getValidForumPerms() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like PermissionHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PermissionHandler, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace XoopsModules\Newbb;
4
5
/**
6
 * NewBB 5.0x,  the forum module for XOOPS project
7
 *
8
 * @copyright      XOOPS Project (https://xoops.org)
9
 * @license        GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
10
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>
11
 * @since          4.00
12
 * @package        module::newbb
13
 */
14
15
use XoopsModules\Newbb;
16
17
18
19
\defined('NEWBB_FUNCTIONS_INI') || require $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
20
\define('NEWBB_HANDLER_PERMISSION', 1);
21
22
// Initializing XoopsGroupPermHandler if not loaded yet
23
if (!\class_exists('XoopsGroupPermHandler')) {
24
    require_once $GLOBALS['xoops']->path('kernel/groupperm.php');
25
}
26
27
/**
28
 * Class PermissionHandler
29
 */
30
class PermissionHandler extends \XoopsGroupPermHandler
31
{
32
    /** @var \Xmf\Module\Helper\Cache */
33
    protected $cacheHelper;
34
35
    /** @var array */
36
    private $_handler;
37
38
    /**
39
     * @param \XoopsDatabase|null $db
40
     */
41
    public function __construct(\XoopsDatabase $db = null)
42
    {
43
        $this->cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
44
45
        $this->db = $db;
46
        parent::__construct($db);
0 ignored issues
show
Bug introduced by
It seems like $db can also be of type null; however, parameter $db of XoopsGroupPermHandler::__construct() does only seem to accept XoopsDatabase, 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

46
        parent::__construct(/** @scrutinizer ignore-type */ $db);
Loading history...
47
    }
48
49
    /**
50
     * @param $name
51
     * @return mixed
52
     */
53
    public function loadHandler($name)
54
    {
55
        if (!isset($this->_handler[$name])) {
56
            //            require_once __DIR__ . "/permission.{$name}.php";
57
            $className             = '\\XoopsModules\\Newbb\\Permission' . \ucfirst($name) . 'Handler';
58
            $this->_handler[$name] = new $className($this->db);
59
        }
60
61
        return $this->_handler[$name];
62
    }
63
64
    /**
65
     * @param bool $fullname
66
     * @return mixed
67
     */
68
    public function getValidForumPerms($fullname = false)
69
    {
70
        $handler = $this->loadHandler('Forum');
71
72
        return $handler->getValidPerms($fullname);
73
    }
74
75
    /**
76
     * @param int  $forum
77
     * @param bool $topic_locked
78
     * @param bool $isAdmin
79
     * @return mixed
80
     */
81
    public function getPermissionTable($forum = 0, $topic_locked = false, $isAdmin = false)
82
    {
83
        $handler = $this->loadHandler('Forum');
84
        $perm    = $handler->getPermissionTable($forum, $topic_locked, $isAdmin);
85
86
        return $perm;
87
    }
88
89
    /**
90
     * @param $forum_id
91
     * @return mixed
92
     */
93
    public function deleteByForum($forum_id)
94
    {
95
        $this->cacheHelper->delete('permission_forum');
96
        $handler = $this->loadHandler('Forum');
97
98
        return $handler->deleteByForum($forum_id);
99
    }
100
101
    /**
102
     * @param $cat_id
103
     * @return mixed
104
     */
105
    public function deleteByCategory($cat_id)
106
    {
107
        $this->cacheHelper->delete('permission_category');
108
        $handler = $this->loadHandler('Category');
109
110
        return $handler->deleteByCategory($cat_id);
111
    }
112
113
    /**
114
     * @param        $category
115
     * @param array  $groups
116
     * @return mixed
117
     */
118
    public function setCategoryPermission($category, array $groups = [])
119
    {
120
        $this->cacheHelper->delete('permission_category');
121
        $handler = $this->loadHandler('Category');
122
123
        return $handler->setCategoryPermission($category, $groups);
124
    }
125
126
    /**
127
     * @param         $type
128
     * @param string  $gperm_name
129
     * @param int     $id
130
     * @return bool
131
     */
132
    public function getPermission($type, $gperm_name = 'access', $id = 0)
133
    {
134
        global $xoopsModule;
135
        $ret = false;
136
        if ($GLOBALS['xoopsUserIsAdmin'] && 'newbb' === $xoopsModule->getVar('dirname')) {
137
            $ret = true;
138
        }
139
140
        $groups = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [XOOPS_GROUP_ANONYMOUS];
141
        if (!$groups) {
142
            $ret = false;
143
        }
144
        if (!$allowed_groups = $this->getGroups("{$type}_{$gperm_name}", $id)) {
145
            $ret = false;
146
        }
147
148
        if (\count(\array_intersect($allowed_groups, $groups)) > 0) {
149
            $ret = true;
150
        }
151
152
        return $ret;
153
    }
154
155
    /**
156
     * @param string $perm_name
157
     * @return array
158
     */
159
    public function &getCategories($perm_name = 'access')
160
    {
161
        $ret = $this->getAllowedItems('category', "category_{$perm_name}");
162
163
        return $ret;
164
    }
165
166
    /**
167
     * @param string $perm_name
168
     * @return array
169
     */
170
    public function getForums($perm_name = 'access')
171
    {
172
        $ret = $this->getAllowedItems('forum', "forum_{$perm_name}");
173
174
        return $ret;
175
    }
176
177
    /**
178
     * @param $type
179
     * @param $perm_name
180
     * @return array
181
     */
182
    public function getAllowedItems($type, $perm_name)
183
    {
184
        $ret = [];
185
186
        $groups = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [XOOPS_GROUP_ANONYMOUS];
187
        if (\count($groups) < 1) {
188
            return $ret;
189
        }
190
191
        if (!$_cachedPerms = $this->loadPermData($perm_name, $type)) {
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Newbb\Permi...Handler::loadPermData() has too many arguments starting with $type. ( Ignorable by Annotation )

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

191
        if (!$_cachedPerms = $this->/** @scrutinizer ignore-call */ loadPermData($perm_name, $type)) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
192
            return $ret;
193
        }
194
195
        $allowed_items = [];
196
        foreach ($_cachedPerms as $id => $allowed_groups) {
197
            if (0 == $id || empty($allowed_groups)) {
198
                continue;
199
            }
200
201
            if (\array_intersect($groups, $allowed_groups)) {
202
                $allowed_items[$id] = 1;
203
            }
204
        }
205
        unset($_cachedPerms);
206
        $ret = \array_keys($allowed_items);
207
208
        return $ret;
209
    }
210
211
    /**
212
     * @param        $gperm_name
213
     * @param int    $id
214
     * @return array
215
     */
216
    public function getGroups($gperm_name, $id = 0)
217
    {
218
        $_cachedPerms = $this->loadPermData($gperm_name);
219
        $groups       = empty($_cachedPerms[$id]) ? [] : \array_unique($_cachedPerms[$id]);
220
        unset($_cachedPerms);
221
222
        return $groups;
223
    }
224
225
    /**
226
     * @param string $perm_name
227
     * @return array
228
     */
229
    public function createPermData($perm_name = 'forum_all')
230
    {
231
        global $xoopsModule;
232
        /** @var \XoopsModuleHandler $moduleHandler */
233
        $perms = [];
234
235
        if (\is_object($xoopsModule) && 'newbb' === $xoopsModule->getVar('dirname')) {
236
            $modid = $xoopsModule->getVar('mid');
237
        } else {
238
            $moduleHandler = \xoops_getHandler('module');
239
            $module        = $moduleHandler->getByDirname('newbb');
0 ignored issues
show
Bug introduced by
The method getByDirname() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsModuleHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

239
            /** @scrutinizer ignore-call */ 
240
            $module        = $moduleHandler->getByDirname('newbb');
Loading history...
240
            $modid         = $module->getVar('mid');
241
            unset($module);
242
        }
243
244
        if (\in_array($perm_name, ['forum_all', 'category_all'])) {
245
            /** @var \XoopsMemberHandler $memberHandler */
246
            $memberHandler = \xoops_getHandler('member');
247
            $groups        = \array_keys($memberHandler->getGroupList());
248
249
            $type          = ('category_all' === $perm_name) ? 'category' : 'forum';
250
            $objectHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler($type);
251
            $object_ids    = $objectHandler->getIds();
0 ignored issues
show
Bug introduced by
The method getIds() 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

251
            /** @scrutinizer ignore-call */ 
252
            $object_ids    = $objectHandler->getIds();
Loading history...
252
            foreach ($object_ids as $item_id) {
253
                $perms[$perm_name][$item_id] = $groups;
254
            }
255
        } else {
256
            $grouppermHandler = \xoops_getHandler('groupperm');
0 ignored issues
show
Unused Code introduced by
The assignment to $grouppermHandler is dead and can be removed.
Loading history...
257
            $criteria         = new \CriteriaCompo(new \Criteria('gperm_modid', $modid));
258
            if (!empty($perm_name) && 'forum_all' !== $perm_name && 'category_all' !== $perm_name) {
259
                $criteria->add(new \Criteria('gperm_name', $perm_name));
260
            }
261
            $permissions = $this->getObjects($criteria);
262
263
            foreach ($permissions as $gperm) {
264
                $item_id                                         = $gperm->getVar('gperm_itemid');
265
                $group_id                                        = (int)$gperm->getVar('gperm_groupid');
266
                $perms[$gperm->getVar('gperm_name')][$item_id][] = $group_id;
267
            }
268
        }
269
        if (\count($perms) > 0) {
270
            foreach (\array_keys($perms) as $perm) {
271
                $this->cacheHelper->write("permission_{$perm}", $perms[$perm]);
272
            }
273
        }
274
        $ret = !empty($perm_name) ? @$perms[$perm_name] : $perms;
275
276
        return $ret;
277
    }
278
279
    /**
280
     * @param string $perm_name
281
     * @return array|mixed|null
282
     */
283
    public function &loadPermData($perm_name = 'forum_access')
284
    {
285
        if (!$perms = $this->cacheHelper->read("permission_{$perm_name}")) {
286
            $perms = $this->createPermData($perm_name);
287
        }
288
289
        return $perms;
290
    }
291
292
    /**
293
     * @param       $perm
294
     * @param       $itemid
295
     * @param       $groupid
296
     * @param null  $mid
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $mid is correct as it would always require null to be passed?
Loading history...
297
     * @return bool
298
     */
299
    public function validateRight($perm, $itemid, $groupid, $mid = null)
300
    {
301
        if (empty($mid)) {
302
            if (\is_object($GLOBALS['xoopsModule']) && 'newbb' === $GLOBALS['xoopsModule']->getVar('dirname')) {
303
                $mid = $GLOBALS['xoopsModule']->getVar('mid');
304
            } else {
305
                /** @var \XoopsModuleHandler $moduleHandler */
306
                $moduleHandler = \xoops_getHandler('module');
307
                $mod           = $moduleHandler->getByDirname('newbb');
308
                $mid           = $mod->getVar('mid');
309
                unset($mod);
310
            }
311
        }
312
        if ($this->myCheckRight($perm, $itemid, $groupid, $mid)) {
313
            return true;
314
        }
315
        $this->cacheHelper->delete('permission');
316
        $this->addRight($perm, $itemid, $groupid, $mid);
317
318
        return true;
319
    }
320
321
    /**
322
     * Check permission (directly)
323
     *
324
     * @param string $gperm_name   Name of permission
325
     * @param int    $gperm_itemid ID of an item
326
     * @param int           /array $gperm_groupid A group ID or an array of group IDs
0 ignored issues
show
Documentation Bug introduced by
The doc comment /array at position 0 could not be parsed: Unknown type name '/array' at position 0 in /array.
Loading history...
327
     * @param int    $gperm_modid  ID of a module
328
     *
329
     * @return bool TRUE if permission is enabled
330
     */
331
    public function myCheckRight($gperm_name, $gperm_itemid, $gperm_groupid, $gperm_modid = 1)
332
    {
333
        $ret      = false;
334
        $criteria = new \CriteriaCompo(new \Criteria('gperm_modid', $gperm_modid));
335
        $criteria->add(new \Criteria('gperm_name', $gperm_name));
336
        $gperm_itemid = (int)$gperm_itemid;
337
        if ($gperm_itemid > 0) {
338
            $criteria->add(new \Criteria('gperm_itemid', $gperm_itemid));
339
        }
340
        if (\is_array($gperm_groupid)) {
341
            $criteria2 = new \CriteriaCompo();
342
            foreach ($gperm_groupid as $gid) {
343
                $criteria2->add(new \Criteria('gperm_groupid', $gid), 'OR');
344
            }
345
            $criteria->add($criteria2);
346
        } else {
347
            $criteria->add(new \Criteria('gperm_groupid', $gperm_groupid));
348
        }
349
        if ($this->getCount($criteria) > 0) {
350
            $ret = true;
351
        }
352
353
        return $ret;
354
    }
355
356
    /**
357
     * @param       $perm
358
     * @param       $itemid
359
     * @param       $groupid
360
     * @param null  $mid
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $mid is correct as it would always require null to be passed?
Loading history...
361
     * @return bool
362
     */
363
    public function deleteRight($perm, $itemid, $groupid, $mid = null)
364
    {
365
        $this->cacheHelper->delete('permission');
366
        if (null === $mid) {
0 ignored issues
show
introduced by
The condition null === $mid is always true.
Loading history...
367
            if (\is_object($GLOBALS['xoopsModule']) && 'newbb' === $GLOBALS['xoopsModule']->getVar('dirname')) {
368
                $mid = $GLOBALS['xoopsModule']->getVar('mid');
369
            } else {
370
                /** @var \XoopsModuleHandler $moduleHandler */
371
                $moduleHandler = \xoops_getHandler('module');
372
                $mod           = $moduleHandler->getByDirname('newbb');
373
                $mid           = $mod->getVar('mid');
374
                unset($mod);
375
            }
376
        }
377
        if (\is_callable('parent::deleteRight')) {
378
            return parent::deleteRight($perm, $itemid, $groupid, $mid);
0 ignored issues
show
Bug introduced by
The method deleteRight() does not exist on XoopsGroupPermHandler. Did you maybe mean delete()? ( Ignorable by Annotation )

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

378
            return parent::/** @scrutinizer ignore-call */ deleteRight($perm, $itemid, $groupid, $mid);

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...
379
        }
380
        $criteria = new \CriteriaCompo(new \Criteria('gperm_name', $perm));
381
        $criteria->add(new \Criteria('gperm_groupid', $groupid));
382
        $criteria->add(new \Criteria('gperm_itemid', $itemid));
383
        $criteria->add(new \Criteria('gperm_modid', $mid));
384
        $permsObject = $this->getObjects($criteria);
385
        if (!empty($permsObject)) {
386
            foreach ($permsObject as $permObject) {
387
                $this->delete($permObject);
388
            }
389
        }
390
        unset($criteria, $permsObject);
391
392
        return true;
393
    }
394
395
    /**
396
     * @param        $forum
397
     * @param int    $mid
398
     * @return mixed
399
     */
400
    public function applyTemplate($forum, $mid = 0)
401
    {
402
        $this->cacheHelper->delete('permission_forum');
403
        $handler = $this->loadHandler('Forum');
404
405
        return $handler->applyTemplate($forum, $mid);
406
    }
407
408
    /**
409
     * @return mixed
410
     */
411
    public function getTemplate()
412
    {
413
        $handler  = $this->loadHandler('Forum');
414
        $template = $handler->getTemplate();
415
416
        return $template;
417
    }
418
419
    /**
420
     * @param $perms
421
     * @return mixed
422
     */
423
    public function setTemplate($perms)
424
    {
425
        $handler = $this->loadHandler('Forum');
426
427
        return $handler->setTemplate($perms);
428
    }
429
}
430