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

Post::showPost()   F

Complexity

Conditions 42
Paths > 20000

Size

Total Lines 241
Code Lines 179

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 42
eloc 179
c 1
b 0
f 0
nc 29196288
nop 1
dl 0
loc 241
rs 0

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
//  ------------------------------------------------------------------------ //
4
//                XOOPS - PHP Content Management System                      //
5
//                  Copyright (c) 2000-2016 XOOPS.org                        //
6
//                       <http://xoops.org/>                             //
7
//  ------------------------------------------------------------------------ //
8
//  This program is free software; you can redistribute it and/or modify     //
9
//  it under the terms of the GNU General Public License as published by     //
10
//  the Free Software Foundation; either version 2 of the License, or        //
11
//  (at your option) any later version.                                      //
12
//                                                                           //
13
//  You may not change or alter any portion of this comment or credits       //
14
//  of supporting developers from this source code or any supporting         //
15
//  source code which is considered copyrighted (c) material of the          //
16
//  original comment or credit authors.                                      //
17
//                                                                           //
18
//  This program is distributed in the hope that it will be useful,          //
19
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
20
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
21
//  GNU General Public License for more details.                             //
22
//                                                                           //
23
//  You should have received a copy of the GNU General Public License        //
24
//  along with this program; if not, write to the Free Software              //
25
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
26
//  ------------------------------------------------------------------------ //
27
//  Author: phppp (D.J., [email protected])                                  //
28
//  URL: http://xoopsforge.com, http://xoops.org.cn                          //
29
//  Project: Article Project                                                 //
30
//  ------------------------------------------------------------------------ //
31
32
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
33
34
defined('NEWBB_FUNCTIONS_INI') || include XOOPS_ROOT_PATH . '/modules/newbb/include/functions.ini.php';
35
newbb_load_object();
0 ignored issues
show
Bug introduced by
The function newbb_load_object 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

35
/** @scrutinizer ignore-call */ 
36
newbb_load_object();
Loading history...
36
37
/**
38
 * Class Post
39
 */
40
class Post extends XoopsObject
41
{
42
    //class Post extends XoopsObject {
43
    public $attachment_array = array();
44
45
    /**
46
     * Post constructor.
47
     */
48
    public function __construct()
49
    {
50
        parent::__construct('bb_posts');
0 ignored issues
show
Unused Code introduced by
The call to XoopsObject::__construct() has too many arguments starting with 'bb_posts'. ( Ignorable by Annotation )

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

50
        parent::/** @scrutinizer ignore-call */ 
51
                __construct('bb_posts');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
51
        $this->initVar('post_id', XOBJ_DTYPE_INT);
52
        $this->initVar('topic_id', XOBJ_DTYPE_INT, 0, true);
53
        $this->initVar('forum_id', XOBJ_DTYPE_INT, 0, true);
54
        $this->initVar('post_time', XOBJ_DTYPE_INT, 0, true);
55
        $this->initVar('poster_ip', XOBJ_DTYPE_INT, 0);
56
        $this->initVar('poster_name', XOBJ_DTYPE_TXTBOX, '');
57
        $this->initVar('subject', XOBJ_DTYPE_TXTBOX, '', true);
58
        $this->initVar('pid', XOBJ_DTYPE_INT, 0);
59
        $this->initVar('dohtml', XOBJ_DTYPE_INT, 0);
60
        $this->initVar('dosmiley', XOBJ_DTYPE_INT, 1);
61
        $this->initVar('doxcode', XOBJ_DTYPE_INT, 1);
62
        $this->initVar('doimage', XOBJ_DTYPE_INT, 1);
63
        $this->initVar('dobr', XOBJ_DTYPE_INT, 1);
64
        $this->initVar('uid', XOBJ_DTYPE_INT, 1);
65
        $this->initVar('icon', XOBJ_DTYPE_TXTBOX, '');
66
        $this->initVar('attachsig', XOBJ_DTYPE_INT, 0);
67
        $this->initVar('approved', XOBJ_DTYPE_INT, 1);
68
        $this->initVar('post_karma', XOBJ_DTYPE_INT, 0);
69
        $this->initVar('require_reply', XOBJ_DTYPE_INT, 0);
70
        $this->initVar('attachment', XOBJ_DTYPE_TXTAREA, '');
71
        $this->initVar('post_text', XOBJ_DTYPE_TXTAREA, '');
72
        $this->initVar('post_edit', XOBJ_DTYPE_TXTAREA, '');
73
    }
74
75
    // ////////////////////////////////////////////////////////////////////////////////////
76
    // attachment functions    TODO: there should be a file/attachment management class
77
    /**
78
     * @return array|mixed|null
79
     */
80
    public function getAttachment()
81
    {
82
        if (count($this->attachment_array)) {
83
            return $this->attachment_array;
84
        }
85
        $attachment = $this->getVar('attachment');
86
        if (empty($attachment)) {
87
            $this->attachment_array = null;
88
        } else {
89
            $this->attachment_array = @unserialize(base64_decode($attachment));
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

89
            $this->attachment_array = @unserialize(base64_decode(/** @scrutinizer ignore-type */ $attachment));
Loading history...
90
        }
91
92
        return $this->attachment_array;
93
    }
94
95
    /**
96
     * @param $attach_key
97
     * @return bool
98
     */
99
    public function incrementDownload($attach_key)
100
    {
101
        if (!$attach_key) {
102
            return false;
103
        }
104
        $this->attachment_array[(string)$attach_key]['num_download']++;
105
106
        return $this->attachment_array[(string)$attach_key]['num_download'];
107
    }
108
109
    /**
110
     * @return bool
111
     */
112
    public function saveAttachment()
113
    {
114
        $attachment_save = '';
115
        if (is_array($this->attachment_array) && count($this->attachment_array) > 0) {
116
            $attachment_save = base64_encode(serialize($this->attachment_array));
117
        }
118
        $this->setVar('attachment', $attachment_save);
119
        $sql = 'UPDATE ' . $GLOBALS['xoopsDB']->prefix('bb_posts') . ' SET attachment=' . $GLOBALS['xoopsDB']->quoteString($attachment_save) . ' WHERE post_id = ' . $this->getVar('post_id');
120
        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...
121
            //xoops_error($GLOBALS["xoopsDB"]->error());
122
            return false;
123
        }
124
125
        return true;
126
    }
127
128
    /**
129
     * @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...
130
     * @return bool
131
     */
132
    public function deleteAttachment($attach_array = null)
133
    {
134
        $attach_old = $this->getAttachment();
135
        if (!is_array($attach_old) || count($attach_old) < 1) {
136
            return true;
137
        }
138
        $this->attachment_array = array();
139
140
        if ($attach_array === null) {
0 ignored issues
show
introduced by
The condition $attach_array === null is always true.
Loading history...
141
            $attach_array = array_keys($attach_old);
142
        } // to delete all!
143
        if (!is_array($attach_array)) {
0 ignored issues
show
introduced by
The condition is_array($attach_array) is always true.
Loading history...
144
            $attach_array = array($attach_array);
145
        }
146
147
        foreach ($attach_old as $key => $attach) {
148
            if (in_array($key, $attach_array)) {
149
                @unlink(XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['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

149
                /** @scrutinizer ignore-unhandled */ @unlink(XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['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...
150
                @unlink(XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['dir_attachments'] . '/thumbs/' . $attach['name_saved']); // delete thumbnails
151
                continue;
152
            }
153
            $this->attachment_array[$key] = $attach;
154
        }
155
        if (is_array($this->attachment_array) && count($this->attachment_array) > 0) {
156
            $attachment_save = base64_encode(serialize($this->attachment_array));
157
        } else {
158
            $attachment_save = '';
159
        }
160
        $this->setVar('attachment', $attachment_save);
161
162
        return true;
163
    }
164
165
    /**
166
     * @param  string $name_saved
167
     * @param  string $name_display
168
     * @param  string $mimetype
169
     * @param  int    $num_download
170
     * @return bool
171
     */
172
    public function setAttachment($name_saved = '', $name_display = '', $mimetype = '', $num_download = 0)
173
    {
174
        static $counter = 0;
175
        $this->attachment_array = $this->getAttachment();
176
        if ($name_saved) {
177
            $key                          = (string)(time() + $counter++);
178
            $this->attachment_array[$key] = array(
179
                'name_saved'   => $name_saved,
180
                'name_display' => isset($name_display) ? $name_display : $name_saved,
181
                'mimetype'     => $mimetype,
182
                'num_download' => isset($num_download) ? (int)$num_download : 0
183
            );
184
        }
185
        if (is_array($this->attachment_array)) {
186
            $attachment_save = base64_encode(serialize($this->attachment_array));
187
        } else {
188
            $attachment_save = null;
189
        }
190
        $this->setVar('attachment', $attachment_save);
191
192
        return true;
193
    }
194
195
    /**
196
     * TODO: refactor
197
     * @param  bool $asSource
198
     * @return string
199
     */
200
    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

200
    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...
201
    {
202
        $post_attachment = '';
203
        $attachments     = $this->getAttachment();
204
        if (is_array($attachments) && count($attachments) > 0) {
205
            $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

205
            $iconHandler = /** @scrutinizer ignore-call */ newbb_getIconHandler();
Loading history...
206
            $mime_path    = $iconHandler->getPath('mime');
207
            include_once $GLOBALS['xoops']->path('modules/' . $GLOBALS['xoopsModule']->getVar('dirname', 'n') . '/include/functions.image.php');
208
            $image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'bmp'); // need improve !!!
209
            $post_attachment .= '<br><strong>' . _MD_ATTACHMENT . '</strong>:';
210
            $post_attachment .= "<div style='margin: 1em 0; border-top: 1px solid;'></div>\n";
211
            //            $post_attachment .= '<br><hr style="height: 1px;" noshade="noshade" /><br>';
212
            foreach ($attachments as $key => $att) {
213
                $file_extension = ltrim(strrchr($att['name_saved'], '.'), '.');
214
                $filetype       = $file_extension;
215
                if (file_exists($GLOBALS['xoops']->path("{$mime_path}/{$filetype}.gif"))) {
216
                    $icon_filetype = $GLOBALS['xoops']->url("{$mime_path}/{$filetype}.gif");
217
                } else {
218
                    $icon_filetype = $GLOBALS['xoops']->url("{$mime_path}/unknown.gif");
219
                }
220
                $file_size = @filesize($GLOBALS['xoops']->path($GLOBALS['xoopsModuleConfig']['dir_attachments'] . '/' . $att['name_saved']));
221
                $file_size = number_format($file_size / 1024, 2) . ' KB';
222
                if (in_array(strtolower($file_extension), $image_extensions)
223
                    && $GLOBALS['xoopsModuleConfig']['media_allowed']
224
                ) {
225
                    $post_attachment .= '<br><img src="' . $icon_filetype . '" alt="' . $filetype . '" /><strong>&nbsp; ' . $att['name_display'] . '</strong> <small>(' . $file_size . ')</small>';
226
                    $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

226
                    $post_attachment .= '<br>' . /** @scrutinizer ignore-call */ newbb_attachmentImage($att['name_saved']);
Loading history...
227
                    $isDisplayed = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $isDisplayed is dead and can be removed.
Loading history...
228
                } else {
229
                    if (empty($GLOBALS['xoopsModuleConfig']['show_userattach'])) {
230
                        $post_attachment .= "<a href='" . $GLOBALS['xoops']->url('/modules/' . $GLOBALS['xoopsModule']->getVar('dirname', 'n') . "/dl_attachment.php?attachid={$key}&amp;post_id=" . $this->getVar('post_id'))
231
                                            . "'> <img src='{$icon_filetype}' alt='{$filetype}' /> {$att['name_display']}</a> " . _MD_FILESIZE . ": {$file_size}; " . _MD_HITS . ": {$att['num_download']}";
232
                    } elseif (($GLOBALS['xoopsUser'] instanceof XoopsUser) && $GLOBALS['xoopsUser']->uid() > 0
233
                              && $GLOBALS['xoopsUser']->isActive()
234
                    ) {
235
                        $post_attachment .= "<a href='" . $GLOBALS['xoops']->url('/modules/' . $GLOBALS['xoopsModule']->getVar('dirname', 'n') . "/dl_attachment.php?attachid={$key}&amp;post_id=" . $this->getVar('post_id')) . "'> <img src='"
236
                                            . $icon_filetype . "' alt='{$filetype}' /> {$att['name_display']}</a> " . _MD_FILESIZE . ": {$file_size}; " . _MD_HITS . ": {$att['num_download']}";
237
                    } else {
238
                        $post_attachment .= _MD_NEWBB_SEENOTGUEST;
239
                    }
240
                }
241
                $post_attachment .= '<br>';
242
            }
243
        }
244
245
        return $post_attachment;
246
    }
247
    // attachment functions
248
    // ////////////////////////////////////////////////////////////////////////////////////
249
250
    /**
251
     * @param  string $poster_name
252
     * @param  string $post_editmsg
253
     * @return bool
254
     */
255
    public function setPostEdit($poster_name = '', $post_editmsg = '')
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

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

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...
256
    {
257
        if (empty($GLOBALS['xoopsModuleConfig']['recordedit_timelimit'])
258
            || (time() - $this->getVar('post_time')) < $GLOBALS['xoopsModuleConfig']['recordedit_timelimit'] * 60
259
            || $this->getVar('approved') < 1
260
        ) {
261
            return true;
262
        }
263
        if (($GLOBALS['xoopsUser'] instanceof XoopsUser) && $GLOBALS['xoopsUser']->isActive()) {
264
            if ($GLOBALS['xoopsModuleConfig']['show_realname'] && $GLOBALS['xoopsUser']->getVar('name')) {
265
                $edit_user = $GLOBALS['xoopsUser']->getVar('name');
266
            } else {
267
                $edit_user = $GLOBALS['xoopsUser']->getVar('uname');
268
            }
269
        }
270
        $post_edit              = array();
271
        $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...
272
        $post_edit['edit_time'] = time();
273
        $post_edit['edit_msg']  = $post_editmsg;
274
275
        $post_edits = $this->getVar('post_edit');
276
        if (!empty($post_edits)) {
277
            $post_edits = unserialize(base64_decode($post_edits));
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));
Loading history...
278
        }
279
        if (!is_array($post_edits)) {
280
            $post_edits = array();
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
297
        if (empty($GLOBALS['xoopsModuleConfig']['recordedit_timelimit'])) {
298
            return false;
299
        }
300
301
        $post_edit  = '';
302
        $post_edits = $this->getVar('post_edit');
303
        if (!empty($post_edits)) {
304
            $post_edits = unserialize(base64_decode($post_edits));
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

304
            $post_edits = unserialize(base64_decode(/** @scrutinizer ignore-type */ $post_edits));
Loading history...
305
        }
306
        if (!isset($post_edits) || !is_array($post_edits)) {
307
            $post_edits = array();
308
        }
309
        if (is_array($post_edits) && count($post_edits) > 0) {
310
            foreach ($post_edits as $postedit) {
311
                $edit_time = (int)$postedit['edit_time'];
312
                $edit_user = $myts->stripSlashesGPC($postedit['edit_user']);
313
                $edit_msg  = (!empty($postedit['edit_msg'])) ? $myts->stripSlashesGPC($postedit['edit_msg']) : '';
314
                // Start irmtfan add option to do only the latest edit when do_latestedit=0 (Alfred)
315
                if (empty($GLOBALS['xoopsModuleConfig']['do_latestedit'])) {
316
                    $post_edit = '';
317
                }
318
                // End irmtfan add option to do only the latest edit when do_latestedit=0 (Alfred)
319
                // START hacked by irmtfan
320
                // display/save all edit records.
321
                $post_edit .= _MD_EDITEDBY . ' ' . $edit_user . ' ' . _MD_ON . ' ' . newbb_formatTimestamp((int)$edit_time) . '<br>';
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

321
                $post_edit .= _MD_EDITEDBY . ' ' . $edit_user . ' ' . _MD_ON . ' ' . /** @scrutinizer ignore-call */ newbb_formatTimestamp((int)$edit_time) . '<br>';
Loading history...
322
                // if reason is not empty
323
                if ($edit_msg !== '') {
324
                    $post_edit .= _MD_EDITEDMSG . ' ' . $edit_msg . '<br>';
325
                }
326
                // START hacked by irmtfan
327
            }
328
        }
329
330
        return $post_edit;
331
    }
332
333
    /**
334
     * @return array
335
     */
336
    public function &getPostBody()
337
    {
338
        global $myts;
339
        $GLOBALS['xoopsModuleConfig'] = newbb_load_config(); // irmtfan  load all newbb configs - newbb config in blocks activated in some modules like profile
0 ignored issues
show
Bug introduced by
The function newbb_load_config 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

339
        $GLOBALS['xoopsModuleConfig'] = /** @scrutinizer ignore-call */ newbb_load_config(); // irmtfan  load all newbb configs - newbb config in blocks activated in some modules like profile
Loading history...
340
        mod_loadFunctions('user', 'newbb');
341
        mod_loadFunctions('render', 'newbb');
342
343
        $uid           = ($GLOBALS['xoopsUser'] instanceof XoopsUser) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
344
        $karmaHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Karma');
345
        $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

345
        /** @scrutinizer ignore-call */ 
346
        $user_karma    = $karmaHandler->getUserKarma();
Loading history...
346
347
        $post               = array();
348
        $post['attachment'] = false;
349
        $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

349
        $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...
350
        if (newbb_isAdmin($this->getVar('forum_id')) or $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

350
        if (/** @scrutinizer ignore-call */ newbb_isAdmin($this->getVar('forum_id')) or $this->checkIdentity()) {
Loading history...
351
            $post['text'] = $post_text . '<br>' . $this->displayAttachment();
352
        } elseif ($GLOBALS['xoopsModuleConfig']['enable_karma'] && $this->getVar('post_karma') > $user_karma) {
353
            $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

353
            $post['text'] = sprintf(_MD_KARMA_REQUIREMENT, $user_karma, /** @scrutinizer ignore-type */ $this->getVar('post_karma'));
Loading history...
354
        } elseif ($GLOBALS['xoopsModuleConfig']['allow_require_reply'] && $this->getVar('require_reply')
355
                  && (!$uid
356
                      || !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...
357
        ) {
358
            $post['text'] = _MD_REPLY_REQUIREMENT;
359
        } else {
360
            $post['text'] = $post_text . '<br>' . $this->displayAttachment();
361
        }
362
        $memberHandler = xoops_getHandler('member');
363
        $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

363
        /** @scrutinizer ignore-call */ 
364
        $eachposter     = $memberHandler->getUser($this->getVar('uid'));
Loading history...
364
        if (is_object($eachposter) && $eachposter->isActive()) {
365
            if ($GLOBALS['xoopsModuleConfig']['show_realname'] && $eachposter->getVar('name')) {
366
                $post['author'] = $eachposter->getVar('name');
367
            } else {
368
                $post['author'] = $eachposter->getVar('uname');
369
            }
370
            unset($eachposter);
371
        } else {
372
            $post['author'] = $this->getVar('poster_name') ?: $GLOBALS['xoopsConfig']['anonymous'];
373
        }
374
375
        $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

375
        $post['subject'] = /** @scrutinizer ignore-call */ newbb_htmlspecialchars($this->vars['subject']['value']);
Loading history...
376
        $post['date']    = $this->getVar('post_time');
377
378
        return $post;
379
    }
380
381
    /**
382
     * @return bool
383
     */
384
    public function isTopic()
385
    {
386
        return !$this->getVar('pid');
387
    }
388
389
    /**
390
     * @param  string $action_tag
391
     * @return bool
392
     */
393
    public function checkTimelimit($action_tag = 'edit_timelimit')
394
    {
395
        $newbb_config = newbb_load_config();
0 ignored issues
show
Bug introduced by
The function newbb_load_config 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

395
        $newbb_config = /** @scrutinizer ignore-call */ newbb_load_config();
Loading history...
396
        if (empty($newbb_config['edit_timelimit'])) {
397
            return true;
398
        }
399
400
        return ($this->getVar('post_time') > time() - $newbb_config[$action_tag] * 60);
401
    }
402
403
    /**
404
     * @param  int $uid
405
     * @return bool
406
     */
407
    public function checkIdentity($uid = -1)
408
    {
409
        $uid = ($uid > -1) ? $uid : (($GLOBALS['xoopsUser'] instanceof XoopsUser) ? $GLOBALS['xoopsUser']->getVar('uid') : 0);
410
        if ($this->getVar('uid') > 0) {
411
            $user_ok = ($uid === $this->getVar('uid')) ? true : false;
412
        } else {
413
            static $user_ip;
414
            if (!isset($user_ip)) {
415
                $user_ip = XoopsUserUtility::getIP();
416
            }
417
            $user_ok = ($user_ip === $this->getVar('poster_ip')) ? true : false;
418
        }
419
420
        return $user_ok;
421
    }
422
423
    // TODO: cleaning up and merge with post hanldings in viewpost.php
424
    /**
425
     * @param $isadmin
426
     * @return array
427
     */
428
    public function showPost($isadmin)
429
    {
430
        global $myts;
431
        global $forumUrl, $forumImage;
432
        global $viewtopic_users, $viewtopic_posters, $forum_obj, $topic_obj, $online, $user_karma, $viewmode, $order, $start, $total_posts, $topic_status;
433
        static $post_NO = 0;
434
        static $name_anonymous;
435
436
        if (!isset($name_anonymous)) {
437
            $name_anonymous = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
438
        }
439
440
        mod_loadFunctions('time', 'newbb');
441
        mod_loadFunctions('render', 'newbb');
442
        mod_loadFunctions('text', 'newbb'); // irmtfan add text functions
443
444
        $post_id  = $this->getVar('post_id');
445
        $topic_id = $this->getVar('topic_id');
446
        $forum_id = $this->getVar('forum_id');
447
448
        $query_vars              = array('status', 'order', 'start', 'mode', 'viewmode');
449
        $query_array             = array();
450
        $query_array['topic_id'] = "topic_id={$topic_id}";
451
        foreach ($query_vars as $var) {
452
            if (!empty($_GET[$var])) {
453
                $query_array[$var] = "{$var}={$_GET[$var]}";
454
            }
455
        }
456
        $page_query = htmlspecialchars(implode('&', array_values($query_array)));
457
458
        $uid = ($GLOBALS['xoopsUser'] instanceof XoopsUser) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
459
460
        ++$post_NO;
461
        if (strtolower($order) === 'desc') {
462
            $post_no = $total_posts - ($start + $post_NO) + 1;
463
        } else {
464
            $post_no = $start + $post_NO;
465
        }
466
467
        if ($isadmin || $this->checkIdentity()) {
468
            $post_text       = $this->getVar('post_text');
469
            $post_attachment = $this->displayAttachment();
470
        } elseif ($GLOBALS['xoopsModuleConfig']['enable_karma'] && $this->getVar('post_karma') > $user_karma) {
471
            $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

471
            $post_text       = "<div class='karma'>" . sprintf(_MD_KARMA_REQUIREMENT, $user_karma, /** @scrutinizer ignore-type */ $this->getVar('post_karma')) . '</div>';
Loading history...
472
            $post_attachment = '';
473
        } elseif ($GLOBALS['xoopsModuleConfig']['allow_require_reply'] && $this->getVar('require_reply')
474
                  && (!$uid
475
                      || !in_array($uid, $viewtopic_posters))
476
        ) {
477
            $post_text       = "<div class='karma'>" . _MD_REPLY_REQUIREMENT . "</div>\n";
478
            $post_attachment = '';
479
        } else {
480
            $post_text       = $this->getVar('post_text');
481
            $post_attachment = $this->displayAttachment();
482
        }
483
        // START irmtfan add highlight feature
484
        // Hightlighting searched words
485
        $post_title = $this->getVar('subject');
486
        if (isset($_GET['keywords']) && !empty($_GET['keywords'])) {
487
            $keywords   = $myts->htmlSpecialChars(trim(urldecode($_GET['keywords'])));
488
            $post_text  = newbb_highlightText($post_text, $keywords);
489
            $post_title = newbb_highlightText($post_title, $keywords);
490
        }
491
        // END irmtfan add highlight feature
492
        if (isset($viewtopic_users[$this->getVar('uid')])) {
493
            $poster = $viewtopic_users[$this->getVar('uid')];
494
        } else {
495
            $name   = ($post_name = $this->getVar('poster_name')) ? $post_name : $name_anonymous;
496
            $poster = array(
497
                'poster_uid' => 0,
498
                'name'       => $name,
499
                'link'       => $name
500
            );
501
        }
502
503
        if ($posticon = $this->getVar('icon')) {
504
            $post_image = "<a name='{$post_id}'><img src='" . $GLOBALS['xoops']->url("images/subject/{$posticon}") . "' alt='' /></a>";
505
        } else {
506
            $post_image = "<a name='{$post_id}'><img src='" . $GLOBALS['xoops']->url('images/icons/posticon.gif') . "' alt='' /></a>";
507
        }
508
509
        $thread_buttons = array();
510
        $mod_buttons    = array();
511
512
        if ($isadmin
513
            && (($GLOBALS['xoopsUser'] instanceof XoopsUser)
514
                && $GLOBALS['xoopsUser']->getVar('uid') !== $this->getVar('uid'))
515
            && ($this->getVar('uid') > 0)
516
        ) {
517
            $mod_buttons['bann']['image']    = newbb_displayImage('p_bann', _MD_SUSPEND_MANAGEMENT);
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

517
            $mod_buttons['bann']['image']    = /** @scrutinizer ignore-call */ newbb_displayImage('p_bann', _MD_SUSPEND_MANAGEMENT);
Loading history...
518
            $mod_buttons['bann']['link']     = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/moderate.php?forum={$forum_id}&amp;fuid=" . $this->getVar('uid'));
519
            $mod_buttons['bann']['name']     = _MD_SUSPEND_MANAGEMENT;
520
            $thread_buttons['bann']['image'] = newbb_displayImage('p_bann', _MD_SUSPEND_MANAGEMENT);
521
            $thread_buttons['bann']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/moderate.php?forum={$forum_id}&amp;fuid=" . $this->getVar('uid'));
522
            $thread_buttons['bann']['name']  = _MD_SUSPEND_MANAGEMENT;
523
        }
524
525
        if ($GLOBALS['xoopsModuleConfig']['enable_permcheck']) {
526
            /** @var NewbbTopicHandler $topicHandler */
527
            $topicHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Topic');
528
            $topic_status  = $topic_obj->getVar('topic_status');
529
            if ($topicHandler->getPermission($forum_id, $topic_status, 'edit')) {
530
                $edit_ok = ($isadmin || ($this->checkIdentity() && $this->checkTimelimit('edit_timelimit')));
531
                if ($edit_ok) {
532
                    $thread_buttons['edit']['image'] = newbb_displayImage('p_edit', _EDIT);
533
                    $thread_buttons['edit']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/edit.php?{$page_query}");
534
                    $thread_buttons['edit']['name']  = _EDIT;
535
                    $mod_buttons['edit']['image']    = newbb_displayImage('p_edit', _EDIT);
536
                    $mod_buttons['edit']['link']     = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/edit.php?{$page_query}");
537
                    $mod_buttons['edit']['name']     = _EDIT;
538
                }
539
            }
540
541
            if ($topicHandler->getPermission($forum_id, $topic_status, 'delete')) {
542
                $delete_ok = ($isadmin || ($this->checkIdentity() && $this->checkTimelimit('delete_timelimit')));
543
544
                if ($delete_ok) {
545
                    $thread_buttons['delete']['image'] = newbb_displayImage('p_delete', _DELETE);
546
                    $thread_buttons['delete']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/delete.php?{$page_query}");
547
                    $thread_buttons['delete']['name']  = _DELETE;
548
                    $mod_buttons['delete']['image']    = newbb_displayImage('p_delete', _DELETE);
549
                    $mod_buttons['delete']['link']     = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/delete.php?{$page_query}");
550
                    $mod_buttons['delete']['name']     = _DELETE;
551
                }
552
            }
553
            if ($topicHandler->getPermission($forum_id, $topic_status, 'reply')) {
554
                $thread_buttons['reply']['image'] = newbb_displayImage('p_reply', _MD_REPLY);
555
                $thread_buttons['reply']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/reply.php?{$page_query}");
556
                $thread_buttons['reply']['name']  = _MD_REPLY;
557
558
                $thread_buttons['quote']['image'] = newbb_displayImage('p_quote', _MD_QUOTE);
559
                $thread_buttons['quote']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/reply.php?{$page_query}&amp;quotedac=1");
560
                $thread_buttons['quote']['name']  = _MD_QUOTE;
561
            }
562
        } else {
563
            $mod_buttons['edit']['image'] = newbb_displayImage('p_edit', _EDIT);
564
            $mod_buttons['edit']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/edit.php?{$page_query}");
565
            $mod_buttons['edit']['name']  = _EDIT;
566
567
            $mod_buttons['delete']['image'] = newbb_displayImage('p_delete', _DELETE);
568
            $mod_buttons['delete']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/delete.php?{$page_query}");
569
            $mod_buttons['delete']['name']  = _DELETE;
570
571
            $thread_buttons['reply']['image'] = newbb_displayImage('p_reply', _MD_REPLY);
572
            $thread_buttons['reply']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/reply.php?{$page_query}");
573
            $thread_buttons['reply']['name']  = _MD_REPLY;
574
        }
575
576
        if (!$isadmin && $GLOBALS['xoopsModuleConfig']['reportmod_enabled']) {
577
            $thread_buttons['report']['image'] = newbb_displayImage('p_report', _MD_REPORT);
578
            $thread_buttons['report']['link']  = $GLOBALS['xoops']->url('modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/report.php?{$page_query}");
579
            $thread_buttons['report']['name']  = _MD_REPORT;
580
        }
581
582
        $thread_action = array();
583
        // irmtfan add pdf permission
584
        if (file_exists($GLOBALS['xoops']->path('Frameworks/tcpdf/tcpdf.php'))
585
            && $topicHandler->getPermission($forum_id, $topic_status, 'pdf')
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $topicHandler does not seem to be defined for all execution paths leading up to this point.
Loading history...
586
        ) {
587
            $thread_action['pdf']['image']  = newbb_displayImage('pdf', _MD_PDF);
588
            $thread_action['pdf']['link']   = $GLOBALS['xoops']->url('modules/newbb/makepdf.php?type=post&amp;pageid=0');
589
            $thread_action['pdf']['name']   = _MD_PDF;
590
            $thread_action['pdf']['target'] = '_blank';
591
        }
592
        // irmtfan add print permission
593
        if ($topicHandler->getPermission($forum_id, $topic_status, 'print')) {
594
            $thread_action['print']['image']  = newbb_displayImage('printer', _MD_PRINT);
595
            $thread_action['print']['link']   = $GLOBALS['xoops']->url("modules/newbb/print.php?form=2&amp;forum={$forum_id}&amp;topic_id={$topic_id}");
596
            $thread_action['print']['name']   = _MD_PRINT;
597
            $thread_action['print']['target'] = '_blank';
598
        }
599
600
        if ($GLOBALS['xoopsModuleConfig']['show_sociallinks']) {
601
            $full_title  = $this->getVar('subject');
602
            $clean_title = preg_replace('/[^A-Za-z0-9-]+/', '+', $this->getVar('subject'));
603
            $full_link   = $GLOBALS['xoops']->url("modules/newbb/viewtopic.php?post_id={$post_id}");
604
605
            $thread_action['social_twitter']['image']  = newbb_displayImage('twitter', _MD_SHARE_TWITTER);
606
            $thread_action['social_twitter']['link']   = "http://twitter.com/share?text={$clean_title}&amp;url={$full_link}";
607
            $thread_action['social_twitter']['name']   = _MD_SHARE_TWITTER;
608
            $thread_action['social_twitter']['target'] = '_blank';
609
610
            $thread_action['social_facebook']['image']  = newbb_displayImage('facebook', _MD_SHARE_FACEBOOK);
611
            $thread_action['social_facebook']['link']   = "http://www.facebook.com/sharer.php?u={$full_link}";
612
            $thread_action['social_facebook']['name']   = _MD_SHARE_FACEBOOK;
613
            $thread_action['social_facebook']['target'] = '_blank';
614
615
            $thread_action['social_gplus']['image']  = newbb_displayImage('googleplus', _MD_SHARE_GOOGLEPLUS);
616
            $thread_action['social_gplus']['link']   = "https://plusone.google.com/_/+1/confirm?hl=en&url={$full_link}";
617
            $thread_action['social_gplus']['name']   = _MD_SHARE_GOOGLEPLUS;
618
            $thread_action['social_gplus']['target'] = '_blank';
619
620
            $thread_action['social_linkedin']['image']  = newbb_displayImage('linkedin', _MD_SHARE_LINKEDIN);
621
            $thread_action['social_linkedin']['link']   = "http://www.linkedin.com/shareArticle?mini=true&amp;title={$full_title}&amp;url={$full_link}";
622
            $thread_action['social_linkedin']['name']   = _MD_SHARE_LINKEDIN;
623
            $thread_action['social_linkedin']['target'] = '_blank';
624
625
            $thread_action['social_delicious']['image']  = newbb_displayImage('delicious', _MD_SHARE_DELICIOUS);
626
            $thread_action['social_delicious']['link']   = "http://del.icio.us/post?title={$full_title}&amp;url={$full_link}";
627
            $thread_action['social_delicious']['name']   = _MD_SHARE_DELICIOUS;
628
            $thread_action['social_delicious']['target'] = '_blank';
629
630
            $thread_action['social_digg']['image']  = newbb_displayImage('digg', _MD_SHARE_DIGG);
631
            $thread_action['social_digg']['link']   = "http://digg.com/submit?phase=2&amp;title={$full_title}&amp;url={$full_link}";
632
            $thread_action['social_digg']['name']   = _MD_SHARE_DIGG;
633
            $thread_action['social_digg']['target'] = '_blank';
634
635
            $thread_action['social_reddit']['image']  = newbb_displayImage('reddit', _MD_SHARE_REDDIT);
636
            $thread_action['social_reddit']['link']   = "http://reddit.com/submit?title={$full_title}&amp;url={$full_link}";
637
            $thread_action['social_reddit']['name']   = _MD_SHARE_REDDIT;
638
            $thread_action['social_reddit']['target'] = '_blank';
639
640
            $thread_action['social_wong']['image']  = newbb_displayImage('wong', _MD_SHARE_MRWONG);
641
            $thread_action['social_wong']['link']   = "http://www.mister-wong.de/index.php?action=addurl&bm_url=$full_link}";
642
            $thread_action['social_wong']['name']   = _MD_SHARE_MRWONG;
643
            $thread_action['social_wong']['target'] = '_blank';
644
        }
645
646
        $post = array(
647
            'post_id'         => $post_id,
648
            'post_parent_id'  => $this->getVar('pid'),
649
            '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

649
            'post_date'       => /** @scrutinizer ignore-call */ newbb_formatTimestamp($this->getVar('post_time')),
Loading history...
650
            'post_image'      => $post_image,
651
            'post_title'      => $post_title,        // irmtfan $post_title to add highlight keywords
652
            'post_text'       => $post_text,
653
            'post_attachment' => $post_attachment,
654
            'post_edit'       => $this->displayPostEdit(),
655
            'post_no'         => $post_no,
656
            'post_signature'  => $this->getVar('attachsig') ? @$poster['signature'] : '',
657
            'poster_ip'       => ($isadmin
658
                                  && $GLOBALS['xoopsModuleConfig']['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

658
                                  && $GLOBALS['xoopsModuleConfig']['show_ip']) ? long2ip(/** @scrutinizer ignore-type */ $this->getVar('poster_ip')) : '',
Loading history...
659
            'thread_action'   => $thread_action,
660
            'thread_buttons'  => $thread_buttons,
661
            'mod_buttons'     => $mod_buttons,
662
            'poster'          => $poster,
663
            'post_permalink'  => "<a href='" . $GLOBALS['xoops']->url('/modules/' . $GLOBALS['xoopsModule']->getVar('dirname') . "/viewtopic.php?post_id={$post_id}") . "'></a>"
664
        );
665
666
        unset($thread_buttons, $mod_buttons, $eachposter);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $eachposter does not exist. Did you maybe mean $poster?
Loading history...
667
668
        return $post;
669
    }
670
}
671
672
/**
673
 * Class NewbbPostHandler
674
 */
675
//class NewbbPostHandler extends ArtObjectHandler
676
class NewbbPostHandler extends XoopsPersistableObjectHandler
677
{
678
    /**
679
     * @param null|XoopsDatabase $db
680
     */
681
    public function __construct(XoopsDatabase $db)
682
    {
683
        parent::__construct($db, 'bb_posts', 'Post', 'post_id', 'subject');
684
    }
685
686
    /**
687
     * @param  mixed|null $id
688
     * @return null|XoopsObject
689
     */
690
    public function get($id)
691
    {
692
        $id   = (int)$id;
693
        $post = null;
694
        $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;
695
        if ($array = $this->db->fetchArray($this->db->query($sql))) {
696
            $post = $this->create(false);
697
            $post->assignVars($array);
698
        }
699
700
        return $post;
701
    }
702
703
    /**
704
     * @param  int $topic_id
705
     * @param  int $limit
706
     * @param  int $approved
707
     * @return array
708
     */
709
    public function &getByLimit($topic_id, $limit, $approved = 1)
710
    {
711
        $sql    = 'SELECT p.*, t.*, tp.topic_status FROM ' . $this->db->prefix('bb_posts') . ' p LEFT JOIN ' . $this->db->prefix('bb_posts_text') . ' t ON p.post_id=t.post_id LEFT JOIN ' . $this->db->prefix('bb_topics')
712
                  . ' tp ON tp.topic_id=p.topic_id WHERE p.topic_id=' . $topic_id . ' AND p.approved =' . $approved . ' ORDER BY p.post_time DESC';
713
        $result = $this->db->query($sql, $limit, 0);
714
        $ret    = array();
715
        while ($myrow = $this->db->fetchArray($result)) {
716
            $post = $this->create(false);
717
            $post->assignVars($myrow);
718
719
            $ret[$myrow['post_id']] = $post;
720
            unset($post);
721
        }
722
723
        return $ret;
724
    }
725
726
    /**
727
     * @param $post
728
     * @return mixed
729
     */
730
    public function getPostForPDF(&$post)
731
    {
732
        return $post->getPostBody(true);
733
    }
734
735
    /**
736
     * @param $post
737
     * @return mixed
738
     */
739
    public function getPostForPrint(&$post)
740
    {
741
        return $post->getPostBody();
742
    }
743
744
    /**
745
     * @param       $post
746
     * @param  bool $force
747
     * @return bool
748
     */
749
    public function approve(&$post, $force = false)
750
    {
751
        if (empty($post)) {
752
            return false;
753
        }
754
        if (is_numeric($post)) {
755
            $post = $this->get($post);
756
        }
757
        $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...
758
759
        $wasApproved = $post->getVar('approved');
760
        // irmtfan approve post if the approved = 0 (pending) or -1 (deleted)
761
        if (empty($force) && $wasApproved > 0) {
762
            return true;
763
        }
764
        $post->setVar('approved', 1);
765
        $this->insert($post, true);
766
767
        /** @var NewbbTopicHandler $topicHandler */
768
        $topicHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Topic');
769
        $topic_obj     = $topicHandler->get($post->getVar('topic_id'));
770
        if ($topic_obj->getVar('topic_last_post_id') < $post->getVar('post_id')) {
771
            $topic_obj->setVar('topic_last_post_id', $post->getVar('post_id'));
772
        }
773
        if ($post->isTopic()) {
774
            $topic_obj->setVar('approved', 1);
775
        } else {
776
            $topic_obj->setVar('topic_replies', $topic_obj->getVar('topic_replies') + 1);
777
        }
778
        $topicHandler->insert($topic_obj, true);
779
780
        /** @var NewbbForumHandler $forumHandler */
781
        $forumHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Forum');
782
        $forum_obj     = $forumHandler->get($post->getVar('forum_id'));
783
        if ($forum_obj->getVar('forum_last_post_id') < $post->getVar('post_id')) {
784
            $forum_obj->setVar('forum_last_post_id', $post->getVar('post_id'));
785
        }
786
        $forum_obj->setVar('forum_posts', $forum_obj->getVar('forum_posts') + 1);
787
        if ($post->isTopic()) {
788
            $forum_obj->setVar('forum_topics', $forum_obj->getVar('forum_topics') + 1);
789
        }
790
        $forumHandler->insert($forum_obj, true);
791
792
        // Update user stats
793
        if ($post->getVar('uid') > 0) {
794
            $memberHandler = xoops_getHandler('member');
795
            $poster         = $memberHandler->getUser($post->getVar('uid'));
796
            if (is_object($poster) && $post->getVar('uid') === $poster->getVar('uid')) {
797
                $poster->setVar('posts', $poster->getVar('posts') + 1);
798
                $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

798
                /** @scrutinizer ignore-call */ 
799
                $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...
799
                unset($poster);
800
            }
801
        }
802
803
        // Update forum stats
804
        $statsHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Stats');
805
        $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

805
        $statsHandler->/** @scrutinizer ignore-call */ 
806
                       update($post->getVar('forum_id'), 'post');
Loading history...
806
        if ($post->isTopic()) {
807
            $statsHandler->update($post->getVar('forum_id'), 'topic');
808
        }
809
810
        return true;
811
    }
812
813
    /**
814
     * @param  XoopsObject $post
815
     * @param  bool   $force
816
     * @return bool
817
     */
818
    public function insert(XoopsObject $post, $force = true)
819
    {
820
        // Set the post time
821
        // The time should be 'publish' time. To be adjusted later
822
        if (!$post->getVar('post_time')) {
823
            $post->setVar('post_time', time());
824
        }
825
826
        /** @var NewbbTopicHandler $topicHandler */
827
        $topicHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Topic');
828
        // Verify the topic ID
829
        if ($topic_id = $post->getVar('topic_id')) {
830
            $topic_obj = $topicHandler->get($topic_id);
831
            // Invalid topic OR the topic is no approved and the post is not top post
832
            if (!$topic_obj
833
                //            || (!$post->isTopic() && $topic_obj->getVar("approved") < 1)
834
            ) {
835
                return false;
836
            }
837
        }
838
        if (empty($topic_id)) {
839
            $post->setVar('topic_id', 0);
840
            $post->setVar('pid', 0);
841
            $post->setNew();
842
            $topic_obj = $topicHandler->create();
843
        }
844
        $textHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Text');
845
        $post_text_vars = array('post_text', 'post_edit', 'dohtml', 'doxcode', 'dosmiley', 'doimage', 'dobr');
846
        if ($post->isNew()) {
847
            if (!$topic_id = $post->getVar('topic_id')) {
848
                $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...
849
                $topic_obj->setVar('topic_poster', $post->getVar('uid'));
850
                $topic_obj->setVar('forum_id', $post->getVar('forum_id'));
851
                $topic_obj->setVar('topic_time', $post->getVar('post_time'));
852
                $topic_obj->setVar('poster_name', $post->getVar('poster_name'), true);
853
                $topic_obj->setVar('approved', $post->getVar('approved'), true);
854
855
                if (!$topic_id = $topicHandler->insert($topic_obj, $force)) {
856
                    $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

856
                    $post->/** @scrutinizer ignore-call */ 
857
                           deleteAttachment();
Loading history...
857
                    $post->setErrors('insert topic error');
858
859
                    //xoops_error($topic_obj->getErrors());
860
                    return false;
861
                }
862
                $post->setVar('topic_id', $topic_id);
863
864
                $pid = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $pid is dead and can be removed.
Loading history...
865
                $post->setVar('pid', 0);
866
            } elseif (!$post->getVar('pid')) {
867
                $pid = $topicHandler->getTopPostId($topic_id);
868
                $post->setVar('pid', $pid);
869
            }
870
871
            $text_obj = $textHandler->create();
872
            foreach ($post_text_vars as $key) {
873
                $text_obj->vars[$key] = $post->vars[$key];
874
            }
875
            $post->destroyVars($post_text_vars);
876
            if (!$post_id = parent::insert($post, $force)) {
877
                return false;
878
            } else {
879
                $post->unsetNew();
880
            }
881
            $text_obj->setVar('post_id', $post_id);
882
            if (!$textHandler->insert($text_obj, $force)) {
883
                $this->delete($post);
884
                $post->setErrors('post text insert error');
885
886
                //xoops_error($text_obj->getErrors());
887
                return false;
888
            }
889
            if ($post->getVar('approved') > 0) {
890
                $this->approve($post, true);
891
            }
892
            $post->setVar('post_id', $post_id);
893
        } else {
894
            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

894
            if ($post->/** @scrutinizer ignore-call */ isTopic()) {
Loading history...
895
                if ($post->getVar('subject') !== $topic_obj->getVar('topic_title')) {
896
                    $topic_obj->setVar('topic_title', $post->getVar('subject', 'n'));
897
                }
898
                if ($post->getVar('approved') !== $topic_obj->getVar('approved')) {
899
                    $topic_obj->setVar('approved', $post->getVar('approved'));
900
                }
901
                $topic_obj->setDirty();
902
                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...
903
                    $post->setErrors('update topic error');
904
905
                    //                    xoops_error($topic_obj->getErrors());
906
                    return false;
907
                }
908
            }
909
            $text_obj =& $textHandler->get($post->getVar('post_id'));
910
            $text_obj->setDirty();
911
            foreach ($post_text_vars as $key) {
912
                $text_obj->vars[$key] = $post->vars[$key];
913
            }
914
            $post->destroyVars($post_text_vars);
915
            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...
916
                //                xoops_error($post->getErrors());
917
                return false;
918
            } else {
919
                $post->unsetNew();
920
            }
921
            if (!$textHandler->insert($text_obj, $force)) {
922
                $post->setErrors('update post text error');
923
924
                //                xoops_error($text_obj->getErrors());
925
                return false;
926
            }
927
        }
928
929
        return $post->getVar('post_id');
930
    }
931
932
    /**
933
     * @param  XoopsObject $post
934
     * @param  bool   $isDeleteOne
935
     * @param  bool   $force
936
     * @return bool
937
     */
938
    public function delete($post, $isDeleteOne = true, $force = false)
939
    {
940
        $retVal = false;
941
        if (($post instanceof Post) && ($post->getVar('post_id') > 0)) {
942
            if ($isDeleteOne) {
943
                if ($post->isTopic()) {
944
                    $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

944
                    $criteria = new CriteriaCompo(new Criteria('topic_id', /** @scrutinizer ignore-type */ $post->getVar('topic_id')));
Loading history...
945
                    $criteria->add(new Criteria('approved', 1));
946
                    $criteria->add(new Criteria('pid', 0, '>'));
947
                    if (!$this->getPostCount($criteria) > 0) {
948
                        $retVal = $this->_delete($post, $force);
949
                    }
950
                } else {
951
                    $retVal = $this->_delete($post, $force);
952
                }
953
            } else { // want to delete multiple posts
954
                //@TODO: test replacement of XoopsTree with XoopsObjectTree
955
                require_once $GLOBALS['xoops']->path('class/tree.php');
956
                // get tree with this object as the root
957
                $myObjTree = new XoopsObjectTree($this->getAll(), 'post_id', 'pid', $post->getVar('post_id'));
0 ignored issues
show
Bug introduced by
It seems like $post->getVar('post_id') can also be of type array and array; however, parameter $rootId of XoopsObjectTree::__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

957
                $myObjTree = new XoopsObjectTree($this->getAll(), 'post_id', 'pid', /** @scrutinizer ignore-type */ $post->getVar('post_id'));
Loading history...
Unused Code introduced by
The assignment to $myObjTree is dead and can be removed.
Loading history...
958
                $arr       = $myObjtree->getAllChild(); // get all children of this object
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $myObjtree does not exist. Did you maybe mean $myObjTree?
Loading history...
959
                /*
960
                                require_once $GLOBALS['xoops']->path("class/xoopstree.php");
961
                                $mytree = new XoopsTree($this->db->prefix("bb_posts"), "post_id", "pid");
962
                                $arr = $mytree->getAllChild($post->getVar('post_id'));
963
                */
964
                // irmtfan - delete children in a reverse order
965
                $success = true;
966
                for ($i = count($arr) - 1; $i >= 0; $i--) {
967
                    $childpost = $this->create(false);
968
                    $childpost->assignVars($arr[$i]);
969
                    $thisSuccess = $this->_delete($childpost, $force);
970
                    $success     = $success && $thisSuccess;
971
                    unset($childpost);
972
                }
973
                if ($success) {
974
                    // if we successfully deleted all children then try and delete this post
975
                    $retVal = $this->_delete($post, $force);
976
                } else {
977
                    // did not successfully delte all children so don't delete this post
978
                    $retVal = false;
979
                }
980
            }
981
        }
982
983
        return $retVal;
984
    }
985
986
    /**
987
     * @param       $post
988
     * @param  bool $force
989
     * @return bool
990
     */
991
    private function _delete(&$post, $force = false)
992
    {
993
        if ((!$post instanceof Post) || (0 === $post->getVar('post_id'))) {
994
            return false;
995
        }
996
997
        /* Set active post as deleted */
998
        if (($post->getVar('approved') > 0) && empty($force)) {
999
            $sql = 'UPDATE ' . $this->db->prefix('bb_posts') . ' SET approved = -1 WHERE post_id = ' . $post->getVar('post_id');
1000
            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...
1001
                //@TODO: add error check here
1002
            }
1003
        } else { /* delete pending post directly */
1004
            $sql = sprintf('DELETE FROM %s WHERE post_id = %u', $this->db->prefix('bb_posts'), $post->getVar('post_id'));
0 ignored issues
show
Bug introduced by
It seems like $post->getVar('post_id') 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

1004
            $sql = sprintf('DELETE FROM %s WHERE post_id = %u', $this->db->prefix('bb_posts'), /** @scrutinizer ignore-type */ $post->getVar('post_id'));
Loading history...
1005
            if (!$result = $this->db->queryF($sql)) {
1006
                $post->setErrors('delte post error: ' . $sql);
1007
1008
                return false;
1009
            }
1010
            $post->deleteAttachment();
1011
1012
            $sql = sprintf('DELETE FROM %s WHERE post_id = %u', $this->db->prefix('bb_posts_text'), $post->getVar('post_id'));
1013
            if (!$result = $this->db->queryF($sql)) {
1014
                $post->setErrors('Could not remove post text: ' . $sql);
1015
1016
                return false;
1017
            }
1018
        }
1019
1020
        if ($post->isTopic()) {
1021
            /** @var NewbbTopicHandler $topicHandler */
1022
            $topicHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Topic');
1023
            $topic_obj     = $topicHandler->get($post->getVar('topic_id'));
1024
            if (is_object($topic_obj) && $topic_obj->getVar('approved') > 0 && empty($force)) {
1025
                $topiccount_toupdate = 1;
0 ignored issues
show
Unused Code introduced by
The assignment to $topiccount_toupdate is dead and can be removed.
Loading history...
1026
                $topic_obj->setVar('approved', -1);
1027
                $topicHandler->insert($topic_obj);
1028
                xoops_notification_deletebyitem($GLOBALS['xoopsModule']->getVar('mid'), 'thread', $post->getVar('topic_id'));
1029
            } else {
1030
                if (is_object($topic_obj)) {
1031
                    if ($topic_obj->getVar('approved') > 0) {
1032
                        xoops_notification_deletebyitem($GLOBALS['xoopsModule']->getVar('mid'), 'thread', $post->getVar('topic_id'));
1033
                    }
1034
1035
                    $poll_id       = $topic_obj->getVar('poll_id');
1036
                    /** @var XoopsModuleHandler $moduleHandler */
1037
                    $moduleHandler = xoops_getHandler('module');
1038
                    if ($poll_id > 0) {
1039
                        $poll_moduleHandler = $moduleHandler->getByDirname('xoopspoll');
1040
                        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

1040
                        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...
1041
                            $pollHandler = xoops_getModuleHandler('poll', 'xoopspoll');
1042
                            if (false !== $pollHandler->deleteAll(new Criteria('poll_id', $poll_id, '='))) {
1043
                                $optionHandler = xoops_getModuleHandler('option', 'xoopspoll');
1044
                                $optionHandler->deleteAll(new Criteria('poll_id', $poll_id, '='));
1045
                                $logHandler = xoops_getModuleHandler('log', 'xoopspoll');
1046
                                $logHandler->deleteAll(new Criteria('poll_id', $poll_id, '='));
1047
                                xoops_comment_delete($GLOBALS['xoopsModule']->getVar('mid'), $poll_id);
1048
                            }
1049
                        } else {
1050
                            $poll_moduleHandler = $moduleHandler->getByDirname('umfrage');
1051
                            if (($poll_moduleHandler instanceof XoopsModuleHandler)
0 ignored issues
show
introduced by
$poll_moduleHandler is never a sub-type of XoopsModuleHandler.
Loading history...
1052
                                && $poll_moduleHandler->isactive()
1053
                            ) {
1054
                                include_once $GLOBALS['xoops']->path('modules/umfrage/class/umfrage.php');
1055
                                include_once $GLOBALS['xoops']->path('modules/umfrage/class/umfrageoption.php');
1056
                                include_once $GLOBALS['xoops']->path('modules/umfrage/class/umfragelog.php');
1057
                                include_once $GLOBALS['xoops']->path('modules/umfrage/class/umfragerenderer.php');
1058
1059
                                $poll = new Umfrage($poll_id);
0 ignored issues
show
Bug introduced by
The type Umfrage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1060
                                if (false !== $poll->delete()) {
1061
                                    UmfrageOption::deleteByPollId($poll_id);
0 ignored issues
show
Bug introduced by
The type UmfrageOption was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1062
                                    UmfrageLog::deleteByPollId($poll_id);
0 ignored issues
show
Bug introduced by
The type UmfrageLog was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1063
                                    xoops_comment_delete($GLOBALS['xoopsModule']->getVar('mid'), $poll_id);
1064
                                }
1065
                            }
1066
                        }
1067
                    }
1068
                }
1069
1070
                $sql = sprintf('DELETE FROM %s WHERE topic_id = %u', $this->db->prefix('bb_topics'), $post->getVar('topic_id'));
1071
                if (!$result = $this->db->queryF($sql)) {
1072
                    //                  xoops_error($this->db->error());
1073
                }
1074
                $sql = sprintf('DELETE FROM %s WHERE topic_id = %u', $this->db->prefix('bb_votedata'), $post->getVar('topic_id'));
1075
                if (!$result = $this->db->queryF($sql)) {
1076
                    //                  xoops_error($this->db->error());
1077
                }
1078
            }
1079
        } else {
1080
            $sql = 'UPDATE ' . $this->db->prefix('bb_topics') . ' t ' . 'LEFT JOIN ' . $this->db->prefix('bb_posts') . ' p ON p.topic_id = t.topic_id ' . 'SET t.topic_last_post_id = p.post_id ' . 'WHERE t.topic_last_post_id = '
1081
                   . $post->getVar('post_id') . ' ' . 'AND p.post_id = (SELECT MAX(post_id) FROM ' . $this->db->prefix('bb_posts') . ' ' . 'WHERE topic_id=t.topic_id)';
1082
            if (!$result = $this->db->queryF($sql)) {
1083
                //@TODO: add error checking here
1084
            }
1085
        }
1086
1087
        $postcount_toupdate = $post->getVar('approved');
1088
1089
        if ($postcount_toupdate > 0) {
1090
            // Update user stats
1091
            if ($post->getVar('uid') > 0) {
1092
                $memberHandler = xoops_getHandler('member');
1093
                $poster         = $memberHandler->getUser($post->getVar('uid'));
1094
                if (is_object($poster) && $post->getVar('uid') === $poster->getVar('uid')) {
1095
                    $poster->setVar('posts', $poster->getVar('posts') - 1);
1096
                    $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...
1097
                    unset($poster);
1098
                }
1099
            }
1100
            // irmtfan - just update the pid for approved posts when the post is not topic (pid=0)
1101
            if (!$post->isTopic()) {
1102
                $sql = 'UPDATE ' . $this->db->prefix('bb_posts') . ' SET pid = ' . $post->getVar('pid') . ' WHERE approved=1 AND pid=' . $post->getVar('post_id');
1103
                if (!$result = $this->db->queryF($sql)) {
1104
                    //                  xoops_error($this->db->error());
1105
                }
1106
            }
1107
        }
1108
1109
        return true;
1110
    }
1111
1112
    // START irmtfan enhance getPostCount when there is join (read_mode = 2)
1113
    /**
1114
     * @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...
1115
     * @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...
1116
     * @return int|null
1117
     */
1118
    public function getPostCount($criteria = null, $join = null)
1119
    {
1120
        // If not join get the count from XOOPS/class/model/stats as before
1121
        if (empty($join)) {
1122
            return parent::getCount($criteria);
1123
        }
1124
1125
        $sql = 'SELECT COUNT(*) AS count' . ' ' . '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';
1126
        // LEFT JOIN
1127
        $sql .= $join;
1128
        // WHERE
1129
        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
1130
            $sql .= ' ' . $criteria->renderWhere();
1131
        }
1132
        if (!$result = $this->db->query($sql)) {
1133
            //            xoops_error($this->db->error().'<br>'.$sql);
1134
            return null;
1135
        }
1136
        $myrow = $this->db->fetchArray($result);
1137
        $count = $myrow['count'];
1138
1139
        return $count;
1140
    }
1141
    // END irmtfan enhance getPostCount when there is join (read_mode = 2)
1142
1143
    /*
1144
     *@TODO: combining viewtopic.php
1145
     */
1146
    /**
1147
     * @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...
1148
     * @param  int  $limit
1149
     * @param  int  $start
1150
     * @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...
1151
     * @return array
1152
     */
1153
    public function &getPostsByLimit($criteria = null, $limit = 1, $start = 0, $join = null)
1154
    {
1155
        $ret = array();
1156
        $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';
1157
        if (!empty($join)) {
1158
            $sql .= (substr($join, 0, 1) === ' ') ? $join : ' ' . $join;
1159
        }
1160
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
1161
            $sql .= ' ' . $criteria->renderWhere();
1162
            if ($criteria->getSort() !== '') {
1163
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
1164
            }
1165
        }
1166
        $result = $this->db->query($sql, (int)$limit, (int)$start);
1167
        if (!$result) {
1168
            //            xoops_error($this->db->error());
1169
            return $ret;
1170
        }
1171
        while ($myrow = $this->db->fetchArray($result)) {
1172
            $post = $this->create(false);
1173
            $post->assignVars($myrow);
1174
            $ret[$myrow['post_id']] = $post;
1175
            unset($post);
1176
        }
1177
1178
        return $ret;
1179
    }
1180
1181
    /**
1182
     * @return bool
1183
     */
1184
    public function synchronization()
1185
    {
1186
        //      $this->cleanOrphan();
1187
        return true;
1188
    }
1189
1190
    /**
1191
     * clean orphan items from database
1192
     *
1193
     * @return bool true on success
1194
     */
1195
    public function cleanOrphan()
1196
    {
1197
        $this->deleteAll(new Criteria('post_time', 0), true, true);
1198
        parent::cleanOrphan($this->db->prefix('bb_topics'), 'topic_id');
1199
        parent::cleanOrphan($this->db->prefix('bb_posts_text'), 'post_id');
1200
1201
        if ($this->mysql_major_version() >= 4) { /* for MySQL 4.1+ */
0 ignored issues
show
Bug introduced by
The method mysql_major_version() does not exist on NewbbPostHandler. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1201
        if ($this->/** @scrutinizer ignore-call */ mysql_major_version() >= 4) { /* for MySQL 4.1+ */
Loading history...
1202
            $sql = 'DELETE FROM ' . $this->db->prefix('bb_posts_text') . ' ' . 'WHERE (post_id NOT IN ( SELECT DISTINCT post_id FROM ' . $this->table . ') )';
1203
        } else { /* for 4.0+ */
1204
            /* */
1205
            $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 ' . ' '
1206
                   . 'WHERE (aa.post_id IS NULL)';
1207
            /* */
1208
            // Alternative for 4.1+
1209
            /*
1210
            $sql = "DELETE bb FROM ".$this->db->prefix("bb_posts_text")." AS bb" . " "
1211
                       . "LEFT JOIN ".$this->table." AS aa ON bb.post_id = aa.post_id " . " "
1212
                       . "WHERE (aa.post_id IS NULL)";
1213
            */
1214
        }
1215
        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...
1216
            //            xoops_error($this->db->error());
1217
            return false;
1218
        }
1219
1220
        return true;
1221
    }
1222
1223
    /**
1224
     * clean expired objects from database
1225
     *
1226
     * @param  int $expire time limit for expiration
1227
     * @return bool true on success
1228
     */
1229
    public function cleanExpires($expire = 0)
1230
    {
1231
        // irmtfan if 0 no cleanup look include/plugin.php
1232
        if (!func_num_args()) {
1233
            $newbbConfig = newbb_load_config();
0 ignored issues
show
Bug introduced by
The function newbb_load_config 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

1233
            $newbbConfig = /** @scrutinizer ignore-call */ newbb_load_config();
Loading history...
1234
            $expire      = isset($newbbConfig['pending_expire']) ? (int)$newbbConfig['pending_expire'] : 7;
1235
            $expire      = $expire * 24 * 3600; // days to seconds
1236
        }
1237
        if (empty($expire)) {
1238
            return false;
1239
        }
1240
        $crit_expire = new CriteriaCompo(new Criteria('approved', 0, '<='));
1241
        //        if (!empty($expire)) {
1242
        $crit_expire->add(new Criteria('post_time', time() - (int)$expire, '<'));
1243
1244
        //        }
1245
        return $this->deleteAll($crit_expire, true/*, true*/);
1246
    }
1247
}
1248