Completed
Branch master (a84b6a)
by Michael
02:37
created

AdslightUtilities::recurseCopy()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 4
nop 2
dl 0
loc 15
rs 8.8571
c 0
b 0
f 0
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 45 and the first side effect is on line 37.

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
-------------------------------------------------------------------------
4
                     ADSLIGHT 2 : Module for Xoops
5
6
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
7
        Started with the Classifieds module and made MANY changes
8
        Website : http://www.luc-bizet.fr
9
        Contact : [email protected]
10
-------------------------------------------------------------------------
11
             Original credits below Version History
12
##########################################################################
13
#                    Classified Module for Xoops                         #
14
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
15
#      Started with the MyAds module and made MANY changes               #
16
##########################################################################
17
 Original Author: Pascal Le Boustouller
18
 Author Website : [email protected]
19
 Licence Type   : GPL
20
-------------------------------------------------------------------------
21
*/
22
23
/**
24
 * AdslightUtilities Class
25
 *
26
 * @copyright   XOOPS Project (http://xoops.org)
27
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
28
 * @author      XOOPS Development Team
29
 * @package     GBook
30
 * @since       1.03
31
 *
32
 */
33
34
//namespace Xoopsmodules/Adslight;
35
36
37
$moduleDirName = basename(dirname(__DIR__));
38
$main_lang = '_' . strtoupper($moduleDirName);
39
require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
40
include_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
41
$myts = MyTextSanitizer::getInstance();
42
/**
43
 * Class AdslightUtilities
44
 */
45
class AdslightUtilities
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...
46
{
47
    public static function expireAd()
48
    {
49
        global $xoopsDB, $xoopsConfig, $xoopsModule, $xoopsModuleConfig, $myts, $meta, $moduleDirName, $main_lang;
1 ignored issue
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...
50
51
        $datenow = time();
52
53
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM '
54
                                   . $xoopsDB->prefix('adslight_listing')
55
                                   . " WHERE valid='Yes'");
56
57
        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...
58
            $title     = $myts->htmlSpecialChars($title);
59
            $expire    = $myts->htmlSpecialChars($expire);
60
            $type      = $myts->htmlSpecialChars($type);
61
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
62
            $submitter = $myts->htmlSpecialChars($submitter);
63
            $remind    = $myts->htmlSpecialChars($remind);
64
            $supprdate = $dateann + ($expire * 86400);
65
            $almost    = $xoopsModuleConfig['adslight_almost'];
66
67
            // give warning that add is about to expire
68
69
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow && $valid === 'Yes' && $remind == 0) {
70
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
71
72 View Code Duplication
                if ($email) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
73
                    $tags               = array();
74
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
75
                    $tags['TITLE']      = $title;
76
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
77
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
78
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
79
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
80
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
81
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
82
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
83
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
84
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
85
                    $tags['TYPE']       = static::getNameType($type);
86
                    $tags['DESCTEXT']   = $desctext;
87
                    $tags['HITS']       = $hits;
88
                    $tags['META_TITLE'] = $meta['title'];
89
                    $tags['SUBMITTER']  = $submitter;
90
                    $tags['DURATION']   = $expire;
91
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
92
                    $mail               =& getMailer();
93
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
94
                    $mail->setTemplate('listing_expires.tpl');
95
                    $mail->useMail();
96
                    $mail->multimailer->isHTML(true);
97
                    $mail->setFromName($meta['title']);
98
                    $mail->setFromEmail($xoopsConfig['adminmail']);
99
                    $mail->setToEmails($email);
100
                    $mail->setSubject($subject);
101
                    $mail->assign($tags);
102
                    $mail->send();
103
                    echo $mail->getErrors();
104
                }
105
            }
106
107
            // expire ad
108
109
            if ($supprdate < $datenow) {
110
                if ($photo != 0) {
111
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids) . '');
112
113
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
114
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
115
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
116
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
117
                        if (file_exists("$destination/$url")) {
118
                            unlink("$destination/$url");
119
                        }
120
                        if (file_exists("$destination2/thumb_$url")) {
121
                            unlink("$destination2/thumb_$url");
122
                        }
123
                        if (file_exists("$destination3/resized_$url")) {
124
                            unlink("$destination3/resized_$url");
125
                        }
126
                    }
127
                }
128
129
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids) . '');
130
131
                //  Specification for Japan:
132
                //  $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."";
133 View Code Duplication
                if ($email) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
                    $tags               = array();
135
                    $subject            = '' . _ADSLIGHT_STOP . '';
136
                    $tags['TITLE']      = $title;
137
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
138
                    $tags['TYPE']       = static::getNameType($type);
139
                    $tags['DESCTEXT']   = $desctext;
140
                    $tags['HITS']       = $hits;
141
                    $tags['META_TITLE'] = $meta['title'];
142
                    $tags['SUBMITTER']  = $submitter;
143
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
144
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
145
                    $tags['MESSTEXT']   = stripslashes($message);
0 ignored issues
show
Bug introduced by
The variable $message does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
146
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
147
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
148
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
149
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
150
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
151
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
152
                    $tags['DURATION']   = $expire;
153
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
154
                    $mail               =& getMailer();
155
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
156
                    $mail->setTemplate('listing_expired.tpl');
157
                    $mail->useMail();
158
                    $mail->multimailer->isHTML(true);
159
                    $mail->setFromName($meta['title']);
160
                    $mail->setFromEmail($xoopsConfig['adminmail']);
161
                    $mail->setToEmails($email);
162
                    $mail->setSubject($subject);
163
                    $mail->assign($tags);
164
                    $mail->send();
165
                    echo $mail->getErrors();
166
                }
167
            }
168
        }
169
    }
170
171
    //updates rating data in itemtable for a given user
172
    /**
173
     * @param $sel_id
174
     */
175 View Code Duplication
    public static function updateUserRating($sel_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
updateUserRating 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...
176
    {
177
        global $xoopsDB, $xoopsUser, $moduleDirName, $main_lang;
1 ignored issue
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...
178
179
        if (isset($_GET['usid'])) {
180
            $usid = (int)$_GET['usid'];
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...
181
        } else {
182
            $usid = 0;
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...
183
        }
184
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . '';
185
        //echo $query;
186
        $voteresult  = $xoopsDB->query($query);
187
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
188
        $totalrating = 0;
189
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
190
            $totalrating += $rating;
191
        }
192
        $finalrating = $totalrating / $votesDB;
193
        $finalrating = number_format($finalrating, 4);
194
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
195
        //echo $query;
196
        $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...
197
    }
198
199
    //updates rating data in itemtable for a given item
200
    /**
201
     * @param $sel_id
202
     */
203 View Code Duplication
    public static function updateItemRating($sel_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
updateItemRating 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...
204
    {
205
        global $xoopsDB, $xoopsUser, $moduleDirName, $main_lang;
1 ignored issue
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...
206
207
        if (isset($_GET['lid'])) {
208
            $lid = (int)$_GET['lid'];
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...
209
        } else {
210
            $lid = 0;
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...
211
        }
212
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
213
        //echo $query;
214
        $voteresult  = $xoopsDB->query($query);
215
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
216
        $totalrating = 0;
217
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
218
            $totalrating += $rating;
219
        }
220
        $finalrating = $totalrating / $votesDB;
221
        $finalrating = number_format($finalrating, 4);
222
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
223
        //echo $query;
224
        $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...
225
    }
226
227
    /**
228
     * @param        $sel_id
229
     * @param string $status
230
     *
231
     * @return int
232
     */
233
    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...
234
    {
235
        global $xoopsDB, $mytree, $moduleDirName;
1 ignored issue
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...
236
        $categories = AdslightUtilities::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...
237
        $count      = 0;
238
        $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...
239
        if (in_array($sel_id, $categories)) {
240
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " and valid='Yes' AND status!='1'";
241
242
            $result = $xoopsDB->query($query);
243
            list($thing) = $xoopsDB->fetchRow($result);
244
            $count = $thing;
245
            $arr   = $mytree->getAllChildId($sel_id);
246
            $size  = count($arr);
247
            for ($i = 0; $i < $size; ++$i) {
248
                if (in_array($arr[$i], $categories)) {
249
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " and valid='Yes' AND status!='1'";
250
251
                    $result2 = $xoopsDB->query($query2);
252
                    list($thing) = $xoopsDB->fetchRow($result2);
253
                    $count += $thing;
254
                }
255
            }
256
        }
257
258
        return $count;
259
    }
260
261
    /**
262
     * @param $permtype
263
     *
264
     * @return mixed
265
     */
266
    public static function getMyItemIds($permtype)
267
    {
268
        global $xoopsUser, $moduleDirName;
1 ignored issue
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...
269
        static $permissions = array();
270
        if (is_array($permissions) && array_key_exists($permtype, $permissions)) {
271
            return $permissions[$permtype];
272
        }
273
274
        /** @var XoopsModuleHandler $moduleHandler */
275
        $moduleHandler          = xoops_getHandler('module');
276
        $myModule               = $moduleHandler->getByDirname('adslight');
277
        $groups                 = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
278
        $gpermHandler          = xoops_getHandler('groupperm');
279
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
280
        $permissions[$permtype] = $categories;
281
282
        return $categories;
283
    }
284
285
    /**
286
     * @param        $option
287
     * @param string $repmodule
288
     *
289
     * @return bool
290
     */
291
    public static function getModuleOption($option, $repmodule = 'adslight')
1 ignored issue
show
Coding Style introduced by
getModuleOption uses the super-global variable $GLOBALS 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...
292
    {
293
        global $xoopsModuleConfig, $xoopsModule;
1 ignored issue
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...
294
        static $tbloptions = array();
295
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
296
            return $tbloptions[$option];
297
        }
298
299
        $retval = false;
300
        if (isset($xoopsModuleConfig)
301
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
302
                && $xoopsModule->getVar('isactive'))
303
        ) {
304
            if (isset($xoopsModuleConfig[$option])) {
305
                $retval = $xoopsModuleConfig[$option];
306
            }
307
        } else {
308
            /** @var XoopsModuleHandler $moduleHandler */
309
            $moduleHandler  = xoops_getHandler('module');
310
            $module         = $moduleHandler->getByDirname($repmodule);
311
            $config_handler = xoops_getHandler('config');
312
            if ($module) {
313
                $moduleConfig =& $config_handler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
314
                if (isset($moduleConfig[$option])) {
315
                    $retval = $moduleConfig[$option];
316
                }
317
            }
318
        }
319
        $tbloptions[$option] = $retval;
320
321
        return $retval;
322
    }
323
324
    public static function showImage()
325
    {
326
        global $moduleDirName;
1 ignored issue
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...
327
        echo "<script type=\"text/javascript\">\n";
328
        echo "<!--\n\n";
329
        echo "function showimage() {\n";
330
        echo "if (!document.images)\n";
331
        echo "return\n";
332
        echo "document.images.avatar.src=\n";
333
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
334
        echo "}\n\n";
335
        echo "//-->\n";
336
        echo "</script>\n";
337
    }
338
339
    //Reusable Link Sorting Functions
340
    /**
341
     * @param $orderby
342
     *
343
     * @return string
344
     */
345
    public static function convertOrderByIn($orderby)
346
    {
347
        switch (trim($orderby)) {
348
            case 'titleA':
349
                $orderby = 'title ASC';
350
                break;
351
            case 'dateA':
352
                $orderby = 'date ASC';
353
                break;
354
            case 'hitsA':
355
                $orderby = 'hits ASC';
356
                break;
357
            case 'priceA':
358
                $orderby = 'price ASC';
359
                break;
360
            case 'titleD':
361
                $orderby = 'title DESC';
362
                break;
363
            case 'hitsD':
364
                $orderby = 'hits DESC';
365
                break;
366
            case 'priceD':
367
                $orderby = 'price DESC';
368
                break;
369
            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...
370
            default:
371
                $orderby = 'date DESC';
372
                break;
373
        }
374
375
        return $orderby;
376
    }
377
378
    /**
379
     * @param $orderby
380
     *
381
     * @return string
382
     */
383
    public static function convertOrderByTrans($orderby)
384
    {
385
        global $main_lang;
1 ignored issue
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...
386
387
        if ($orderby === 'hits ASC') {
388
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
389
        }
390
        if ($orderby === 'hits DESC') {
391
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
392
        }
393
        if ($orderby === 'title ASC') {
394
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
395
        }
396
        if ($orderby === 'title DESC') {
397
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
398
        }
399
        if ($orderby === 'date ASC') {
400
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
401
        }
402
        if ($orderby === 'date DESC') {
403
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
404
        }
405
        if ($orderby === 'price ASC') {
406
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
407
        }
408
        if ($orderby === 'price DESC') {
409
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
410
        }
411
412
        return $orderbyTrans;
0 ignored issues
show
Bug introduced by
The variable $orderbyTrans does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
413
    }
414
415
    /**
416
     * @param $orderby
417
     *
418
     * @return string
419
     */
420
    public static function convertOrderByOut($orderby)
421
    {
422
        if ($orderby === 'title ASC') {
423
            $orderby = 'titleA';
424
        }
425
        if ($orderby === 'date ASC') {
426
            $orderby = 'dateA';
427
        }
428
        if ($orderby === 'hits ASC') {
429
            $orderby = 'hitsA';
430
        }
431
        if ($orderby === 'price ASC') {
432
            $orderby = 'priceA';
433
        }
434
        if ($orderby === 'title DESC') {
435
            $orderby = 'titleD';
436
        }
437
        if ($orderby === 'date DESC') {
438
            $orderby = 'dateD';
439
        }
440
        if ($orderby === 'hits DESC') {
441
            $orderby = 'hitsD';
442
        }
443
        if ($orderby === 'price DESC') {
444
            $orderby = 'priceD';
445
        }
446
447
        return $orderby;
448
    }
449
450
    /**
451
     * @param string $caption
452
     * @param string $name
453
     * @param string $value
454
     * @param string $width
455
     * @param string $height
456
     * @param string $supplemental
457
     *
458
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
459
     */
460
    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...
461
    {
462
463
        global $xoopsUser, $xoopsModule, $xoopsModuleConfig;
1 ignored issue
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...
464
        $options = array();
465
        $isAdmin = $xoopsUser->isAdmin($xoopsModule->getVar('mid'));
466
467
        if (class_exists('XoopsFormEditor')) {
468
            $options['name']   = $name;
469
            $options['value']  = $value;
470
            $options['rows']   = 20;
471
            $options['cols']   = '100%';
472
            $options['width']  = $width;
473
            $options['height'] = $height;
474
            if ($isAdmin) {
475
                $myEditor = new XoopsFormEditor(ucfirst($name), $xoopsModuleConfig['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
476
            } else {
477
                $myEditor = new XoopsFormEditor(ucfirst($name), $xoopsModuleConfig['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
478
            }
479
        } else {
480
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
481
        }
482
483
        //        $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...
484
485
        return $myEditor;
486
    }
487
488
    /**
489
     * @param $tablename
490
     *
491
     * @return bool
492
     */
493
    public static function checkTableExists($tablename)
494
    {
495
        global $xoopsDB;
1 ignored issue
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...
496
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
497
498
        return ($xoopsDB->getRowsNum($result) > 0);
499
    }
500
501
    /**
502
     * @param $fieldname
503
     * @param $table
504
     *
505
     * @return bool
506
     */
507
    public static function checkFieldExists($fieldname, $table)
508
    {
509
        global $xoopsDB;
1 ignored issue
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...
510
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
511
512
        return ($xoopsDB->getRowsNum($result) > 0);
513
    }
514
515
    /**
516
     * @param $field
517
     * @param $table
518
     *
519
     * @return mixed
520
     */
521
    public static function addField($field, $table)
522
    {
523
        global $xoopsDB;
1 ignored issue
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...
524
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
525
526
        return $result;
527
    }
528
529
    /**
530
     * @param $cid
531
     *
532
     * @return bool
533
     */
534
    public static function getCatNameFromId($cid)
535
    {
536
        global $xoopsDB, $xoopsConfig, $myts, $xoopsUser, $moduleDirName;
1 ignored issue
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...
537
538
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
539
540
        if (!$result = $xoopsDB->query($sql)) {
541
            return false;
542
        }
543
544
        if (!$arr = $xoopsDB->fetchArray($result)) {
545
            return false;
546
        }
547
548
        $title = $arr['title'];
549
550
        return $title;
551
    }
552
553
    /**
554
     * @return mixed
555
     */
556 View Code Duplication
    public static function goCategory
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
557
()
558
    {
559
        global $xoopsDB;
1 ignored issue
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...
560
561
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
562
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
563
        ob_start();
564
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
565
        $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...
566
        ob_end_clean();
567
568
        return $block;
569
    }
570
571
    // ADSLIGHT Version 2 //
572
    // Fonction rss.php RSS par categories
573
    /**
574
     * @return array
575
     */
576
    public static function returnAllAdsRss()
0 ignored issues
show
Coding Style introduced by
returnAllAdsRss 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...
577
    {
578
        global $xoopsDB, $xoopsModuleConfig, $xoopsUser;
1 ignored issue
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...
579
580
        $cid = !isset($_GET['cid']) ? null : $_GET['cid'];
581
582
        $result = array();
583
584
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
585
586
        $resultValues = $xoopsDB->query($sql);
587
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
588
            array_push($result, $resultTemp);
589
        }
590
591
        return $result;
592
    }
593
594
    // Fonction fluxrss.php RSS Global
595
    /**
596
     * @return array
597
     */
598
    public static function returnAllAdsFluxRss()
599
    {
600
        global $xoopsDB, $xoopsModuleConfig, $xoopsUser;
1 ignored issue
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...
601
602
        $result = array();
603
604
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
605
606
        $resultValues = $xoopsDB->query($sql);
607
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
608
            array_push($result, $resultTemp);
609
        }
610
611
        return $result;
612
    }
613
614
    /**
615
     * @param $type
616
     *
617
     * @return mixed
618
     */
619
    public static function getNameType($type)
620
    {
621
        global $xoopsDB;
1 ignored issue
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...
622
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . ' WHERE id_type=' . $xoopsDB->escape($type) . '');
623
        list($nom_type) = $xoopsDB->fetchRow($sql);
624
625
        return $nom_type;
626
    }
627
628
    /**
629
     * @param $format
630
     * @param $number
631
     *
632
     * @return mixed
633
     */
634
    public static function getMoneyFormat($format, $number)
635
    {
636
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
637
        if (setlocale(LC_MONETARY, 0) === 'C') {
638
            setlocale(LC_MONETARY, '');
639
        }
640
641
        setlocale(LC_ALL, 'en_US');
642
        $locale = localeconv();
643
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
644
        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...
645
            $value      = (float)$number;
646
            $flags      = array(
647
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
648
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
649
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
650
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
651
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
652
            );
653
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
654
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
655
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
656
            $conversion = $fmatch[5];
657
658
            $positive = true;
659
            if ($value < 0) {
660
                $positive = false;
661
                $value *= -1;
662
            }
663
            $letter = $positive ? 'p' : 'n';
664
665
            $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...
666
667
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
668
            switch (true) {
669 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
670
                    $prefix = $signal;
671
                    break;
672 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
673
                    $suffix = $signal;
674
                    break;
675 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
676
                    $cprefix = $signal;
677
                    break;
678 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
679
                    $csuffix = $signal;
680
                    break;
681
                case $flags['usesignal'] === '(':
682
                case $locale["{$letter}_sign_posn"] == 0:
683
                    $prefix = '(';
684
                    $suffix = ')';
685
                    break;
686
            }
687
            if (!$flags['nosimbol']) {
688
                $currency = $cprefix . ($conversion === 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
689
            } else {
690
                $currency = '';
691
            }
692
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
693
694
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
695
            $value = @explode($locale['mon_decimal_point'], $value);
696
697
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
698
            if ($left > 0 && $left > $n) {
699
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
700
            }
701
            $value = implode($locale['mon_decimal_point'], $value);
702
            if ($locale["{$letter}_cs_precedes"]) {
703
                $value = $prefix . $currency . $space . $value . $suffix;
704
            } else {
705
                $value = $prefix . $value . $space . $currency . $suffix;
706
            }
707
            if ($width > 0) {
708
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
709
            }
710
711
            $format = str_replace($fmatch[0], $value, $format);
712
        }
713
714
        return $format;
715
    }
716
717
    /**
718
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
719
     *
720
     * @param string $folder The full path of the directory to check
721
     *
722
     * @return void
723
     */
724
    public static function createFolder($folder)
725
    {
726
        try {
727
            if (!@mkdir($folder) && !is_dir($folder)) {
728
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
729
            } else {
730
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
731
            }
732
        }
733
        catch (Exception $e) {
734
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
735
        }
736
    }
737
738
    /**
739
     * @param $file
740
     * @param $folder
741
     * @return bool
742
     */
743
    public static function copyFile($file, $folder)
744
    {
745
        return copy($file, $folder);
746
        //        try {
747
        //            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...
748
        //                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...
749
        //            } 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...
750
        //                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...
751
        //            }
752
        //        } 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...
753
        //            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...
754
        //        }
755
        //        return false;
756
    }
757
758
    /**
759
     * @param $src
760
     * @param $dst
761
     */
762
    public static function recurseCopy($src, $dst)
763
    {
764
        $dir = opendir($src);
765
        //    @mkdir($dst);
766
        while (false !== ($file = readdir($dir))) {
767
            if (($file !== '.') && ($file !== '..')) {
768
                if (is_dir($src . '/' . $file)) {
769
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
770
                } else {
771
                    copy($src . '/' . $file, $dst . '/' . $file);
772
                }
773
            }
774
        }
775
        closedir($dir);
776
    }
777
        /**
778
     *
779
     * Verifies XOOPS version meets minimum requirements for this module
780
     * @static
781
     * @param XoopsModule $module
782
     *
783
     * @return bool true if meets requirements, false if not
784
     */
785
    public static function checkXoopsVer(XoopsModule $module)
786
    {
787
        xoops_loadLanguage('admin', $module->dirname());
788
        //check for minimum XOOPS version
789
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
790
        $currArray   = explode('.', $currentVer);
791
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
792
        $reqArray    = explode('.', $requiredVer);
793
        $success     = true;
794
        foreach ($reqArray as $k => $v) {
795
            if (isset($currArray[$k])) {
796
                if ($currArray[$k] > $v) {
797
                    break;
798
                } elseif ($currArray[$k] == $v) {
799
                    continue;
800
                } else {
801
                    $success = false;
802
                    break;
803
                }
804
            } else {
805
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
806
                    $success = false;
807
                    break;
808
                }
809
            }
810
        }
811
812
        if (!$success) {
813
            $module->setErrors(sprintf(_AM_GBOOK_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
814
        }
815
816
        return $success;
817
    }
818
819
    /**
820
     *
821
     * Verifies PHP version meets minimum requirements for this module
822
     * @static
823
     * @param XoopsModule $module
824
     *
825
     * @return bool true if meets requirements, false if not
826
     */
827
    public static function checkPhpVer(XoopsModule $module)
828
    {
829
        xoops_loadLanguage('admin', $module->dirname());
830
        // check for minimum PHP version
831
        $success = true;
832
        $verNum  = phpversion();
833
        $reqVer  =& $module->getInfo('min_php');
834
        if (false !== $reqVer && '' !== $reqVer) {
835
            if (version_compare($verNum, $reqVer, '<')) {
836
                $module->setErrors(sprintf(_AM_GBOOK_ERROR_BAD_PHP, $reqVer, $verNum));
837
                $success = false;
838
            }
839
        }
840
841
        return $success;
842
    }
843
}
844