DigestHandler   A
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 114
dl 0
loc 254
rs 9.52
c 0
b 0
f 0
wmc 36

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A delete() 0 12 3
A notify() 0 10 1
A getDigestCount() 0 10 2
A checkStatus() 0 9 3
A process() 0 24 6
A getLastDigest() 0 10 3
C buildDigest() 0 78 14
A insert() 0 5 1
A getAllDigests() 0 15 2
1
<?php
2
3
namespace XoopsModules\Newbb;
4
5
/**
6
 * NewBB 5.0x,  the forum module for XOOPS project
7
 *
8
 * @copyright      XOOPS Project (https://xoops.org)
9
 * @license        GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
10
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>
11
 * @since          4.00
12
 * @package        module::newbb
13
 */
14
15
use XoopsModules\Newbb;
16
17
/**
18
 * Class DigestHandler
19
 */
20
class DigestHandler extends \XoopsPersistableObjectHandler
21
{
22
    public $last_digest;
23
24
    /**
25
     * Constructor
26
     *
27
     * @param null|\XoopsDatabase $db database connection
28
     */
29
    public function __construct(\XoopsDatabase $db = null)
30
    {
31
        parent::__construct($db, 'newbb_digest', Digest::class, 'digest_id');
32
    }
33
34
    /**
35
     * @param bool $isForced
36
     * @return int
37
     */
38
    public function process($isForced = false)
39
    {
40
        $this->getLastDigest();
41
        if (!$isForced) {
42
            $status = $this->checkStatus();
43
            if ($status < 1) {
44
                return 1;
45
            }
46
        }
47
        $digest = $this->create();
48
        $status = $this->buildDigest($digest);
49
        if (!$status) {
50
            return 2;
51
        }
52
        $status = $this->insert($digest);
53
        if (!$status) {
54
            return 3;
55
        }
56
        $status = $this->notify($digest);
57
        if (!$status) {
0 ignored issues
show
introduced by
The condition $status is always true.
Loading history...
58
            return 4;
59
        }
60
61
        return 0;
62
    }
63
64
    /**
65
     * @param \XoopsObject $digest
66
     * @return bool
67
     */
68
    public function notify(\XoopsObject $digest)
69
    {
70
        //$content                = $digest->getVar('digest_content');
71
        /** @var \XoopsNotificationHandler $notificationHandler */
72
        $notificationHandler    = \xoops_getHandler('notification');
73
        $tags['DIGEST_ID']      = $digest->getVar('digest_id');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$tags was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tags = array(); before regardless.
Loading history...
74
        $tags['DIGEST_CONTENT'] = $digest->getVar('digest_content', 'E');
75
        $notificationHandler->triggerEvent('global', 0, 'digest', $tags);
76
77
        return true;
78
    }
79
80
    /**
81
     * @param        $start
82
     * @param int    $perpage
83
     * @return array
84
     */
85
    public function getAllDigests($start = 0, $perpage = 5)
86
    {
87
        //        if (empty($start)) {
88
        //            $start = 0;
89
        //        }
90
91
        $sql    = 'SELECT * FROM ' . $this->db->prefix('newbb_digest') . ' ORDER BY digest_id DESC';
92
        $result = $this->db->query($sql, $perpage, $start);
93
        $ret    = [];
94
        //        $reportHandler =  Newbb\Helper::getInstance()->getHandler('Report');
95
        while (false !== ($myrow = $this->db->fetchArray($result))) {
96
            $ret[] = $myrow; // return as array
97
        }
98
99
        return $ret;
100
    }
101
102
    /**
103
     * @return int
104
     */
105
    public function getDigestCount()
106
    {
107
        $sql    = 'SELECT COUNT(*) AS count FROM ' . $this->db->prefix('newbb_digest');
108
        $result = $this->db->query($sql);
109
        if (!$result) {
110
            return 0;
111
        }
112
        $array = $this->db->fetchArray($result);
113
114
        return $array['count'];
115
    }
116
117
    public function getLastDigest()
118
    {
119
        $sql    = 'SELECT MAX(digest_time) AS last_digest FROM ' . $this->db->prefix('newbb_digest');
120
        $result = $this->db->query($sql);
121
        if (!$result) {
122
            $this->last_digest = 0;
123
            // echo "<br>no data:".$query;
124
        } else {
125
            $array             = $this->db->fetchArray($result);
126
            $this->last_digest = isset($array['last_digest']) ? $array['last_digest'] : 0;
127
        }
128
    }
129
130
    /**
131
     * @return int
132
     */
133
    public function checkStatus()
134
    {
135
        if (!isset($this->last_digest)) {
136
            $this->getLastDigest();
137
        }
138
        $deadline  = (1 == $GLOBALS['xoopsModuleConfig']['email_digest']) ? 60 * 60 * 24 : 60 * 60 * 24 * 7;
139
        $time_diff = \time() - $this->last_digest;
140
141
        return $time_diff - $deadline;
142
    }
143
144
    /**
145
     * @param \XoopsObject $digest
146
     * @param bool         $force flag to force the query execution despite security settings
147
     * @return mixed       object ID or false
148
     */
149
    public function insert(\XoopsObject $digest, $force = true)
150
    {
151
        $digest->setVar('digest_time', \time());
152
153
        return parent::insert($digest, $force);
154
        /*
155
        $content = $digest->getVar('digest_content', 'E');
156
157
        $id  = $this->db->genId($digest->table . '_digest_id_seq');
158
        $sql = 'INSERT INTO ' . $digest->table . ' (digest_id, digest_time, digest_content)    VALUES (' . $id . ', ' . time() . ', ' . $this->db->quoteString($content) . ' )';
159
160
        if (!$this->db->queryF($sql)) {
161
            //echo "<br>digest insert error::" . $sql;
162
            return false;
163
        }
164
        if (empty($id)) {
165
            $id = $this->db->getInsertId();
166
        }
167
        $digest->setVar('digest_id', $id);
168
169
        return true;
170
        */
171
    }
172
173
    /**
174
     * @param \XoopsObject $digest
175
     * @param bool         $force (ignored)
176
     * @return bool        FALSE if failed.
177
     */
178
    public function delete(\XoopsObject $digest, $force = false)
179
    {
180
        $digest_id = $digest->getVar('digest_id');
181
182
        if (!isset($this->last_digest)) {
183
            $this->getLastDigest();
184
        }
185
        if ($this->last_digest == $digest_id) {
186
            return false;
187
        } // It is not allowed to delete the last digest
188
189
        return parent::delete($digest, true);
190
    }
191
192
    /**
193
     * @param \XoopsObject $digest
194
     * @return bool
195
     */
196
    public function buildDigest(\XoopsObject $digest)
197
    {
198
        global $xoopsModule;
199
200
        if (!\defined('SUMMARY_LENGTH')) {
201
            \define('SUMMARY_LENGTH', 100);
202
        }
203
204
        /** @var Newbb\ForumHandler $forumHandler */
205
        $forumHandler         = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Forum');
206
        $thisUser             = $GLOBALS['xoopsUser'];
207
        $GLOBALS['xoopsUser'] = null; // To get posts accessible by anonymous
208
        $GLOBALS['xoopsUser'] = $thisUser;
209
210
        $accessForums    = $forumHandler->getIdsByPermission(); // get all accessible forums
211
        $forumCriteria   = ' AND t.forum_id IN (' . \implode(',', $accessForums) . ')';
212
        $approveCriteria = ' AND t.approved = 1 AND p.approved = 1';
213
        $time_criteria   = ' AND t.digest_time > ' . $this->last_digest;
214
215
        $karma_criteria = $GLOBALS['xoopsModuleConfig']['enable_karma'] ? ' AND p.post_karma=0' : '';
216
        $reply_criteria = $GLOBALS['xoopsModuleConfig']['allow_require_reply'] ? ' AND p.require_reply=0' : '';
217
218
        $query = 'SELECT t.topic_id, t.forum_id, t.topic_title, t.topic_time, t.digest_time, p.uid, p.poster_name, pt.post_text FROM '
219
                 . $this->db->prefix('newbb_topics')
220
                 . ' t, '
221
                 . $this->db->prefix('newbb_posts_text')
222
                 . ' pt, '
223
                 . $this->db->prefix('newbb_posts')
224
                 . ' p WHERE t.topic_digest = 1 AND p.topic_id=t.topic_id AND p.pid=0 '
225
                 . $forumCriteria
226
                 . $approveCriteria
227
                 . $time_criteria
228
                 . $karma_criteria
229
                 . $reply_criteria
230
                 . ' AND pt.post_id=p.post_id ORDER BY t.digest_time DESC';
231
        if (!$result = $this->db->query($query)) {
232
            //echo "<br>No result:<br>$query";
233
            return false;
234
        }
235
        $rows  = [];
236
        $users = [];
237
        while (false !== ($row = $this->db->fetchArray($result))) {
238
            $users[$row['uid']] = 1;
239
            $rows[]             = $row;
240
        }
241
        if (\count($rows) < 1) {
242
            return false;
243
        }
244
        $uids = \array_keys($users);
245
        if (\count($uids) > 0) {
246
            /** @var \XoopsMemberHandler $memberHandler */
247
            $memberHandler = \xoops_getHandler('member');
248
            $user_criteria = new \Criteria('uid', '(' . \implode(',', $uids) . ')', 'IN');
249
            $users         = $memberHandler->getUsers($user_criteria, true);
250
        } else {
251
            $users = [];
252
        }
253
254
        foreach ($rows as $topic) {
255
            if ($topic['uid'] > 0) {
256
                if (isset($users[$topic['uid']]) && \is_object($users[$topic['uid']])
257
                    && $users[$topic['uid']]->isActive()) {
258
                    $topic['uname'] = $users[$topic['uid']]->getVar('uname');
259
                } else {
260
                    $topic['uname'] = $GLOBALS['xoopsConfig']['anonymous'];
261
                }
262
            } else {
263
                $topic['uname'] = $topic['poster_name'] ?: $GLOBALS['xoopsConfig']['anonymous'];
264
            }
265
            $summary = \Xmf\Metagen::generateDescription($topic['post_text'], SUMMARY_LENGTH);
266
            $author  = $topic['uname'] . ' (' . \formatTimestamp($topic['topic_time']) . ')';
267
            $link    = XOOPS_URL . '/modules/' . $xoopsModule->dirname() . '/viewtopic.php?topic_id=' . $topic['topic_id'] . '&amp;forum=' . $topic['forum_id'];
268
            $title   = $topic['topic_title'];
269
            $digest->addItem($title, $link, $author, $summary);
0 ignored issues
show
Bug introduced by
The method addItem() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Newbb\Digest. ( Ignorable by Annotation )

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

269
            $digest->/** @scrutinizer ignore-call */ 
270
                     addItem($title, $link, $author, $summary);
Loading history...
270
        }
271
        $digest->buildContent();
0 ignored issues
show
Bug introduced by
The method buildContent() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Newbb\Digest. ( Ignorable by Annotation )

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

271
        $digest->/** @scrutinizer ignore-call */ 
272
                 buildContent();
Loading history...
272
273
        return true;
274
    }
275
}
276