Passed
Pull Request — master (#18)
by Michael
02:59
created

PostHandler::_delete()   F

Complexity

Conditions 25
Paths 822

Size

Total Lines 103
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 62
c 0
b 0
f 0
nc 822
nop 2
dl 0
loc 103
rs 0.2472

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Newbb module
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright       XOOPS Project (https://xoops.org)
13
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
14
 * @package         newbb
15
 * @since           4.0
16
 * @author          Taiwen Jiang <[email protected]>
17
 */
18
19
use XoopsModules\Newbb;
20
use XoopsModules\Xoopspoll;
21
22
 /**
23
 * Class post
24
 */
25
class Post extends \XoopsObject
26
{
27
    public $attachment_array = [];
28
29
    /**
30
     * Post constructor.
31
     */
32
    public function __construct()
33
    {
34
        //$this->ArtObject("bb_posts");
35
        $this->initVar('post_id', XOBJ_DTYPE_INT);
36
        $this->initVar('topic_id', XOBJ_DTYPE_INT, 0, true);
37
        $this->initVar('forum_id', XOBJ_DTYPE_INT, 0, true);
38
        $this->initVar('post_time', XOBJ_DTYPE_INT, 0, true);
39
        $this->initVar('poster_ip', XOBJ_DTYPE_INT, 0);
40
        $this->initVar('poster_name', XOBJ_DTYPE_TXTBOX, '');
41
        $this->initVar('subject', XOBJ_DTYPE_TXTBOX, '', true);
42
        $this->initVar('pid', XOBJ_DTYPE_INT, 0);
43
        $this->initVar('dohtml', XOBJ_DTYPE_INT, 0);
44
        $this->initVar('dosmiley', XOBJ_DTYPE_INT, 1);
45
        $this->initVar('doxcode', XOBJ_DTYPE_INT, 1);
46
        $this->initVar('doimage', XOBJ_DTYPE_INT, 1);
47
        $this->initVar('dobr', XOBJ_DTYPE_INT, 1);
48
        $this->initVar('uid', XOBJ_DTYPE_INT, 1);
49
        $this->initVar('icon', XOBJ_DTYPE_TXTBOX, '');
50
        $this->initVar('attachsig', XOBJ_DTYPE_INT, 0);
51
        $this->initVar('approved', XOBJ_DTYPE_INT, 1);
52
        $this->initVar('post_karma', XOBJ_DTYPE_INT, 0);
53
        $this->initVar('require_reply', XOBJ_DTYPE_INT, 0);
54
        $this->initVar('attachment', XOBJ_DTYPE_TXTAREA, '');
55
        $this->initVar('post_text', XOBJ_DTYPE_TXTAREA, '');
56
        $this->initVar('post_edit', XOBJ_DTYPE_TXTAREA, '');
57
    }
58
59
    // ////////////////////////////////////////////////////////////////////////////////////
60
    // attachment functions    TODO: there should be a file/attachment management class
61
62
    /**
63
     * @return array|mixed|null
64
     */
65
    public function getAttachment()
66
    {
67
        if (count($this->attachment_array)) {
68
            return $this->attachment_array;
69
        }
70
        $attachment = $this->getVar('attachment');
71
        if (empty($attachment)) {
72
            $this->attachment_array = null;
73
        } else {
74
            $this->attachment_array = @unserialize(base64_decode($attachment, true));
0 ignored issues
show
Bug introduced by
It seems like $attachment can also be of type array and array; however, parameter $data of base64_decode() 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

74
            $this->attachment_array = @unserialize(base64_decode(/** @scrutinizer ignore-type */ $attachment, true));
Loading history...
75
        }
76
77
        return $this->attachment_array;
78
    }
79
80
    /**
81
     * @param $attach_key
82
     * @return bool
83
     */
84
    public function incrementDownload($attach_key)
85
    {
86
        if (!$attach_key) {
87
            return false;
88
        }
89
        $this->attachment_array[(string)$attach_key]['num_download']++;
90
91
        return $this->attachment_array[(string)$attach_key]['num_download'];
92
    }
93
94
    /**
95
     * @return bool
96
     */
97
    public function saveAttachment()
98
    {
99
        $attachment_save = '';
100
        if ($this->attachment_array && is_array($this->attachment_array)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->attachment_array of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
101
            $attachment_save = base64_encode(serialize($this->attachment_array));
102
        }
103
        $this->setVar('attachment', $attachment_save);
104
        $sql = 'UPDATE ' . $GLOBALS['xoopsDB']->prefix('bb_posts') . ' SET attachment=' . $GLOBALS['xoopsDB']->quoteString($attachment_save) . ' WHERE post_id = ' . $this->getVar('post_id');
105
        if (!$result = $GLOBALS['xoopsDB']->queryF($sql)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
106
            //xoops_error($GLOBALS['xoopsDB']->error());
107
            return false;
108
        }
109
110
        return true;
111
    }
112
113
    /**
114
     * @param null $attach_array
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $attach_array is correct as it would always require null to be passed?
Loading history...
115
     * @return bool
116
     */
117
    public function deleteAttachment($attach_array = null)
118
    {
119
        /** @var Xoopspoll\Helper $helper */
120
        $helper = Xoopspoll\Helper::getInstance();
121
122
        $attach_old = $this->getAttachment();
123
        if (!is_array($attach_old) || count($attach_old) < 1) {
124
            return true;
125
        }
126
        $this->attachment_array = [];
127
128
        if (null === $attach_array) {
0 ignored issues
show
introduced by
The condition null === $attach_array is always true.
Loading history...
129
            $attach_array = array_keys($attach_old);
130
        } // to delete all!
131
        if (!is_array($attach_array)) {
0 ignored issues
show
introduced by
The condition is_array($attach_array) is always true.
Loading history...
132
            $attach_array = [$attach_array];
133
        }
134
135
        foreach ($attach_old as $key => $attach) {
136
            if (in_array($key, $attach_array)) {
137
                @unlink(XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments') . '/' . $attach['name_saved']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

137
                /** @scrutinizer ignore-unhandled */ @unlink(XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments') . '/' . $attach['name_saved']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
138
                @unlink(XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments') . '/thumbs/' . $attach['name_saved']); // delete thumbnails
139
                continue;
140
            }
141
            $this->attachment_array[$key] = $attach;
142
        }
143
        $attachment_save = '';
144
        if ($this->attachment_array && is_array($this->attachment_array)) {
145
            $attachment_save = base64_encode(serialize($this->attachment_array));
146
        }
147
        $this->setVar('attachment', $attachment_save);
148
149
        return true;
150
    }
151
152
    /**
153
     * @param string $name_saved
154
     * @param string $name_display
155
     * @param string $mimetype
156
     * @param int    $num_download
157
     * @return bool
158
     */
159
    public function setAttachment($name_saved = '', $name_display = '', $mimetype = '', $num_download = 0)
160
    {
161
        static $counter = 0;
162
        $this->attachment_array = $this->getAttachment();
163
        if ($name_saved) {
164
            $key                          = (string)(time() + $counter++);
165
            $this->attachment_array[$key] = [
166
                'name_saved'   => $name_saved,
167
                'name_display' => isset($name_display) ? $name_display : $name_saved,
168
                'mimetype'     => $mimetype,
169
                'num_download' => isset($num_download) ? (int)$num_download : 0,
170
            ];
171
        }
172
        $attachment_save = null;
173
        if (is_array($this->attachment_array)) {
174
            $attachment_save = base64_encode(serialize($this->attachment_array));
175
        }
176
        $this->setVar('attachment', $attachment_save);
177
178
        return true;
179
    }
180
181
    /**
182
     * TODO: refactor
183
     * @param bool $asSource
184
     * @return string
185
     */
186
    public function displayAttachment($asSource = false)
0 ignored issues
show
Unused Code introduced by
The parameter $asSource is not used and could be removed. ( Ignorable by Annotation )

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

186
    public function displayAttachment(/** @scrutinizer ignore-unused */ $asSource = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
187
    {
188
        global $xoopsModule;
189
        /** @var Xoopspoll\Helper $helper */
190
        $helper = Xoopspoll\Helper::getInstance();
191
192
        $post_attachment = '';
193
        $attachments     = $this->getAttachment();
194
        if ($attachments && is_array($attachments)) {
195
            $iconHandler = newbb_getIconHandler();
0 ignored issues
show
Bug introduced by
The function newbb_getIconHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

195
            $iconHandler = /** @scrutinizer ignore-call */ newbb_getIconHandler();
Loading history...
196
            $mime_path   = $iconHandler->getPath('mime');
197
            require_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname', 'n') . '/include/functions.image.php';
198
            $image_extensions = ['jpg', 'jpeg', 'gif', 'png', 'bmp']; // need improve !!!
199
            $post_attachment  .= '<br><strong>' . _MD_ATTACHMENT . '</strong>:';
200
            $post_attachment  .= '<br><hr size="1" noshade="noshade"><br>';
201
            foreach ($attachments as $key => $att) {
202
                $file_extension = ltrim(mb_strrchr($att['name_saved'], '.'), '.');
203
                $filetype       = $file_extension;
204
                if (file_exists(XOOPS_ROOT_PATH . '/' . $mime_path . '/' . $filetype . '.gif')) {
205
                    $icon_filetype = XOOPS_URL . '/' . $mime_path . '/' . $filetype . '.gif';
206
                } else {
207
                    $icon_filetype = XOOPS_URL . '/' . $mime_path . '/unknown.gif';
208
                }
209
                $file_size = @filesize(XOOPS_ROOT_PATH . '/' . $helper->getConfig('dir_attachments') . '/' . $att['name_saved']);
210
                $file_size = number_format($file_size / 1024, 2) . ' KB';
211
                if (in_array(mb_strtolower($file_extension), $image_extensions) && $helper->getConfig('media_allowed')) {
212
                    $post_attachment .= '<br><img src="' . $icon_filetype . '" alt="' . $filetype . '"><strong>&nbsp; ' . $att['name_display'] . '</strong> <small>(' . $file_size . ')</small>';
213
                    $post_attachment .= '<br>' . newbb_attachmentImage($att['name_saved']);
0 ignored issues
show
Bug introduced by
The function newbb_attachmentImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

213
                    $post_attachment .= '<br>' . /** @scrutinizer ignore-call */ newbb_attachmentImage($att['name_saved']);
Loading history...
214
                    $isDisplayed     = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $isDisplayed is dead and can be removed.
Loading history...
215
                } else {
216
                    $post_attachment .= '<a href="'
217
                                        . XOOPS_URL
218
                                        . '/modules/'
219
                                        . $xoopsModule->getVar('dirname', 'n')
220
                                        . '/dl_attachment.php?attachid='
221
                                        . $key
222
                                        . '&amp;post_id='
223
                                        . $this->getVar('post_id')
224
                                        . '"> <img src="'
225
                                        . $icon_filetype
226
                                        . '" alt="'
227
                                        . $filetype
228
                                        . '"> '
229
                                        . $att['name_display']
230
                                        . '</a> '
231
                                        . _MD_FILESIZE
232
                                        . ': '
233
                                        . $file_size
234
                                        . '; '
235
                                        . _MD_HITS
236
                                        . ': '
237
                                        . $att['num_download'];
238
                }
239
                $post_attachment .= '<br>';
240
            }
241
        }
242
243
        return $post_attachment;
244
    }
245
246
    // attachment functions
247
    // ////////////////////////////////////////////////////////////////////////////////////
248
249
    /**
250
     * @param string $poster_name
251
     * @return bool
252
     */
253
    public function setPostEdit($poster_name = '')
0 ignored issues
show
Unused Code introduced by
The parameter $poster_name is not used and could be removed. ( Ignorable by Annotation )

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

253
    public function setPostEdit(/** @scrutinizer ignore-unused */ $poster_name = '')

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
254
    {
255
        global $xoopsUser;
256
        /** @var Xoopspoll\Helper $helper */
257
        $helper = Xoopspoll\Helper::getInstance();
258
259
        if (empty($helper->getConfig('recordedit_timelimit'))
260
            || (time() - $this->getVar('post_time')) < $helper->getConfig('recordedit_timelimit') * 60
261
            || $this->getVar('approved') < 1) {
262
            return true;
263
        }
264
        if (is_object($xoopsUser) && $xoopsUser->isActive()) {
265
            if ($helper->getConfig('show_realname') && $xoopsUser->getVar('name')) {
266
                $edit_user = $xoopsUser->getVar('name');
267
            } else {
268
                $edit_user = $xoopsUser->getVar('uname');
269
            }
270
        }
271
        $post_edit              = [];
272
        $post_edit['edit_user'] = $edit_user; // The proper way is to store uid instead of name. However, to save queries when displaying, the current way is ok.
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $edit_user does not seem to be defined for all execution paths leading up to this point.
Loading history...
273
        $post_edit['edit_time'] = time();
274
275
        $post_edits = $this->getVar('post_edit');
276
        if (!empty($post_edits)) {
277
            $post_edits = unserialize(base64_decode($post_edits, true));
0 ignored issues
show
Bug introduced by
It seems like $post_edits can also be of type array and array; however, parameter $data of base64_decode() 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

277
            $post_edits = unserialize(base64_decode(/** @scrutinizer ignore-type */ $post_edits, true));
Loading history...
278
        }
279
        if (!is_array($post_edits)) {
280
            $post_edits = [];
281
        }
282
        $post_edits[] = $post_edit;
283
        $post_edit    = base64_encode(serialize($post_edits));
284
        unset($post_edits);
285
        $this->setVar('post_edit', $post_edit);
286
287
        return true;
288
    }
289
290
    /**
291
     * @return bool|string
292
     */
293
    public function displayPostEdit()
294
    {
295
        global $myts;
296
        /** @var Xoopspoll\Helper $helper */
297
        $helper = Xoopspoll\Helper::getInstance();
298
299
        if (empty($helper->getConfig('recordedit_timelimit'))) {
300
            return false;
301
        }
302
303
        $post_edit  = '';
304
        $post_edits = $this->getVar('post_edit');
305
        if (!empty($post_edits)) {
306
            $post_edits = unserialize(base64_decode($post_edits, true));
0 ignored issues
show
Bug introduced by
It seems like $post_edits can also be of type array and array; however, parameter $data of base64_decode() 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

306
            $post_edits = unserialize(base64_decode(/** @scrutinizer ignore-type */ $post_edits, true));
Loading history...
307
        }
308
        if (!isset($post_edits) || !is_array($post_edits)) {
309
            $post_edits = [];
310
        }
311
        if ($post_edits && is_array($post_edits)) {
312
            foreach ($post_edits as $postedit) {
313
                $edit_time = (int)$postedit['edit_time'];
314
                $edit_user = $myts->stripSlashesGPC($postedit['edit_user']);
315
                $post_edit .= _MD_EDITEDBY . ' ' . $edit_user . ' ' . _MD_ON . ' ' . formatTimestamp($edit_time) . '<br>';
316
            }
317
        }
318
319
        return $post_edit;
320
    }
321
322
    /**
323
     * @return array
324
     */
325
    public function &getPostBody()
326
    {
327
        global $xoopsConfig, $xoopsUser, $myts;
328
        /** @var Xoopspoll\Helper $helper */
329
        $helper = Xoopspoll\Helper::getInstance();
330
331
        require_once XOOPS_ROOT_PATH . '/modules/newbb/include/functions.user.php';
332
        require_once XOOPS_ROOT_PATH . '/modules/newbb/include/functions.render.php';
333
334
        $uid          = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
335
        $karmaHandler = Newbb\Helper::getInstance()->getHandler('Karma');
336
        $user_karma   = $karmaHandler->getUserKarma();
0 ignored issues
show
Bug introduced by
The method getUserKarma() 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

336
        /** @scrutinizer ignore-call */ 
337
        $user_karma   = $karmaHandler->getUserKarma();
Loading history...
337
338
        $post               = [];
339
        $post['attachment'] = false;
340
        $post_text          = &newbb_displayTarea($this->vars['post_text']['value'], $this->getVar('dohtml'), $this->getVar('dosmiley'), $this->getVar('doxcode'), $this->getVar('doimage'), $this->getVar('dobr'));
0 ignored issues
show
Bug introduced by
The function newbb_displayTarea was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

340
        $post_text          = &/** @scrutinizer ignore-call */ newbb_displayTarea($this->vars['post_text']['value'], $this->getVar('dohtml'), $this->getVar('dosmiley'), $this->getVar('doxcode'), $this->getVar('doimage'), $this->getVar('dobr'));
Loading history...
341
        if (newbb_isAdmin($this->getVar('forum_id')) || $this->checkIdentity()) {
0 ignored issues
show
Bug introduced by
The function newbb_isAdmin was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

341
        if (/** @scrutinizer ignore-call */ newbb_isAdmin($this->getVar('forum_id')) || $this->checkIdentity()) {
Loading history...
342
            $post['text'] = $post_text . '<br>' . $this->displayAttachment();
343
        } elseif ($helper->getConfig('enable_karma') && $this->getVar('post_karma') > $user_karma) {
344
            $post['text'] = sprintf(_MD_KARMA_REQUIREMENT, $user_karma, $this->getVar('post_karma'));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('post_karma') can also be of type array and array; however, parameter $args of sprintf() 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

344
            $post['text'] = sprintf(_MD_KARMA_REQUIREMENT, $user_karma, /** @scrutinizer ignore-type */ $this->getVar('post_karma'));
Loading history...
345
        } elseif ($helper->getConfig('allow_require_reply') && $this->getVar('require_reply')
346
                  && (!$uid
347
                      || !isset($viewtopic_users[$uid]))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viewtopic_users seems to never exist and therefore isset should always be false.
Loading history...
348
            $post['text'] = _MD_REPLY_REQUIREMENT;
349
        } else {
350
            $post['text'] = $post_text . '<br>' . $this->displayAttachment();
351
        }
352
        $memberHandler = xoops_getHandler('member');
353
        $eachposter    = $memberHandler->getUser($this->getVar('uid'));
0 ignored issues
show
Bug introduced by
The method getUser() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsAvatarHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

353
        /** @scrutinizer ignore-call */ 
354
        $eachposter    = $memberHandler->getUser($this->getVar('uid'));
Loading history...
354
        if (is_object($eachposter) && $eachposter->isActive()) {
355
            if ($helper->getConfig('show_realname') && $eachposter->getVar('name')) {
356
                $post['author'] = $eachposter->getVar('name');
357
            } else {
358
                $post['author'] = $eachposter->getVar('uname');
359
            }
360
            unset($eachposter);
361
        } else {
362
            $post['author'] = $this->getVar('poster_name') ?: $xoopsConfig['anonymous'];
363
        }
364
365
        $post['subject'] = newbb_htmlspecialchars($this->vars['subject']['value']);
0 ignored issues
show
Bug introduced by
The function newbb_htmlspecialchars was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

365
        $post['subject'] = /** @scrutinizer ignore-call */ newbb_htmlspecialchars($this->vars['subject']['value']);
Loading history...
366
367
        $post['date'] = $this->getVar('post_time');
368
369
        return $post;
370
    }
371
372
    /**
373
     * @return bool
374
     */
375
    public function isTopic()
376
    {
377
        return !$this->getVar('pid');
378
    }
379
380
    /**
381
     * @param string $action_tag
382
     * @return bool
383
     */
384
    public function checkTimelimit($action_tag = 'edit_timelimit')
385
    {
386
        require_once XOOPS_ROOT_PATH . '/modules/newbb/include/functions.config.php';
387
        $newbb_config = newbb_loadConfig();
0 ignored issues
show
Bug introduced by
The function newbb_loadConfig was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

387
        $newbb_config = /** @scrutinizer ignore-call */ newbb_loadConfig();
Loading history...
388
        if (empty($newbb_config['edit_timelimit'])) {
389
            return true;
390
        }
391
392
        return ($this->getVar('post_time') > time() - $newbb_config[$action_tag] * 60);
393
    }
394
395
    /**
396
     * @param int $uid
397
     * @return bool
398
     */
399
    public function checkIdentity($uid = -1)
400
    {
401
        global $xoopsUser;
402
403
        $uid = ($uid > -1) ? $uid : (is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0);
404
        if ($this->getVar('uid') > 0) {
405
            $user_ok = $uid == $this->getVar('uid');
406
        } else {
407
            static $user_ip;
408
            if (!isset($user_ip)) {
409
                $user_ip = newbb_getIP();
0 ignored issues
show
Bug introduced by
The function newbb_getIP was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

409
                $user_ip = /** @scrutinizer ignore-call */ newbb_getIP();
Loading history...
410
            }
411
            $user_ok = $user_ip == $this->getVar('poster_ip');
412
        }
413
414
        return $user_ok;
415
    }
416
417
    // TODO: cleaning up and merge with post hanldings in viewpost.php
418
419
    /**
420
     * @param $isadmin
421
     * @return array
422
     */
423
    public function showPost($isadmin)
424
    {
425
        global $xoopsConfig, $xoopsModule, $xoopsUser, $myts;
426
        /** @var Xoopspoll\Helper $helper */
427
        $helper = Xoopspoll\Helper::getInstance();
428
429
        global $forumUrl, $forumImage;
430
        global $viewtopic_users, $viewtopic_posters, $forum_obj, $topic_obj, $online, $user_karma, $viewmode, $order, $start, $total_posts, $topic_status;
431
        static $post_NO = 0;
432
        static $name_anonymous;
433
434
        if (!isset($name_anonymous)) {
435
            $name_anonymous = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
436
        }
437
438
        require_once XOOPS_ROOT_PATH . '/modules/newbb/include/functions.time.php';
439
        require_once XOOPS_ROOT_PATH . '/modules/newbb/include/functions.render.php';
440
441
        $post_id  = $this->getVar('post_id');
442
        $topic_id = $this->getVar('topic_id');
443
        $forum_id = $this->getVar('forum_id');
444
445
        $query_vars              = ['status', 'order', 'start', 'mode', 'viewmode'];
446
        $query_array             = [];
447
        $query_array['topic_id'] = "topic_id={$topic_id}";
448
        foreach ($query_vars as $var) {
449
            if (!empty($_GET[$var])) {
450
                $query_array[$var] = "{$var}={$_GET[$var]}";
451
            }
452
        }
453
        $page_query = htmlspecialchars(implode('&', array_values($query_array)), ENT_QUOTES | ENT_HTML5);
454
455
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
456
457
        ++$post_NO;
458
        if ('desc' === mb_strtolower($order)) {
459
            $post_no = $total_posts - ($start + $post_NO) + 1;
460
        } else {
461
            $post_no = $start + $post_NO;
462
        }
463
464
        if ($isadmin || $this->checkIdentity()) {
465
            $post_text       = $this->getVar('post_text');
466
            $post_attachment = $this->displayAttachment();
467
        } elseif ($helper->getConfig('enable_karma') && $this->getVar('post_karma') > $user_karma) {
468
            $post_text       = "<div class='karma'>" . sprintf(_MD_KARMA_REQUIREMENT, $user_karma, $this->getVar('post_karma')) . '</div>';
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('post_karma') can also be of type array and array; however, parameter $args of sprintf() 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

468
            $post_text       = "<div class='karma'>" . sprintf(_MD_KARMA_REQUIREMENT, $user_karma, /** @scrutinizer ignore-type */ $this->getVar('post_karma')) . '</div>';
Loading history...
469
            $post_attachment = '';
470
        } elseif ($helper->getConfig('allow_require_reply') && $this->getVar('require_reply')
471
                  && (!$uid
472
                      || !in_array($uid, $viewtopic_posters))) {
473
            $post_text       = "<div class='karma'>" . _MD_REPLY_REQUIREMENT . '</div>';
474
            $post_attachment = '';
475
        } else {
476
            $post_text       = $this->getVar('post_text');
477
            $post_attachment = $this->displayAttachment();
478
        }
479
        if (isset($viewtopic_users[$this->getVar('uid')])) {
480
            $poster = $viewtopic_users[$this->getVar('uid')];
481
        } else {
482
            $name   = ($post_name = $this->getVar('poster_name')) ? $post_name : $name_anonymous;
483
            $poster = [
484
                'poster_uid' => 0,
485
                'name'       => $name,
486
                'link'       => $name,
487
            ];
488
        }
489
490
        $posticon = $this->getVar('icon');
491
        if ($posticon) {
492
            $post_image = '<a name="' . $post_id . '"><img src="' . XOOPS_URL . '/images/subject/' . $posticon . '" alt=""></a>';
493
        } else {
494
            $post_image = '<a name="' . $post_id . '"><img src="' . XOOPS_URL . '/images/icons/posticon.gif" alt=""></a>';
495
        }
496
497
        $thread_buttons = [];
498
499
        if ($GLOBALS['xoopsModuleConfig']['enable_permcheck']) {
500
            /** @var Newbb\TopicHandler $topicHandler */
501
            $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
502
            $topic_status = $topic_obj->getVar('topic_status');
503
            if ($topicHandler->getPermission($forum_id, $topic_status, 'edit')) {
504
                $edit_ok = ($isadmin || ($this->checkIdentity() && $this->checkTimelimit('edit_timelimit')));
505
506
                if ($edit_ok) {
507
                    $thread_buttons['edit']['image'] = newbb_displayImage('p_edit', _EDIT);
0 ignored issues
show
Bug introduced by
The function newbb_displayImage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

507
                    $thread_buttons['edit']['image'] = /** @scrutinizer ignore-call */ newbb_displayImage('p_edit', _EDIT);
Loading history...
508
                    $thread_buttons['edit']['link']  = "edit.php?{$page_query}";
509
                    $thread_buttons['edit']['name']  = _EDIT;
510
                }
511
            }
512
513
            if ($topicHandler->getPermission($forum_id, $topic_status, 'delete')) {
514
                $delete_ok = ($isadmin || ($this->checkIdentity() && $this->checkTimelimit('delete_timelimit')));
515
516
                if ($delete_ok) {
517
                    $thread_buttons['delete']['image'] = newbb_displayImage('p_delete', _DELETE);
518
                    $thread_buttons['delete']['link']  = "delete.php?{$page_query}";
519
                    $thread_buttons['delete']['name']  = _DELETE;
520
                }
521
            }
522
            if ($topicHandler->getPermission($forum_id, $topic_status, 'reply')) {
523
                $thread_buttons['reply']['image'] = newbb_displayImage('p_reply', _MD_REPLY);
524
                $thread_buttons['reply']['link']  = "reply.php?{$page_query}";
525
                $thread_buttons['reply']['name']  = _MD_REPLY;
526
527
                $thread_buttons['quote']['image'] = newbb_displayImage('p_quote', _MD_QUOTE);
528
                $thread_buttons['quote']['link']  = "reply.php?{$page_query}&amp;quotedac=1";
529
                $thread_buttons['quote']['name']  = _MD_QUOTE;
530
            }
531
        } else {
532
            $thread_buttons['edit']['image'] = newbb_displayImage('p_edit', _EDIT);
533
            $thread_buttons['edit']['link']  = "edit.php?{$page_query}";
534
            $thread_buttons['edit']['name']  = _EDIT;
535
536
            $thread_buttons['delete']['image'] = newbb_displayImage('p_delete', _DELETE);
537
            $thread_buttons['delete']['link']  = "delete.php?{$page_query}";
538
            $thread_buttons['delete']['name']  = _DELETE;
539
540
            $thread_buttons['reply']['image'] = newbb_displayImage('p_reply', _MD_REPLY);
541
            $thread_buttons['reply']['link']  = "reply.php?{$page_query}";
542
            $thread_buttons['reply']['name']  = _MD_REPLY;
543
        }
544
545
        if (!$isadmin && $helper->getConfig('reportmod_enabled')) {
546
            $thread_buttons['report']['image'] = newbb_displayImage('p_report', _MD_REPORT);
547
            $thread_buttons['report']['link']  = "report.php?{$page_query}";
548
            $thread_buttons['report']['name']  = _MD_REPORT;
549
        }
550
551
        $thread_action = [];
552
553
        $post = [
554
            'post_id'         => $post_id,
555
            'post_parent_id'  => $this->getVar('pid'),
556
            'post_date'       => newbb_formatTimestamp($this->getVar('post_time')),
0 ignored issues
show
Bug introduced by
The function newbb_formatTimestamp was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

556
            'post_date'       => /** @scrutinizer ignore-call */ newbb_formatTimestamp($this->getVar('post_time')),
Loading history...
557
            'post_image'      => $post_image,
558
            'post_title'      => $this->getVar('subject'),
559
            'post_text'       => $post_text,
560
            'post_attachment' => $post_attachment,
561
            'post_edit'       => $this->displayPostEdit(),
562
            'post_no'         => $post_no,
563
            'post_signature'  => $this->getVar('attachsig') ? @$poster['signature'] : '',
564
            'poster_ip'       => ($isadmin && $helper->getConfig('show_ip')) ? long2ip($this->getVar('poster_ip')) : '',
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('poster_ip') can also be of type array and array; however, parameter $proper_address of long2ip() does only seem to accept integer|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

564
            'poster_ip'       => ($isadmin && $helper->getConfig('show_ip')) ? long2ip(/** @scrutinizer ignore-type */ $this->getVar('poster_ip')) : '',
Loading history...
565
            'thread_action'   => $thread_action,
566
            'thread_buttons'  => $thread_buttons,
567
            'poster'          => $poster,
568
        ];
569
570
        unset($thread_buttons, $eachposter);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $eachposter does not exist. Did you maybe mean $poster?
Loading history...
571
572
        return $post;
573
    }
574
}
575
576
/**
577
 * Class PostHandler
578
 */
579
class PostHandler extends \XoopsPersistableObjectHandler
580
{
581
    /**
582
     * @param null|\XoopsDatabase $db
583
     */
584
    public function __construct(\XoopsDatabase $db = null)
585
    {
586
        parent::__construct($db, 'bb_posts', 'Post', 'post_id', 'subject');
587
    }
588
589
    /**
590
     * @param mixed|null $id
591
     * @param null       $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
592
     * @return null|\XoopsObject
593
     */
594
    public function get($id = null, $fields = null)
595
    {
596
        $id    = (int)$id;
597
        $post  = null;
598
        $sql   = 'SELECT p.*, t.* FROM ' . $this->db->prefix('bb_posts') . ' p LEFT JOIN ' . $this->db->prefix('bb_posts_text') . ' t ON p.post_id=t.post_id WHERE p.post_id=' . $id;
599
        $array = $this->db->fetchArray($this->db->query($sql));
600
        if ($array) {
601
            $post = $this->create(false);
602
            $post->assignVars($array);
603
        }
604
605
        return $post;
606
    }
607
608
    /**
609
     * @param int $topic_id
610
     * @param int $limit
611
     * @param int $approved
612
     * @return array
613
     */
614
    public function &getByLimit($topic_id, $limit, $approved = 1)
615
    {
616
        $sql    = 'SELECT p.*, t.*, tp.topic_status FROM '
617
                  . $this->db->prefix('bb_posts')
618
                  . ' p LEFT JOIN '
619
                  . $this->db->prefix('bb_posts_text')
620
                  . ' t ON p.post_id=t.post_id LEFT JOIN '
621
                  . $this->db->prefix('bb_topics')
622
                  . ' tp ON tp.topic_id=p.topic_id WHERE p.topic_id='
623
                  . $topic_id
624
                  . ' AND p.approved ='
625
                  . $approved
626
                  . ' ORDER BY p.post_time DESC';
627
        $result = $this->db->query($sql, $limit, 0);
628
        $ret    = [];
629
        while (false !== ($myrow = $this->db->fetchArray($result))) {
630
            $post = $this->create(false);
631
            $post->assignVars($myrow);
632
633
            $ret[$myrow['post_id']] = $post;
634
            unset($post);
635
        }
636
637
        return $ret;
638
    }
639
640
    /**
641
     * @param $post
642
     * @return mixed
643
     */
644
    public function getPostForPDF($post)
645
    {
646
        return $post->getPostBody(true);
647
    }
648
649
    /**
650
     * @param $post
651
     * @return mixed
652
     */
653
    public function getPostForPrint($post)
654
    {
655
        return $post->getPostBody();
656
    }
657
658
    /**
659
     * @param       $post
660
     * @param bool  $force
661
     * @return bool
662
     */
663
    public function approve(&$post, $force = false)
664
    {
665
        if (empty($post)) {
666
            return false;
667
        }
668
        if (is_numeric($post)) {
669
            $post = $this->get($post);
670
        } else {
671
            $post->unsetNew();
672
        }
673
        $post_id     = $post->getVar('post_id');
0 ignored issues
show
Unused Code introduced by
The assignment to $post_id is dead and can be removed.
Loading history...
674
        $wasApproved = $post->getVar('approved');
675
        if (empty($force) && $wasApproved) {
676
            return true;
677
        }
678
        $post->setVar('approved', 1);
679
        $this->insert($post, true);
680
681
        /** @var Newbb\TopicHandler $topicHandler */
682
        $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
683
        $topic_obj    = $topicHandler->get($post->getVar('topic_id'));
684
        if ($topic_obj->getVar('topic_last_post_id') < $post->getVar('post_id')) {
685
            $topic_obj->setVar('topic_last_post_id', $post->getVar('post_id'));
686
        }
687
        if ($post->isTopic()) {
688
            $topic_obj->setVar('approved', 1);
689
        } else {
690
            $topic_obj->setVar('topic_replies', $topic_obj->getVar('topic_replies') + 1);
691
        }
692
        $topicHandler->insert($topic_obj, true);
0 ignored issues
show
Bug introduced by
It seems like $topic_obj can also be of type null; however, parameter $object of XoopsModules\Newbb\TopicHandler::insert() 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

692
        $topicHandler->insert(/** @scrutinizer ignore-type */ $topic_obj, true);
Loading history...
693
694
        /** @var Newbb\ForumHandler $forumHandler */
695
        $forumHandler = Newbb\Helper::getInstance()->getHandler('Forum');
696
        $forum_obj    = $forumHandler->get($post->getVar('forum_id'));
697
        if ($forum_obj->getVar('forum_last_post_id') < $post->getVar('post_id')) {
698
            $forum_obj->setVar('forum_last_post_id', $post->getVar('post_id'));
699
        }
700
        $forum_obj->setVar('forum_posts', $forum_obj->getVar('forum_posts') + 1);
701
        if ($post->isTopic()) {
702
            $forum_obj->setVar('forum_topics', $forum_obj->getVar('forum_topics') + 1);
703
        }
704
        $forumHandler->insert($forum_obj, true);
705
706
        // Update user stats
707
        if ($post->getVar('uid') > 0) {
708
            $memberHandler = xoops_getHandler('member');
709
            $poster        = $memberHandler->getUser($post->getVar('uid'));
710
            if (is_object($poster) && $post->getVar('uid') == $poster->getVar('uid')) {
711
                $poster->setVar('posts', $poster->getVar('posts') + 1);
712
                $res = $memberHandler->insertUser($poster, true);
0 ignored issues
show
Bug introduced by
The method insertUser() does not exist on XoopsObjectHandler. Did you maybe mean insert()? ( Ignorable by Annotation )

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

712
                /** @scrutinizer ignore-call */ 
713
                $res = $memberHandler->insertUser($poster, true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Unused Code introduced by
The assignment to $res is dead and can be removed.
Loading history...
713
                unset($poster);
714
            }
715
        }
716
717
        // Update forum stats
718
        $statsHandler = Newbb\Helper::getInstance()->getHandler('Stats');
719
        $statsHandler->update($post->getVar('forum_id'), 'post');
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

719
        $statsHandler->/** @scrutinizer ignore-call */ 
720
                       update($post->getVar('forum_id'), 'post');
Loading history...
720
        if ($post->isTopic()) {
721
            $statsHandler->update($post->getVar('forum_id'), 'topic');
722
        }
723
724
        return true;
725
    }
726
727
    /**
728
     * @param \XoopsObject $post
729
     * @param bool         $force
730
     * @return bool
731
     */
732
    public function insert(\XoopsObject $post, $force = true)
733
    {
734
        global $xoopsUser;
735
736
        // Set the post time
737
        // The time should be "publish" time. To be adjusted later
738
        if (!$post->getVar('post_time')) {
739
            $post->setVar('post_time', time());
740
        }
741
742
        /** @var Newbb\TopicHandler $topicHandler */
743
        $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
744
        // Verify the topic ID
745
        $topic_id = $post->getVar('topic_id');
746
        if ($topic_id) {
747
            $topic_obj = $topicHandler->get($topic_id);
748
            // Invalid topic OR the topic is no approved and the post is not top post
749
            if (!$topic_obj//    || (!$post->isTopic() && $topic_obj->getVar("approved") < 1)
750
            ) {
751
                return false;
752
            }
753
        }
754
        if (empty($topic_id)) {
755
            $post->setVar('topic_id', 0);
756
            $post->setVar('pid', 0);
757
            $post->setNew();
758
            $topic_obj = $topicHandler->create();
759
        }
760
        $textHandler    = Newbb\Helper::getInstance()->getHandler('Text');
761
        $post_text_vars = ['post_text', 'post_edit', 'dohtml', 'doxcode', 'dosmiley', 'doimage', 'dobr'];
762
        if ($post->isNew()) {
763
            if (!$topic_id = $post->getVar('topic_id')) {
764
                $topic_obj->setVar('topic_title', $post->getVar('subject', 'n'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $topic_obj does not seem to be defined for all execution paths leading up to this point.
Loading history...
765
                $topic_obj->setVar('topic_poster', $post->getVar('uid'));
766
                $topic_obj->setVar('forum_id', $post->getVar('forum_id'));
767
                $topic_obj->setVar('topic_time', $post->getVar('post_time'));
768
                $topic_obj->setVar('poster_name', $post->getVar('poster_name'), true);
769
                $topic_obj->setVar('approved', $post->getVar('approved'), true);
770
                if (!$topic_id = $topicHandler->insert($topic_obj, $force)) {
771
                    $post->deleteAttachment();
0 ignored issues
show
Bug introduced by
The method deleteAttachment() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as Post or XoopsModules\Newbb\Post. ( Ignorable by Annotation )

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

771
                    $post->/** @scrutinizer ignore-call */ 
772
                           deleteAttachment();
Loading history...
772
                    $post->setErrors('insert topic error');
773
774
                    return false;
775
                }
776
                $post->setVar('topic_id', $topic_id);
777
778
                $pid = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $pid is dead and can be removed.
Loading history...
779
                $post->setVar('pid', 0);
780
            } elseif (!$post->getVar('pid')) {
781
                $pid = $topicHandler->getTopPostId($topic_id);
782
                $post->setVar('pid', $pid);
783
            }
784
785
            $text_obj = $textHandler->create();
786
            foreach ($post_text_vars as $key) {
787
                $text_obj->vars[$key] = $post->vars[$key];
788
            }
789
            $post->destroyVars($post_text_vars);
790
            if (!$post_id = parent::insert($post, $force)) {
791
                return false;
792
            }
793
            $text_obj->setVar('post_id', $post_id);
794
            if (!$textHandler->insert($text_obj, $force)) {
795
                $this->delete($post);
796
                $post->setErrors('post text insert error');
797
798
                return false;
799
            }
800
            if ($post->getVar('approved') > 0) {
801
                $this->approve($post, true);
802
            }
803
            $post->setVar('post_id', $post_id);
804
        } else {
805
            if ($post->isTopic()) {
0 ignored issues
show
Bug introduced by
The method isTopic() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as Post or XoopsModules\Newbb\Post. ( Ignorable by Annotation )

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

805
            if ($post->/** @scrutinizer ignore-call */ isTopic()) {
Loading history...
806
                if ($post->getVar('subject') != $topic_obj->getVar('topic_title')) {
807
                    $topic_obj->setVar('topic_title', $post->getVar('subject', 'n'));
808
                }
809
                if ($post->getVar('approved') != $topic_obj->getVar('approved')) {
810
                    $topic_obj->setVar('approved', $post->getVar('approved'));
811
                }
812
                if (!$result = $topicHandler->insert($topic_obj, $force)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
813
                    $post->setErrors('update topic error');
814
815
                    return false;
816
                }
817
            }
818
            $text_obj = $textHandler->get($post->getVar('post_id'));
819
            $text_obj->setDirty();
820
            foreach ($post_text_vars as $key) {
821
                $text_obj->vars[$key] = $post->vars[$key];
822
            }
823
            $post->destroyVars($post_text_vars);
824
            if (!$post_id = parent::insert($post, $force)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $post_id is dead and can be removed.
Loading history...
825
                return false;
826
            }
827
            if (!$textHandler->insert($text_obj, $force)) {
828
                $post->setErrors('update post text error');
829
830
                return false;
831
            }
832
        }
833
834
        return $post->getVar('post_id');
835
    }
836
837
    /**
838
     * @param \XoopsObject $post
839
     * @param bool         $isDeleteOne
840
     * @param bool         $force
841
     * @return bool
842
     */
843
    public function delete(\XoopsObject $post, $isDeleteOne = true, $force = false)
844
    {
845
        if (!is_object($post) || 0 == $post->getVar('post_id')) {
846
            return false;
847
        }
848
        if ($isDeleteOne) {
849
            if ($post->isTopic()) {
850
                $criteria = new \CriteriaCompo(new \Criteria('topic_id', $post->getVar('topic_id')));
0 ignored issues
show
Bug introduced by
It seems like $post->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

850
                $criteria = new \CriteriaCompo(new \Criteria('topic_id', /** @scrutinizer ignore-type */ $post->getVar('topic_id')));
Loading history...
851
                $criteria->add(new \Criteria('approved', 1));
852
                $criteria->add(new \Criteria('pid', 0, '>'));
853
                if ($this->getPostCount($criteria) > 0) {
854
                    return false;
855
                }
856
            }
857
858
            return $this->_delete($post, $force);
859
        }
860
        require_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
861
        $mytree = new \XoopsTree($this->db->prefix('bb_posts'), 'post_id', 'pid');
862
        $arr    = $mytree->getAllChild($post->getVar('post_id'));
863
        for ($i = 0, $iMax = count($arr); $i < $iMax; ++$i) {
0 ignored issues
show
Bug introduced by
It seems like $arr can also be of type mixed; however, parameter $var of count() does only seem to accept Countable|array, 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

863
        for ($i = 0, $iMax = count(/** @scrutinizer ignore-type */ $arr); $i < $iMax; ++$i) {
Loading history...
864
            $childpost = $this->create(false);
865
            $childpost->assignVars($arr[$i]);
866
            $this->_delete($childpost, $force);
867
            unset($childpost);
868
        }
869
        $this->_delete($post, $force);
870
871
        return true;
872
    }
873
874
    /**
875
     * @param       $post
876
     * @param bool  $force
877
     * @return bool
878
     */
879
    public function _delete($post, $force = false)
880
    {
881
        global $xoopsModule;
882
883
        if (!is_object($post) || 0 == $post->getVar('post_id')) {
884
            return false;
885
        }
886
887
        /* Set active post as deleted */
888
        if ($post->getVar('approved') > 0 && empty($force)) {
889
            $sql = 'UPDATE ' . $this->db->prefix('bb_posts') . ' SET approved = -1 WHERE post_id = ' . $post->getVar('post_id');
890
            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...
891
            }
892
            /* delete pending post directly */
893
        } else {
894
            $sql = sprintf('DELETE FROM `%s` WHERE post_id = %u', $this->db->prefix('bb_posts'), $post->getVar('post_id'));
895
            if (!$result = $this->db->queryF($sql)) {
896
                $post->setErrors('delte post error: ' . $sql);
897
898
                return false;
899
            }
900
            $post->deleteAttachment();
901
902
            $sql = sprintf('DELETE FROM `%s` WHERE post_id = %u', $this->db->prefix('bb_posts_text'), $post->getVar('post_id'));
903
            if (!$result = $this->db->queryF($sql)) {
904
                $post->setErrors('Could not remove post text: ' . $sql);
905
906
                return false;
907
            }
908
        }
909
910
        if ($post->isTopic()) {
911
            /** @var Newbb\TopicHandler $topicHandler */
912
            $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
913
            $topic_obj    = $topicHandler->get($post->getVar('topic_id'));
914
            if ($topic_obj instanceof Newbb\Topic) {
915
                if (($topic_obj->getVar('approved') > 0) && empty($force)) {
916
                    $topiccount_toupdate = 1;
0 ignored issues
show
Unused Code introduced by
The assignment to $topiccount_toupdate is dead and can be removed.
Loading history...
917
                    $topic_obj->setVar('approved', -1);
918
                    $topicHandler->insert($topic_obj);
919
                    xoops_notification_deletebyitem($xoopsModule->getVar('mid'), 'thread', $post->getVar('topic_id'));
920
                } else {
921
                    if ($topic_obj->getVar('approved') > 0) {
922
                        xoops_notification_deletebyitem($xoopsModule->getVar('mid'), 'thread', $post->getVar('topic_id'));
923
                    }
924
                    $poll_id = $topic_obj->getVar('poll_id');
925
                    if ($poll_id > 0) {
926
                        /** @var \XoopsModuleHandler $moduleHandler */
927
                        $moduleHandler      = xoops_getHandler('module');
928
                        $poll_moduleHandler = $moduleHandler->getByDirname('xoopspoll');
929
                        if (($poll_moduleHandler instanceof \XoopsModuleHandler) && $poll_moduleHandler->isactive()) {
0 ignored issues
show
Bug introduced by
The method isactive() does not exist on XoopsModuleHandler. ( Ignorable by Annotation )

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

929
                        if (($poll_moduleHandler instanceof \XoopsModuleHandler) && $poll_moduleHandler->/** @scrutinizer ignore-call */ isactive()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
introduced by
$poll_moduleHandler is never a sub-type of XoopsModuleHandler.
Loading history...
930
                            $pollHandler = Xoopspoll\Helper::getInstance()->getHandler('Poll');
931
                            if (false !== $pollHandler->deleteAll(new \Criteria('poll_id', $poll_id, '='))) {
932
                                $optionHandler = Xoopspoll\Helper::getInstance()->getHandler('Option');
933
                                $optionHandler->deleteAll(new \Criteria('poll_id', $poll_id, '='));
934
                                $logHandler = Xoopspoll\Helper::getInstance()->getHandler('Log');
935
                                $logHandler->deleteAll(new \Criteria('poll_id', $poll_id, '='));
936
                                xoops_comment_delete($GLOBALS['xoopsModule']->getVar('mid'), $poll_id);
937
                            }
938
                        }
939
                    }
940
                }
941
942
                $sql = sprintf('DELETE FROM `%s` WHERE topic_id = %u', $this->db->prefix('bb_topics'), $post->getVar('topic_id'));
943
                if (!$result = $this->db->queryF($sql)) {
944
                    //xoops_error($this->db->error());
945
                }
946
                $sql = sprintf('DELETE FROM `%s` WHERE topic_id = %u', $this->db->prefix('bb_votedata'), $post->getVar('topic_id'));
947
                if (!$result = $this->db->queryF($sql)) {
948
                    //xoops_error($this->db->error());
949
                }
950
            }
951
        } else {
952
            $sql = 'UPDATE ' . $this->db->prefix('bb_topics') . ' t
953
                            LEFT JOIN ' . $this->db->prefix('bb_posts') . ' p ON p.topic_id = t.topic_id
954
                            SET t.topic_last_post_id = p.post_id
955
                            WHERE t.topic_last_post_id = ' . $post->getVar('post_id') . '
956
                                    AND p.post_id = (SELECT MAX(post_id) FROM ' . $this->db->prefix('bb_posts') . ' WHERE topic_id=t.topic_id)';
957
            if (!$result = $this->db->queryF($sql)) {
958
            }
959
        }
960
961
        $postcount_toupdate = $post->getVar('approved');
962
963
        if ($postcount_toupdate > 0) {
964
            // Update user stats
965
            if ($post->getVar('uid') > 0) {
966
                $memberHandler = xoops_getHandler('member');
967
                $poster        = $memberHandler->getUser($post->getVar('uid'));
968
                if (is_object($poster) && $post->getVar('uid') == $poster->getVar('uid')) {
969
                    $poster->setVar('posts', $poster->getVar('posts') - 1);
970
                    $res = $memberHandler->insertUser($poster, true);
0 ignored issues
show
Unused Code introduced by
The assignment to $res is dead and can be removed.
Loading history...
971
                    unset($poster);
972
                }
973
            }
974
975
            $sql = 'UPDATE ' . $this->db->prefix('bb_posts') . ' SET pid = ' . $post->getVar('pid') . ' WHERE pid=' . $post->getVar('post_id');
976
            if (!$result = $this->db->queryF($sql)) {
977
                //xoops_error($this->db->error());
978
            }
979
        }
980
981
        return true;
982
    }
983
984
    /**
985
     * @param null $criteria
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $criteria is correct as it would always require null to be passed?
Loading history...
986
     * @return int
987
     */
988
    public function getPostCount($criteria = null)
989
    {
990
        return parent::getCount($criteria);
991
    }
992
993
    /*
994
     * TODO: combining viewtopic.php
995
     */
996
997
    /**
998
     * @param null $criteria
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $criteria is correct as it would always require null to be passed?
Loading history...
999
     * @param int  $limit
1000
     * @param int  $start
1001
     * @param null $join
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $join is correct as it would always require null to be passed?
Loading history...
1002
     * @return array
1003
     */
1004
    public function &getPostsByLimit($criteria = null, $limit = 1, $start = 0, $join = null)
1005
    {
1006
        $ret = [];
1007
        $sql = 'SELECT p.*, t.* ' . ' FROM ' . $this->db->prefix('bb_posts') . ' AS p' . ' LEFT JOIN ' . $this->db->prefix('bb_posts_text') . ' AS t ON t.post_id = p.post_id';
1008
        if (!empty($join)) {
1009
            $sql .= $join;
1010
        }
1011
        if (isset($criteria) && $criteria instanceof \CriteriaElement) {
1012
            $sql .= ' ' . $criteria->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

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

1012
            $sql .= ' ' . $criteria->/** @scrutinizer ignore-call */ renderWhere();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1013
            if ('' != $criteria->getSort()) {
1014
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
1015
            }
1016
        }
1017
        $result = $this->db->query($sql, (int)$limit, (int)$start);
1018
        if (!$result) {
1019
            //xoops_error($this->db->error());
1020
            return $ret;
1021
        }
1022
        while (false !== ($myrow = $this->db->fetchArray($result))) {
1023
            $post = $this->create(false);
1024
            $post->assignVars($myrow);
1025
            $ret[$myrow['post_id']] = $post;
1026
            unset($post);
1027
        }
1028
1029
        return $ret;
1030
    }
1031
1032
    /**
1033
     * clean orphan items from database
1034
     *
1035
     * @return bool true on success
1036
     */
1037
    public function cleanOrphan()
1038
    {
1039
        global $xoopsDB;
1040
        $this->deleteAll(new \Criteria('post_time', 0), true, true);
1041
        parent::cleanOrphan($this->db->prefix('bb_topics'), 'topic_id');
1042
        parent::cleanOrphan($this->db->prefix('bb_posts_text'), 'post_id');
1043
1044
        /* for MySQL 4.1+ */
1045
        if (version_compare(mysqli_get_server_info($xoopsDB->conn), '4.1.0', 'ge')):
1046
            $sql = 'DELETE FROM ' . $this->db->prefix('bb_posts_text') . " WHERE (post_id NOT IN ( SELECT DISTINCT post_id FROM {$this->table}) )";
1047
        else:
1048
            // for 4.0+
1049
1050
            $sql = 'DELETE ' . $this->db->prefix('bb_posts_text') . ' FROM ' . $this->db->prefix('bb_posts_text') . " LEFT JOIN {$this->table} AS aa ON " . $this->db->prefix('bb_posts_text') . '.post_id = aa.post_id ' . ' WHERE (aa.post_id IS NULL)';
1051
1052
            // Alternative for 4.1+
1053
            /*
1054
            $sql =     "DELETE bb FROM ".$this->db->prefix("bb_posts_text")." AS bb".
1055
                    " LEFT JOIN ".$this->table." AS aa ON bb.post_id = aa.post_id ".
1056
                    " WHERE (aa.post_id IS NULL)";
1057
            */ endif;
1058
        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...
1059
            //xoops_error($this->db->error());
1060
            return false;
1061
        }
1062
1063
        return true;
1064
    }
1065
1066
    /**
1067
     * clean expired objects from database
1068
     *
1069
     * @param int $expire time limit for expiration
1070
     * @return bool true on success
1071
     */
1072
    public function cleanExpires($expire = 0)
1073
    {
1074
        $crit_expire = new \CriteriaCompo(new \Criteria('approved', 0, '<='));
1075
        //if (!empty($expire)) {
1076
        $crit_expire->add(new \Criteria('post_time', time() - (int)$expire, '<'));
1077
1078
        //}
1079
        return $this->deleteAll($crit_expire, true/*, true*/);
1080
    }
1081
}
1082