Passed
Pull Request — master (#18)
by Michael
04:31
created

NewbbPostHandler::insert()   F

Complexity

Conditions 20
Paths 474

Size

Total Lines 112
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 20
eloc 71
c 1
b 0
f 0
nc 474
nop 2
dl 0
loc 112
rs 0.7305

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');
0 ignored issues
show
Bug introduced by
The type XoopsModules\Newbb\Helper 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...
345
        $user_karma    = $karmaHandler->getUserKarma();
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);
0 ignored issues
show
Bug introduced by
The function newbb_highlightText 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

488
            $post_text  = /** @scrutinizer ignore-call */ newbb_highlightText($post_text, $keywords);
Loading history...
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 $db
688
     */
689
    public function NewbbPostHandler(XoopsDatabase $db)
690
    {
691
        $this->__construct($db);
692
    }
693
694
    /**
695
     * @param  mixed|null $id
696
     * @return null|XoopsObject
697
     */
698
    public function get($id)
699
    {
700
        $id   = (int)$id;
701
        $post = null;
702
        $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;
703
        if ($array = $this->db->fetchArray($this->db->query($sql))) {
704
            $post = $this->create(false);
705
            $post->assignVars($array);
706
        }
707
708
        return $post;
709
    }
710
711
    /**
712
     * @param  int $topic_id
713
     * @param  int $limit
714
     * @param  int $approved
715
     * @return array
716
     */
717
    public function &getByLimit($topic_id, $limit, $approved = 1)
718
    {
719
        $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')
720
                  . ' tp ON tp.topic_id=p.topic_id WHERE p.topic_id=' . $topic_id . ' AND p.approved =' . $approved . ' ORDER BY p.post_time DESC';
721
        $result = $this->db->query($sql, $limit, 0);
722
        $ret    = array();
723
        while ($myrow = $this->db->fetchArray($result)) {
724
            $post = $this->create(false);
725
            $post->assignVars($myrow);
726
727
            $ret[$myrow['post_id']] = $post;
728
            unset($post);
729
        }
730
731
        return $ret;
732
    }
733
734
    /**
735
     * @param $post
736
     * @return mixed
737
     */
738
    public function getPostForPDF(&$post)
739
    {
740
        return $post->getPostBody(true);
741
    }
742
743
    /**
744
     * @param $post
745
     * @return mixed
746
     */
747
    public function getPostForPrint(&$post)
748
    {
749
        return $post->getPostBody();
750
    }
751
752
    /**
753
     * @param       $post
754
     * @param  bool $force
755
     * @return bool
756
     */
757
    public function approve(&$post, $force = false)
758
    {
759
        if (empty($post)) {
760
            return false;
761
        }
762
        if (is_numeric($post)) {
763
            $post = $this->get($post);
764
        }
765
        $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...
766
767
        $wasApproved = $post->getVar('approved');
768
        // irmtfan approve post if the approved = 0 (pending) or -1 (deleted)
769
        if (empty($force) && $wasApproved > 0) {
770
            return true;
771
        }
772
        $post->setVar('approved', 1);
773
        $this->insert($post, true);
774
775
        /** @var NewbbTopicHandler $topicHandler */
776
        $topicHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Topic');
777
        $topic_obj     = $topicHandler->get($post->getVar('topic_id'));
778
        if ($topic_obj->getVar('topic_last_post_id') < $post->getVar('post_id')) {
779
            $topic_obj->setVar('topic_last_post_id', $post->getVar('post_id'));
780
        }
781
        if ($post->isTopic()) {
782
            $topic_obj->setVar('approved', 1);
783
        } else {
784
            $topic_obj->setVar('topic_replies', $topic_obj->getVar('topic_replies') + 1);
785
        }
786
        $topicHandler->insert($topic_obj, true);
787
788
        /** @var NewbbForumHandler $forumHandler */
789
        $forumHandler = \XoopsModules\Newbb\Helper::getInstance()->getHandler('Forum');
790
        $forum_obj     = $forumHandler->get($post->getVar('forum_id'));
791
        if ($forum_obj->getVar('forum_last_post_id') < $post->getVar('post_id')) {
792
            $forum_obj->setVar('forum_last_post_id', $post->getVar('post_id'));
793
        }
794
        $forum_obj->setVar('forum_posts', $forum_obj->getVar('forum_posts') + 1);
795
        if ($post->isTopic()) {
796
            $forum_obj->setVar('forum_topics', $forum_obj->getVar('forum_topics') + 1);
797
        }
798
        $forumHandler->insert($forum_obj, true);
799
800
        // Update user stats
801
        if ($post->getVar('uid') > 0) {
802
            $memberHandler = xoops_getHandler('member');
803
            $poster         = $memberHandler->getUser($post->getVar('uid'));
804
            if (is_object($poster) && $post->getVar('uid') === $poster->getVar('uid')) {
805
                $poster->setVar('posts', $poster->getVar('posts') + 1);
806
                $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

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

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

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

952
                    $criteria = new CriteriaCompo(new Criteria('topic_id', /** @scrutinizer ignore-type */ $post->getVar('topic_id')));
Loading history...
953
                    $criteria->add(new Criteria('approved', 1));
954
                    $criteria->add(new Criteria('pid', 0, '>'));
955
                    if (!$this->getPostCount($criteria) > 0) {
956
                        $retVal = $this->_delete($post, $force);
957
                    }
958
                } else {
959
                    $retVal = $this->_delete($post, $force);
960
                }
961
            } else { // want to delete multiple posts
962
                //@TODO: test replacement of XoopsTree with XoopsObjectTree
963
                require_once $GLOBALS['xoops']->path('class/tree.php');
964
                // get tree with this object as the root
965
                $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

965
                $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...
966
                $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...
967
                /*
968
                                require_once $GLOBALS['xoops']->path("class/xoopstree.php");
969
                                $mytree = new XoopsTree($this->db->prefix("bb_posts"), "post_id", "pid");
970
                                $arr = $mytree->getAllChild($post->getVar('post_id'));
971
                */
972
                // irmtfan - delete children in a reverse order
973
                $success = true;
974
                for ($i = count($arr) - 1; $i >= 0; $i--) {
975
                    $childpost = $this->create(false);
976
                    $childpost->assignVars($arr[$i]);
977
                    $thisSuccess = $this->_delete($childpost, $force);
978
                    $success     = $success && $thisSuccess;
979
                    unset($childpost);
980
                }
981
                if ($success) {
982
                    // if we successfully deleted all children then try and delete this post
983
                    $retVal = $this->_delete($post, $force);
984
                } else {
985
                    // did not successfully delte all children so don't delete this post
986
                    $retVal = false;
987
                }
988
            }
989
        }
990
991
        return $retVal;
992
    }
993
994
    /**
995
     * @param       $post
996
     * @param  bool $force
997
     * @return bool
998
     */
999
    private function _delete(&$post, $force = false)
1000
    {
1001
        if ((!$post instanceof Post) || (0 === $post->getVar('post_id'))) {
1002
            return false;
1003
        }
1004
1005
        /* Set active post as deleted */
1006
        if (($post->getVar('approved') > 0) && empty($force)) {
1007
            $sql = 'UPDATE ' . $this->db->prefix('bb_posts') . ' SET approved = -1 WHERE post_id = ' . $post->getVar('post_id');
1008
            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...
1009
                //@TODO: add error check here
1010
            }
1011
        } else { /* delete pending post directly */
1012
            $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

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

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

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

1241
            $newbbConfig = /** @scrutinizer ignore-call */ newbb_load_config();
Loading history...
1242
            $expire      = isset($newbbConfig['pending_expire']) ? (int)$newbbConfig['pending_expire'] : 7;
1243
            $expire      = $expire * 24 * 3600; // days to seconds
1244
        }
1245
        if (empty($expire)) {
1246
            return false;
1247
        }
1248
        $crit_expire = new CriteriaCompo(new Criteria('approved', 0, '<='));
1249
        //        if (!empty($expire)) {
1250
        $crit_expire->add(new Criteria('post_time', time() - (int)$expire, '<'));
1251
1252
        //        }
1253
        return $this->deleteAll($crit_expire, true/*, true*/);
1254
    }
1255
}
1256