wfdownloads_search()   F
last analyzed

Complexity

Conditions 36
Paths 112

Size

Total Lines 251
Code Lines 109

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 36
eloc 109
nc 112
nop 9
dl 0
loc 251
rs 3.2533
c 0
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
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
/**
13
 * Wfdownloads module
14
 *
15
 * @copyright       XOOPS Project (https://xoops.org)
16
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
17
 * @package         wfdownload
18
 * @since           3.23
19
 * @author          Xoops Development Team
20
 */
21
22
use XoopsModules\Wfdownloads;
23
use XoopsModules\Wfdownloads\{
24
    Helper,
25
    Utility
26
};
27
/** @var Helper $helper */
28
/** @var Utility $utility */
29
30
defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
31
require_once __DIR__ . '/common.php';
32
/**
33
 * @param        $queryArray
34
 * @param        $andor
35
 * @param        $limit
36
 * @param        $offset
37
 * @param int    $userId
38
 * @param array  $categories
39
 * @param int    $sortBy
40
 * @param string $searchIn
41
 * @param string $extra
42
 *
43
 * @return array
44
 */
45
function wfdownloads_search($queryArray, $andor, $limit, $offset, $userId = 0, $categories = [], $sortBy = 0, $searchIn = '', $extra = '')
0 ignored issues
show
Unused Code introduced by
The parameter $searchIn 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

45
function wfdownloads_search($queryArray, $andor, $limit, $offset, $userId = 0, $categories = [], $sortBy = 0, /** @scrutinizer ignore-unused */ $searchIn = '', $extra = '')

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...
Unused Code introduced by
The parameter $extra 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

45
function wfdownloads_search($queryArray, $andor, $limit, $offset, $userId = 0, $categories = [], $sortBy = 0, $searchIn = '', /** @scrutinizer ignore-unused */ $extra = '')

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...
Unused Code introduced by
The parameter $sortBy 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

45
function wfdownloads_search($queryArray, $andor, $limit, $offset, $userId = 0, $categories = [], /** @scrutinizer ignore-unused */ $sortBy = 0, $searchIn = '', $extra = '')

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...
Unused Code introduced by
The parameter $categories 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

45
function wfdownloads_search($queryArray, $andor, $limit, $offset, $userId = 0, /** @scrutinizer ignore-unused */ $categories = [], $sortBy = 0, $searchIn = '', $extra = '')

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...
46
{
47
    $helper = Helper::getInstance();
48
49
    $userGroups = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : [0 => XOOPS_GROUP_ANONYMOUS];
50
51
    /** @var \XoopsGroupPermHandler $grouppermHandler */
52
    $grouppermHandler         = xoops_getHandler('groupperm');
53
    $allowedDownCategoriesIds = $grouppermHandler->getItemIds('WFDownCatPerm', $userGroups, $helper->getModule()->mid());
54
    $downloads_lids           = $downloads_intersect = [];
55
    $criteria                 = new CriteriaCompo(new Criteria('cid', '(' . implode(',', $allowedDownCategoriesIds) . ')', 'IN'));
56
    if (0 != $userId) {
57
        $criteria->add(new Criteria('submitter', (int)$userId));
58
    }
59
60
    // changed and added - start - April 23, 2006 - jwe
61
    // moved these up here since we need to complete the $criteria object a little sooner now
62
    $criteria->setSort('published');
63
    $criteria->setOrder('DESC');
64
65
    // because count() returns 1 even if a supplied variable
66
    // is not an array, we must check if $querryarray is really an array
67
    $queryArray_count = 0;
68
    if ((is_array($queryArray) && $queryArray_count = count($queryArray)) || 0 != $userId) {
69
        // $userId != 0 added August 13 2007 -- ACCOUNTS FOR CASES WHERE THERE ARE NO QUERY TERMS BUT A USER ID IS PASSED -- FREEFORM SOLUTIONS
70
        if (0 == $queryArray_count) {
71
            $queryArray_count = 1; // AUGUST 13 2007 -- MAKE COUNT EQUAL 1 SINCE WE HAVE TO DO AT LEAST ONE SEARCH (BASED ON USER ID) EVEN IF THERE ARE NO QUERY TERMS -- FREEFORM SOLUTIONS
0 ignored issues
show
Unused Code introduced by
The assignment to $queryArray_count is dead and can be removed.
Loading history...
72
            $queryArray       = [];
73
        }
74
75
        // Formulize module support - jpc - start
76
        /*
77
                // queryarray[0] now handled inside loop -- perhaps this "0 out of loop, 1 and up inside loop" approach was an unsuccessful attempt to fix the "unset" bug.  Interesting that subcrit was unset prior to the FOR loop.
78
                $subCriteria = new \CriteriaCompo(new \Criteria("title", "%".$queryArray[0]."%", 'LIKE'), 'OR');
79
                $subCriteria->add(new \Criteria("description", "%".$queryArray[0]."%", 'LIKE'), 'OR');
80
                $criteria->add($subCriteria);
81
                unset($subCriteria);
82
83
                $allSubCriterias = new \CriteriaCompo(); // added to fix bug related to nesting of ( )
84
                for ($i = 0;$i < $queryArray_count;++$i) { // 1 changed to 0 so everything happens in one loop now
85
                    $subCriteria = new \CriteriaCompo(new \Criteria("title", "%".$queryArray[$i]."%", 'LIKE'), 'OR');
86
                    $subCriteria->add(new \Criteria("description", "%".$queryArray[$i]."%", 'LIKE'), 'OR');
87
                    $allSubCriterias->add($subCriteria, $andor); // $criteria changed to $allSubCriterias to fix bug
88
                    unset($subCriteria); // added to fix bug
89
                }
90
                $criteria->add($allSubCriterias); // added to fix bug
91
92
        There are two bugs in the above code: all subcrits need to be added to the main
93
        criteria as a group, so it was a bug to have them added one at a time as they
94
        were, since the nesting of the () in the rendered where clause is incorrect also
95
        there was a bug which caused only the first and last items in the query array to
96
        be processed, and the last item would be processed multiple times.  ie: terms
97
        "green, orange, black" resulted in a search for "green, black, black" -- this
98
        "bug" was introduced with php 4.4.0 (and some version of 5 as well) after a
99
        change in how objects are managed in memory or something like that.
100
        The fix is to specifically unset the $subCriteria object at the end of each
101
        iteration of the loop. The same bug hit Liase, Formulaire and Formulize.
102
        You can see the structure of the query by printing the output of $criteria's
103
        render or renderWhere method ( ie: print $criteria->renderWhere(); )
104
        However, the whole approach to handling queries has been changed, so the above
105
        code is unused.  It is included here for reference with regard to the bugs
106
        mentioned above.
107
        With custom forms, because a multi term query using AND could have some terms
108
        match only custom form fields and other terms match only native Wfdownloads
109
        fields, each term must be evaluated independently,
110
        across both modules, and then if an AND operator is in effect, the intersection
111
        of the results is returned.  If OR is in effect, then all results are returned.
112
        */
113
        // Determine what the custom forms are that need searching, if any
114
        if (Utility::checkModule('formulize')) {
115
            $fids = [];
116
            foreach ($allowedDownCategoriesIds as $cid) {
117
                $categoryObj = $helper->getHandler('Category')->get($cid);
118
                if (null !== $categoryObj && $fid = $categoryObj->getVar('formulize_fid')) {
119
                    $fids[] = $fid;
120
                }
121
            }
122
123
            // Set criteria for the captions that the user can see if necessary
124
            if ($fids && is_array($fids)) {
125
                $formulizeElementCriteria = new CriteriaCompo();
126
                $formulizeElementCriteria->add(new Criteria('ele_display', 1), 'OR');
127
                foreach ($userGroups as $group) {
128
                    $formulizeElementCriteria->add(new Criteria('ele_display', '%,' . $group . ',%', 'LIKE'), 'OR');
129
                }
130
                $formulizeElementCriteria->setSort('ele_order');
131
                $formulizeElementCriteria->setOrder('ASC');
132
            }
133
        }
134
135
        $downloadObjs = [];
136
        // Loop through all query terms
137
        foreach ($queryArray as $i => $iValue) {
138
            // Make a copy of the $criteria for use with this term only
139
            $queryCriteria = clone $criteria;
140
141
            // Setup criteria for searching the title and description fields of Wfdownloads for the current term
142
            $allSubCriterias = new CriteriaCompo();
143
            $thisSearchTerm  = count($queryArray) > 0 ? $queryArray[$i] : '';
144
            $subCriteria     = new CriteriaCompo();
145
            $subCriteria->add(new Criteria('title', '%' . $thisSearchTerm . '%', 'LIKE'), 'OR'); // search in title field
146
            $subCriteria->add(new Criteria('description', '%' . $thisSearchTerm . '%', 'LIKE'), 'OR'); // search in description fiels
147
            $allSubCriterias->add($subCriteria, $andor);
148
            unset($subCriteria);
149
150
            $saved_ids = [];
151
152
            // Find all IDs of entries in all custom forms which match the current term
153
            if (Utility::checkModule('formulize')) {
154
                foreach ($fids as $fid) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fids does not seem to be defined for all execution paths leading up to this point.
Loading history...
155
                    if (null === $formulizeElementsHandler) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formulizeElementsHandler does not seem to be defined for all execution paths leading up to this point.
Loading history...
156
                        $formulizeElementsHandler = $helper->getHandler('Elements', 'formulize');
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Wfdownloads\Helper::getHandler() has too many arguments starting with 'formulize'. ( Ignorable by Annotation )

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

156
                        /** @scrutinizer ignore-call */ 
157
                        $formulizeElementsHandler = $helper->getHandler('Elements', 'formulize');

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...
157
                    }
158
                    require_once XOOPS_ROOT_PATH . '/modules/formulize/include/extract.php';
159
                    // Setup the filter string based on the elements in the form and the current query term
160
                    $formulizeElements = $formulizeElementsHandler->getObjects2($formulizeElementCriteria, $fid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formulizeElementCriteria does not seem to be defined for all execution paths leading up to this point.
Loading history...
161
                    $filter_string     = '';
162
                    $indexer           = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $indexer is dead and can be removed.
Loading history...
163
                    $start             = 1;
164
                    foreach ($formulizeElements as $formulizeElement) {
165
                        if ($start) {
166
                            $filter_string = $formulizeElement->getVar('ele_id') . '/**/' . $iValue;
167
                            $start         = 0;
168
                        } else {
169
                            $filter_string .= '][' . $formulizeElement->getVar('ele_id') . '/**/' . $iValue;
170
                        }
171
                    }
172
                    unset($formulizeElements);
173
174
                    // Query for the ids of the records in the form that match the queryarray
175
                    $data           = getData('', $fid, $filter_string, 'OR'); // is a 'formulize' function
0 ignored issues
show
Bug introduced by
The function getData 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

175
                    $data           = /** @scrutinizer ignore-call */ getData('', $fid, $filter_string, 'OR'); // is a 'formulize' function
Loading history...
176
                    $formHandle     = getFormHandleFromEntry($data[0], 'uid'); // is a 'formulize' function
0 ignored issues
show
Bug introduced by
The function getFormHandleFromEntry 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

176
                    $formHandle     = /** @scrutinizer ignore-call */ getFormHandleFromEntry($data[0], 'uid'); // is a 'formulize' function
Loading history...
177
                    $temp_saved_ids = [];
178
                    foreach ($data as $entry) {
179
                        // Gather all IDs for this $fid
180
                        $found_ids      = internalRecordIds($entry, $formHandle); // is a 'formulize' function
0 ignored issues
show
Bug introduced by
The function internalRecordIds 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

180
                        $found_ids      = /** @scrutinizer ignore-call */ internalRecordIds($entry, $formHandle); // is a 'formulize' function
Loading history...
181
                        $temp_saved_ids = array_merge($temp_saved_ids, $found_ids);
182
                        unset($found_ids);
183
                    }
184
                    $saved_ids = array_merge($saved_ids, $temp_saved_ids); // merge this $fid's IDs with IDs from all previous $fids
185
                    unset($temp_saved_ids, $data);
186
                } // end of foreach $fids
187
            }
188
            // Formulize module support - jpc - end
189
            // Make a criteria object that includes the custom form ids that were found, if any
190
            if (count($saved_ids) > 0 && is_array($saved_ids)) {
191
                $subs_plus_custom = new CriteriaCompo(new Criteria('formulize_idreq', '(' . implode(',', $saved_ids) . ')', 'IN'));
192
                $subs_plus_custom->add($allSubCriterias, 'OR');
193
                $queryCriteria->add($subs_plus_custom);
194
                unset($allSubCriterias, $subs_plus_custom, $saved_ids);
195
            } else {
196
                $queryCriteria->add($allSubCriterias);
197
                unset($allSubCriterias);
198
            }
199
200
            // Check to see if this term matches any files
201
            $tempDownloadObjs = $helper->getHandler('Download')->getActiveDownloads($queryCriteria);
202
            unset($queryCriteria);
203
204
            // Make an array of the downloads based on the lid, and a separate list of all the lids found (the separate list is used in the case of an AND operator to derive an intersection of the hits across all search terms -- and it is used to determine the start and limit points of the main results array for an OR query)
205
            foreach ($tempDownloadObjs as $tempDownloadObj) {
206
                $downloadObjs[(int)$tempDownloadObj->getVar('lid')] = $tempDownloadObj;
207
                $downloads_lids[]                                   = (int)$tempDownloadObj->getVar('lid');
208
            }
209
210
            // Do an intersection of the found lids if the operator is AND
211
            if ('AND' === $andor) {
212
                if (null === $downloads_lids) {
213
                    $downloads_lids[] = '';
214
                }
215
                if (null === $downloads_intersect) {
216
                    $downloads_intersect = $downloads_lids;
217
                } // first time through initialize the array with all the found files
218
                $downloads_intersect = array_intersect($downloads_intersect, $downloads_lids);
219
                unset($downloads_lids);
220
            }
221
            unset($tempDownloadObjs);
222
        } // end of for loop through query terms
223
    } // end of if there are query terms
224
225
    // If an AND operator was used, cull the $downloadObjs array based on the intersection found
226
    if ('AND' === $andor) {
227
        foreach ($downloadObjs as $lid => $downloadObj) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $downloadObjs does not seem to be defined for all execution paths leading up to this point.
Loading history...
228
            if (!in_array($lid, $downloads_intersect)) {
229
                unset($downloadObjs[$lid]);
230
            }
231
        }
232
        $limitOffsetIndex = $downloads_intersect;
233
    } else {
234
        $limitOffsetIndex = $downloads_lids;
235
    }
236
237
    $ret        = [];
238
    $i          = 0;
239
    $storedLids = [];
240
241
    // foreach (array_keys($downloadObjs) as $i)
242
    if (is_array($limitOffsetIndex)) {
0 ignored issues
show
introduced by
The condition is_array($limitOffsetIndex) is always true.
Loading history...
243
        $counter = count($limitOffsetIndex);
244
        for ($x = $offset; $i < $limit && $x < $counter; ++$x) {
245
            $lid = $limitOffsetIndex[$x];
246
            $obj = $downloadObjs[$lid];
247
            if (is_object($obj) && !isset($storedLids[$lid])) {
248
                $storedLids[$lid] = true;
249
                $ret[$i]['image'] = 'assets/images/size2.gif';
250
                $ret[$i]['link']  = "singlefile.php?cid={$obj->getVar('cid')}&amp;lid={$lid}";
251
                $ret[$i]['title'] = $obj->getVar('title');
252
                $ret[$i]['time']  = $obj->getVar('published');
253
                $ret[$i]['uid']   = $obj->getVar('submitter');
254
                ++$i;
255
            }
256
        }
257
    }
258
259
    /*
260
        // Swish-e support EXPERIMENTAL
261
        if (($helper->getConfig('enable_swishe') === true) && Utility::checkSwishe() === true) {
262
    // IN PROGRESS
263
            $swisheCriteria = new \CriteriaCompo(new \Criteria('cid', '(' . implode(',', $allowedDownCategoriesIds) . ')', 'IN'));
264
            if ($userId != 0) {
265
                $swisheCriteria->add(new \Criteria('submitter', (int) $userId));
266
            }
267
            if ($andor = 'AND') {
268
                $swisheQueryWords = implode (' AND ', $queryArray);
269
            } elseif ($andor = 'OR') {
270
                $swisheQueryWords = implode (' OR ', $queryArray);
271
            } else {
272
                $swisheQueryWords = '';
273
            }
274
            if (strlen($swisheQueryWords) > 0) {
275
                $swisheSearchResults = Utility::searchSwishe($swisheQueryWords);
276
                foreach ($swisheSearchResults as $swisheSearchResult) {
277
                    $tempSwisheCriteria = clone($swisheCriteria);
278
                    $tempSwisheCriteria->add(new \Criteria('filename', $swisheSearchResult['file_path']));
279
                    $tempDownloadObjs = $helper->getHandler('Download')->getActiveDownloads($tempSwisheCriteria);
280
                    $tempDownloadObj = $tempDownloadObjs[0];
281
                    if (is_object($tempDownloadObj)) {
282
                        $tempRet['image'] = "assets/images/size2.gif";
283
                        $tempRet['link'] = "singlefile.php?cid={$tempDownloadObj->getVar('cid')}&amp;lid={$tempDownloadObj->getVar('lid')}";
284
                        $tempRet['title'] = $tempDownloadObj->getVar('title');
285
                        $tempRet['time'] = $tempDownloadObj->getVar('published');
286
                        $tempRet['uid'] = $tempDownloadObj->getVar('submitter');
287
    // IN PROGRESS
288
                    }
289
                }
290
            }
291
        }
292
        // Swish-e support EXPERIMENTAL
293
    */
294
295
    return $ret;
296
}
297