Completed
Push — master ( 2a7c05...7c1d68 )
by Michael
02:50
created

AdslightUtility   F

Complexity

Total Complexity 138

Size/Duplication

Total Lines 853
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 853
rs 1.263
c 0
b 0
f 0
wmc 138
lcom 0
cbo 0

26 Methods

Rating   Name   Duplication   Size   Complexity  
D expireAd() 0 127 14
A updateUserRating() 0 20 3
A updateItemRating() 0 20 3
B getTotalItems() 0 27 4
A getMyItemIds() 0 21 4
D getModuleOption() 0 34 10
A showImage() 0 14 1
D convertOrderByIn() 0 32 9
F convertOrderByTrans() 0 31 9
F convertOrderByOut() 0 29 9
B getEditor() 0 26 3
A checkTableExists() 0 7 1
A checkFieldExists() 0 7 1
A addField() 0 7 1
A getCatNameFromId() 0 18 3
A goCategory() 0 13 1
A returnAllAdsRss() 0 17 2
A returnAllAdsFluxRss() 0 15 2
A getNameType() 0 8 1
F getMoneyFormat() 0 88 30
B createFolder() 0 14 5
A copyFile() 0 14 1
B recurseCopy() 0 15 5
C checkXoopsVer() 0 33 7
A checkPhpVer() 0 16 4
B saveCategoryPermissions() 0 28 5

How to fix   Complexity   

Complex Class

Complex classes like AdslightUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AdslightUtility, and based on these observations, apply Extract Interface, too.

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 48 and the first side effect is on line 39.

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
// namespace Xoopsmodules/adslight;
4
/*
5
-------------------------------------------------------------------------
6
                     ADSLIGHT 2 : Module for Xoops
7
8
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
9
        Started with the Classifieds module and made MANY changes
10
        Website : http://www.luc-bizet.fr
11
        Contact : [email protected]
12
-------------------------------------------------------------------------
13
             Original credits below Version History
14
##########################################################################
15
#                    Classified Module for Xoops                         #
16
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
17
#      Started with the MyAds module and made MANY changes               #
18
##########################################################################
19
 Original Author: Pascal Le Boustouller
20
 Author Website : [email protected]
21
 Licence Type   : GPL
22
-------------------------------------------------------------------------
23
*/
24
25
/**
26
 * AdslightUtil Class
27
 *
28
 * @copyright   XOOPS Project (http://xoops.org)
29
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
30
 * @author      XOOPS Development Team
31
 * @package     AdsLight
32
 * @since       1.03
33
 *
34
 */
35
36
use Xmf\Request;
37
use Xmf\Module\Helper;
38
39
$moduleDirName = basename(dirname(__DIR__));
40
$main_lang     = '_' . strtoupper($moduleDirName);
41
require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
42
require_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
43
$myts = MyTextSanitizer::getInstance();
44
45
/**
46
 * Class AdslightUtility
47
 */
48
class AdslightUtility
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
49
{
50
    public static function expireAd()
51
    {
52
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
53
54
        $datenow = time();
55
        $message = '';
56
57
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM '
58
                                   . $xoopsDB->prefix('adslight_listing')
59
                                   . " WHERE valid='Yes'");
60
61
        while (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $comments is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
62
            $title     = $myts->htmlSpecialChars($title);
63
            $expire    = $myts->htmlSpecialChars($expire);
64
            $type      = $myts->htmlSpecialChars($type);
65
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
66
            $submitter = $myts->htmlSpecialChars($submitter);
67
            $remind    = $myts->htmlSpecialChars($remind);
68
            $supprdate = $dateann + ($expire * 86400);
69
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
70
71
            // give warning that add is about to expire
72
73
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
74
                && $valid === 'Yes'
75
                && $remind == 0
76
            ) {
77
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
78
79
                if ($email) {
80
                    $tags               = array();
81
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
82
                    $tags['TITLE']      = $title;
83
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
84
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
85
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
86
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
87
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
88
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
89
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
90
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
91
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
92
                    $tags['TYPE']       = static::getNameType($type);
93
                    $tags['DESCTEXT']   = $desctext;
94
                    $tags['HITS']       = $hits;
95
                    $tags['META_TITLE'] = $meta['title'];
96
                    $tags['SUBMITTER']  = $submitter;
97
                    $tags['DURATION']   = $expire;
98
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
99
                    $mail               =& getMailer();
100
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
101
                    $mail->setTemplate('listing_expires.tpl');
102
                    $mail->useMail();
103
                    $mail->multimailer->isHTML(true);
104
                    $mail->setFromName($meta['title']);
105
                    $mail->setFromEmail($xoopsConfig['adminmail']);
106
                    $mail->setToEmails($email);
107
                    $mail->setSubject($subject);
108
                    $mail->assign($tags);
109
                    $mail->send();
110
                    echo $mail->getErrors();
111
                }
112
            }
113
114
            // expire ad
115
116
            if ($supprdate < $datenow) {
117
                if ($photo != 0) {
118
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
119
120
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
121
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
122
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
123
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
124
                        if (file_exists("$destination/$url")) {
125
                            unlink("$destination/$url");
126
                        }
127
                        if (file_exists("$destination2/thumb_$url")) {
128
                            unlink("$destination2/thumb_$url");
129
                        }
130
                        if (file_exists("$destination3/resized_$url")) {
131
                            unlink("$destination3/resized_$url");
132
                        }
133
                    }
134
                }
135
136
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
137
138
                //  Specification for Japan:
139
                //  $message = ""._ADS_HELLO." $submitter,\n\n"._ADS_STOP2."\n $type : $title\n $desctext\n"._ADS_STOP3."\n\n"._ADS_VU." $lu "._ADS_VU2."\n\n"._ADS_OTHER." ".XOOPS_URL."/modules/myAds\n\n"._ADS_THANK."\n\n"._ADS_TEAM." ".$meta['title']."\n".XOOPS_URL."";
140
                if ($email) {
141
                    $tags               = array();
142
                    $subject            = '' . _ADSLIGHT_STOP . '';
143
                    $tags['TITLE']      = $title;
144
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
145
                    $tags['TYPE']       = static::getNameType($type);
146
                    $tags['DESCTEXT']   = $desctext;
147
                    $tags['HITS']       = $hits;
148
                    $tags['META_TITLE'] = $meta['title'];
149
                    $tags['SUBMITTER']  = $submitter;
150
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
151
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
152
                    $tags['MESSTEXT']   = stripslashes($message);
153
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
154
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
155
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
156
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
157
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
158
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
159
                    $tags['DURATION']   = $expire;
160
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
161
                    $mail               =& getMailer();
162
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
163
                    $mail->setTemplate('listing_expired.tpl');
164
                    $mail->useMail();
165
                    $mail->multimailer->isHTML(true);
166
                    $mail->setFromName($meta['title']);
167
                    $mail->setFromEmail($xoopsConfig['adminmail']);
168
                    $mail->setToEmails($email);
169
                    $mail->setSubject($subject);
170
                    $mail->assign($tags);
171
                    $mail->send();
172
                    echo $mail->getErrors();
173
                }
174
            }
175
        }
176
    }
177
178
    //updates rating data in itemtable for a given user
179
180
    /**
181
     * @param $sel_id
182
     */
183
    public static function updateUserRating($sel_id)
184
    {
185
        global $xoopsDB, $moduleDirName, $main_lang;
186
187
        $usid = Request::getInt('usid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
$usid 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...
188
189
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
190
        //echo $query;
191
        $voteresult  = $xoopsDB->query($query);
192
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
193
        $totalrating = 0;
194
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
195
            $totalrating += $rating;
196
        }
197
        $finalrating = $totalrating / $votesDB;
198
        $finalrating = number_format($finalrating, 4);
199
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
200
        //echo $query;
201
        $xoopsDB->query($query) || exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method updateUserRating() 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...
202
    }
203
204
    //updates rating data in itemtable for a given item
205
206
    /**
207
     * @param $sel_id
208
     */
209
    public static function updateItemRating($sel_id)
210
    {
211
        global $xoopsDB, $moduleDirName, $main_lang;
212
213
        $lid = Request::getInt('lid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
$lid 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...
214
215
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
216
        //echo $query;
217
        $voteresult  = $xoopsDB->query($query);
218
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
219
        $totalrating = 0;
220
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
221
            $totalrating += $rating;
222
        }
223
        $finalrating = $totalrating / $votesDB;
224
        $finalrating = number_format($finalrating, 4);
225
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
226
        //echo $query;
227
        $xoopsDB->query($query) || exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method updateItemRating() 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...
228
    }
229
230
    /**
231
     * @param        $sel_id
232
     * @param string $status
233
     *
234
     * @return int
235
     */
236
    public static function getTotalItems($sel_id, $status = '')
0 ignored issues
show
Unused Code introduced by
The parameter $status is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
237
    {
238
        global $xoopsDB, $mytree, $moduleDirName;
239
        $categories = AdslightUtility::getMyItemIds('adslight_view');
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
240
        $count      = 0;
241
        $arr        = array();
0 ignored issues
show
Unused Code introduced by
$arr 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...
242
        if (in_array($sel_id, $categories)) {
243
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " AND valid='Yes' AND status!='1'";
244
245
            $result = $xoopsDB->query($query);
246
            list($thing) = $xoopsDB->fetchRow($result);
247
            $count = $thing;
248
            $arr   = $mytree->getAllChildId($sel_id);
249
            $size  = count($arr);
250
            for ($i = 0; $i < $size; ++$i) {
251
                if (in_array($arr[$i], $categories)) {
252
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " AND valid='Yes' AND status!='1'";
253
254
                    $result2 = $xoopsDB->query($query2);
255
                    list($thing) = $xoopsDB->fetchRow($result2);
256
                    $count += $thing;
257
                }
258
            }
259
        }
260
261
        return $count;
262
    }
263
264
    /**
265
     * @param $permtype
266
     *
267
     * @return mixed
268
     */
269
    public static function getMyItemIds($permtype)
270
    {
271
        global $moduleDirName;
272
        static $permissions = array();
273
        if (is_array($permissions)
274
            && array_key_exists($permtype, $permissions)
275
        ) {
276
            return $permissions[$permtype];
277
        }
278
279
        /** @var XoopsModuleHandler $moduleHandler */
280
        $moduleHandler = xoops_getHandler('module');
281
        $myModule      = $moduleHandler->getByDirname('adslight');
282
        $groups        = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
283
        /** @var XoopsGroupPermHandler $gpermHandler */
284
        $gpermHandler           = xoops_getHandler('groupperm');
285
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
286
        $permissions[$permtype] = $categories;
287
288
        return $categories;
289
    }
290
291
    /**
292
     * Returns a module's option
293
     * @param        $option module option's name
294
     * @param string $repmodule
295
     *
296
     * @return option's value
0 ignored issues
show
Documentation introduced by
The doc-type option's could not be parsed: Unknown type name "option's" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
297
     */
298
    public static function getModuleOption($option, $repmodule = 'adslight')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
299
    {
300
        global $xoopsModule;
301
        static $tbloptions = array();
302
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
303
            return $tbloptions[$option];
304
        }
305
306
        $retval = false;
307
        if (isset($GLOBALS['xoopsModuleConfig'])
308
            && (is_object($xoopsModule)
309
                && $xoopsModule->getVar('dirname') == $repmodule
310
                && $xoopsModule->getVar('isactive'))
311
        ) {
312
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
313
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
314
            }
315
        } else {
316
            /** @var XoopsModuleHandler $moduleHandler */
317
            $moduleHandler = xoops_getHandler('module');
318
            $module        = $moduleHandler->getByDirname($repmodule);
319
            /** @var XoopsModuleHandler $moduleHandler */
320
            $configHandler = xoops_getHandler('config');
321
            if ($module) {
322
                $moduleConfig = $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
0 ignored issues
show
Unused Code introduced by
$moduleConfig 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...
323
                if (null !== ($moduleHelper->getConfig($option))) {
0 ignored issues
show
Bug introduced by
The variable $moduleHelper does not exist. Did you mean $module?

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...
324
                    $retval = $moduleHelper->getConfig($option);
0 ignored issues
show
Bug introduced by
The variable $moduleHelper does not exist. Did you mean $module?

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...
325
                }
326
            }
327
        }
328
        $tbloptions[$option] = $retval;
329
330
        return $retval;
331
    }
332
333
    public static function showImage()
334
    {
335
        global $moduleDirName;
336
        echo "<script type=\"text/javascript\">\n";
337
        echo "<!--\n\n";
338
        echo "function showimage() {\n";
339
        echo "if (!document.images)\n";
340
        echo "return\n";
341
        echo "document.images.avatar.src=\n";
342
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
343
        echo "}\n\n";
344
        echo "//-->\n";
345
        echo "</script>\n";
346
    }
347
348
    //Reusable Link Sorting Functions
349
350
    /**
351
     * @param $orderby
352
     *
353
     * @return string
354
     */
355
    public static function convertOrderByIn($orderby)
356
    {
357
        switch (trim($orderby)) {
358
            case 'titleA':
359
                $orderby = 'title ASC';
360
                break;
361
            case 'dateA':
362
                $orderby = 'date ASC';
363
                break;
364
            case 'hitsA':
365
                $orderby = 'hits ASC';
366
                break;
367
            case 'priceA':
368
                $orderby = 'price ASC';
369
                break;
370
            case 'titleD':
371
                $orderby = 'title DESC';
372
                break;
373
            case 'hitsD':
374
                $orderby = 'hits DESC';
375
                break;
376
            case 'priceD':
377
                $orderby = 'price DESC';
378
                break;
379
            case'dateD':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
380
            default:
381
                $orderby = 'date DESC';
382
                break;
383
        }
384
385
        return $orderby;
386
    }
387
388
    /**
389
     * @param $orderby
390
     *
391
     * @return string
392
     */
393
    public static function convertOrderByTrans($orderby)
394
    {
395
        global $main_lang;
396
        $orderbyTrans = '';
397
        if ($orderby === 'hits ASC') {
398
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
399
        }
400
        if ($orderby === 'hits DESC') {
401
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
402
        }
403
        if ($orderby === 'title ASC') {
404
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
405
        }
406
        if ($orderby === 'title DESC') {
407
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
408
        }
409
        if ($orderby === 'date ASC') {
410
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
411
        }
412
        if ($orderby === 'date DESC') {
413
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
414
        }
415
        if ($orderby === 'price ASC') {
416
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
417
        }
418
        if ($orderby === 'price DESC') {
419
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
420
        }
421
422
        return $orderbyTrans;
423
    }
424
425
    /**
426
     * @param $orderby
427
     *
428
     * @return string
429
     */
430
    public static function convertOrderByOut($orderby)
431
    {
432
        if ($orderby === 'title ASC') {
433
            $orderby = 'titleA';
434
        }
435
        if ($orderby === 'date ASC') {
436
            $orderby = 'dateA';
437
        }
438
        if ($orderby === 'hits ASC') {
439
            $orderby = 'hitsA';
440
        }
441
        if ($orderby === 'price ASC') {
442
            $orderby = 'priceA';
443
        }
444
        if ($orderby === 'title DESC') {
445
            $orderby = 'titleD';
446
        }
447
        if ($orderby === 'date DESC') {
448
            $orderby = 'dateD';
449
        }
450
        if ($orderby === 'hits DESC') {
451
            $orderby = 'hitsD';
452
        }
453
        if ($orderby === 'price DESC') {
454
            $orderby = 'priceD';
455
        }
456
457
        return $orderby;
458
    }
459
460
    /**
461
     * @param string $caption
462
     * @param string $name
463
     * @param string $value
464
     * @param string $width
465
     * @param string $height
466
     * @param string $supplemental
467
     *
468
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
469
     */
470
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
0 ignored issues
show
Unused Code introduced by
The parameter $caption is not used and could be removed.

This check looks from 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 $supplemental is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
471
    {
472
        global $xoopsModule;
473
        $options = array();
474
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
475
476
        if (class_exists('XoopsFormEditor')) {
477
            $options['name']   = $name;
478
            $options['value']  = $value;
479
            $options['rows']   = 20;
480
            $options['cols']   = '100%';
481
            $options['width']  = $width;
482
            $options['height'] = $height;
483
            if ($isAdmin) {
484
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
485
            } else {
486
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
487
            }
488
        } else {
489
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
490
        }
491
492
        //        $form->addElement($descEditor);
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...
493
494
        return $myEditor;
495
    }
496
497
    /**
498
     * @param $tablename
499
     *
500
     * @return bool
501
     */
502
    public static function checkTableExists($tablename)
503
    {
504
        global $xoopsDB;
505
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
506
507
        return ($xoopsDB->getRowsNum($result) > 0);
508
    }
509
510
    /**
511
     * @param $fieldname
512
     * @param $table
513
     *
514
     * @return bool
515
     */
516
    public static function checkFieldExists($fieldname, $table)
517
    {
518
        global $xoopsDB;
519
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
520
521
        return ($xoopsDB->getRowsNum($result) > 0);
522
    }
523
524
    /**
525
     * @param $field
526
     * @param $table
527
     *
528
     * @return mixed
529
     */
530
    public static function addField($field, $table)
531
    {
532
        global $xoopsDB;
533
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
534
535
        return $result;
536
    }
537
538
    /**
539
     * @param $cid
540
     *
541
     * @return bool
542
     */
543
    public static function getCatNameFromId($cid)
544
    {
545
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
546
547
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
548
549
        if (!$result = $xoopsDB->query($sql)) {
550
            return false;
551
        }
552
553
        if (!$arr = $xoopsDB->fetchArray($result)) {
554
            return false;
555
        }
556
557
        $title = $arr['title'];
558
559
        return $title;
560
    }
561
562
    /**
563
     * @return mixed
564
     */
565
    public static function goCategory()
566
    {
567
        global $xoopsDB;
568
569
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
570
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
571
        ob_start();
572
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
573
        $block['selectbox'] = ob_get_contents();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$block was never initialized. Although not strictly required by PHP, it is generally a good practice to add $block = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
574
        ob_end_clean();
575
576
        return $block;
577
    }
578
579
    // ADSLIGHT Version 2 //
580
    // Fonction rss.php RSS par categories
581
    /**
582
     * @return array
583
     */
584
    public static function returnAllAdsRss()
585
    {
586
        global $xoopsDB;
587
588
        $cid = Request::getInt('cid', null, 'GET');
589
590
        $result = array();
591
592
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
593
594
        $resultValues = $xoopsDB->query($sql);
595
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
596
            array_push($result, $resultTemp);
597
        }
598
599
        return $result;
600
    }
601
602
    // Fonction fluxrss.php RSS Global
603
604
    /**
605
     * @return array
606
     */
607
    public static function returnAllAdsFluxRss()
608
    {
609
        global $xoopsDB;
610
611
        $result = array();
612
613
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
614
615
        $resultValues = $xoopsDB->query($sql);
616
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
617
            array_push($result, $resultTemp);
618
        }
619
620
        return $result;
621
    }
622
623
    /**
624
     * @param $type
625
     *
626
     * @return mixed
627
     */
628
    public static function getNameType($type)
629
    {
630
        global $xoopsDB;
631
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
632
        list($nom_type) = $xoopsDB->fetchRow($sql);
633
634
        return $nom_type;
635
    }
636
637
    /**
638
     * @param $format
639
     * @param $number
640
     *
641
     * @return mixed
642
     */
643
    public static function getMoneyFormat($format, $number)
644
    {
645
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
646
        if (setlocale(LC_MONETARY, 0) === 'C') {
647
            setlocale(LC_MONETARY, '');
648
        }
649
650
        setlocale(LC_ALL, 'en_US');
651
        //        setlocale(LC_ALL, 'fr_FR');
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
652
653
        $locale = localeconv();
654
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
655
        foreach ($matches as $fmatch) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
656
            $value      = (float)$number;
657
            $flags      = array(
658
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
659
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
660
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
661
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
662
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
663
            );
664
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
665
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
666
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
667
            $conversion = $fmatch[5];
668
669
            $positive = true;
670
            if ($value < 0) {
671
                $positive = false;
672
                $value    *= -1;
673
            }
674
            $letter = $positive ? 'p' : 'n';
675
676
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
0 ignored issues
show
Unused Code introduced by
$signal 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...
677
678
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
679
            switch (true) {
680
                case $locale["{$letter}_sign_posn"] == 1
681
                     && $flags['usesignal'] == '+':
682
                    $prefix = $signal;
683
                    break;
684
                case $locale["{$letter}_sign_posn"] == 2
685
                     && $flags['usesignal'] == '+':
686
                    $suffix = $signal;
687
                    break;
688
                case $locale["{$letter}_sign_posn"] == 3
689
                     && $flags['usesignal'] == '+':
690
                    $cprefix = $signal;
691
                    break;
692
                case $locale["{$letter}_sign_posn"] == 4
693
                     && $flags['usesignal'] == '+':
694
                    $csuffix = $signal;
695
                    break;
696
                case $flags['usesignal'] === '(':
697
                case $locale["{$letter}_sign_posn"] == 0:
698
                    $prefix = '(';
699
                    $suffix = ')';
700
                    break;
701
            }
702
            if (!$flags['nosimbol']) {
703
                $currency = $cprefix . ($conversion === 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
704
            } else {
705
                $currency = '';
706
            }
707
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
708
709
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
710
            $value = @explode($locale['mon_decimal_point'], $value);
711
712
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
713
            if ($left > 0 && $left > $n) {
714
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
715
            }
716
            $value = implode($locale['mon_decimal_point'], $value);
717
            if ($locale["{$letter}_cs_precedes"]) {
718
                $value = $prefix . $currency . $space . $value . $suffix;
719
            } else {
720
                $value = $prefix . $value . $space . $currency . $suffix;
721
            }
722
            if ($width > 0) {
723
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
724
            }
725
726
            $format = str_replace($fmatch[0], $value, $format);
727
        }
728
729
        return $format;
730
    }
731
732
    /**
733
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
734
     *
735
     * @param string $folder The full path of the directory to check
736
     *
737
     * @return void
738
     */
739
    public static function createFolder($folder)
740
    {
741
        try {
742
            if (!file_exists($folder)) {
743
                if (!mkdir($folder) && !is_dir($folder)) {
744
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
745
                } else {
746
                    file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
747
                }
748
            }
749
        } catch (Exception $e) {
750
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
751
        }
752
    }
753
754
    /**
755
     * @param $file
756
     * @param $folder
757
     * @return bool
758
     */
759
    public static function copyFile($file, $folder)
760
    {
761
        return copy($file, $folder);
762
        //        try {
763
        //            if (!is_dir($folder)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
764
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
765
        //            } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
766
        //                return copy($file, $folder);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
767
        //            }
768
        //        } catch (Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
769
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
770
        //        }
771
        //        return false;
772
    }
773
774
    /**
775
     * @param $src
776
     * @param $dst
777
     */
778
    public static function recurseCopy($src, $dst)
779
    {
780
        $dir = opendir($src);
781
        //    @mkdir($dst);
782
        while (false !== ($file = readdir($dir))) {
783
            if (($file !== '.') && ($file !== '..')) {
784
                if (is_dir($src . '/' . $file)) {
785
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
786
                } else {
787
                    copy($src . '/' . $file, $dst . '/' . $file);
788
                }
789
            }
790
        }
791
        closedir($dir);
792
    }
793
794
    /**
795
     *
796
     * Verifies XOOPS version meets minimum requirements for this module
797
     * @static
798
     * @param XoopsModule $module
799
     *
800
     * @return bool true if meets requirements, false if not
801
     */
802
    public static function checkXoopsVer(XoopsModule $module)
803
    {
804
        xoops_loadLanguage('admin', $module->dirname());
805
        //check for minimum XOOPS version
806
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
807
        $currArray   = explode('.', $currentVer);
808
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
809
        $reqArray    = explode('.', $requiredVer);
810
        $success     = true;
811
        foreach ($reqArray as $k => $v) {
812
            if (isset($currArray[$k])) {
813
                if ($currArray[$k] > $v) {
814
                    break;
815
                } elseif ($currArray[$k] == $v) {
816
                    continue;
817
                } else {
818
                    $success = false;
819
                    break;
820
                }
821
            } else {
822
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
823
                    $success = false;
824
                    break;
825
                }
826
            }
827
        }
828
829
        if (!$success) {
830
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
831
        }
832
833
        return $success;
834
    }
835
836
    /**
837
     *
838
     * Verifies PHP version meets minimum requirements for this module
839
     * @static
840
     * @param XoopsModule $module
841
     *
842
     * @return bool true if meets requirements, false if not
843
     */
844
    public static function checkPhpVer(XoopsModule $module)
845
    {
846
        xoops_loadLanguage('admin', $module->dirname());
847
        // check for minimum PHP version
848
        $success = true;
849
        $verNum  = PHP_VERSION;
850
        $reqVer  = $module->getInfo('min_php');
851
        if (false !== $reqVer && '' !== $reqVer) {
852
            if (version_compare($verNum, $reqVer, '<')) {
853
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
854
                $success = false;
855
            }
856
        }
857
858
        return $success;
859
    }
860
861
    /**
862
     * Saves permissions for the selected category
863
     *
864
     *   saveCategory_Permissions()
865
     *
866
     * @param  array   $groups     : group with granted permission
867
     * @param  integer $categoryid : categoryid on which we are setting permissions
868
     * @param  string  $perm_name  : name of the permission
0 ignored issues
show
Documentation introduced by
There is no parameter named $categoryid. Did you maybe mean $categoryId?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
869
     * @return boolean : TRUE if the no errors occured
0 ignored issues
show
Bug introduced by
There is no parameter named $perm_name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
870
     */
871
872
    public static function saveCategoryPermissions($groups, $categoryId, $permName)
873
    {
874
        global $xoopsModule;
875
        if (!isset($moduleDirName)) {
0 ignored issues
show
Bug introduced by
The variable $moduleDirName 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...
876
            $moduleDirName = basename(dirname(__DIR__));
877
        }
878
879
        if (false !== ($moduleHelper = Helper::getHelper($moduleDirName))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
880
        } else {
881
            $moduleHelper = Helper::getHelper('system');
882
        }
883
884
        $result = true;
885
        //        $xoopsModule = sf_getModuleInfo();
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
886
        $moduleId = $moduleHelper->getModule()->getVar('mid');
887
888
        $gpermHandler = xoops_getHandler('groupperm');
889
        // First, if the permissions are already there, delete them
890
        $gpermHandler->deleteByModule($moduleId, $permName, $categoryId);
891
        // Save the new permissions
892
        if (count($groups) > 0) {
893
            foreach ($groups as $groupId) {
894
                $gpermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
895
            }
896
        }
897
898
        return $result;
899
    }
900
}
901