PermissionForumHandler   A
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 245
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 108
dl 0
loc 245
rs 9.0399
c 0
b 0
f 0
wmc 42

9 Methods

Rating   Name   Duplication   Size   Complexity  
B applyTemplate() 0 33 8
A __construct() 0 5 1
B getPermissions() 0 45 8
A getValidPerms() 0 15 4
A setTemplate() 0 3 1
B getValidItems() 0 33 9
B getPermissionTable() 0 27 8
A getTemplate() 0 5 1
A deleteByForum() 0 13 2

How to fix   Complexity   

Complex Class

Complex classes like PermissionForumHandler 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 PermissionForumHandler, 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_HANDLER_PERMISSION") || require_once __DIR__  .'/permission.php';
20
//define("NEWBB_HANDLER_PERMISSION_FORUM", 1);
21
22
if (\defined('FORUM_PERM_ITEMS') && \class_exists('ForumPermissionHandler')) {
23
    exit('access denied');
24
}
25
// irmtfan add pdf and print permissions.
26
\define('FORUM_PERM_ITEMS', 'access,view,post,reply,edit,delete,addpoll,vote,attach,noapprove,type,html,signature,pdf,print');
27
28
/**
29
 * Class PermissionForumHandler
30
 */
31
class PermissionForumHandler extends PermissionHandler
32
{
33
    protected $templateFilename;
34
35
    /**
36
     * @param \XoopsDatabase|null $db
37
     */
38
    public function __construct(\XoopsDatabase $db = null)
39
    {
40
        //        $this->PermissionHandler($db);
41
        parent::__construct($db);
42
        $this->templateFilename = XOOPS_VAR_PATH . '/configs/newbb_permission_template.php';
43
    }
44
45
    /**
46
     * @param bool $fullname
47
     * @return array
48
     */
49
    public function getValidPerms($fullname = false)
50
    {
51
        static $validPerms = [];
52
        if (isset($validPerms[(int)$fullname])) {
53
            return $validPerms[(int)$fullname];
54
        }
55
        $items = \array_filter(\array_map('\trim', \explode(',', FORUM_PERM_ITEMS)));
56
        if (!empty($fullname)) {
57
            foreach (\array_keys($items) as $key) {
58
                $items[$key] = 'forum_' . $items[$key];
59
            }
60
        }
61
        $validPerms[(int)$fullname] = $items;
62
63
        return $items;
64
    }
65
66
    /**
67
     * @param        $mid
68
     * @param int    $id
69
     * @return array
70
     */
71
    public function getValidItems($mid, $id = 0)
72
    {
73
        static $suspension = [];
74
        $full_items = [];
75
        if (empty($mid)) {
76
            return $full_items;
77
        }
78
79
        require_once \dirname(__DIR__) . '/include/functions.user.php';
80
        $uid = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
81
        $ip  = \Xmf\IPAddress::fromRequest()->asReadable();
82
        if (!empty($GLOBALS['xoopsModuleConfig']['enable_usermoderate']) && !isset($suspension[$uid][$id])
83
            && !\newbbIsAdmin($id)) {
84
            /** @var Newbb\ModerateHandler $moderateHandler */
85
            $moderateHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Moderate');
86
            if (!$moderateHandler->verifyUser($uid, '', $id)) {
87
                $suspension[$uid][$ip][$id] = 1;
88
            } else {
89
                $suspension[$uid][$ip][$id] = 0;
90
            }
91
        }
92
93
        $items = $this->getValidPerms();
94
        foreach ($items as $item) {
95
            /* skip access for suspended users */
96
            //if ( !empty($suspension[$uid][$ip][$id]) && in_array($item, array("post", "reply", "edit", "delete", "addpoll", "vote", "attach", "noapprove", "type")) ) continue;
97
            if (!empty($suspension[$uid][$ip][$id])) {
98
                continue;
99
            }
100
            $full_items[] = "'forum_{$item}'";
101
        }
102
103
        return $full_items;
104
    }
105
106
    /*
107
    * Returns permissions for a certain type
108
    *
109
    * @param int $id id of the item (forum, topic or possibly post) to get permissions for
110
    *
111
    * @return array
112
    */
113
114
    /**
115
     * @param int|array $id
116
     * @return bool|array
117
     */
118
    public function getPermissions($id = 0)
119
    {
120
        $permissions = [];
121
        if (\is_object($GLOBALS['xoopsModule']) && 'newbb' === $GLOBALS['xoopsModule']->getVar('dirname')) {
122
            $modid = $GLOBALS['xoopsModule']->getVar('mid');
123
        } else {
124
            /** @var \XoopsModuleHandler $moduleHandler */
125
            $moduleHandler = \xoops_getHandler('module');
126
            $xoopsNewBB    = $moduleHandler->getByDirname('newbb');
127
            $modid         = $xoopsNewBB->getVar('mid');
128
            unset($xoopsNewBB);
129
        }
130
131
        // Get user's groups
132
        $groups = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [XOOPS_GROUP_ANONYMOUS];
133
        // Create string of groupid's separated by commas, inserted in a set of brackets
134
        if (\count($groups) < 1) {
135
            return false;
136
        }
137
        // Create criteria for getting only the permissions regarding this module and this user's groups
138
        $criteria = new \CriteriaCompo(new \Criteria('gperm_modid', $modid));
139
        $criteria->add(new \Criteria('gperm_groupid', '(' . \implode(',', $groups) . ')', 'IN'));
140
        if ($id) {
141
            if (\is_array($id)) {
142
                $criteria->add(new \Criteria('gperm_itemid', '(' . \implode(',', $id) . ')', 'IN'));
143
            } else {
144
                $criteria->add(new \Criteria('gperm_itemid', (int)$id));
145
            }
146
        }
147
        $gperm_names = \implode(', ', $this->getValidItems($modid, $id));
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type array; however, parameter $id of XoopsModules\Newbb\Permi...andler::getValidItems() does only seem to accept integer, 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

147
        $gperm_names = \implode(', ', $this->getValidItems($modid, /** @scrutinizer ignore-type */ $id));
Loading history...
148
149
        // Add criteria for gpermnames
150
        $criteria->add(new \Criteria('gperm_name', '(' . $gperm_names . ')', 'IN'));
151
        // Get all permission objects in this module and for this user's groups
152
        $userpermissions = $this->getObjects($criteria, true);
153
154
        // Set the granted permissions to 1
155
        foreach ($userpermissions as $gperm_id => $gperm) {
156
            $permissions[$gperm->getVar('gperm_itemid')][$gperm->getVar('gperm_name')] = 1;
157
        }
158
        $userpermissions = null;
159
        unset($userpermissions);
160
161
        // Return the permission array
162
        return $permissions;
163
    }
164
165
    /**
166
     * @param Forum|int $forum
167
     * @param bool      $topic_locked
168
     * @param bool      $isAdmin
169
     * @return array
170
     */
171
    public function getPermissionTable($forum = 0, $topic_locked = false, $isAdmin = false)
172
    {
173
        $perm = [];
174
175
        $forumId = $forum;
176
        if (\is_object($forum)) {
177
            $forumId = $forum->getVar('forum_id');
178
        }
179
180
        $permission_set = $this->getPermissions($forumId);
181
182
        $permItems = $this->getValidPerms();
183
        foreach ($permItems as $item) {
184
            if ('access' === $item) {
185
                continue;
186
            }
187
            if ($isAdmin
188
                || (isset($permission_set[$forumId]['forum_' . $item])
189
                    && (!$topic_locked
190
                        || 'view' === $item))) {
191
                $perm[] = \constant('_MD_NEWBB_CAN_' . mb_strtoupper($item));
192
            } else {
193
                $perm[] = \constant('_MD_NEWBB_CANNOT_' . mb_strtoupper($item));
194
            }
195
        }
196
197
        return $perm;
198
    }
199
200
    /**
201
     * @param $forum_id
202
     * @return bool
203
     */
204
    public function deleteByForum($forum_id)
205
    {
206
        $forum_id = (int)$forum_id;
207
        if (empty($forum_id)) {
208
            return false;
209
        }
210
        $grouppermHandler = \xoops_getHandler('groupperm');
211
        $criteria         = new \CriteriaCompo(new \Criteria('gperm_modid', $GLOBALS['xoopsModule']->getVar('mid')));
212
        $items            = $this->getValidPerms(true);
213
        $criteria->add(new \Criteria('gperm_name', "('" . \implode("', '", $items) . "')", 'IN'));
214
        $criteria->add(new \Criteria('gperm_itemid', $forum_id));
215
216
        return $grouppermHandler->deleteAll($criteria);
0 ignored issues
show
Bug introduced by
The method deleteAll() does not exist on XoopsObjectHandler. 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

216
        return $grouppermHandler->/** @scrutinizer ignore-call */ deleteAll($criteria);

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...
217
    }
218
219
    /**
220
     * @param       $forum
221
     * @param int   $mid
222
     * @return bool
223
     */
224
    public function applyTemplate($forum, $mid = 0)
225
    {
226
        if (!$perm_template = $this->getTemplate()) {
227
            return false;
228
        }
229
230
        if (empty($mid)) {
231
            if (\is_object($GLOBALS['xoopsModule']) && 'newbb' === $GLOBALS['xoopsModule']->getVar('dirname')) {
232
                $mid = $GLOBALS['xoopsModule']->getVar('mid');
233
            } else {
234
                /** @var \XoopsModuleHandler $moduleHandler */
235
                $moduleHandler = \xoops_getHandler('module');
236
                $newbb         = $moduleHandler->getByDirname('newbb');
237
                $mid           = $newbb->getVar('mid');
238
                unset($newbb);
239
            }
240
        }
241
242
        /** @var \XoopsMemberHandler $memberHandler */
243
        $memberHandler = \xoops_getHandler('member');
244
        $glist         = $memberHandler->getGroupList();
245
        $perms         = $this->getValidPerms(true);
246
        foreach (\array_keys($glist) as $group) {
247
            foreach ($perms as $perm) {
248
                if (!empty($perm_template[$group][$perm])) {
249
                    $this->validateRight($perm, $forum, $group, $mid);
250
                } else {
251
                    $this->deleteRight($perm, $forum, $group, $mid);
252
                }
253
            }
254
        }
255
256
        return true;
257
    }
258
259
    /**
260
     * @return array|false
261
     */
262
    public function getTemplate()
263
    {
264
        $perms = \Xmf\Yaml::readWrapped($this->templateFilename);
265
266
        return $perms;
267
    }
268
269
    /**
270
     * @param array $perms
271
     * @return bool
272
     */
273
    public function setTemplate($perms)
274
    {
275
        return \Xmf\Yaml::saveWrapped($perms, $this->templateFilename);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Xmf\Yaml::saveWra...this->templateFilename) also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
276
    }
277
}
278