Passed
Push — master ( d3e687...4990f6 )
by Michael
02:43
created

TopicHandler   F

Complexity

Total Complexity 92

Size/Duplication

Total Lines 566
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 566
rs 1.5789
c 0
b 0
f 0
wmc 92

20 Methods

Rating   Name   Duplication   Size   Complexity  
B get() 0 17 6
B insert() 0 18 7
B showTreeItem() 0 25 5
A getTopPost() 0 22 2
A __construct() 0 3 1
B getPermission() 0 22 6
B getByMove() 0 17 7
B approve() 0 22 4
D findPollModule() 0 41 10
A getByPost() 0 15 2
A getPostCount() 0 20 3
A getActivePolls() 0 12 3
A cleanOrphan() 0 7 1
B delete() 0 18 5
D synchronization() 0 36 9
A getPostTree() 0 9 1
C getAllPosts() 0 50 10
A cleanExpires() 0 15 4
A getAllPosters() 0 17 4
A getTopPostId() 0 11 2

How to fix   Complexity   

Complex Class

Complex classes like TopicHandler 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 TopicHandler, and based on these observations, apply Extract Interface, too.

1
<?php namespace XoopsModules\Newbb;
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 22 and the first side effect is on line 17.

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
/**
4
 * NewBB 5.0x,  the forum module for XOOPS project
5
 *
6
 * @copyright      XOOPS Project (https://xoops.org)
7
 * @license        GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
8
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>
9
 * @since          4.00
10
 * @package        module::newbb
11
 */
12
13
use XoopsModules\Newbb;
14
15
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
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...
16
17
defined('NEWBB_FUNCTIONS_INI') || include $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
18
19
/**
20
 * Class TopicHandler
21
 */
22
class TopicHandler extends \XoopsPersistableObjectHandler
0 ignored issues
show
Bug introduced by
The type XoopsPersistableObjectHandler was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
{
24
    /**
25
     * @param \XoopsDatabase $db
26
     */
27
    public function __construct(\XoopsDatabase $db)
0 ignored issues
show
Bug introduced by
The type XoopsDatabase was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
    {
29
        parent::__construct($db, 'newbb_topics', Topic::class, 'topic_id', 'topic_title');
30
    }
31
32
    /**
33
     * @param  mixed      $id
34
     * @param  null|array $fields
35
     * @return mixed|null
36
     */
37
    public function get($id = null, $fields = null) //get($id, $var = null)
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
38
    {
39
        $var  = $fields;
40
        $ret  = null;
41
        $tags = $var;
42
        if (!empty($var) && is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
43
            $tags = [$var];
44
        }
45
        if (!$topicObject = parent::get($id, $tags)) {
46
            return $ret;
47
        }
48
        $ret = $topicObject;
49
        if (!empty($var) && is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
50
            $ret = @$topicObject->getVar($var);
51
        }
52
53
        return $ret;
54
    }
55
56
    /**
57
     * @param \XoopsObject $object
58
     * @param  bool        $force
59
     * @return mixed
60
     */
61
    public function insert(\XoopsObject $object, $force = true)
0 ignored issues
show
Bug introduced by
The type XoopsObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
62
    {
63
        if (!$object->getVar('topic_time')) {
64
            $object->setVar('topic_time', time());
65
        }
66
        if (!parent::insert($object, $force) || !$object->getVar('approved')) {
67
            return $object->getVar('topic_id');
68
        }
69
70
        $newbbConfig = newbbLoadConfig();
71
        if (!empty($newbbConfig['do_tag'])
72
            && @include_once $GLOBALS['xoops']->path('modules/tag/include/functions.php')) {
73
            if ($tagHandler = tag_getTagHandler()) {
0 ignored issues
show
Bug introduced by
The function tag_getTagHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

73
            if ($tagHandler = /** @scrutinizer ignore-call */ tag_getTagHandler()) {
Loading history...
74
                $tagHandler->updateByItem($object->getVar('topic_tags', 'n'), $object->getVar('topic_id'), 'newbb');
75
            }
76
        }
77
78
        return $object->getVar('topic_id');
79
    }
80
81
    /**
82
     * @param       $object
83
     * @param  bool $force
84
     * @return bool
85
     */
86
    public function approve($object, $force = false)
87
    {
88
        $topic_id = $object->getVar('topic_id');
89
        if ($force) {
90
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = -1 WHERE topic_id = {$topic_id}";
91
        } else {
92
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = 1 WHERE topic_id = {$topic_id}";
93
        }
94
        if (!$result = $this->db->queryF($sql)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
95
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
96
            return false;
97
        }
98
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
99
        $postsObject = $postHandler->getAll(new \Criteria('topic_id', $topic_id));
0 ignored issues
show
Bug introduced by
The type Criteria was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
100
        foreach (array_keys($postsObject) as $post_id) {
101
            $postHandler->approve($postsObject[$post_id]);
102
        }
103
        unset($postsObject);
104
        $statsHandler = Newbb\Helper::getInstance()->getHandler('Stats');
105
        $statsHandler->update($object->getVar('forum_id'), 'topic');
106
107
        return true;
108
    }
109
110
    /**
111
     * get previous/next topic
112
     *
113
     * @param integer $topic_id current topic ID
114
     * @param integer $action
115
     *                          <ul>
116
     *                          <li> -1: previous </li>
117
     *                          <li> 0: current </li>
118
     *                          <li> 1: next </li>
119
     *                          </ul>
120
     * @param integer $forum_id the scope for moving
121
     *                          <ul>
122
     *                          <li> >0 : inside the forum </li>
123
     *                          <li> <= 0: global </li>
124
     *                          </ul>
125
     * @access public
126
     * @return mixed|null|\XoopsObject
127
     */
128
    public function &getByMove($topic_id, $action, $forum_id = 0)
129
    {
130
        $topic = null;
131
        if (!empty($action)) {
132
            $sql = 'SELECT * FROM ' . $this->table . ' WHERE 1=1' . (($forum_id > 0) ? ' AND forum_id=' . (int)$forum_id : '') . ' AND topic_id ' . (($action > 0) ? '>' : '<') . (int)$topic_id . ' ORDER BY topic_id ' . (($action > 0) ? 'ASC' : 'DESC') . ' LIMIT 1';
133
            if ($result = $this->db->query($sql)) {
134
                if ($row = $this->db->fetchArray($result)) {
135
                    $topic = $this->create(false);
136
                    $topic->assignVars($row);
137
138
                    return $topic;
139
                }
140
            }
141
        }
142
        $topic = $this->get($topic_id);
143
144
        return $topic;
145
    }
146
147
    /**
148
     * @param $post_id
149
     * @return null|\XoopsObject
150
     */
151
    public function &getByPost($post_id)
152
    {
153
        $topic  = null;
154
        $sql    = 'SELECT t.* FROM ' . $this->db->prefix('newbb_topics') . ' t, ' . $this->db->prefix('newbb_posts') . ' p
155
                WHERE t.topic_id = p.topic_id AND p.post_id = ' . (int)$post_id;
156
        $result = $this->db->query($sql);
157
        if (!$result) {
158
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
159
            return $topic;
160
        }
161
        $row   = $this->db->fetchArray($result);
162
        $topic = $this->create(false);
163
        $topic->assignVars($row);
164
165
        return $topic;
166
    }
167
168
    /**
169
     * @param  Topic  $topic
170
     * @param  string $type
171
     * @return mixed
172
     */
173
    public function getPostCount(&$topic, $type = '')
174
    {
175
        switch ($type) {
176
            case 'pending':
177
                $approved = 0;
178
                break;
179
            case 'deleted':
180
                $approved = -1;
181
                break;
182
            default:
183
                $approved = 1;
184
                break;
185
        }
186
        $criteria = new \CriteriaCompo(new \Criteria('topic_id', $topic->getVar('topic_id')));
0 ignored issues
show
Bug introduced by
The type CriteriaCompo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
187
        $criteria->add(new \Criteria('approved', $approved));
188
        /** @var Newbb\PostHandler $postHandler */
189
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
190
        $count       = $postHandler->getCount($criteria);
191
192
        return $count;
193
    }
194
195
    /**
196
     * @param $topic_id
197
     * @return null|\Post
0 ignored issues
show
Bug introduced by
The type Post was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
198
     */
199
    public function &getTopPost($topic_id)
200
    {
201
        $post = null;
202
        $sql  = 'SELECT p.*, t.* FROM ' . $this->db->prefix('newbb_posts') . ' p,
203
            ' . $this->db->prefix('newbb_posts_text') . ' t
204
            WHERE
205
            p.topic_id = ' . $topic_id . ' AND p.pid = 0
206
            AND t.post_id = p.post_id';
207
208
        $result = $this->db->query($sql);
209
        if (!$result) {
210
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
211
            return $post;
212
        }
213
        /** @var Newbb\PostHandler $postHandler */
214
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
215
        $myrow       = $this->db->fetchArray($result);
216
        /** @var Newbb\Post $post */
217
        $post = $postHandler->create(false);
218
        $post->assignVars($myrow);
219
220
        return $post;
221
    }
222
223
    /**
224
     * @param $topic_id
225
     * @return bool
226
     */
227
    public function getTopPostId($topic_id)
228
    {
229
        $sql    = 'SELECT MIN(post_id) AS post_id FROM ' . $this->db->prefix('newbb_posts') . ' WHERE topic_id = ' . $topic_id . ' AND pid = 0';
230
        $result = $this->db->query($sql);
231
        if (!$result) {
232
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
233
            return false;
234
        }
235
        list($post_id) = $this->db->fetchRow($result);
236
237
        return $post_id;
238
    }
239
240
    /**
241
     * @param         $topic
242
     * @param  string $order
243
     * @param  int    $perpage
244
     * @param         $start
245
     * @param  int    $post_id
246
     * @param  string $type
247
     * @return array
248
     */
249
    public function &getAllPosts(&$topic, $order = 'ASC', $perpage = 10, &$start, $post_id = 0, $type = '')
250
    {
251
        $ret     = [];
252
        $perpage = ((int)$perpage > 0) ? (int)$perpage : (empty($GLOBALS['xoopsModuleConfig']['posts_per_page']) ? 10 : $GLOBALS['xoopsModuleConfig']['posts_per_page']);
253
        $start   = (int)$start;
254
        switch ($type) {
255
            case 'pending':
256
                $approveCriteria = ' AND p.approved = 0';
257
                break;
258
            case 'deleted':
259
                $approveCriteria = ' AND p.approved = -1';
260
                break;
261
            default:
262
                $approveCriteria = ' AND p.approved = 1';
263
                break;
264
        }
265
266
        if ($post_id) {
267
            if ('DESC' === $order) {
268
                $operator_for_position = '>';
269
            } else {
270
                $order                 = 'ASC';
271
                $operator_for_position = '<';
272
            }
273
            //$approveCriteria = ' AND approved = 1'; // any others?
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
274
            $sql    = 'SELECT COUNT(*) FROM ' . $this->db->prefix('newbb_posts') . ' AS p WHERE p.topic_id=' . (int)$topic->getVar('topic_id') . $approveCriteria . " AND p.post_id $operator_for_position $post_id";
275
            $result = $this->db->query($sql);
276
            if (!$result) {
277
                //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
278
                return $ret;
279
            }
280
            list($position) = $this->db->fetchRow($result);
281
            $start = (int)($position / $perpage) * $perpage;
282
        }
283
284
        $sql    = 'SELECT p.*, t.* FROM ' . $this->db->prefix('newbb_posts') . ' p, ' . $this->db->prefix('newbb_posts_text') . ' t WHERE p.topic_id=' . $topic->getVar('topic_id') . ' AND p.post_id = t.post_id' . $approveCriteria . " ORDER BY p.post_id $order";
285
        $result = $this->db->query($sql, $perpage, $start);
286
        if (!$result) {
287
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
288
            return $ret;
289
        }
290
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
291
       while (false !== ($myrow = $this->db->fetchArray($result))) {
292
            $post = $postHandler->create(false);
293
            $post->assignVars($myrow);
294
            $ret[$myrow['post_id']] = $post;
295
            unset($post);
296
        }
297
298
        return $ret;
299
    }
300
301
    /**
302
     * @param        $postArray
303
     * @param  int   $pid
304
     * @return mixed
305
     */
306
    public function &getPostTree(&$postArray, $pid = 0)
307
    {
308
        //        include_once $GLOBALS['xoops']->path('modules/newbb/class/Tree.php');
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% 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...
309
        $NewBBTree = new Newbb\Tree('newbb_posts');
310
        $NewBBTree->setPrefix('&nbsp;&nbsp;');
311
        $NewBBTree->setPostArray($postArray);
312
        $NewBBTree->getPostTree($postsArray, $pid);
313
314
        return $postsArray;
315
    }
316
317
    /**
318
     * @param $topic
319
     * @param $postArray
320
     * @return mixed
321
     */
322
    public function showTreeItem(&$topic, &$postArray)
323
    {
324
        global $viewtopic_users, $myts;
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...
325
326
        $postArray['post_time'] = newbbFormatTimestamp($postArray['post_time']);
327
328
        if (!empty($postArray['icon'])) {
329
            $postArray['icon'] = '<img src="' . XOOPS_URL . '/images/subject/' . htmlspecialchars($postArray['icon']) . '" alt="" />';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Newbb\XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
330
        } else {
331
            $postArray['icon'] = '<a name="' . $postArray['post_id'] . '"><img src="' . XOOPS_URL . '/images/icons/no_posticon.gif" alt="" /></a>';
332
        }
333
334
        $postArray['subject'] = '<a href="viewtopic.php?viewmode=thread&amp;topic_id=' . $topic->getVar('topic_id') . '&amp;forum=' . $postArray['forum_id'] . '&amp;post_id=' . $postArray['post_id'] . '">' . $postArray['subject'] . '</a>';
335
336
        $isActiveUser = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isActiveUser is dead and can be removed.
Loading history...
337
        if (isset($viewtopic_users[$postArray['uid']]['name'])) {
338
            $postArray['poster'] = $viewtopic_users[$postArray['uid']]['name'];
339
            if ($postArray['uid'] > 0) {
340
                $postArray['poster'] = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $postArray['uid'] . '">' . $viewtopic_users[$postArray['uid']]['name'] . '</a>';
341
            }
342
        } else {
343
            $postArray['poster'] = empty($postArray['poster_name']) ? $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']) : $postArray['poster_name'];
344
        }
345
346
        return $postArray;
347
    }
348
349
    /**
350
     * @param        $topic
351
     * @param  bool  $isApproved
352
     * @return array
353
     */
354
    public function &getAllPosters(&$topic, $isApproved = true)
355
    {
356
        $sql = 'SELECT DISTINCT uid FROM ' . $this->db->prefix('newbb_posts') . '  WHERE topic_id=' . $topic->getVar('topic_id') . ' AND uid>0';
357
        if ($isApproved) {
358
            $sql .= ' AND approved = 1';
359
        }
360
        $result = $this->db->query($sql);
361
        if (!$result) {
362
            //xoops_error($this->db->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
363
            return [];
364
        }
365
        $ret = [];
366
       while (false !== ($myrow = $this->db->fetchArray($result))) {
367
            $ret[] = $myrow['uid'];
368
        }
369
370
        return $ret;
371
    }
372
373
    /**
374
     * @param \XoopsObject $topic
375
     * @param  bool        $force
376
     * @return bool
377
     */
378
    public function delete(\XoopsObject $topic, $force = true)
379
    {
380
        $topic_id = is_object($topic) ? $topic->getVar('topic_id') : (int)$topic;
381
        if (empty($topic_id)) {
382
            return false;
383
        }
384
        $postObject = $this->getTopPost($topic_id);
385
        /** @var Newbb\PostHandler $postHandler */
386
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
387
        $postHandler->delete($postObject, false, $force);
388
389
        $newbbConfig = newbbLoadConfig();
390
        /** @var \XoopsModules\Tag\Handler $tagHandler */
391
        if (!empty($newbbConfig['do_tag']) && $tagHandler = @xoops_getModuleHandler('tag', 'tag', true)) {
0 ignored issues
show
Bug introduced by
The function xoops_getModuleHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

391
        if (!empty($newbbConfig['do_tag']) && $tagHandler = @/** @scrutinizer ignore-call */ xoops_getModuleHandler('tag', 'tag', true)) {
Loading history...
392
            $tagHandler->updateByItem([], $topic_id, 'newbb');
393
        }
394
395
        return true;
396
    }
397
398
    // get permission
399
    // parameter: $type: 'post', 'view',  'reply', 'edit', 'delete', 'addpoll', 'vote', 'attach'
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% 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...
400
    // $gperm_names = "'forum_can_post', 'forum_can_view', 'forum_can_reply', 'forum_can_edit', 'forum_can_delete', 'forum_can_addpoll', 'forum_can_vote', 'forum_can_attach', 'forum_can_noapprove'";
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
401
    /**
402
     * @param   Newbb\Forum $forum
403
     * @param  int     $topic_locked
404
     * @param  string  $type
405
     * @return bool
406
     */
407
    public function getPermission($forum, $topic_locked = 0, $type = 'view')
408
    {
409
        static $_cachedTopicPerms;
410
        include_once __DIR__ . '/../include/functions.user.php';
411
        if (newbbIsAdmin($forum)) {
412
            return true;
413
        }
414
415
        $forum_id = is_object($forum) ? $forum->getVar('forum_id') : (int)$forum;
416
        if ($forum_id < 1) {
417
            return false;
418
        }
419
420
        if ($topic_locked && 'view' !== $type) {
421
            $permission = false;
422
        } else {
423
            /** var Newbb\PermissionHandler $permHandler */
424
            $permHandler = Newbb\Helper::getInstance()->getHandler('Permission');
425
            $permission  = $permHandler->getPermission('forum', $type, $forum_id);
426
        }
427
428
        return $permission;
429
    }
430
431
    /**
432
     * clean orphan items from database
433
     *
434
     * @param  string $table_link
435
     * @param  string $field_link
436
     * @param  string $field_object
437
     * @return bool   true on success
438
     */
439
    public function cleanOrphan($table_link = '', $field_link = '', $field_object = '') //cleanOrphan()
440
    {
441
        $this->deleteAll(new \Criteria('topic_time', 0), true, true);
442
        parent::cleanOrphan($this->db->prefix('newbb_forums'), 'forum_id');
443
        parent::cleanOrphan($this->db->prefix('newbb_posts'), 'topic_id');
444
445
        return true;
446
    }
447
448
    /**
449
     * clean expired objects from database
450
     *
451
     * @param  int $expire time limit for expiration
452
     * @return bool true on success
453
     */
454
    public function cleanExpires($expire = 0)
455
    {
456
        // irmtfan if 0 no cleanup look include/plugin.php
457
        if (!func_num_args()) {
458
            $newbbConfig = newbbLoadConfig();
459
            $expire      = isset($newbbConfig['pending_expire']) ? (int)$newbbConfig['pending_expire'] : 7;
460
            $expire      = $expire * 24 * 3600; // days to seconds
461
        }
462
        if (empty($expire)) {
463
            return false;
464
        }
465
        $crit_expire = new \CriteriaCompo(new \Criteria('approved', 0, '<='));
466
        $crit_expire->add(new \Criteria('topic_time', time() - (int)$expire, '<'));
467
468
        return $this->deleteAll($crit_expire, true/*, true*/);
469
    }
470
471
    // START irmtfan - rewrite topic synchronization function. add pid sync and remove hard-code db access
472
473
    /**
474
     * @param  null $object
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $object is correct as it would always require null to be passed?
Loading history...
475
     * @param  bool $force
476
     * @return bool
477
     */
478
    public function synchronization($object = null, $force = true)
479
    {
480
        if (!is_object($object)) {
481
            $object = $this->get((int)$object);
482
        }
483
        if (!is_object($object) || !$object->getVar('topic_id')) {
484
            return false;
485
        }
486
487
        /** @var Newbb\PostHandler $postHandler */
488
        $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
489
        $criteria    = new \CriteriaCompo();
490
        $criteria->add(new \Criteria('topic_id', $object->getVar('topic_id')), 'AND');
491
        $criteria->add(new \Criteria('approved', 1), 'AND');
492
        $post_ids = $postHandler->getIds($criteria);
493
        if (empty($post_ids)) {
494
            return false;
495
        }
496
        $last_post     = max($post_ids);
497
        $top_post      = min($post_ids);
498
        $topic_replies = count($post_ids) - 1;
499
        if ($object->getVar('topic_last_post_id') != $last_post) {
500
            $object->setVar('topic_last_post_id', $last_post);
501
        }
502
        if ($object->getVar('topic_replies') != $topic_replies) {
503
            $object->setVar('topic_replies', $topic_replies);
504
        }
505
        $b1 = $this->insert($object, $force);
506
        $criteria->add(new \Criteria('post_id', $top_post, '<>'), 'AND');
507
        $criteria->add(new \Criteria('pid', '(' . implode(', ', $post_ids) . ')', 'NOT IN'), 'AND');
508
        $b2       = $postHandler->updateAll('pid', $top_post, $criteria, $force);
509
        $criteria = new \CriteriaCompo();
510
        $criteria->add(new \Criteria('post_id', $top_post, '='), 'AND');
511
        $b3 = $postHandler->updateAll('pid', 0, $criteria, $force);
512
513
        return ($b1 && $b2 && $b3);
514
    }
515
    // END irmtfan - rewrite topic synchronization function. add pid sync and remove hard-code db access
516
    // START irmtfan getActivePolls
517
    /**
518
     * get all active poll modules in the current xoops installtion.
519
     * @access public
520
     * @return array $pollDirs = array($dirname1=>$dirname1, $dirname2=>$dirname2, ...) dirnames of all active poll modules
521
     */
522
    public function getActivePolls()
523
    {
524
        $pollDirs = [];
525
        $allDirs  = xoops_getActiveModules();
0 ignored issues
show
Bug introduced by
The function xoops_getActiveModules was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

525
        $allDirs  = /** @scrutinizer ignore-call */ xoops_getActiveModules();
Loading history...
526
        foreach ($allDirs as $dirname) {
527
            // pollresults.php file is exist in all xoopspoll versions and umfrage versions
528
            if (file_exists($GLOBALS['xoops']->path('modules/' . $dirname . '/pollresults.php'))) {
529
                $pollDirs[$dirname] = $dirname;
530
            }
531
        }
532
533
        return $pollDirs;
534
    }
535
    // END irmtfan getActivePolls
536
537
    // START irmtfan findPollModule
538
    /**
539
     * find poll module that is in used in the current newbb installtion.
540
     * @access public
541
     * @param  array $pollDirs dirnames of all active poll modules
542
     * @return bool|string $dir_def | true | false
543
     *                         $dir_def: dirname of poll module that is in used in the current newbb installtion.
544
     *                         true: no poll module is installed | newbb has no topic with poll | newbb has no topic
545
     *                         false: errors (see below xoops_errors)
546
     */
547
    public function findPollModule(array $pollDirs = [])
548
    {
549
        $dir_def = '';
550
        if (empty($pollDirs)) {
551
            $pollDirs = $this->getActivePolls();
552
        }
553
        if (empty($pollDirs)) {
554
            return true;
555
        }
556
        // if only one active poll module still we need to check!!!
557
        //if(count($pollDirs) === 1) return end($pollDirs);
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...
558
        $topicPollObjs = $this->getAll(new \Criteria('topic_haspoll', 1), ['topic_id', 'poll_id']);
559
        if (empty($topicPollObjs)) {
560
            return true;
561
        } // no poll or no topic!!!
562
        foreach ($topicPollObjs as $tObj) {
563
            $poll_idInMod = 0;
564
            foreach ($pollDirs as $dirname) {
565
                $pollObj = $tObj->getPoll($tObj->getVar('poll_id'), $dirname);
566
                if (is_object($pollObj) && ($pollObj->getVar('poll_id') == $tObj->getVar('poll_id'))) {
567
                    ++$poll_idInMod;
568
                    $dir_def = $dirname;
569
                }
570
            }
571
            // Only one poll module should has this poll_id
572
            // if 0 there is an error
573
            if (0 == $poll_idInMod) {
574
                xoops_error("Error: Cannot find poll module for poll_id='{$tObj->getVar('poll_id')}'");
0 ignored issues
show
Bug introduced by
The function xoops_error was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

574
                /** @scrutinizer ignore-call */ 
575
                xoops_error("Error: Cannot find poll module for poll_id='{$tObj->getVar('poll_id')}'");
Loading history...
575
576
                return false;
577
            }
578
            // if 1 => $dir_def is correct
579
            if (1 == $poll_idInMod) {
580
                return $dir_def;
581
            }
582
            // if more than 1 continue
583
        }
584
        // if there is some topics but no module or more than one module have polls
585
        xoops_error("Error: Cannot find poll module that is in used in newbb!!! <br\><br\>You should select the correct poll module yourself in newbb > preferences > poll module setting.");
586
587
        return false;
588
    }
589
    // END irmtfan findPollModule
590
}
591