TopicHandler   F
last analyzed

Complexity

Total Complexity 94

Size/Duplication

Total Lines 574
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 255
dl 0
loc 574
rs 2
c 0
b 0
f 0
wmc 94

20 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 17 6
A __construct() 0 3 1
B insert() 0 19 8
A showTreeItem() 0 25 5
A getTopPost() 0 22 2
A getPermission() 0 22 6
B getByMove() 0 19 7
A approve() 0 22 4
B findPollModule() 0 41 10
A getByPost() 0 15 2
A getPostCount() 0 20 3
A getActivePolls() 0 12 3
A cleanOrphan() 0 7 1
A delete() 0 18 6
B synchronization() 0 36 9
A getPostTree() 0 9 1
B 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
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
use XoopsModules\Tag;
17
18
19
20
\defined('NEWBB_FUNCTIONS_INI') || require $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
21
22
/**
23
 * Class TopicHandler
24
 */
25
class TopicHandler extends \XoopsPersistableObjectHandler
26
{
27
    /**
28
     * @param \XoopsDatabase|null $db
29
     */
30
    public function __construct(\XoopsDatabase $db = null)
31
    {
32
        parent::__construct($db, 'newbb_topics', Topic::class, 'topic_id', 'topic_title');
33
    }
34
35
    /**
36
     * @param mixed      $id
37
     * @param null|array $fields
38
     * @return mixed|null
39
     */
40
    public function get($id = null, $fields = null) //get($id, $var = null)
41
    {
42
        $var  = $fields;
43
        $ret  = null;
44
        $tags = $var;
45
        if (!empty($var) && \is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
46
            $tags = [$var];
47
        }
48
        if (!$topicObject = parent::get($id, $tags)) {
49
            return $ret;
50
        }
51
        $ret = $topicObject;
52
        if (!empty($var) && \is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
53
            $ret = @$topicObject->getVar($var);
54
        }
55
56
        return $ret;
57
    }
58
59
    /**
60
     * @param \XoopsObject $object
61
     * @param bool         $force
62
     * @return mixed
63
     */
64
    public function insert(\XoopsObject $object, $force = true)
65
    {
66
        if (!$object->getVar('topic_time')) {
67
            $object->setVar('topic_time', \time());
68
        }
69
        if (!parent::insert($object, $force) || !$object->getVar('approved')) {
70
            return $object->getVar('topic_id');
71
        }
72
73
        $newbbConfig = \newbbLoadConfig();
74
        if (!empty($newbbConfig['do_tag']) && \class_exists('TagFormTag')
75
            && @require $GLOBALS['xoops']->path('modules/tag/include/functions.php')) {
76
            $tagHandler = \tag_getTagHandler();
0 ignored issues
show
Deprecated Code introduced by
The function tag_getTagHandler() has been deprecated: - use Tag\Helper::getInstance()->getHandler('Tag') instead ( Ignorable by Annotation )

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

76
            $tagHandler = /** @scrutinizer ignore-deprecated */ \tag_getTagHandler();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
77
            if ($tagHandler) {
0 ignored issues
show
introduced by
$tagHandler is of type XoopsModules\Tag\TagHandler, thus it always evaluated to true.
Loading history...
78
                $tagHandler->updateByItem($object->getVar('topic_tags', 'n'), $object->getVar('topic_id'), 'newbb');
79
            }
80
        }
81
82
        return $object->getVar('topic_id');
83
    }
84
85
    /**
86
     * @param       $object
87
     * @param bool  $force
88
     * @return bool
89
     */
90
    public function approve($object, $force = false)
91
    {
92
        $topic_id = $object->getVar('topic_id');
93
        if ($force) {
94
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = -1 WHERE topic_id = {$topic_id}";
95
        } else {
96
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = 1 WHERE topic_id = {$topic_id}";
97
        }
98
        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...
99
            //xoops_error($this->db->error());
100
            return false;
101
        }
102
        $postHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Post');
103
        $postsObject = $postHandler->getAll(new \Criteria('topic_id', $topic_id));
104
        foreach (\array_keys($postsObject) as $post_id) {
105
            $postHandler->approve($postsObject[$post_id]);
106
        }
107
        unset($postsObject);
108
        $statsHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Stats');
109
        $statsHandler->update($object->getVar('forum_id'), 'topic');
0 ignored issues
show
Bug introduced by
The method update() 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

109
        $statsHandler->/** @scrutinizer ignore-call */ 
110
                       update($object->getVar('forum_id'), 'topic');
Loading history...
110
111
        return true;
112
    }
113
114
    /**
115
     * get previous/next topic
116
     *
117
     * @param int $topic_id     current topic ID
118
     * @param int $action
119
     *                          <ul>
120
     *                          <li> -1: previous </li>
121
     *                          <li> 0: current </li>
122
     *                          <li> 1: next </li>
123
     *                          </ul>
124
     * @param int $forum_id     the scope for moving
125
     *                          <ul>
126
     *                          <li> >0 : inside the forum </li>
127
     *                          <li> <= 0: global </li>
128
     *                          </ul>
129
     * @access public
130
     * @return mixed|null|\XoopsObject
131
     */
132
    public function &getByMove($topic_id, $action, $forum_id = 0)
133
    {
134
        $topic = null;
135
        if (!empty($action)) {
136
            $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';
137
            $result = $this->db->query($sql);
138
            if ($result) {
139
                $row = $this->db->fetchArray($result);
140
                if ($row) {
141
                    $topic = $this->create(false);
142
                    $topic->assignVars($row);
143
144
                    return $topic;
145
                }
146
            }
147
        }
148
        $topic = $this->get($topic_id);
149
150
        return $topic;
151
    }
152
153
    /**
154
     * @param $post_id
155
     * @return null|\XoopsObject
156
     */
157
    public function &getByPost($post_id)
158
    {
159
        $topic  = null;
160
        $sql    = 'SELECT t.* FROM ' . $this->db->prefix('newbb_topics') . ' t, ' . $this->db->prefix('newbb_posts') . ' p
161
                WHERE t.topic_id = p.topic_id AND p.post_id = ' . (int)$post_id;
162
        $result = $this->db->query($sql);
163
        if (!$result) {
164
            //xoops_error($this->db->error());
165
            return $topic;
166
        }
167
        $row   = $this->db->fetchArray($result);
168
        $topic = $this->create(false);
169
        $topic->assignVars($row);
170
171
        return $topic;
172
    }
173
174
    /**
175
     * @param Topic  $topic
176
     * @param string $type
177
     * @return mixed
178
     */
179
    public function getPostCount($topic, $type = '')
180
    {
181
        switch ($type) {
182
            case 'pending':
183
                $approved = 0;
184
                break;
185
            case 'deleted':
186
                $approved = -1;
187
                break;
188
            default:
189
                $approved = 1;
190
                break;
191
        }
192
        $criteria = new \CriteriaCompo(new \Criteria('topic_id', $topic->getVar('topic_id')));
0 ignored issues
show
Bug introduced by
It seems like $topic->getVar('topic_id') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, 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

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

393
        $postHandler->delete(/** @scrutinizer ignore-type */ $postObject, false, $force);
Loading history...
394
395
        $newbbConfig = \newbbLoadConfig();
396
        /** @var \XoopsModules\Tag\TagHandler $tagHandler */
397
        if (!empty($newbbConfig['do_tag']) && \class_exists('TagFormTag') && $tagHandler = Tag\Helper::getInstance()->getHandler('Tag')) { //@xoops_getModuleHandler('tag', 'tag', true)) {
398
            $tagHandler->updateByItem([], $topic_id, 'newbb');
399
        }
400
401
        return true;
402
    }
403
404
    // get permission
405
    // parameter: $type: 'post', 'view',  'reply', 'edit', 'delete', 'addpoll', 'vote', 'attach'
406
    // $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'";
407
408
    /**
409
     * @param Newbb\Forum $forum
410
     * @param int         $topic_locked
411
     * @param string      $type
412
     * @return bool
413
     */
414
    public function getPermission($forum, $topic_locked = 0, $type = 'view')
415
    {
416
        static $_cachedTopicPerms;
417
        require_once \dirname(__DIR__) . '/include/functions.user.php';
418
        if (\newbbIsAdmin($forum)) {
419
            return true;
420
        }
421
422
        $forum_id = \is_object($forum) ? $forum->getVar('forum_id') : (int)$forum;
423
        if ($forum_id < 1) {
424
            return false;
425
        }
426
427
        if ($topic_locked && 'view' !== $type) {
428
            $permission = false;
429
        } else {
430
            /** var Newbb\PermissionHandler $permHandler */
431
            $permHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Permission');
432
            $permission  = $permHandler->getPermission('forum', $type, $forum_id);
433
        }
434
435
        return $permission;
436
    }
437
438
    /**
439
     * clean orphan items from database
440
     *
441
     * @param string $table_link
442
     * @param string $field_link
443
     * @param string $field_object
444
     * @return bool   true on success
445
     */
446
    public function cleanOrphan($table_link = '', $field_link = '', $field_object = '') //cleanOrphan()
447
    {
448
        $this->deleteAll(new \Criteria('topic_time', 0), true, true);
449
        parent::cleanOrphan($this->db->prefix('newbb_forums'), 'forum_id');
450
        parent::cleanOrphan($this->db->prefix('newbb_posts'), 'topic_id');
451
452
        return true;
453
    }
454
455
    /**
456
     * clean expired objects from database
457
     *
458
     * @param int $expire time limit for expiration
459
     * @return bool true on success
460
     */
461
    public function cleanExpires($expire = 0)
462
    {
463
        // irmtfan if 0 no cleanup look include/plugin.php
464
        if (!\func_num_args()) {
465
            $newbbConfig = \newbbLoadConfig();
466
            $expire      = isset($newbbConfig['pending_expire']) ? (int)$newbbConfig['pending_expire'] : 7;
467
            $expire      = $expire * 24 * 3600; // days to seconds
468
        }
469
        if (empty($expire)) {
470
            return false;
471
        }
472
        $crit_expire = new \CriteriaCompo(new \Criteria('approved', 0, '<='));
473
        $crit_expire->add(new \Criteria('topic_time', \time() - (int)$expire, '<'));
474
475
        return $this->deleteAll($crit_expire, true/*, true*/);
476
    }
477
478
    // START irmtfan - rewrite topic synchronization function. add pid sync and remove hard-code db access
479
480
    /**
481
     * @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...
482
     * @param bool $force
483
     * @return bool
484
     */
485
    public function synchronization($object = null, $force = true)
486
    {
487
        if (!\is_object($object)) {
488
            $object = $this->get((int)$object);
489
        }
490
        if (!\is_object($object) || !$object->getVar('topic_id')) {
491
            return false;
492
        }
493
494
        /** @var Newbb\PostHandler $postHandler */
495
        $postHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Post');
496
        $criteria    = new \CriteriaCompo();
497
        $criteria->add(new \Criteria('topic_id', $object->getVar('topic_id')), 'AND');
498
        $criteria->add(new \Criteria('approved', 1), 'AND');
499
        $post_ids = $postHandler->getIds($criteria);
500
        if (empty($post_ids)) {
501
            return false;
502
        }
503
        $last_post     = \max($post_ids);
504
        $top_post      = \min($post_ids);
505
        $topic_replies = \count($post_ids) - 1;
506
        if ($object->getVar('topic_last_post_id') != $last_post) {
507
            $object->setVar('topic_last_post_id', $last_post);
508
        }
509
        if ($object->getVar('topic_replies') != $topic_replies) {
510
            $object->setVar('topic_replies', $topic_replies);
511
        }
512
        $b1 = $this->insert($object, $force);
513
        $criteria->add(new \Criteria('post_id', $top_post, '<>'), 'AND');
514
        $criteria->add(new \Criteria('pid', '(' . \implode(', ', $post_ids) . ')', 'NOT IN'), 'AND');
515
        $b2       = $postHandler->updateAll('pid', $top_post, $criteria, $force);
516
        $criteria = new \CriteriaCompo();
517
        $criteria->add(new \Criteria('post_id', $top_post, '='), 'AND');
518
        $b3 = $postHandler->updateAll('pid', 0, $criteria, $force);
519
520
        return ($b1 && $b2 && $b3);
521
    }
522
523
    // END irmtfan - rewrite topic synchronization function. add pid sync and remove hard-code db access
524
    // START irmtfan getActivePolls
525
526
    /**
527
     * get all active poll modules in the current xoops installtion.
528
     * @access public
529
     * @return array $pollDirs = array($dirname1=>$dirname1, $dirname2=>$dirname2, ...) dirnames of all active poll modules
530
     */
531
    public function getActivePolls()
532
    {
533
        $pollDirs = [];
534
        $allDirs  = \xoops_getActiveModules();
535
        foreach ($allDirs as $dirname) {
536
            // pollresults.php file is exist in all xoopspoll versions and umfrage versions
537
            if (\file_exists($GLOBALS['xoops']->path('modules/' . $dirname . '/pollresults.php'))) {
538
                $pollDirs[$dirname] = $dirname;
539
            }
540
        }
541
542
        return $pollDirs;
543
    }
544
545
    // END irmtfan getActivePolls
546
547
    // START irmtfan findPollModule
548
549
    /**
550
     * find poll module that is in used in the current newbb installtion.
551
     * @access public
552
     * @param array $pollDirs  dirnames of all active poll modules
553
     * @return bool|string $dir_def | true | false
554
     *                         $dir_def: dirname of poll module that is in used in the current newbb installtion.
555
     *                         true: no poll module is installed | newbb has no topic with poll | newbb has no topic
556
     *                         false: errors (see below xoops_errors)
557
     */
558
    public function findPollModule(array $pollDirs = [])
559
    {
560
        $dir_def = '';
561
        if (empty($pollDirs)) {
562
            $pollDirs = $this->getActivePolls();
563
        }
564
        if (empty($pollDirs)) {
565
            return true;
566
        }
567
        // if only one active poll module still we need to check!!!
568
        //if(count($pollDirs) === 1) return end($pollDirs);
569
        $topicPollObjs = $this->getAll(new \Criteria('topic_haspoll', 1), ['topic_id', 'poll_id']);
570
        if (empty($topicPollObjs)) {
571
            return true;
572
        } // no poll or no topic!!!
573
        foreach ($topicPollObjs as $tObj) {
574
            $poll_idInMod = 0;
575
            foreach ($pollDirs as $dirname) {
576
                $pollObj = $tObj->getPoll($tObj->getVar('poll_id'), $dirname);
577
                if (\is_object($pollObj) && ($pollObj->getVar('poll_id') == $tObj->getVar('poll_id'))) {
578
                    ++$poll_idInMod;
579
                    $dir_def = $dirname;
580
                }
581
            }
582
            // Only one poll module should has this poll_id
583
            // if 0 there is an error
584
            if (0 == $poll_idInMod) {
585
                \xoops_error("Error: Cannot find poll module for poll_id='{$tObj->getVar('poll_id')}'");
586
587
                return false;
588
            }
589
            // if 1 => $dir_def is correct
590
            if (1 == $poll_idInMod) {
591
                return $dir_def;
592
            }
593
            // if more than 1 continue
594
        }
595
        // if there is some topics but no module or more than one module have polls
596
        \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.");
597
598
        return false;
599
    }
600
601
    // END irmtfan findPollModule
602
}
603