Completed
Pull Request — master (#15)
by Richard
02:18
created

NewbbDigestHandler::delete()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 2
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
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
class Digest extends XoopsObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
13
{
14
    public $digest_id;
15
    public $digest_time;
16
    public $digest_content;
17
18
    public $items;
19
    public $isHtml    = false;
20
    public $isSummary = true;
21
22
    /**
23
     *
24
     */
25 View Code Duplication
    public function __construct()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
26
    {
27
        parent::__construct();
28
        $this->initVar('digest_id', XOBJ_DTYPE_INT);
29
        $this->initVar('digest_time', XOBJ_DTYPE_INT);
30
        $this->initVar('digest_content', XOBJ_DTYPE_TXTAREA);
31
        $this->items = [];
32
    }
33
34
    public function setHtml()
35
    {
36
        $this->isHtml = true;
37
    }
38
39
    public function setSummary()
40
    {
41
        $this->isSummary = true;
42
    }
43
44
    /**
45
     * @param        $title
46
     * @param        $link
47
     * @param        $author
48
     * @param string $summary
49
     */
50
    public function addItem($title, $link, $author, $summary = '')
51
    {
52
        $title  = $this->cleanup($title);
53
        $author = $this->cleanup($author);
54
        if (!empty($summary)) {
55
            $summary = $this->cleanup($summary);
56
        }
57
        $this->items[] = ['title' => $title, 'link' => $link, 'author' => $author, 'summary' => $summary];
58
    }
59
60
    /**
61
     * @param $text
62
     * @return mixed|string
63
     */
64
    public function cleanup($text)
65
    {
66
        global $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...
67
68
        $clean = stripslashes($text);
69
        $clean =& $myts->displayTarea($clean, 1, 0, 1);
70
        $clean = strip_tags($clean);
71
        $clean = htmlspecialchars($clean, ENT_QUOTES);
72
73
        return $clean;
74
    }
75
76
    /**
77
     * @param  bool $isSummary
78
     * @param  bool $isHtml
79
     * @return bool
80
     */
81
    public function buildContent($isSummary = true, $isHtml = false)
82
    {
83
        $digest_count = count($this->items);
84
        $content      = '';
85
        if ($digest_count > 0) {
86
            $linebreak = $isHtml ? '<br>' : "\n";
87
            for ($i = 0; $i < $digest_count; ++$i) {
88
                if ($isHtml) {
89
                    $content .= ($i + 1) . '. <a href=' . $this->items[$i]['link'] . '>' . $this->items[$i]['title'] . '</a>';
90
                } else {
91
                    $content .= ($i + 1) . '. ' . $this->items[$i]['title'] . $linebreak . $this->items[$i]['link'];
92
                }
93
94
                $content .= $linebreak . $this->items[$i]['author'];
95
                if ($isSummary) {
96
                    $content .= $linebreak . $this->items[$i]['summary'];
97
                }
98
                $content .= $linebreak . $linebreak;
99
            }
100
        }
101
        $this->setVar('digest_content', $content);
102
103
        return true;
104
    }
105
}
106
107
/**
108
 * Class NewbbDigestHandler
109
 */
110
class NewbbDigestHandler extends XoopsPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
111
{
112
    public $last_digest;
113
114
    /**
115
     * Constructor
116
     *
117
     * @param null|XoopsDatabase $db             database connection
118
     */
119
    function __construct(XoopsDatabase $db)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
120
    {
121
        parent::__construct($db, 'newbb_digest', 'Digest', 'digest_id');
122
    }
123
124
    /**
125
     * @param  bool $isForced
126
     * @return int
127
     */
128
    public function process($isForced = false)
129
    {
130
        $this->getLastDigest();
131
        if (!$isForced) {
132
            $status = $this->checkStatus();
133
            if ($status < 1) {
134
                return 1;
135
            }
136
        }
137
        $digest = $this->create();
138
        $status = $this->buildDigest($digest);
139
        if (!$status) {
140
            return 2;
141
        }
142
        $status = $this->insert($digest);
143
        if (!$status) {
144
            return 3;
145
        }
146
        $status = $this->notify($digest);
147
        if (!$status) {
148
            return 4;
149
        }
150
151
        return 0;
152
    }
153
154
    /**
155
     * @param  XoopsObject $digest
156
     * @return bool
157
     */
158
    public function notify(XoopsObject $digest)
159
    {
160
        //$content                = $digest->getVar('digest_content');
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...
161
        /** @var \XoopsNotificationHandler $notificationHandler */
162
        $notificationHandler    = xoops_getHandler('notification');
163
        $tags['DIGEST_ID']      = $digest->getVar('digest_id');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tags was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tags = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
164
        $tags['DIGEST_CONTENT'] = $digest->getVar('digest_content', 'E');
165
        $notificationHandler->triggerEvent('global', 0, 'digest', $tags);
166
167
        return true;
168
    }
169
170
    /**
171
     * @param        $start
172
     * @param  int   $perpage
173
     * @return array
174
     */
175
    public function getAllDigests($start = 0, $perpage = 5)
176
    {
177
        //        if (empty($start)) {
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...
178
        //            $start = 0;
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...
179
        //        }
180
181
        $sql    = 'SELECT * FROM ' . $this->db->prefix('newbb_digest') . ' ORDER BY digest_id DESC';
182
        $result = $this->db->query($sql, $perpage, $start);
183
        $ret    = [];
184
        //        $reportHandler = xoops_getModuleHandler('report', 'newbb');
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
185
        while ($myrow = $this->db->fetchArray($result)) {
186
            $ret[] = $myrow; // return as array
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
187
        }
188
189
        return $ret;
190
    }
191
192
    /**
193
     * @return int
194
     */
195
    public function getDigestCount()
196
    {
197
        $sql    = 'SELECT COUNT(*) AS count FROM ' . $this->db->prefix('newbb_digest');
198
        $result = $this->db->query($sql);
199
        if (!$result) {
200
            return 0;
201
        } else {
202
            $array = $this->db->fetchArray($result);
203
204
            return $array['count'];
205
        }
206
    }
207
208
    public function getLastDigest()
209
    {
210
        $sql    = 'SELECT MAX(digest_time) AS last_digest FROM ' . $this->db->prefix('newbb_digest');
211
        $result = $this->db->query($sql);
212
        if (!$result) {
213
            $this->last_digest = 0;
214
            // echo "<br>no data:".$query;
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
215
        } else {
216
            $array             = $this->db->fetchArray($result);
217
            $this->last_digest = isset($array['last_digest']) ? $array['last_digest'] : 0;
218
        }
219
    }
220
221
    /**
222
     * @return int
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
223
     */
224
    public function checkStatus()
0 ignored issues
show
Coding Style introduced by
checkStatus uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
225
    {
226
        if (!isset($this->last_digest)) {
227
            $this->getLastDigest();
228
        }
229
        $deadline  = (1 == $GLOBALS['xoopsModuleConfig']['email_digest']) ? 60 * 60 * 24 : 60 * 60 * 24 * 7;
230
        $time_diff = time() - $this->last_digest;
231
232
        return $time_diff - $deadline;
233
    }
234
235
    /**
236
     * @param  XoopsObject $digest
237
     * @param  bool        $force  flag to force the query execution despite security settings
238
     * @return mixed       object ID or false
239
     */
240
    public function insert(XoopsObject $digest, $force = true)
241
    {
242
        return parent::insert($digest, $force);
243
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% 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...
244
        $content = $digest->getVar('digest_content', 'E');
245
246
        $id  = $this->db->genId($digest->table . '_digest_id_seq');
247
        $sql = 'INSERT INTO ' . $digest->table . ' (digest_id, digest_time, digest_content)    VALUES (' . $id . ', ' . time() . ', ' . $this->db->quoteString($content) . ' )';
248
249
        if (!$this->db->queryF($sql)) {
250
            //echo "<br>digest insert error::" . $sql;
251
            return false;
252
        }
253
        if (empty($id)) {
254
            $id = $this->db->getInsertId();
255
        }
256
        $digest->setVar('digest_id', $id);
257
258
        return true;
259
        */
260
    }
261
262
    /**
263
     * @param  XoopsObject $digest
264
     * @param  bool        $force (ignored)
265
     * @return bool        FALSE if failed.
266
     */
267
    public function delete(XoopsObject $digest, $force = false)
268
    {
269
        $digest_id = $digest->getVar('digest_id');
270
271
        if (!isset($this->last_digest)) {
272
            $this->getLastDigest();
273
        }
274
        if ($this->last_digest == $digest_id) {
275
            return false;
276
        } // It is not allowed to delete the last digest
277
278
        return parent::delete($digest, true);
279
    }
280
281
    /**
282
     * @param  XoopsObject|\Digest $digest
283
     * @return bool
284
     */
285
    public function buildDigest(XoopsObject $digest)
0 ignored issues
show
Coding Style introduced by
buildDigest uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
286
    {
287
        global $xoopsModule;
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...
288
289
        if (!defined('SUMMARY_LENGTH')) {
290
            define('SUMMARY_LENGTH', 100);
291
        }
292
293
        /** @var \NewbbForumHandler $forumHandler */
294
        $forumHandler         = xoops_getModuleHandler('forum', 'newbb');
295
        $thisUser             = $GLOBALS['xoopsUser'];
296
        $GLOBALS['xoopsUser'] = null; // To get posts accessible by anonymous
297
        $GLOBALS['xoopsUser'] = $thisUser;
298
299
        $accessForums    = $forumHandler->getIdsByPermission(); // get all accessible forums
300
        $forumCriteria   = ' AND t.forum_id IN (' . implode(',', $accessForums) . ')';
301
        $approveCriteria = ' AND t.approved = 1 AND p.approved = 1';
302
        $time_criteria   = ' AND t.digest_time > ' . $this->last_digest;
303
304
        $karma_criteria = $GLOBALS['xoopsModuleConfig']['enable_karma'] ? ' AND p.post_karma=0' : '';
305
        $reply_criteria = $GLOBALS['xoopsModuleConfig']['allow_require_reply'] ? ' AND p.require_reply=0' : '';
306
307
        $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 '
308
                 . $this->db->prefix('newbb_topics')
309
                 . ' t, '
310
                 . $this->db->prefix('newbb_posts_text')
311
                 . ' pt, '
312
                 . $this->db->prefix('newbb_posts')
313
                 . ' p WHERE t.topic_digest = 1 AND p.topic_id=t.topic_id AND p.pid=0 '
314
                 . $forumCriteria
315
                 . $approveCriteria
316
                 . $time_criteria
317
                 . $karma_criteria
318
                 . $reply_criteria
319
                 . ' AND pt.post_id=p.post_id ORDER BY t.digest_time DESC';
320
        if (!$result = $this->db->query($query)) {
321
            //echo "<br>No result:<br>$query";
322
            return false;
323
        }
324
        $rows  = [];
325
        $users = [];
326
        while ($row = $this->db->fetchArray($result)) {
327
            $users[$row['uid']] = 1;
328
            $rows[]             = $row;
329
        }
330
        if (count($rows) < 1) {
331
            return false;
332
        }
333
        $uids = array_keys($users);
334
        if (count($uids) > 0) {
335
            /** @var \XoopsMemberHandler $memberHandler */
336
            $memberHandler = xoops_getHandler('member');
337
            $user_criteria = new Criteria('uid', '(' . implode(',', $uids) . ')', 'IN');
338
            $users         = $memberHandler->getUsers($user_criteria, true);
339
        } else {
340
            $users = [];
341
        }
342
343
        foreach ($rows as $topic) {
344
            if ($topic['uid'] > 0) {
345
                if (isset($users[$topic['uid']]) && is_object($users[$topic['uid']])
346
                    && $users[$topic['uid']]->isActive()) {
347
                    $topic['uname'] = $users[$topic['uid']]->getVar('uname');
348
                } else {
349
                    $topic['uname'] = $GLOBALS['xoopsConfig']['anonymous'];
350
                }
351
            } else {
352
                $topic['uname'] = $topic['poster_name'] ?: $GLOBALS['xoopsConfig']['anonymous'];
353
            }
354
            $summary = \Xmf\Metagen::generateDescription($topic['post_text'], SUMMARY_LENGTH);
355
            $author  = $topic['uname'] . ' (' . formatTimestamp($topic['topic_time']) . ')';
356
            $link    = XOOPS_URL . '/modules/' . $xoopsModule->dirname() . '/viewtopic.php?topic_id=' . $topic['topic_id'] . '&amp;forum=' . $topic['forum_id'];
357
            $title   = $topic['topic_title'];
358
            $digest->addItem($title, $link, $author, $summary);
359
        }
360
        $digest->buildContent();
361
362
        return true;
363
    }
364
}
365