Completed
Push — master ( 4e8684...61995d )
by Michael
08:37
created

NewbbPermissionForumHandler::getPermissionTable()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 18
nc 8
nop 3
dl 0
loc 28
rs 5.3846
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 21 and the first side effect is on line 18.

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
/**
3
 * NewBB 5.0x,  the forum module for XOOPS project
4
 *
5
 * @copyright      XOOPS Project (http://xoops.org)
6
 * @license        GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
7
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>
8
 * @since          4.00
9
 * @package        module::newbb
10
 */
11
12
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
13
14
//defined("NEWBB_HANDLER_PERMISSION") || include __DIR__.'/permission.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
15
//define("NEWBB_HANDLER_PERMISSION_FORUM", 1);
16
17
if (defined('FORUM_PERM_ITEMS') && class_exists('NewbbForumPermissionHandler')) {
18
    exit('access denied');
19
}
20
// irmtfan add pdf and print permissions.
21
define('FORUM_PERM_ITEMS', 'access,view,post,reply,edit,delete,addpoll,vote,attach,noapprove,type,html,signature,pdf,print');
22
23
/**
24
 * Class NewbbPermissionForumHandler
25
 */
26
class NewbbPermissionForumHandler extends NewbbPermissionHandler
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...
27
{
28
    /**
29
     * @param XoopsDatabase|null $db
30
     */
31
    public function __construct(XoopsDatabase $db)
32
    {
33
        //        $this->NewbbPermissionHandler($db);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
34
        parent::__construct($db);
35
    }
36
37
    /**
38
     * @param  bool $fullname
39
     * @return array
40
     */
41
    public function getValidPerms($fullname = false)
42
    {
43
        static $validPerms = [];
44
        if (isset($validPerms[(int)$fullname])) {
45
            return $validPerms[(int)$fullname];
46
        }
47
        $items = array_filter(array_map('trim', explode(',', FORUM_PERM_ITEMS)));
48
        if (!empty($fullname)) {
49
            foreach (array_keys($items) as $key) {
50
                $items[$key] = 'forum_' . $items[$key];
51
            }
52
        }
53
        $validPerms[(int)$fullname] = $items;
54
55
        return $items;
56
    }
57
58
    /**
59
     * @param        $mid
60
     * @param  int   $id
61
     * @return array
62
     */
63
    public function getValidItems($mid, $id = 0)
0 ignored issues
show
Coding Style introduced by
getValidItems uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
64
    {
65
        static $suspension = [];
66
        $full_items = [];
67
        if (empty($mid)) {
68
            return $full_items;
69
        }
70
71
        include_once __DIR__ . '/../include/functions.user.php';
72
        $uid = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
73
        $ip  = \Xmf\IPAddress::fromRequest()->asReadable();
74
        if (!empty($GLOBALS['xoopsModuleConfig']['enable_usermoderate']) && !isset($suspension[$uid][$id])
75
            && !newbbIsAdmin($id)) {
76
            /** @var \NewbbModerateHandler $moderateHandler */
77
            $moderateHandler = xoops_getModuleHandler('moderate', 'newbb');
78
            if (!$moderateHandler->verifyUser($uid, '', $id)) {
79
                $suspension[$uid][$ip][$id] = 1;
80
            } else {
81
                $suspension[$uid][$ip][$id] = 0;
82
            }
83
        }
84
85
        $items = $this->getValidPerms();
86
        foreach ($items as $item) {
87
            /* skip access for suspended users */
88
            //if ( !empty($suspension[$uid][$ip][$id]) && in_array($item, array("post", "reply", "edit", "delete", "addpoll", "vote", "attach", "noapprove", "type")) ) continue;
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
89
            if (!empty($suspension[$uid][$ip][$id])) {
90
                continue;
91
            }
92
            $full_items[] = "'forum_{$item}'";
93
        }
94
95
        return $full_items;
96
    }
97
98
    /*
99
    * Returns permissions for a certain type
100
    *
101
    * @param int $id id of the item (forum, topic or possibly post) to get permissions for
102
    *
103
    * @return array
104
    */
105
    /**
106
     * @param  int $id
107
     * @return bool|array
108
     */
109
    public function getPermissions($id = 0)
0 ignored issues
show
Coding Style introduced by
getPermissions uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
110
    {
111
        $permissions = [];
112 View Code Duplication
        if (is_object($GLOBALS['xoopsModule']) && $GLOBALS['xoopsModule']->getVar('dirname') === 'newbb') {
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...
113
            $modid = $GLOBALS['xoopsModule']->getVar('mid');
114
        } else {
115
            /** @var \XoopsModuleHandler $moduleHandler */
116
            $moduleHandler = xoops_getHandler('module');
117
            $xoopsNewBB    = $moduleHandler->getByDirname('newbb');
118
            $modid         = $xoopsNewBB->getVar('mid');
119
            unset($xoopsNewBB);
120
        }
121
122
        // Get user's groups
123
        $groups = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [XOOPS_GROUP_ANONYMOUS];
124
        // Create string of groupid's separated by commas, inserted in a set of brackets
125
        if (count($groups) < 1) {
126
            return false;
127
        }
128
        // Create criteria for getting only the permissions regarding this module and this user's groups
129
        $criteria = new CriteriaCompo(new Criteria('gperm_modid', $modid));
130
        $criteria->add(new Criteria('gperm_groupid', '(' . implode(',', $groups) . ')', 'IN'));
131 View Code Duplication
        if ($id) {
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...
132
            if (is_array($id)) {
133
                $criteria->add(new Criteria('gperm_itemid', '(' . implode(',', $id) . ')', 'IN'));
134
            } else {
135
                $criteria->add(new Criteria('gperm_itemid', (int)$id));
136
            }
137
        }
138
        $gperm_names = implode(', ', $this->getValidItems($modid, $id));
139
140
        // Add criteria for gpermnames
141
        $criteria->add(new Criteria('gperm_name', '(' . $gperm_names . ')', 'IN'));
142
        // Get all permission objects in this module and for this user's groups
143
        $userpermissions = $this->getObjects($criteria, true);
144
145
        // Set the granted permissions to 1
146
        foreach ($userpermissions as $gperm_id => $gperm) {
147
            $permissions[$gperm->getVar('gperm_itemid')][$gperm->getVar('gperm_name')] = 1;
148
        }
149
        $userpermissions = null;
150
        unset($userpermissions);
151
152
        // Return the permission array
153
        return $permissions;
154
    }
155
156
    /**
157
     * @param  NewbbForum|int $forum
158
     * @param  bool           $topic_locked
159
     * @param  bool           $isAdmin
160
     * @return array
161
     */
162
    public function getPermissionTable($forum = 0, $topic_locked = false, $isAdmin = false)
163
    {
164
        $perm = [];
165
166
        $forumId = $forum;
167
        if (is_object($forum)) {
168
            $forumId = $forum->getVar('forum_id');
169
        }
170
171
        $permission_set = $this->getPermissions($forumId);
172
173
        $permItems = $this->getValidPerms();
174
        foreach ($permItems as $item) {
175
            if ($item === 'access') {
176
                continue;
177
            }
178
            if ($isAdmin
179
                || (isset($permission_set[$forumId]['forum_' . $item])
180
                    && (!$topic_locked
181
                        || $item === 'view'))) {
182
                $perm[] = constant('_MD_NEWBB_CAN_' . strtoupper($item));
183
            } else {
184
                $perm[] = constant('_MD_NEWBB_CANNOT_' . strtoupper($item));
185
            }
186
        }
187
188
        return $perm;
189
    }
190
191
    /**
192
     * @param $forum_id
193
     * @return bool
194
     */
195
    public function deleteByForum($forum_id)
0 ignored issues
show
Coding Style introduced by
deleteByForum uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
196
    {
197
        $forum_id = (int)$forum_id;
198
        if (empty($forum_id)) {
199
            return false;
200
        }
201
        $gpermHandler = xoops_getHandler('groupperm');
202
        $criteria     = new CriteriaCompo(new Criteria('gperm_modid', $GLOBALS['xoopsModule']->getVar('mid')));
203
        $items        = $this->getValidPerms(true);
204
        $criteria->add(new Criteria('gperm_name', "('" . implode("', '", $items) . "')", 'IN'));
205
        $criteria->add(new Criteria('gperm_itemid', $forum_id));
206
207
        return $gpermHandler->deleteAll($criteria);
208
    }
209
210
    /**
211
     * @param       $forum
212
     * @param  int  $mid
213
     * @return bool
214
     */
215
    public function applyTemplate($forum, $mid = 0)
0 ignored issues
show
Coding Style introduced by
applyTemplate uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
216
    {
217
218
        if (!$perm_template = $this->getTemplate()) {
219
            return false;
220
        }
221
222 View Code Duplication
        if (empty($mid)) {
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...
223
            if (is_object($GLOBALS['xoopsModule']) && $GLOBALS['xoopsModule']->getVar('dirname') === 'newbb') {
224
                $mid = $GLOBALS['xoopsModule']->getVar('mid');
225
            } else {
226
                /** @var \XoopsModuleHandler $moduleHandler */
227
                $moduleHandler = xoops_getHandler('module');
228
                $newbb         = $moduleHandler->getByDirname('newbb');
229
                $mid           = $newbb->getVar('mid');
230
                unset($newbb);
231
            }
232
        }
233
234
        /** @var \XoopsMemberHandler $memberHandler */
235
        $memberHandler = xoops_getHandler('member');
236
        $glist         = $memberHandler->getGroupList();
237
        $perms         = $this->getValidPerms(true);
238
        foreach (array_keys($glist) as $group) {
239
            foreach ($perms as $perm) {
240
                if (!empty($perm_template[$group][$perm])) {
241
                    $this->validateRight($perm, $forum, $group, $mid);
242
                } else {
243
                    $this->deleteRight($perm, $forum, $group, $mid);
244
                }
245
            }
246
        }
247
248
        return true;
249
    }
250
251
    /**
252
     * @return mixed|null
253
     */
254
    public function getTemplate()
255
    {
256
        $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
257
        $perms       = $cacheHelper->read('perm_template');
258
259
        return $perms;
260
    }
261
262
    /**
263
     * @param $perms
264
     * @return bool
265
     */
266
    public function setTemplate($perms)
267
    {
268
        $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
269
270
        return $cacheHelper->write('perm_template', $perms);
271
    }
272
}
273