Completed
Push — master ( a25b3b...67bb37 )
by Michael
02:44
created

AdslightUtilities::updateUserRating()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 20
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 4
nop 1
dl 20
loc 20
rs 9.4285
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 36.

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     AdsLight
30
 * @since       1.03
31
 *
32
 */
33
34
//namespace Xoopsmodules/Adslight;
35
36
$moduleDirName = basename(dirname(__DIR__));
37
$main_lang     = '_' . strtoupper($moduleDirName);
38
require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
39
include_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
40
$myts = MyTextSanitizer::getInstance();
41
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()
1 ignored issue
show
Coding Style introduced by
expireAd 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...
48
    {
49
        global $xoopsDB, $xoopsConfig, $xoopsModule, $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    = $GLOBALS['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...
176
    {
177
        global $xoopsDB, $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
        $usid      = XoopsRequest::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...
180
181
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . '';
182
        //echo $query;
183
        $voteresult  = $xoopsDB->query($query);
184
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
185
        $totalrating = 0;
186
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
187
            $totalrating += $rating;
188
        }
189
        $finalrating = $totalrating / $votesDB;
190
        $finalrating = number_format($finalrating, 4);
191
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
192
        //echo $query;
193
        $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...
194
    }
195
196
    //updates rating data in itemtable for a given item
197
    /**
198
     * @param $sel_id
199
     */
200 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...
201
    {
202
        global $xoopsDB, $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...
203
204
        $lid      = XoopsRequest::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...
205
206
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
207
        //echo $query;
208
        $voteresult  = $xoopsDB->query($query);
209
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
210
        $totalrating = 0;
211
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
212
            $totalrating += $rating;
213
        }
214
        $finalrating = $totalrating / $votesDB;
215
        $finalrating = number_format($finalrating, 4);
216
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
217
        //echo $query;
218
        $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...
219
    }
220
221
    /**
222
     * @param        $sel_id
223
     * @param string $status
224
     *
225
     * @return int
226
     */
227
    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...
228
    {
229
        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...
230
        $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...
231
        $count      = 0;
232
        $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...
233
        if (in_array($sel_id, $categories)) {
234
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " and valid='Yes' AND status!='1'";
235
236
            $result = $xoopsDB->query($query);
237
            list($thing) = $xoopsDB->fetchRow($result);
238
            $count = $thing;
239
            $arr   = $mytree->getAllChildId($sel_id);
240
            $size  = count($arr);
241
            for ($i = 0; $i < $size; ++$i) {
242
                if (in_array($arr[$i], $categories)) {
243
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " and valid='Yes' AND status!='1'";
244
245
                    $result2 = $xoopsDB->query($query2);
246
                    list($thing) = $xoopsDB->fetchRow($result2);
247
                    $count += $thing;
248
                }
249
            }
250
        }
251
252
        return $count;
253
    }
254
255
    /**
256
     * @param $permtype
257
     *
258
     * @return mixed
259
     */
260
    public static function getMyItemIds($permtype)
1 ignored issue
show
Coding Style introduced by
getMyItemIds 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...
261
    {
262
        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...
263
        static $permissions = array();
264
        if (is_array($permissions) && array_key_exists($permtype, $permissions)) {
265
            return $permissions[$permtype];
266
        }
267
268
        /** @var XoopsModuleHandler $moduleHandler */
269
        $moduleHandler          = xoops_getHandler('module');
270
        $myModule               = $moduleHandler->getByDirname('adslight');
271
        $groups                 = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
272
        $gpermHandler           = xoops_getHandler('groupperm');
273
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
274
        $permissions[$permtype] = $categories;
275
276
        return $categories;
277
    }
278
279
    /**
280
     * @param        $option
281
     * @param string $repmodule
282
     *
283
     * @return bool
284
     */
285
    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...
286
    {
287
        global $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...
288
        static $tbloptions = array();
289
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
290
            return $tbloptions[$option];
291
        }
292
293
        $retval = false;
294
        if (isset($GLOBALS['xoopsModuleConfig'])
295
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
296
                && $xoopsModule->getVar('isactive'))
297
        ) {
298
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
299
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
300
            }
301
        } else {
302
            /** @var XoopsModuleHandler $moduleHandler */
303
            $moduleHandler  = xoops_getHandler('module');
304
            $module         = $moduleHandler->getByDirname($repmodule);
305
            $config_handler = xoops_getHandler('config');
306
            if ($module) {
307
                $moduleConfig =& $config_handler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
308
                if (isset($moduleConfig[$option])) {
309
                    $retval = $moduleConfig[$option];
310
                }
311
            }
312
        }
313
        $tbloptions[$option] = $retval;
314
315
        return $retval;
316
    }
317
318
    public static function showImage()
319
    {
320
        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...
321
        echo "<script type=\"text/javascript\">\n";
322
        echo "<!--\n\n";
323
        echo "function showimage() {\n";
324
        echo "if (!document.images)\n";
325
        echo "return\n";
326
        echo "document.images.avatar.src=\n";
327
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
328
        echo "}\n\n";
329
        echo "//-->\n";
330
        echo "</script>\n";
331
    }
332
333
    //Reusable Link Sorting Functions
334
    /**
335
     * @param $orderby
336
     *
337
     * @return string
338
     */
339
    public static function convertOrderByIn($orderby)
340
    {
341
        switch (trim($orderby)) {
342
            case 'titleA':
343
                $orderby = 'title ASC';
344
                break;
345
            case 'dateA':
346
                $orderby = 'date ASC';
347
                break;
348
            case 'hitsA':
349
                $orderby = 'hits ASC';
350
                break;
351
            case 'priceA':
352
                $orderby = 'price ASC';
353
                break;
354
            case 'titleD':
355
                $orderby = 'title DESC';
356
                break;
357
            case 'hitsD':
358
                $orderby = 'hits DESC';
359
                break;
360
            case 'priceD':
361
                $orderby = 'price DESC';
362
                break;
363
            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...
364
            default:
365
                $orderby = 'date DESC';
366
                break;
367
        }
368
369
        return $orderby;
370
    }
371
372
    /**
373
     * @param $orderby
374
     *
375
     * @return string
376
     */
377
    public static function convertOrderByTrans($orderby)
378
    {
379
        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...
380
381
        if ($orderby === 'hits ASC') {
382
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
383
        }
384
        if ($orderby === 'hits DESC') {
385
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
386
        }
387
        if ($orderby === 'title ASC') {
388
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
389
        }
390
        if ($orderby === 'title DESC') {
391
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
392
        }
393
        if ($orderby === 'date ASC') {
394
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
395
        }
396
        if ($orderby === 'date DESC') {
397
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
398
        }
399
        if ($orderby === 'price ASC') {
400
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
401
        }
402
        if ($orderby === 'price DESC') {
403
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
404
        }
405
406
        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...
407
    }
408
409
    /**
410
     * @param $orderby
411
     *
412
     * @return string
413
     */
414
    public static function convertOrderByOut($orderby)
415
    {
416
        if ($orderby === 'title ASC') {
417
            $orderby = 'titleA';
418
        }
419
        if ($orderby === 'date ASC') {
420
            $orderby = 'dateA';
421
        }
422
        if ($orderby === 'hits ASC') {
423
            $orderby = 'hitsA';
424
        }
425
        if ($orderby === 'price ASC') {
426
            $orderby = 'priceA';
427
        }
428
        if ($orderby === 'title DESC') {
429
            $orderby = 'titleD';
430
        }
431
        if ($orderby === 'date DESC') {
432
            $orderby = 'dateD';
433
        }
434
        if ($orderby === 'hits DESC') {
435
            $orderby = 'hitsD';
436
        }
437
        if ($orderby === 'price DESC') {
438
            $orderby = 'priceD';
439
        }
440
441
        return $orderby;
442
    }
443
444
    /**
445
     * @param string $caption
446
     * @param string $name
447
     * @param string $value
448
     * @param string $width
449
     * @param string $height
450
     * @param string $supplemental
451
     *
452
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
453
     */
454
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
1 ignored issue
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...
Coding Style introduced by
getEditor 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...
455
    {
456
457
        global $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...
458
        $options = array();
459
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
460
461
        if (class_exists('XoopsFormEditor')) {
462
            $options['name']   = $name;
463
            $options['value']  = $value;
464
            $options['rows']   = 20;
465
            $options['cols']   = '100%';
466
            $options['width']  = $width;
467
            $options['height'] = $height;
468
            if ($isAdmin) {
469
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
470
            } else {
471
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
472
            }
473
        } else {
474
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
475
        }
476
477
        //        $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...
478
479
        return $myEditor;
480
    }
481
482
    /**
483
     * @param $tablename
484
     *
485
     * @return bool
486
     */
487
    public static function checkTableExists($tablename)
488
    {
489
        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...
490
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
491
492
        return ($xoopsDB->getRowsNum($result) > 0);
493
    }
494
495
    /**
496
     * @param $fieldname
497
     * @param $table
498
     *
499
     * @return bool
500
     */
501
    public static function checkFieldExists($fieldname, $table)
502
    {
503
        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...
504
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
505
506
        return ($xoopsDB->getRowsNum($result) > 0);
507
    }
508
509
    /**
510
     * @param $field
511
     * @param $table
512
     *
513
     * @return mixed
514
     */
515
    public static function addField($field, $table)
516
    {
517
        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...
518
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
519
520
        return $result;
521
    }
522
523
    /**
524
     * @param $cid
525
     *
526
     * @return bool
527
     */
528
    public static function getCatNameFromId($cid)
529
    {
530
        global $xoopsDB, $xoopsConfig, $myts, $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...
531
532
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
533
534
        if (!$result = $xoopsDB->query($sql)) {
535
            return false;
536
        }
537
538
        if (!$arr = $xoopsDB->fetchArray($result)) {
539
            return false;
540
        }
541
542
        $title = $arr['title'];
543
544
        return $title;
545
    }
546
547
    /**
548
     * @return mixed
549
     */
550
    public static function goCategory()
551
    {
552
        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...
553
554
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
555
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
556
        ob_start();
557
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
558
        $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...
559
        ob_end_clean();
560
561
        return $block;
562
    }
563
564
    // ADSLIGHT Version 2 //
565
    // Fonction rss.php RSS par categories
566
    /**
567
     * @return array
568
     */
569
    public static function returnAllAdsRss()
570
    {
571
        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...
572
573
        $cid      = XoopsRequest::getInt('cid', null, 'GET');
574
575
        $result = array();
576
577
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
578
579
        $resultValues = $xoopsDB->query($sql);
580
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
581
            array_push($result, $resultTemp);
582
        }
583
584
        return $result;
585
    }
586
587
    // Fonction fluxrss.php RSS Global
588
    /**
589
     * @return array
590
     */
591
    public static function returnAllAdsFluxRss()
592
    {
593
        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...
594
595
        $result = array();
596
597
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
598
599
        $resultValues = $xoopsDB->query($sql);
600
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
601
            array_push($result, $resultTemp);
602
        }
603
604
        return $result;
605
    }
606
607
    /**
608
     * @param $type
609
     *
610
     * @return mixed
611
     */
612
    public static function getNameType($type)
613
    {
614
        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...
615
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
616
        list($nom_type) = $xoopsDB->fetchRow($sql);
617
618
        return $nom_type;
619
    }
620
621
    /**
622
     * @param $format
623
     * @param $number
624
     *
625
     * @return mixed
626
     */
627
    public static function getMoneyFormat($format, $number)
628
    {
629
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
630
        if (setlocale(LC_MONETARY, 0) === 'C') {
631
            setlocale(LC_MONETARY, '');
632
        }
633
634
        setlocale(LC_ALL, 'en_US');
635
        $locale = localeconv();
636
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
637
        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...
638
            $value      = (float)$number;
639
            $flags      = array(
640
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
641
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
642
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
643
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
644
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
645
            );
646
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
647
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
648
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
649
            $conversion = $fmatch[5];
650
651
            $positive = true;
652
            if ($value < 0) {
653
                $positive = false;
654
                $value *= -1;
655
            }
656
            $letter = $positive ? 'p' : 'n';
657
658
            $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...
659
660
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
661
            switch (true) {
662 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...
663
                    $prefix = $signal;
664
                    break;
665 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...
666
                    $suffix = $signal;
667
                    break;
668 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...
669
                    $cprefix = $signal;
670
                    break;
671 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...
672
                    $csuffix = $signal;
673
                    break;
674
                case $flags['usesignal'] === '(':
675
                case $locale["{$letter}_sign_posn"] == 0:
676
                    $prefix = '(';
677
                    $suffix = ')';
678
                    break;
679
            }
680
            if (!$flags['nosimbol']) {
681
                $currency = $cprefix . ($conversion === 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
682
            } else {
683
                $currency = '';
684
            }
685
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
686
687
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
688
            $value = @explode($locale['mon_decimal_point'], $value);
689
690
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
691
            if ($left > 0 && $left > $n) {
692
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
693
            }
694
            $value = implode($locale['mon_decimal_point'], $value);
695
            if ($locale["{$letter}_cs_precedes"]) {
696
                $value = $prefix . $currency . $space . $value . $suffix;
697
            } else {
698
                $value = $prefix . $value . $space . $currency . $suffix;
699
            }
700
            if ($width > 0) {
701
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
702
            }
703
704
            $format = str_replace($fmatch[0], $value, $format);
705
        }
706
707
        return $format;
708
    }
709
710
    /**
711
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
712
     *
713
     * @param string $folder The full path of the directory to check
714
     *
715
     * @return void
716
     */
717
    public static function createFolder($folder)
718
    {
719
        try {
720
            if (!@mkdir($folder) && !is_dir($folder)) {
721
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
722
            } else {
723
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
724
            }
725
        }
726
        catch (Exception $e) {
727
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
728
        }
729
    }
730
731
    /**
732
     * @param $file
733
     * @param $folder
734
     * @return bool
735
     */
736
    public static function copyFile($file, $folder)
737
    {
738
        return copy($file, $folder);
739
        //        try {
740
        //            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...
741
        //                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...
742
        //            } 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...
743
        //                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...
744
        //            }
745
        //        } 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...
746
        //            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...
747
        //        }
748
        //        return false;
749
    }
750
751
    /**
752
     * @param $src
753
     * @param $dst
754
     */
755
    public static function recurseCopy($src, $dst)
756
    {
757
        $dir = opendir($src);
758
        //    @mkdir($dst);
759
        while (false !== ($file = readdir($dir))) {
760
            if (($file !== '.') && ($file !== '..')) {
761
                if (is_dir($src . '/' . $file)) {
762
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
763
                } else {
764
                    copy($src . '/' . $file, $dst . '/' . $file);
765
                }
766
            }
767
        }
768
        closedir($dir);
769
    }
770
771
    /**
772
     *
773
     * Verifies XOOPS version meets minimum requirements for this module
774
     * @static
775
     * @param XoopsModule $module
776
     *
777
     * @return bool true if meets requirements, false if not
778
     */
779
    public static function checkXoopsVer(XoopsModule $module)
780
    {
781
        xoops_loadLanguage('admin', $module->dirname());
782
        //check for minimum XOOPS version
783
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
784
        $currArray   = explode('.', $currentVer);
785
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
786
        $reqArray    = explode('.', $requiredVer);
787
        $success     = true;
788
        foreach ($reqArray as $k => $v) {
789
            if (isset($currArray[$k])) {
790
                if ($currArray[$k] > $v) {
791
                    break;
792
                } elseif ($currArray[$k] == $v) {
793
                    continue;
794
                } else {
795
                    $success = false;
796
                    break;
797
                }
798
            } else {
799
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
800
                    $success = false;
801
                    break;
802
                }
803
            }
804
        }
805
806
        if (!$success) {
807
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
808
        }
809
810
        return $success;
811
    }
812
813
    /**
814
     *
815
     * Verifies PHP version meets minimum requirements for this module
816
     * @static
817
     * @param XoopsModule $module
818
     *
819
     * @return bool true if meets requirements, false if not
820
     */
821
    public static function checkPhpVer(XoopsModule $module)
822
    {
823
        xoops_loadLanguage('admin', $module->dirname());
824
        // check for minimum PHP version
825
        $success = true;
826
        $verNum  = phpversion();
827
        $reqVer  =& $module->getInfo('min_php');
828
        if (false !== $reqVer && '' !== $reqVer) {
829
            if (version_compare($verNum, $reqVer, '<')) {
830
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
831
                $success = false;
832
            }
833
        }
834
835
        return $success;
836
    }
837
}
838