Completed
Pull Request — master (#489)
by Richard
10:39
created

Comments::renderView()   F

Complexity

Conditions 33
Paths 1414

Size

Total Lines 185
Code Lines 133

Duplication

Lines 36
Ratio 19.46 %
Metric Value
dl 36
loc 185
rs 2
cc 33
eloc 133
nc 1414
nop 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
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
use Xoops\Core\Kernel\Handlers\XoopsModule;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModule.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use Xoops\Core\Kernel\Handlers\XoopsUser;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsUser.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
use Xmf\Request;
15
16
/**
17
 * @category  Helper
18
 * @package   Comments
19
 * @author    trabis <[email protected]>
20
 * @copyright 2001-2015 XOOPS Project (http://xoops.org)
21
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
22
 * @link      http://xoops.org
23
 */
24
25
class Comments extends Xoops\Module\Helper\HelperAbstract
26
{
27
    const APPROVE_NONE = 0;
28
    const APPROVE_ALL = 1;
29
    const APPROVE_USER = 2;
30
    const APPROVE_ADMIN = 3;
31
    const STATUS_PENDING = 1;
32
    const STATUS_ACTIVE = 2;
33
    const STATUS_HIDDEN = 3;
34
    const DISPLAY_OLDEST_FIRST = 0;
35
    const DISPLAY_NEWEST_FIRST = 1;
36
37
    /**
38
     * Init the module
39
     *
40
     * @return null|void
41
     */
42
    public function init()
43
    {
44
        $this->setDirname('comments');
45
        $this->loadLanguage('main');
46
    }
47
48
    /**
49
     * @return string
50
     */
51
    public static function getInstance()
52
    {
53
        return parent::getInstance();
54
    }
55
56
    /**
57
     * @return CommentsCommentHandler
58
     */
59
    public function getHandlerComment()
60
    {
61
        return $this->getHandler('comment');
62
    }
63
64
    /**
65
     * @param string $config name of configuration variable
66
     *
67
     * @return mixed
68
     */
69
    public function getUserConfig($config)
70
    {
71
        static $configs = array();
72
        static $fetched = false;
73
        /* @var $helper Userconfigs */
74
        if (!$fetched && $this->xoops()->isUser() && $helper = $this->xoops()->getModuleHelper('userconfigs')) {
75
            $config_handler = $helper->getHandlerConfig();
76
            $configs = $config_handler->getConfigsByUser(
77
                $this->xoops()->user->getVar('uid'),
78
                $this->getModule()->getVar('mid')
79
            );
80
        }
81
        $fetched = true;
82
        return isset($configs[$config]) ? $configs[$config] : $this->getConfig($config);
83
    }
84
85
    /**
86
     * @param CommentsComment $obj comment object
87
     *
88
     * @return void
89
     */
90
    public function displayCommentForm(CommentsComment $obj)
91
    {
92
        $this->getForm($obj, 'comment')->display();
93
    }
94
95
    public function displayNew()
96
    {
97
        $xoops = Xoops::getInstance();
98
        /* @var $obj CommentsComment */
99
        $obj = $this->getHandlerComment()->create();
100
101
        $itemid = Request::getInt('com_itemid');
102
        $modid = Request::getInt('com_modid');
103
104
        if (empty($modid)) {
105
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
106
        }
107
108
        $module = $xoops->getModuleById($modid);
109
        if (!is_object($module)) {
110
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
111
        }
112
113 View Code Duplication
        if ((!$xoops->isAdminSide
114
                && static::APPROVE_NONE == $xoops->getModuleConfig('com_rule', $module->getVar('dirname')))
115
            || (!$xoops->isUser() && !$xoops->getModuleConfig('com_anonpost', $module->getVar('dirname')))
116
            || !$xoops->isModule()) {
117
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
118
        }
119
        /* @var $plugin CommentsPluginInterface */
120
        if (($plugin = \Xoops\Module\Plugin::getPlugin($module->getVar('dirname'), 'comments'))
121
            && $itemid > 0 && $modid > 0
122
        ) {
123
            $xoops->header();
124
            $title = '';
125
            $text = '';
126
            $uid = 0;
127
            $timestamp = 0;
128
            if (is_array($itemInfo = $plugin->itemInfo($itemid))) {
129
                $title = isset($itemInfo['title']) ? $itemInfo['title'] : $title;
130
                $text = isset($itemInfo['text']) ? $itemInfo['text'] : $text;
131
                $uid = isset($itemInfo['uid']) ? $itemInfo['uid'] : $uid;
132
                $timestamp = isset($itemInfo['timestamp']) ? $itemInfo['timestamp'] : $timestamp;
133
            }
134
135
            echo $this->renderHeader($title, $text, $uid, $timestamp);
136
137 View Code Duplication
            if (!preg_match("/^" . XoopsLocale::C_RE . "/i", $title)) {
138
                $title = XoopsLocale::C_RE . " " . XoopsLocale::substr($title, 0, 56);
139
            }
140
141
            $obj->setVar('itemid', $itemid);
142
            $obj->setVar('title', $title);
143
            $obj->setVar('modid', $modid);
144
145
            $this->displayCommentForm($obj);
146
            $xoops->footer();
147
        }
148
        $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
149
    }
150
151
    public function displayPost()
0 ignored issues
show
Coding Style introduced by
displayPost uses the super-global variable $_POST which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
152
    {
153
        $xoops = Xoops::getInstance();
154
        if (Request::getMethod()!=='POST') {
155
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
156
        }
157
        $id = Request::getInt('com_id');
158
        $modid = Request::getInt('com_modid');
159
        if (empty($modid)) {
160
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
161
        }
162
163
        /* @var $comment CommentsComment */
164
        $comment = $this->getHandlerComment()->get($id);
165
        if (!is_object($comment)) {
166
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
167
        }
168
169
        if (!$comment->isNew()) {
170
            $modid = $comment->getVar('modid');
171
        } else {
172
            $comment->setVar('modid', $modid);
173
        }
174
175
        $module = $xoops->getModuleById($modid);
176
        if (!is_object($module)) {
177
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
178
        }
179
180
        $moddir = $module->getVar('dirname');
181
182
        if ($xoops->isAdminSide) {
183
            if (empty($id)) {
184
                $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
185
            }
186
            $redirect_page = $this->url('admin/main.php?com_modid=' . $modid . '&amp;com_itemid');
187
        } else {
188
            if (static::APPROVE_NONE == $xoops->getModuleConfig('com_rule', $module->getVar('dirname'))) {
189
                $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
190
            }
191
            $redirect_page = '';
192
        }
193
194
        /* @var $plugin CommentsPluginInterface */
195
        if ($plugin = \Xoops\Module\Plugin::getPlugin($moddir, 'comments')) {
196
            if (!$xoops->isAdminSide) {
197
                $redirect_page = $xoops->url('modules/' . $moddir . '/' . $plugin->pageName() . '?');
198
                if (is_array($extraParams = $plugin->extraParams())) {
199
                    $extra_params = '';
200
                    foreach ($extraParams as $extra_param) {
201
                        $extra_params .= isset($_POST[$extra_param])
202
                            ? $extra_param . '=' . htmlspecialchars($_POST[$extra_param]) . '&amp;'
203
                            : $extra_param . '=amp;';
204
                    }
205
                    $redirect_page .= $extra_params;
206
                }
207
                $redirect_page .= $plugin->itemName();
208
            }
209
            $comment_url = $redirect_page;
210
211
            $op = Request::getBool('com_dopost') ? 'post' : '';
212
            $op = Request::getBool('com_dopreview') ? 'preview' : $op;
213
            $op = Request::getBool('com_dodelete') ? 'delete' : $op;
214
215
            if ($op === 'preview' || $op === 'post') {
216
                if (!$xoops->security()->check()) {
217
                    $op = '';
218
                }
219
            }
220
            if ($op === 'post' && !$xoops->isUser()) {
221
                $xoopsCaptcha = XoopsCaptcha::getInstance();
222
                if (!$xoopsCaptcha->verify()) {
223
                    $captcha_message = $xoopsCaptcha->getMessage();
224
                    $op = 'preview';
225
                }
226
            }
227
228
            $title = XoopsLocale::trim(Request::getString('com_title'));
229
            $text = XoopsLocale::trim(Request::getString('com_text'));
230
            $mode = XoopsLocale::trim(Request::getString('com_mode', 'flat'));
231
            $order = Request::getInt('com_order', static::DISPLAY_OLDEST_FIRST);
232
            $itemid = Request::getInt('com_itemid');
233
            $pid = Request::getInt('com_pid');
234
            $rootid = Request::getInt('com_rootid');
235
            $status = Request::getInt('com_status');
236
            $dosmiley = Request::getBool('com_dosmiley');
237
            $doxcode = Request::getBool('com_doxcode');
238
            $dobr = Request::getBool('com_dobr');
239
            $dohtml = Request::getBool('com_html');
240
            $doimage = Request::getBool('com_doimage');
241
            $icon = XoopsLocale::trim(Request::getString('com_icon'));
242
243
            $comment->setVar('title', $title);
244
            $comment->setVar('text', $text);
245
            $comment->setVar('itemid', $itemid);
246
            $comment->setVar('pid', $pid);
247
            $comment->setVar('rootid', $rootid);
248
            $comment->setVar('status', $status);
249
            $comment->setVar('dosmiley', $dosmiley);
250
            $comment->setVar('doxcode', $doxcode);
251
            $comment->setVar('dobr', $dobr);
252
            $comment->setVar('dohtml', $dohtml);
253
            $comment->setVar('doimage', $doimage);
254
            $comment->setVar('icon', $icon);
255
256
            switch ($op) {
257
                case "delete":
258
                    $this->displayDelete();
259
                    break;
260
261
                case "preview":
262
                    $comment->setVar('doimage', 1);
263
                    if ($comment->getVar('dohtml') != 0) {
264
                        if ($xoops->isUser()) {
265
                            if (!$xoops->user->isAdmin($comment->getVar('modid'))) {
266
                                $comment->setVar('dohtml', 0);
267
                            }
268
                        } else {
269
                            $comment->setVar('dohtml', 0);
270
                        }
271
                    }
272
273
                    $xoops->header();
274
                    if (!$xoops->isAdminSide && !empty($captcha_message)) {
275
                        echo $xoops->alert('error', $captcha_message);
276
                    }
277
                    echo $this->renderHeader($comment->getVar('title', 'p'), $comment->getVar('text', 'p'), false, time());
278
                    $this->displayCommentForm($comment);
279
                    $xoops->footer();
280
                    break;
281
282
                case "post":
283
                    $comment->setVar('doimage', 1);
284
                    $comment_handler = $this->getHandlerComment();
285
                    $add_userpost = false;
286
                    $call_approvefunc = false;
287
                    $call_updatefunc = false;
288
                    // RMV-NOTIFY - this can be set to 'comment' or 'comment_submit'
289
                    $notify_event = false;
290
                    if (!empty($id)) {
291
                        $accesserror = false;
292
293
                        if ($xoops->isUser()) {
294
                            if ($xoops->user->isAdmin($comment->getVar('modid'))) {
295
                                if (!empty($status) && $status != static::STATUS_PENDING) {
296
                                    $old_status = $comment->getVar('status');
297
                                    $comment->setVar('status', $status);
298
                                    // if changing status from pending state, increment user post
299
                                    if (static::STATUS_PENDING == $old_status) {
300
                                        $add_userpost = true;
301
                                        if (static::STATUS_ACTIVE == $status) {
302
                                            $call_updatefunc = true;
303
                                            $call_approvefunc = true;
304
                                            // RMV-NOTIFY
305
                                            $notify_event = 'comment';
306
                                        }
307
                                    } else {
308
                                        if (static::STATUS_HIDDEN == $old_status && static::STATUS_ACTIVE == $status) {
309
                                            $call_updatefunc = true;
310
                                            // Comments can not be directly posted hidden,
311
                                            // no need to send notification here
312
                                        } else {
313
                                            if (static::STATUS_ACTIVE == $old_status && static::STATUS_HIDDEN == $status) {
314
                                                $call_updatefunc = true;
315
                                            }
316
                                        }
317
                                    }
318
                                }
319
                            } else {
320
                                $comment->setVar('dohtml', 0);
321
                                if ($comment->getVar('uid') != $xoops->user->getVar('uid')) {
322
                                    $accesserror = true;
323
                                }
324
                            }
325
                        } else {
326
                            $comment->setVar('dohtml', 0);
327
                            $accesserror = true;
328
                        }
329 View Code Duplication
                        if (false != $accesserror) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
330
                            $xoops->redirect(
331
                                $redirect_page . '=' . $comment->getVar('itemid')
332
                                . '&amp;com_id=' . $comment->getVar('id')
333
                                . '&amp;com_mode=' . $mode . '&amp;com_order=' . $order,
334
                                1,
335
                                XoopsLocale::E_NO_ACCESS_PERMISSION
336
                            );
337
                        }
338
                    } else {
339
                        $comment->setVar('created', time());
340
                        $comment->setVar('ip', $xoops->getEnv('REMOTE_ADDR'));
341
                        if ($xoops->isUser()) {
342
                            if ($xoops->user->isAdmin($comment->getVar('modid'))) {
343
                                $comment->setVar('status', static::STATUS_ACTIVE);
344
                                $add_userpost = true;
345
                                $call_approvefunc = true;
346
                                $call_updatefunc = true;
347
                                // RMV-NOTIFY
348
                                $notify_event = 'comment';
349 View Code Duplication
                            } else {
350
                                $comment->setVar('dohtml', 0);
351
                                switch ($xoops->getModuleConfig('com_rule')) {
352
                                    case static::APPROVE_ALL:
353
                                    case static::APPROVE_USER:
354
                                        $comment->setVar('status', static::STATUS_ACTIVE);
355
                                        $add_userpost = true;
356
                                        $call_approvefunc = true;
357
                                        $call_updatefunc = true;
358
                                        // RMV-NOTIFY
359
                                        $notify_event = 'comment';
360
                                        break;
361
                                    case static::APPROVE_ADMIN:
362
                                    default:
363
                                        $comment->setVar('status', static::STATUS_PENDING);
364
                                        $notify_event = 'comment_submit';
365
                                        break;
366
                                }
367
                            }
368
                            if ($xoops->getModuleConfig('com_anonpost', $module->getVar('dirname'))
369
                                && $comment->getVar('noname')
370
                            ) {
371
                                $comment->setVar('uid', 0);
372
                            } else {
373
                                $comment->setVar('uid', $xoops->user->getVar('uid'));
374
                            }
375
                        } else {
376
                            $comment->setVar('dohtml', 0);
377
                            $comment->setVar('uid', 0);
378
                            if ($xoops->getModuleConfig('com_anonpost', $module->getVar('dirname')) != 1) {
379
                                $xoops->redirect(
380
                                    $redirect_page . '=' . $comment->getVar('itemid')
381
                                    . '&amp;com_id=' . $comment->getVar('id') . '&amp;com_mode=' . $mode
382
                                    . '&amp;com_order=' . $order,
383
                                    1,
384
                                    XoopsLocale::E_NO_ACCESS_PERMISSION
385
                                );
386
                            }
387
                        }
388 View Code Duplication
                        if ($comment->getVar('uid') == 0) {
389
                            switch ($xoops->getModuleConfig('com_rule')) {
390
                                case static::APPROVE_ALL:
391
                                    $comment->setVar('status', static::STATUS_ACTIVE);
392
                                    $add_userpost = true;
393
                                    $call_approvefunc = true;
394
                                    $call_updatefunc = true;
395
                                    // RMV-NOTIFY
396
                                    $notify_event = 'comment';
397
                                    break;
398
                                case static::APPROVE_ADMIN:
399
                                case static::APPROVE_USER:
400
                                default:
401
                                    $comment->setVar('status', static::STATUS_PENDING);
402
                                    // RMV-NOTIFY
403
                                    $notify_event = 'comment_submit';
404
                                    break;
405
                            }
406
                        }
407
                    }
408
                    if ($comment->getVar('title') == '') {
409
                        $comment->setVar('title', XoopsLocale::NO_TITLE);
410
                    }
411
                    $comment->setVar('modified', time());
412
                    if (isset($extra_params)) {
413
                        $comment->setVar('exparams', $extra_params);
414
                    }
415
416
                    if (false != $comment_handler->insert($comment)) {
417
                        $newcid = $comment->getVar('id');
418
                        // set own id as root id if this is a top comment
419
                        if ($comment->getVar('rootid') == 0) {
420
                            $comment->setVar('rootid', $newcid);
421
                            if (!$comment_handler->updateByField($comment, 'rootid', $comment->getVar('rootid'))) {
422
                                $comment_handler->delete($comment);
423
                                $xoops->header();
424
                                echo $xoops->alert('error', $comment->getHtmlErrors());
425
                                $xoops->footer();
426
                            }
427
                        }
428
                        // call custom approve function if any
429
                        if (false != $call_approvefunc) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
430
                            $plugin->approve($comment);
431
                        }
432
433
                        if (false != $call_updatefunc) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
434
                            $criteria = new CriteriaCompo(new Criteria('modid', $comment->getVar('modid')));
435
                            $criteria->add(new Criteria('itemid', $comment->getVar('itemid')));
436
                            $criteria->add(new Criteria('status', static::STATUS_ACTIVE));
437
                            $comment_count = $comment_handler->getCount($criteria);
0 ignored issues
show
Bug introduced by
The method getCount does only exist in XoopsPersistableObjectHandler, but not in XoopsObjectHandler.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
438
                            $plugin->update($comment->getVar('itemid'), $comment_count);
439
                        }
440
441
                        // increment user post if needed
442
                        $uid = $comment->getVar('uid');
443
                        if ($uid > 0 && false != $add_userpost) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
444
                            $member_handler = $xoops->getHandlerMember();
445
                            $poster = $member_handler->getUser($uid);
446
                            if ($poster instanceof XoopsUser) {
447
                                $member_handler->updateUserByField($poster, 'posts', $poster->getVar('posts') + 1);
448
                            }
449
                        }
450
451
                        // RMV-NOTIFY
452
                        // trigger notification event if necessary
453
                        if ($notify_event && $xoops->isActiveModule('notifications')) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $notify_event of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
454
                            $notifications = Notifications::getInstance();
455
                            $not_modid = $comment->getVar('modid');
456
                            $not_catinfo = $notifications->getCommentsCategory($module->getVar('dirname'));
457
                            $not_category = $not_catinfo['name'];
458
                            $not_itemid = $comment->getVar('itemid');
459
                            $not_event = $notify_event;
460
                            // Build an ABSOLUTE URL to view the comment.  Make sure we
461
                            // point to a viewable page (i.e. not the system administration
462
                            // module).
463
                            $comment_tags = array();
464
                            $comment_tags['X_COMMENT_URL'] = $comment_url . '=' . $comment->getVar('itemid')
465
                                . '&amp;com_id=' . $comment->getVar('id')
466
                                . '&amp;com_rootid=' . $comment->getVar('rootid')
467
                                . '&amp;com_mode=' . $mode . '&amp;com_order=' . $order
468
                                . '#comment' . $comment->getVar('id');
469
470
                            if ($xoops->isActiveModule('notifications')) {
471
                                Notifications::getInstance()->getHandlerNotification()->triggerEvent($not_category, $not_itemid, $not_event, $comment_tags, false, $not_modid);
0 ignored issues
show
Bug introduced by
The method getHandlerNotification() does not exist on Xoops\Module\Helper\HelperAbstract. Did you maybe mean getHandler()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
472
                            }
473
                        }
474
                        if (!isset($comment_post_results)) {
0 ignored issues
show
Bug introduced by
The variable $comment_post_results seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
475
                            // if the comment is active, redirect to posted comment
476
                            if ($comment->getVar('status') == static::STATUS_ACTIVE) {
477
                                $xoops->redirect(
478
                                    $redirect_page . '=' . $comment->getVar('itemid')
479
                                    . '&amp;com_id=' . $comment->getVar('id')
480
                                    . '&amp;com_rootid=' . $comment->getVar('rootid') . '&amp;com_mode=' . $mode
481
                                    . '&amp;com_order=' . $order . '#comment' . $comment->getVar('id'),
482
                                    1,
483
                                    _MD_COMMENTS_THANKSPOST
484
                                );
485 View Code Duplication
                            } else {
486
                                // not active, so redirect to top comment page
487
                                $xoops->redirect(
488
                                    $redirect_page . '=' . $comment->getVar('itemid') . '&amp;com_mode=' . $mode
489
                                    . '&amp;com_order=' . $order . '#comment' . $comment->getVar('id'),
490
                                    1,
491
                                    _MD_COMMENTS_THANKSPOST
492
                                );
493
                            }
494
                        }
495
                    } else {
496
                        if (!isset($purge_comment_post_results)) {
0 ignored issues
show
Bug introduced by
The variable $purge_comment_post_results does not exist. Did you mean $comment?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
497
                            $xoops->header();
498
                            echo $xoops->alert('error', $comment->getHtmlErrors());
499
                            $xoops->footer();
500
                        } else {
501
                            $comment_post_results = $comment->getErrors();
0 ignored issues
show
Unused Code introduced by
$comment_post_results is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
502
                        }
503
                    }
504
                    break;
505
                default:
506
                    $xoops->redirect(
507
                        \XoopsBaseConfig::get('url') . '/',
508
                        1,
509
                        implode('<br />', $xoops->security()->getErrors())
510
                    );
511
                    break;
512
            }
513
        }
514
    }
515
516
    public function displayReply()
517
    {
518
        $xoops = Xoops::getInstance();
519
520
        $modid = Request::getInt('com_modid', 0);
521
522
        if (empty($modid)) {
523
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
524
        }
525
526
        $module = $xoops->getModuleById($modid);
527
        if (!is_object($module)) {
528
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
529
        }
530
531 View Code Duplication
        if ((!$xoops->isAdminSide
532
                && static::APPROVE_NONE == $xoops->getModuleConfig('com_rule', $module->getVar('dirname')))
533
            || (!$xoops->isUser() && !$xoops->getModuleConfig('com_anonpost', $module->getVar('dirname')))
534
            || !$xoops->isModule()
535
        ) {
536
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
537
        }
538
539
        //Original comment
540
        $comment = $this->getHandlerComment()->get(Request::getInt('com_id', 0));
541
542
        /* @var $reply CommentsComment */
543
        $reply = $this->getHandlerComment()->create();
544
545
        $title = $comment->getVar('title', 'e');
546 View Code Duplication
        if (!preg_match("/^" . XoopsLocale::C_RE . "/i", $title)) {
547
            $title = XoopsLocale::C_RE . " " . XoopsLocale::substr($title, 0, 56);
548
        }
549
        $reply->setVar('title', $title);
550
        $reply->setVar('modid', $comment->getVar('modid'));
551
        $reply->setVar('pid', $comment->getVar('id'));
552
        $reply->setVar('rootid', $comment->getVar('rootid'));
553
        $reply->setVar('itemid', $comment->getVar('itemid'));
554
555
        $xoops->header();
556
        echo $this->renderHeader(
557
            $comment->getVar('title'),
558
            $comment->getVar('text'),
559
            $comment->getVar('uid'),
560
            $comment->getVar('created')
561
        );
562
        $this->displayCommentForm($reply);
563
        $xoops->footer();
564
    }
565
566
    /**
567
     * @param string $title     title
568
     * @param string $text      text
569
     * @param int    $uid       id of posting user
570
     * @param int    $timestamp unix timestamp
571
     *
572
     * @return string
573
     */
574
    public function renderHeader($title, $text, $uid, $timestamp)
575
    {
576
        $ret = '<table cellpadding="4" cellspacing="1" width="98%" class="outer">
577
      <tr><td class="head">' . $title . '</td></tr><tr><td><br />';
578
        if ($uid) {
579
            $ret .= _MD_COMMENTS_POSTER . ': <strong>' . XoopsUser::getUnameFromId($uid) . '</strong>&nbsp;&nbsp;';
580
        }
581
        $ret .= _MD_COMMENTS_POSTED . ': <strong>' . XoopsLocale::formatTimestamp($timestamp)
582
            . '</strong><br /><br />' . $text . '<br /></td></tr>';
583
        $ret .= '</table>';
584
        return $ret;
585
    }
586
587
    public function renderView()
0 ignored issues
show
Coding Style introduced by
renderView uses the super-global variable $_GET which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
renderView uses the super-global variable $_POST which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
588
    {
589
        $xoops = Xoops::getInstance();
590
        /* @var $plugin CommentsPluginInterface */
591
        if ($xoops->isModule()
592
            && $plugin = \Xoops\Module\Plugin::getPlugin($xoops->module->getVar('dirname'), 'comments')
593
        ) {
594
            if (static::APPROVE_NONE != $xoops->getModuleConfig('com_rule')) {
595
                $xoops->tpl()->assign('xoops_iscommentadmin', $this->isUserAdmin());
596
597
                $itemid = (trim($plugin->itemName()) != ''
598
                    && isset($_GET[$plugin->itemName()])) ? (int)($_GET[$plugin->itemName()]) : 0;
599
                if ($itemid > 0) {
600
                    $modid = $xoops->module->getVar('mid');
601
                    $mode = Request::getString('com_mode', $this->getUserConfig('com_mode'));
602
                    $xoops->tpl()->assign('comment_mode', $mode);
603
604
                    $order = Request::getInt('com_order', $this->getUserConfig('com_order'));
605
                    if ($order != static::DISPLAY_OLDEST_FIRST) {
606
                        $xoops->tpl()->assign(array(
607
                            'comment_order' => static::DISPLAY_NEWEST_FIRST,
608
                            'order_other'   => static::DISPLAY_OLDEST_FIRST
609
                        ));
610
                        $dborder = 'DESC';
611
                    } else {
612
                        $xoops->tpl()->assign(array(
613
                            'comment_order' => static::DISPLAY_OLDEST_FIRST,
614
                            'order_other'   => static::DISPLAY_NEWEST_FIRST
615
                        ));
616
                        $dborder = 'ASC';
617
                    }
618
                    // admins can view all comments and IPs, others can only view approved(active) comments
619
                    if ($xoops->isUser() && $xoops->user->isAdmin($xoops->module->getVar('mid'))) {
620
                        $admin_view = true;
621
                    } else {
622
                        $admin_view = false;
623
                    }
624
625
                    $id = Request::getInt('com_id', 0);
626
                    $rootid = Request::getInt('com_rootid', 0);
627
628
                    $comment_handler = $this->getHandlerComment();
629
                    if ($mode === 'flat') {
630
                        $comments = $comment_handler->getByItemId($xoops->module->getVar('mid'), $itemid, $dborder);
631
                        $renderer = CommentsCommentRenderer::getInstance($xoops->tpl());
0 ignored issues
show
Bug introduced by
It seems like $xoops->tpl() can be null; however, getInstance() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
632
                        $renderer->setComments($comments);
633
                        $renderer->renderFlatView($admin_view);
634
                    } elseif ($mode === 'thread') {
635
                        // RMV-FIX... added extraParam stuff here
636
                        $comment_url = $plugin->pageName() . '?';
637
                        if (is_array($extraParams = $plugin->extraParams())) {
638
                            $extra_params = '';
639
                            foreach ($extraParams as $extra_param) {
640
                                // This page is included in the module hosting page -- param could be from anywhere
641
642
                                if (isset($_POST[$extra_param])) {
643
                                    $extra_params .= $extra_param . '=' . $_POST[$extra_param] . '&amp;';
644
                                } else {
645
                                    if (isset($_GET[$extra_param])) {
646
                                        $extra_params .= $extra_param . '=' . $_GET[$extra_param] . '&amp;';
647
                                    } else {
648
                                        $extra_params .= $extra_param . '=&amp;';
649
                                    }
650
                                }
651
                            }
652
                            $comment_url .= $extra_params;
653
                        }
654
                        $xoops->tpl()->assign(
655
                            'comment_url',
656
                            $comment_url . $plugin->itemName() . '=' . $itemid . '&amp;com_mode=thread&amp;com_order='
657
                            . $order
658
                        );
659
                        if (!empty($id) && !empty($rootid) && ($id != $rootid)) {
660
                            // Show specific thread tree
661
                            $comments = $comment_handler->getThread($rootid, $id);
662
                            if (false != $comments) {
663
                                $renderer = CommentsCommentRenderer::getInstance($xoops->tpl());
0 ignored issues
show
Bug introduced by
It seems like $xoops->tpl() can be null; however, getInstance() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
664
                                $renderer->setComments($comments);
665
                                $renderer->renderThreadView($id, $admin_view);
666
                            }
667 View Code Duplication
                        } else {
668
                            // Show all threads
669
                            $top_comments = $comment_handler->getTopComments(
670
                                $xoops->module->getVar('mid'),
671
                                $itemid,
672
                                $dborder
673
                            );
674
                            $c_count = count($top_comments);
675
                            if ($c_count > 0) {
676
                                for ($i = 0; $i < $c_count; ++$i) {
677
                                    $comments = $comment_handler->getThread(
678
                                        $top_comments[$i]->getVar('rootid'),
679
                                        $top_comments[$i]->getVar('id')
680
                                    );
681
                                    if (false != $comments) {
682
                                        $renderer = CommentsCommentRenderer::getInstance($xoops->tpl());
0 ignored issues
show
Bug introduced by
It seems like $xoops->tpl() can be null; however, getInstance() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
683
                                        $renderer->setComments($comments);
684
                                        $renderer->renderThreadView($top_comments[$i]->getVar('id'), $admin_view);
685
                                    }
686
                                    unset($comments);
687
                                }
688
                            }
689
                        }
690 View Code Duplication
                    } else {
691
                        // Show all threads
692
                        $top_comments = $comment_handler->getTopComments(
693
                            $xoops->module->getVar('mid'),
694
                            $itemid,
695
                            $dborder
696
                        );
697
                        $c_count = count($top_comments);
698
                        if ($c_count > 0) {
699
                            for ($i = 0; $i < $c_count; ++$i) {
700
                                $comments = $comment_handler->getThread(
701
                                    $top_comments[$i]->getVar('rootid'),
702
                                    $top_comments[$i]->getVar('id')
703
                                );
704
                                $renderer = CommentsCommentRenderer::getInstance($xoops->tpl());
0 ignored issues
show
Bug introduced by
It seems like $xoops->tpl() can be null; however, getInstance() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
705
                                $renderer->setComments($comments);
706
                                $renderer->renderNestView($top_comments[$i]->getVar('id'), $admin_view);
707
                            }
708
                        }
709
                    }
710
                    // assign comment nav bar
711
                    $xoops->tpl()->assign('page_name', $plugin->pageName());
712
                    $xoops->tpl()->assign('order', $order);
713
                    $xoops->tpl()->assign('COMMENTS_OLD1ST', static::DISPLAY_OLDEST_FIRST);
714
                    $xoops->tpl()->assign('COMMENTS_NEW1ST', static::DISPLAY_NEWEST_FIRST);
715
                    $xoops->tpl()->assign('itemid', $itemid);
716
                    $xoops->tpl()->assign('item_name', $plugin->itemName());
717
                    unset($postcomment_link);
718
                    if ($xoops->getModuleConfig('com_anonpost') || $xoops->isUser()) {
719
                        $postcomment_link = $this->url(
720
                            'comment_new.php?com_modid=' . $modid . '&amp;com_itemid=' . $itemid
721
                            . '&amp;com_order=' . $order . '&amp;com_mode=' . $mode
722
                        );
723
                        $xoops->tpl()->assign('anon_canpost', true);
724
                    }
725
                    $link_extra = '';
726
                    if (is_array($extraParams = $plugin->extraParams())) {
727
                        foreach ($extraParams as $extra_param) {
728 View Code Duplication
                            if (isset($_POST[$extra_param])) {
729
                                $extra_param_val = $_POST[$extra_param];
730
                            } else {
731
                                if (isset($_GET[$extra_param])) {
732
                                    $extra_param_val = $_GET[$extra_param];
733
                                }
734
                            }
735
                            if (isset($extra_param_val)) {
736
                                $link_extra .= '&amp;' . $extra_param . '=' . $extra_param_val;
737
                                $hidden_value = htmlspecialchars($extra_param_val, ENT_QUOTES);
738
                                $xoops->tpl()->assign('extra_param', $extra_param);
739
                                $xoops->tpl()->assign('hidden_value', $hidden_value);
740
                            }
741
                        }
742
                    }
743
                    if (isset($postcomment_link)) {
744
                        $xoops->tpl()->assign('postcomment_link', $postcomment_link);
745
                        $xoops->tpl()->assign('link_extra', $link_extra);
746
                    }
747
                    $xoops->tpl()->assign(array(
748
                        'comments_editlink'   => $this->url('comment_edit.php?com_modid=' . $modid . '&amp;com_itemid=' . $itemid . '&amp;com_order=' . $order . '&amp;com_mode=' . $mode . '' . $link_extra),
749
                        'comments_deletelink' => $this->url('comment_delete.php?com_modid=' . $modid . '&amp;com_itemid=' . $itemid . '&amp;com_order=' . $order . '&amp;com_mode=' . $mode . '' . $link_extra),
750
                        'comments_replylink'  => $this->url('comment_reply.php?com_modid=' . $modid . '&amp;com_itemid=' . $itemid . '&amp;com_order=' . $order . '&amp;com_mode=' . $mode . '' . $link_extra)
751
                    ));
752
753
                    // assign some lang variables
754
                    $xoops->tpl()->assign(array(
755
                        'comments_lang_from'    => _MD_COMMENTS_FROM,
756
                        'comments_lang_joined'  => _MD_COMMENTS_JOINED,
757
                        'comments_lang_posts'   => _MD_COMMENTS_POSTS,
758
                        'comments_lang_poster'  => _MD_COMMENTS_POSTER,
759
                        'comments_lang_thread'  => _MD_COMMENTS_THREAD,
760
                        'comments_lang_edit'    => XoopsLocale::A_EDIT,
761
                        'comments_lang_delete'  => XoopsLocale::A_DELETE,
762
                        'comments_lang_reply'   => XoopsLocale::A_REPLY,
763
                        'comments_lang_subject' => _MD_COMMENTS_REPLIES,
764
                        'comments_lang_posted'  => _MD_COMMENTS_POSTED,
765
                        'comments_lang_updated' => _MD_COMMENTS_UPDATED,
766
                        'comments_lang_notice'  => _MD_COMMENTS_NOTICE
767
                    ));
768
                }
769
            }
770
        }
771
    }
772
773
    public function displayEdit()
774
    {
775
        $xoops = Xoops::getInstance();
776
777
        /* @var $comment CommentsComment */
778
        $comment = $this->getHandlerComment()->get(Request::getInt('com_id'));
779
        if (!is_object($comment)) {
780
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
781
        }
782
        $module = $xoops->getModuleById($comment->getVar('modid'));
783
        if (!is_object($module)) {
784
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
785
        }
786
787 View Code Duplication
        if ((!$xoops->isAdminSide
788
                && static::APPROVE_NONE == $xoops->getModuleConfig('com_rule', $module->getVar('dirname')))
789
            || (!$xoops->isUser() && !$xoops->getModuleConfig('com_anonpost', $module->getVar('dirname')))
790
            || !$xoops->isModule()
791
        ) {
792
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
793
        }
794
795
        /* @var $plugin CommentsPluginInterface */
796
        if ($plugin = \Xoops\Module\Plugin::getPlugin($module->getVar('dirname'), 'comments')) {
0 ignored issues
show
Unused Code introduced by
$plugin is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
797
            $xoops->header();
798
            $this->displayCommentForm($comment);
799
            $xoops->footer();
800
        }
801
        $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
802
    }
803
804
    public function displayDelete()
0 ignored issues
show
Coding Style introduced by
displayDelete uses the super-global variable $_GET which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
805
    {
806
        $xoops = Xoops::getInstance();
807
        $op = Request::getCmd('op', 'delete', 'POST');
808
        $mode = Request::getString('com_mode', 'flat');
809
        $order = Request::getString('com_order', static::DISPLAY_OLDEST_FIRST);
810
        $id = Request::getInt('com_id');
811
812
        /* @var $comment CommentsComment */
813
        /* @var $comment_handler CommentsCommentHandler */
814
        $comment_handler = $this->getHandlerComment();
815
        $comment = $comment_handler->get($id);
816
        if (!is_object($comment)) {
817
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
818
        }
819
        $module = $xoops->getModuleById($comment->getVar('modid'));
820
        if (!is_object($module)) {
821
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
822
        }
823
824 View Code Duplication
        if ((!$xoops->isAdminSide
825
                && static::APPROVE_NONE == $xoops->getModuleConfig('com_rule', $module->getVar('dirname')))
826
            || (!$xoops->isUser() && !$xoops->getModuleConfig('com_anonpost', $module->getVar('dirname')))
827
            || !$xoops->isModule()
828
        ) {
829
            $xoops->redirect(\XoopsBaseConfig::get('url'), 1, XoopsLocale::E_NO_ACCESS_PERMISSION);
830
        }
831
832
        $modid = $module->getVar('mid');
833
        /* @var $plugin CommentsPluginInterface */
834
        if ($plugin = \Xoops\Module\Plugin::getPlugin($module->getVar('dirname'), 'comments')) {
835
            if ($xoops->isAdminSide) {
836
                $redirect_page = $this->url('admin/main.php?com_modid=' . $modid . '&amp;com_itemid');
837
            } else {
838
                $redirect_page = $xoops->url('modules/' . $module->getVar('dirname') . '/' . $plugin->pageName() . '?');
839
                $comment_confirm_extra = array();
840
                if (is_array($extraParams = $plugin->extraParams())) {
841
                    foreach ($extraParams as $extra_param) {
842
                        if (isset($_GET[$extra_param])) {
843
                            $redirect_page .= $extra_param . '=' . $_GET[$extra_param] . '&amp;';
844
                            // for the confirmation page
845
                            $comment_confirm_extra[$extra_param] = $_GET[$extra_param];
846
                        }
847
                    }
848
                }
849
                $redirect_page .= $plugin->itemName();
850
            }
851
852
            $accesserror = false;
853
            if (!$xoops->isUser()) {
854
                $accesserror = true;
855
            } else {
856
                if (!$xoops->user->isAdmin($modid)) {
857
                    $accesserror = true;
858
                }
859
            }
860
861
            if (false != $accesserror) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
862
                $ref = $xoops->getEnv('HTTP_REFERER');
863
                if ($ref != '') {
864
                    $xoops->redirect($ref, 2, XoopsLocale::E_NO_ACCESS_PERMISSION);
0 ignored issues
show
Bug introduced by
It seems like $ref defined by $xoops->getEnv('HTTP_REFERER') on line 862 can also be of type boolean; however, Xoops::redirect() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
865
                } else {
866
                    $xoops->redirect(
867
                        $redirect_page . '?' . $plugin->itemName() . '=' . (int)($id),
868
                        2,
869
                        XoopsLocale::E_NO_ACCESS_PERMISSION
870
                    );
871
                }
872
            }
873
874
            switch ($op) {
875
                case 'delete_one':
876
                    if (!$comment_handler->delete($comment)) {
0 ignored issues
show
Bug introduced by
It seems like $comment defined by $comment_handler->get($id) on line 815 can be null; however, Xoops\Core\Kernel\XoopsP...ObjectHandler::delete() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
877
                        $xoops->header();
878
                        echo $xoops->alert('error', _MD_COMMENTS_COMDELETENG . ' (ID: ' . $comment->getVar('id') . ')');
879
                        $xoops->footer();
880
                    }
881
882
                    $itemid = $comment->getVar('itemid');
883
884
                    $criteria = new CriteriaCompo(new Criteria('modid', $modid));
885
                    $criteria->add(new Criteria('itemid', $itemid));
886
                    $criteria->add(new Criteria('status', static::STATUS_ACTIVE));
887
                    $comment_count = $comment_handler->getCount($criteria);
888
                    $plugin->update($itemid, $comment_count);
889
890
                    // update user posts if its not an anonymous post
891
                    if ($comment->getVar('uid') != 0) {
892
                        $member_handler = $xoops->getHandlerMember();
893
                        $poster = $member_handler->getUser($comment->getVar('uid'));
894
                        if (is_object($poster)) {
895
                            $member_handler->updateUserByField($poster, 'posts', $poster->getVar('posts') - 1);
896
                        }
897
                    }
898
899
                    // get all comments posted later within the same thread
900
                    $thread_comments = $comment_handler->getThread($comment->getVar('rootid'), $id);
901
902
                    $xot = new XoopsObjectTree($thread_comments, 'id', 'pid', 'rootid');
903
                    $child_comments = $xot->getFirstChild($id);
904
                    // now set new parent ID for direct child comments
905
                    $new_pid = $comment->getVar('pid');
906
                    $errs = array();
907
                    foreach (array_keys($child_comments) as $i) {
908
                        $child_comments[$i]->setVar('pid', $new_pid);
909
                        // if the deleted comment is a root comment, need to change root id to own id
910
                        if (false != $comment->isRoot()) {
911
                            $new_rootid = $child_comments[$i]->getVar('id');
912
                            $child_comments[$i]->setVar('rootid', $child_comments[$i]->getVar('id'));
913
                            if (!$comment_handler->insert($child_comments[$i])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $comment_handler->insert($child_comments[$i]) of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
914
                                $errs[] = 'Could not change comment parent ID from <strong>' . $id
915
                                    . '</strong> to <strong>' . $new_pid . '</strong>. (ID: ' . $new_rootid . ')';
916
                            } else {
917
                                // need to change root id for all its child comments as well
918
                                $c_child_comments = $xot->getAllChild($new_rootid);
919
                                $cc_count = count($c_child_comments);
0 ignored issues
show
Unused Code introduced by
$cc_count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
920
                                foreach (array_keys($c_child_comments) as $j) {
921
                                    $c_child_comments[$j]->setVar('rootid', $new_rootid);
922
                                    if (!$comment_handler->insert($c_child_comments[$j])) {
923
                                        $errs[] = 'Could not change comment root ID from <strong>' . $id
924
                                            . '</strong> to <strong>' . $new_rootid . '</strong>.';
925
                                    }
926
                                }
927
                            }
928
                        } else {
929
                            if (!$comment_handler->insert($child_comments[$i])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $comment_handler->insert($child_comments[$i]) of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
930
                                $errs[] = 'Could not change comment parent ID from <strong>' . $id
931
                                    . '</strong> to <strong>' . $new_pid . '</strong>.';
932
                            }
933
                        }
934
                    }
935
                    if (count($errs) > 0) {
936
                        $xoops->header();
937
                        echo $xoops->alert('error', $errs);
938
                        $xoops->footer();
939
                        exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method displayDelete() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
940
                    }
941
                    $xoops->redirect($redirect_page . '=' . $itemid . '&amp;com_order=' . $order . '&amp;com_mode=' . $mode, 1, _MD_COMMENTS_COMDELETED);
942
                    break;
943
944
                case 'delete_all':
945
                    $rootid = $comment->getVar('rootid');
946
947
                    // get all comments posted later within the same thread
948
                    $thread_comments = $comment_handler->getThread($rootid, $id);
949
950
                    // construct a comment tree
951
                    $xot = new XoopsObjectTree($thread_comments, 'id', 'pid', 'rootid');
952
                    $child_comments = $xot->getAllChild($id);
953
                    // add itself here
954
                    $child_comments[$id] = $comment;
955
                    $msgs = array();
956
                    $deleted_num = array();
957
                    $member_handler = $xoops->getHandlerMember();
958
                    foreach (array_keys($child_comments) as $i) {
959
                        if (!$comment_handler->delete($child_comments[$i])) {
0 ignored issues
show
Bug introduced by
It seems like $child_comments[$i] can be null; however, delete() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
960
                            $msgs[] = _MD_COMMENTS_COMDELETENG . ' (ID: ' . $child_comments[$i]->getVar('id') . ')';
961
                        } else {
962
                            $msgs[] = _MD_COMMENTS_COMDELETED . ' (ID: ' . $child_comments[$i]->getVar('id') . ')';
963
                            // store poster ID and deleted post number into array for later use
964
                            $poster_id = $child_comments[$i]->getVar('uid');
965 View Code Duplication
                            if ($poster_id > 0) {
966
                                $deleted_num[$poster_id] =
967
                                    !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);
968
                            }
969
                        }
970
                    }
971 View Code Duplication
                    foreach ($deleted_num as $user_id => $post_num) {
972
                        // update user posts
973
                        $poster = $member_handler->getUser($user_id);
974
                        if (is_object($poster)) {
975
                            $member_handler->updateUserByField($poster, 'posts', $poster->getVar('posts') - $post_num);
976
                        }
977
                    }
978
979
                    $itemid = $comment->getVar('itemid');
980
981
                    $criteria = new CriteriaCompo(new Criteria('modid', $modid));
982
                    $criteria->add(new Criteria('itemid', $itemid));
983
                    $criteria->add(new Criteria('status', static::STATUS_ACTIVE));
984
                    $comment_count = $comment_handler->getCount($criteria);
985
                    $plugin->update($itemid, $comment_count);
986
987
                    $xoops->header();
988
                    echo $xoops->alert('info', $msgs);
989
                    echo '<br /><a href="' . $redirect_page . '=' . $itemid . '&amp;com_order=' . $order
990
                        . '&amp;com_mode=' . $mode . '">' . XoopsLocale::GO_BACK . '</a>';
991
                    $xoops->footer();
992
                    break;
993
994
                case 'delete':
995
                default:
996
                    $xoops->header();
997
                    $comment_confirm = array(
998
                        'com_id'    => $id,
999
                        'com_mode'  => $mode,
1000
                        'com_order' => $order,
1001
                        'op'        => array(
1002
                            _MD_COMMENTS_DELETEONE => 'delete_one',
1003
                            _MD_COMMENTS_DELETEALL => 'delete_all'
1004
                        )
1005
                    );
1006
                    if (!empty($comment_confirm_extra) && is_array($comment_confirm_extra)) {
1007
                        $comment_confirm = $comment_confirm + $comment_confirm_extra;
1008
                    }
1009
                    echo $xoops->confirm($comment_confirm, 'comment_delete.php', _MD_COMMENTS_DELETESELECT);
1010
                    $xoops->footer();
1011
                    break;
1012
            }
1013
        }
1014
    }
1015
1016
    /**
1017
     * @param XoopsModule $module module supporting comments
1018
     *
1019
     * @return void
1020
     */
1021 View Code Duplication
    public function insertModuleRelations(XoopsModule $module)
1022
    {
1023
        $xoops = Xoops::getInstance();
1024
        $config_handler = $xoops->getHandlerConfig();
1025
        $configs = $this->getPluginableConfigs();
1026
1027
        //$existingConfigs = $xoops->getModuleConfigs($module->getVar('dirname'));
1028
        $existingConfigs = $config_handler->getConfigsByModule($module->getVar('mid'));
1029
        $order = $config_handler->getConfigCount(
1030
            new \Xoops\Core\Kernel\Criteria('conf_modid', $module->getVar('mid'))
1031
        );
1032
        //$order = count($existingConfigs);
1033
        foreach ($configs as $config) {
1034
            if (!isset($existingConfigs[$config['name']])) {
1035
                $confobj = $config_handler->createConfig();
1036
                $confobj->setVar('conf_modid', $module->getVar('mid'));
1037
                $confobj->setVar('conf_catid', 0);
1038
                $confobj->setVar('conf_name', $config['name']);
1039
                $confobj->setVar('conf_title', $config['title']);
1040
                $confobj->setVar('conf_desc', $config['description']);
1041
                $confobj->setVar('conf_formtype', $config['formtype']);
1042
                $confobj->setVar('conf_valuetype', $config['valuetype']);
1043
                $confobj->setConfValueForInput($config['default']);
1044
                $confobj->setVar('conf_order', $order);
1045
                if (isset($config['options']) && is_array($config['options'])) {
1046
                    foreach ($config['options'] as $key => $value) {
1047
                        $confop = $config_handler->createConfigOption();
1048
                        $confop->setVar('confop_name', $key);
1049
                        $confop->setVar('confop_value', $value);
1050
                        $confobj->setConfOptions($confop);
1051
                        unset($confop);
1052
                    }
1053
                }
1054
                ++$order;
1055
                $config_handler->insertConfig($confobj);
1056
            }
1057
        }
1058
    }
1059
1060
    /**
1061
     * @param XoopsModule $module module supporting comments
1062
     *
1063
     * @return void
1064
     */
1065 View Code Duplication
    public function deleteModuleRelations(XoopsModule $module)
1066
    {
1067
        $xoops = Xoops::getInstance();
1068
        $this->getHandlerComment()->deleteByModule($module->getVar('mid'));
1069
1070
1071
        $configNames = array('com_rule', 'com_anonpost');
1072
        $config_handler = $xoops->getHandlerConfig();
1073
1074
        //Delete all configs
1075
        $criteria = new CriteriaCompo();
1076
        $criteria->add(new Criteria('conf_modid', $module->getVar('mid')));
1077
        $criteria->add(new Criteria('conf_name', "('" . implode("','", $configNames) . "')", 'IN'));
1078
        $configs = $config_handler->getConfigs($criteria);
1079
        /* @var $config XoopsConfigItem */
1080
        foreach ($configs as $config) {
1081
            $config_handler->deleteConfig($config);
1082
        }
1083
    }
1084
1085
    /**
1086
     * @return array
1087
     */
1088
    public function getPluginableConfigs()
1089
    {
1090
        $configs = array();
1091
        array_push($configs, array(
1092
            'name'        => 'com_rule',
1093
            'title'       => '_MD_COMMENTS_COMRULES',
1094
            'description' => '',
1095
            'formtype'    => 'select',
1096
            'valuetype'   => 'int',
1097
            'default'     => 1,
1098
            'options'     => array(
1099
                '_MD_COMMENTS_COMNOCOM'        => static::APPROVE_NONE,
1100
                '_MD_COMMENTS_COMAPPROVEALL'   => static::APPROVE_ALL,
1101
                '_MD_COMMENTS_COMAPPROVEUSER'  => static::APPROVE_USER,
1102
                '_MD_COMMENTS_COMAPPROVEADMIN' => static::APPROVE_ADMIN
1103
            )
1104
        ));
1105
        array_push($configs, array(
1106
            'name'        => 'com_anonpost',
1107
            'title'       => '_MD_COMMENTS_COMANONPOST',
1108
            'description' => '',
1109
            'formtype'    => 'yesno',
1110
            'valuetype'   => 'int',
1111
            'default'     => 0
1112
        ));
1113
        return $configs;
1114
    }
1115
}
1116