Passed
Push — master ( d3e687...4990f6 )
by Michael
02:43
created

newbb_search()   F

Complexity

Conditions 25
Paths 18432

Size

Total Lines 116
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 25
eloc 73
nc 18432
nop 9
dl 0
loc 116
rs 2
c 1
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 30 and the first side effect is on line 16.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * NewBB 5.0x,  the forum module for XOOPS project
4
 *
5
 * @copyright      XOOPS Project (https://xoops.org)
6
 * @license        GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
7
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>, irmtfan <[email protected]>
8
 * @since          4.3
9
 * @package        module::newbb
10
 */
11
12
use XoopsModules\Newbb;
13
14
// completely rewrite by irmtfan - remove hardcode database access, solve order issues, add post_text & topic_id, add highlight and reduce queries
15
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
16
include_once $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
17
18
/**
19
 * @param                $queryarray
20
 * @param                $andor
21
 * @param                $limit
22
 * @param                $offset
23
 * @param                $userid
24
 * @param  int           $forums
25
 * @param  int           $sortby
26
 * @param  string        $searchin
27
 * @param  CriteriaCompo $criteriaExtra
28
 * @return array
29
 */
30
function newbb_search(
31
    $queryarray,
32
    $andor,
33
    $limit,
34
    $offset,
35
    $userid,
36
    $forums = 0,
37
    $sortby = 0,
38
    $searchin = 'both',
39
    CriteriaCompo $criteriaExtra = null
0 ignored issues
show
Bug introduced by
The type CriteriaCompo 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...
40
) {
41
    global $myts, $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
42
    // irmtfan - in XOOPSCORE/search.php $GLOBALS['xoopsModuleConfig'] is not set
43
    if (!isset($GLOBALS['xoopsModuleConfig'])) {
44
        $GLOBALS['xoopsModuleConfig'] = newbbLoadConfig();
45
    }
46
    // irmtfan - in XOOPSCORE/search.php $xoopsModule is not set
47
    if (!is_object($GLOBALS['xoopsModule']) && is_object($GLOBALS['module'])
48
        && 'newbb' === $GLOBALS['module']->getVar('dirname')) {
49
        $GLOBALS['xoopsModule'] = $GLOBALS['module'];
50
    }
51
    /** @var Newbb\ForumHandler $forumHandler */
52
    $forumHandler = Newbb\Helper::getInstance()->getHandler('Forum');
53
    $validForums  = $forumHandler->getIdsByValues($forums); // can we use view permission? $forumHandler->getIdsByValues($forums, "view")
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
54
55
    $criteriaPost = new \CriteriaCompo();
56
    $criteriaPost->add(new \Criteria('p.approved', 1), 'AND'); // only active posts
0 ignored issues
show
Bug introduced by
The type Criteria 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...
57
58
    $forum_list = [];// get forum lists just for forum names
59
    if (count($validForums) > 0) {
60
        $criteriaPermissions = new \CriteriaCompo();
61
        $criteriaPermissions->add(new \Criteria('p.forum_id', '(' . implode(',', $validForums) . ')', 'IN'), 'AND');
62
        $forum_list = $forumHandler->getAll(new \Criteria('forum_id', '(' . implode(', ', $validForums) . ')', 'IN'), 'forum_name', false);
63
    }
64
65
    if (is_numeric($userid) && 0 !== $userid) {
66
        $criteriaUser = new \CriteriaCompo();
67
        $criteriaUser->add(new \Criteria('p.uid', $userid), 'OR');
68
    } elseif (is_array($userid) && count($userid) > 0) {
69
        $userid       = array_map('intval', $userid);
70
        $criteriaUser = new \CriteriaCompo();
71
        $criteriaUser->add(new \Criteria('p.uid', '(' . implode(',', $userid) . ')', 'IN'), 'OR');
72
    }
73
74
    $count = 0;
75
    if (is_array($queryarray)) {
76
        $count = count($queryarray);
77
    }
78
    $highlightKey = '';
79
    if ($count > 0) {
80
        $criteriaKeywords = new \CriteriaCompo();
81
        foreach ($queryarray as $queryTerm) {
82
            $termCriteria  = new \CriteriaCompo();
83
            $queryTermLike = '%' . $xoopsDB->escape($queryTerm) . '%';
84
            if ('title' === $searchin || 'both' === $searchin) {
85
                $termCriteria->add(new \Criteria('p.subject', $queryTermLike, 'LIKE'), 'OR');
86
            }
87
            if ('text' === $searchin || 'both' === $searchin) {
88
                $termCriteria->add(new \Criteria('t.post_text', $queryTermLike, 'LIKE'), 'OR');
89
            }
90
            $criteriaKeywords->add($termCriteria, $andor);
91
        }
92
        // add highlight keywords to post links
93
        $highlightKey = '&amp;keywords=' . implode(' ', $queryarray);
94
        $highlightKey = str_replace(' ', '+', $highlightKey);
95
    }
96
    $criteria = new \CriteriaCompo();
97
    $criteria->add($criteriaPost, 'AND');
98
    if (isset($criteriaPermissions)) {
99
        $criteria->add($criteriaPermissions, 'AND');
100
    }
101
    if (isset($criteriaUser)) {
102
        $criteria->add($criteriaUser, 'AND');
103
    }
104
    if (isset($criteriaKeywords)) {
105
        $criteria->add($criteriaKeywords, 'AND');
106
    }
107
    if (isset($criteriaExtra)) {
108
        $criteria->add($criteriaExtra, 'AND');
109
    }
110
    //$criteria->setLimit($limit); // no need for this
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
111
    //$criteria->setStart($offset); // no need for this
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
112
113
    if (empty($sortby)) {
114
        $sortby = 'p.post_time';
115
    }
116
    $criteria->setSort($sortby);
117
    $order = 'ASC';
118
    if ('p.post_time' === $sortby) {
119
        $order = 'DESC';
120
    }
121
    $criteria->setOrder($order);
122
123
    /** @var Newbb\PostHandler $postHandler */
124
    $postHandler = Newbb\Helper::getInstance()->getHandler('Post');
125
    $posts       = $postHandler->getPostsByLimit($criteria, $limit, $offset);
126
127
    $ret = [];
128
    $i   = 0;
129
    foreach (array_keys($posts) as $id) {
130
        /** @var Newbb\Post $post */
131
        $post                  = $posts[$id];
132
        $post_data             = $post->getPostBody();
133
        $ret[$i]['topic_id']   = $post->getVar('topic_id');
134
        $ret[$i]['link']       = XOOPS_URL . '/modules/newbb/viewtopic.php?post_id=' . $post->getVar('post_id') . $highlightKey; // add highlight key
0 ignored issues
show
Bug introduced by
The constant XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
135
        $ret[$i]['title']      = $post_data['subject'];
136
        $ret[$i]['time']       = $post_data['date'];
137
        $ret[$i]['forum_name'] = $myts->htmlSpecialChars($forum_list[$post->getVar('forum_id')]['forum_name']);
138
        $ret[$i]['forum_link'] = XOOPS_URL . '/modules/newbb/viewforum.php?forum=' . $post->getVar('forum_id');
139
        $ret[$i]['post_text']  = $post_data['text'];
140
        $ret[$i]['uid']        = $post->getVar('uid');
141
        $ret[$i]['poster']     = $post->getVar('uid') ? '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $ret[$i]['uid'] . '">' . $post_data['author'] . '</a>' : $post_data['author'];
142
        ++$i;
143
    }
144
145
    return $ret;
146
}
147