Passed
Push — master ( 301119...8677d9 )
by Michael
03:16 queued 10s
created

TopicHandler::synchronization()   B

Complexity

Conditions 9
Paths 28

Size

Total Lines 36
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 26
nc 28
nop 2
dl 0
loc 36
rs 8.0555
c 0
b 0
f 0
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
\defined('NEWBB_FUNCTIONS_INI') || require $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
19
20
/**
21
 * Class TopicHandler
22
 */
23
class TopicHandler extends \XoopsPersistableObjectHandler
24
{
25
    /**
26
     * @param \XoopsDatabase|null $db
27
     */
28
    public function __construct(\XoopsDatabase $db = null)
29
    {
30
        parent::__construct($db, 'newbb_topics', Topic::class, 'topic_id', 'topic_title');
31
    }
32
33
    /**
34
     * @param mixed      $id
35
     * @param null|array $fields
36
     * @return mixed|null
37
     */
38
    public function get($id = null, $fields = null) //get($id, $var = null)
39
    {
40
        $var  = $fields;
41
        $ret  = null;
42
        $tags = $var;
43
        if (!empty($var) && \is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
44
            $tags = [$var];
45
        }
46
        if (!$topicObject = parent::get($id, $tags)) {
47
            return $ret;
48
        }
49
        $ret = $topicObject;
50
        if (!empty($var) && \is_string($var)) {
0 ignored issues
show
introduced by
The condition is_string($var) is always false.
Loading history...
51
            $ret = @$topicObject->getVar($var);
52
        }
53
54
        return $ret;
55
    }
56
57
    /**
58
     * @param \XoopsObject $object
59
     * @param bool         $force
60
     * @return mixed
61
     */
62
    public function insert(\XoopsObject $object, $force = true)
63
    {
64
        if (!$object->getVar('topic_time')) {
65
            $object->setVar('topic_time', \time());
66
        }
67
        if (!parent::insert($object, $force) || !$object->getVar('approved')) {
68
            return $object->getVar('topic_id');
69
        }
70
71
        $newbbConfig = \newbbLoadConfig();
72
        if (!empty($newbbConfig['do_tag']) && \class_exists('TagFormTag')
73
            && @require $GLOBALS['xoops']->path('modules/tag/include/functions.php')) {
74
            $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

74
            $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...
75
            if ($tagHandler) {
0 ignored issues
show
introduced by
$tagHandler is of type XoopsModules\Tag\TagHandler, thus it always evaluated to true.
Loading history...
76
                $tagHandler->updateByItem($object->getVar('topic_tags', 'n'), $object->getVar('topic_id'), 'newbb');
77
            }
78
        }
79
80
        return $object->getVar('topic_id');
81
    }
82
83
    /**
84
     * @param       $object
85
     * @param bool  $force
86
     * @return bool
87
     */
88
    public function approve($object, $force = false)
89
    {
90
        $topic_id = $object->getVar('topic_id');
91
        if ($force) {
92
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = -1 WHERE topic_id = {$topic_id}";
93
        } else {
94
            $sql = 'UPDATE ' . $this->db->prefix('newbb_topics') . " SET approved = 1 WHERE topic_id = {$topic_id}";
95
        }
96
        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...
97
            //xoops_error($this->db->error());
98
            return false;
99
        }
100
        $postHandler = Helper::getInstance()->getHandler('Post');
101
        $postsObject = $postHandler->getAll(new \Criteria('topic_id', $topic_id));
102
        foreach (\array_keys($postsObject) as $post_id) {
103
            $postHandler->approve($postsObject[$post_id]);
104
        }
105
        unset($postsObject);
106
        /** @var \XoopsModules\Newbb\StatsHandler $statsHandler */
107
        $statsHandler = Helper::getInstance()->getHandler('Stats');
108
        $statsHandler->update($object->getVar('forum_id'), 'topic');
109
110
        return true;
111
    }
112
113
    /**
114
     * get previous/next topic
115
     *
116
     * @param int $topic_id     current topic ID
117
     * @param int $action
118
     *                          <ul>
119
     *                          <li> -1: previous </li>
120
     *                          <li> 0: current </li>
121
     *                          <li> 1: next </li>
122
     *                          </ul>
123
     * @param int $forum_id     the scope for moving
124
     *                          <ul>
125
     *                          <li> >0 : inside the forum </li>
126
     *                          <li> <= 0: global </li>
127
     *                          </ul>
128
     * @access public
129
     * @return mixed|null|\XoopsObject
130
     */
131
    public function &getByMove($topic_id, $action, $forum_id = 0)
132
    {
133
        $topic = null;
134
        if (!empty($action)) {
135
            $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';
136
            $result = $this->db->query($sql);
137
            if ($result) {
138
                $row = $this->db->fetchArray($result);
139
                if ($row) {
140
                    $topic = $this->create(false);
141
                    $topic->assignVars($row);
142
143
                    return $topic;
144
                }
145
            }
146
        }
147
        $topic = $this->get($topic_id);
148
149
        return $topic;
150
    }
151
152
    /**
153
     * @param $post_id
154
     * @return null|\XoopsObject
155
     */
156
    public function &getByPost($post_id)
157
    {
158
        $topic  = null;
159
        $sql    = 'SELECT t.* FROM ' . $this->db->prefix('newbb_topics') . ' t, ' . $this->db->prefix('newbb_posts') . ' p
160
                WHERE t.topic_id = p.topic_id AND p.post_id = ' . (int)$post_id;
161
        $result = $this->db->query($sql);
162
        if (!$result) {
163
            //xoops_error($this->db->error());
164
            return $topic;
165
        }
166
        $row   = $this->db->fetchArray($result);
167
        $topic = $this->create(false);
168
        $topic->assignVars($row);
169
170
        return $topic;
171
    }
172
173
    /**
174
     * @param Topic  $topic
175
     * @param string $type
176
     * @return int
177
     */
178
    public function getPostCount($topic, $type = '')
179
    {
180
        switch ($type) {
181
            case 'pending':
182
                $approved = 0;
183
                break;
184
            case 'deleted':
185
                $approved = -1;
186
                break;
187
            default:
188
                $approved = 1;
189
                break;
190
        }
191
        $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

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

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