DigestHandler   A
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 262
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 119
dl 0
loc 262
rs 9.52
c 0
b 0
f 0
wmc 36

10 Methods

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