Completed
Push — master ( 1aa479...f472f3 )
by Michael
02:12
created

WflinksUtility::getAdminMenu()   F

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 202
Code Lines 131

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 36
eloc 131
nc 3145752
nop 4
dl 0
loc 202
rs 2
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B WflinksUtility::uploadFiles() 0 48 6
B WflinksUtility::getForum() 8 23 4
A WflinksUtility::getLinkListHeader() 0 17 1
C WflinksUtility::getLinkListBody() 0 48 13
A WflinksUtility::getCategoryTitle() 0 9 1
A WflinksUtility::getLinkListFooter() 0 4 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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
use Xmf\Request;
4
5
require_once __DIR__ . '/common/traitversionchecks.php';
6
require_once __DIR__ . '/common/traitserverstats.php';
7
require_once __DIR__ . '/common/traitfilesmgmt.php';
8
9
/**
10
 * Class WflinksUtility
11
 */
12
class WflinksUtility extends XoopsObject
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...
13
{
14
    use VersionChecks; //checkVerXoops, checkVerPhp Traits
15
16
    use ServerStats; // getServerStats Trait
17
18
    use FilesManagement; // Files Management Trait
19
20
    /**
21
     * getHandler()
22
     *
23
     * @param         $name
24
     * @param boolean $optional
25
     *
26
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be object|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
27
     */
28
    public static function getHandler($name, $optional = false)
0 ignored issues
show
Coding Style introduced by
getHandler 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...
29
    {
30
        global $handlers, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
31
32
        $name = strtolower(trim($name));
33
        if (!isset($handlers[$name])) {
34
            if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/class_' . $name . '.php')) {
35
                require_once $hnd_file;
36
            }
37
            $class = 'wfl' . ucfirst($name) . 'Handler';
38
            if (class_exists($class)) {
39
                $handlers[$name] = new $class($GLOBALS['xoopsDB']);
40
            }
41
        }
42
        if (!$optional && !isset($handlers[$name])) {
43
            trigger_error('<div>Class <b>' . $class . '</b> does not exist.</div>
0 ignored issues
show
Bug introduced by
The variable $class 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...
44
                        <div>Handler Name: ' . $name, E_USER_ERROR) . '</div>';
45
        }
46
47
        return isset($handlers[$name]) ? $handlers[$name] : false;
48
    }
49
50
    /**
51
     * @param int    $cid
52
     * @param string $permType
53
     * @param bool   $redirect
54
     *
55
     * @return bool
56
     */
57
    public static function checkGroups($cid = 0, $permType = 'WFLinkCatPerm', $redirect = false)
58
    {
59
        global $xoopsUser, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
60
61
        $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
62
        $gpermHandler = xoops_getHandler('groupperm');
63 View Code Duplication
        if (!$gpermHandler->checkRight($permType, $cid, $groups, $xoopsModule->getVar('mid'))) {
0 ignored issues
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...
64
            if ($redirect === false) {
65
                return false;
66
            }
67
68
            redirect_header('index.php', 3, _NOPERM);
69
        }
70
71
        return true;
72
    }
73
74
    /**
75
     * @param int $lid
76
     * @return array|bool|false
77
     */
78
    public static function getVoteDetails($lid = 0)
79
    {
80
        global $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
81
82
        $sql = 'SELECT
83
        COUNT(rating) AS rate,
84
        MIN(rating) AS min_rate,
85
        MAX(rating) AS max_rate,
86
        AVG(rating) AS avg_rate,
87
        COUNT(ratinguser) AS rating_user,
88
        MAX(ratinguser) AS max_user,
89
        MAX(title) AS max_title,
90
        MIN(title) AS min_title,
91
        sum(ratinguser = 0) AS null_ratinguser
92
        FROM ' . $xoopsDB->prefix('wflinks_votedata');
93
        if ($lid > 0) {
94
            $sql .= " WHERE lid = $lid";
95
        }
96
        if (!$result = $xoopsDB->query($sql)) {
97
            return false;
98
        }
99
        $ret = $xoopsDB->fetchArray($result);
100
101
        return $ret;
102
    }
103
104
    /**
105
     * @param int $sel_id
106
     *
107
     * @return array|bool
108
     */
109
    public static function calculateVoteData($sel_id = 0)
110
    {
111
        $ret                  = [];
112
        $ret['useravgrating'] = 0;
113
114
        $sql = 'SELECT rating FROM ' . $xoopsDB->prefix('wflinks_votedata');
0 ignored issues
show
Bug introduced by
The variable $xoopsDB 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...
115
        if ($sel_id != 0) {
116
            ' WHERE lid = ' . $sel_id;
117
        }
118
        if (!$result = $xoopsDB->query($sql)) {
119
            return false;
120
        }
121
        $ret['uservotes'] = $xoopsDB->getRowsNum($result);
122
        while (list($rating) = $xoopsDB->fetchRow($result)) {
123
            $ret['useravgrating'] += (int)$rating;
124
        }
125
        if ($ret['useravgrating'] > 0) {
126
            $ret['useravgrating'] = number_format($ret['useravgrating'] / $ret['uservotes'], 2);
127
        }
128
129
        return $ret;
130
    }
131
132
    /**
133
     * @param      $array
134
     * @param null $name
135
     * @param null $def
136
     * @param bool $strict
137
     * @param int  $lengthcheck
138
     *
139
     * @return array|int|mixed|null|string
140
     */
141
    public static function cleanRequestVars($array, $name = null, $def = null, $strict = false, $lengthcheck = 15)
142
    {
143
        // Sanitise $_request for further use.  This method gives more control and security.
144
        // Method is more for functionality rather than beauty at the moment, will correct later.
145
        unset($array['usercookie'], $array['PHPSESSID']);
146
147
        if (is_array($array) && $name === null) {
148
            $globals = [];
149
            foreach (array_keys($array) as $k) {
150
                $value = strip_tags(trim($array[$k]));
151
                if ('' !== $value >= $lengthcheck) {
152
                    return null;
153
                }
154 View Code Duplication
                if (ctype_digit($value)) {
0 ignored issues
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...
155
                    $value = (int)$value;
156
                } else {
157
                    if ($strict === true) {
158
                        $value = preg_replace('/\W/', '', trim($value));
159
                    }
160
                    $value = strtolower((string)$value);
161
                }
162
                $globals[$k] = $value;
163
            }
164
165
            return $globals;
166
        }
167
        if (!array_key_exists($name, $array) || !isset($array[$name])) {
168
            return $def;
169
        }
170
171
        $value = strip_tags(trim($array[$name]));
172 View Code Duplication
        if (ctype_digit($value)) {
0 ignored issues
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...
173
            $value = (int)$value;
174
        } else {
175
            if ($strict === true) {
176
                $value = preg_replace('/\W/', '', trim($value));
177
            }
178
            $value = strtolower((string)$value);
179
        }
180
181
        return $value;
182
    }
183
184
    // toolbar()
185
    // @return
186
    /**
187
     * @param int $cid
188
     *
189
     * @return string
190
     */
191
    public static function getToolbar($cid = 0)
192
    {
193
        $toolbar = '[ ';
194
        if (true === static::checkGroups($cid, 'WFLinkSubPerm')) {
195
            $toolbar .= "<a href='submit.php?cid=" . $cid . "'>" . _MD_WFL_SUBMITLINK . '</a> | ';
196
        }
197
        $toolbar .= "<a href='newlist.php?newlinkshowdays=7'>" . _MD_WFL_LATESTLIST . "</a> | <a href='topten.php?list=hit'>" . _MD_WFL_POPULARITY . '</a>  ]';
198
199
        return $toolbar;
200
    }
201
202
203
    // displayicons()
204
    // @param  $time
205
    // @param integer $status
206
    // @param integer $counter
207
    // @return
208
    /**
209
     * @param     $time
210
     * @param int $status
211
     * @param int $counter
212
     *
213
     * @return string
214
     */
215
    public static function displayIcons($time, $status = 0, $counter = 0)
216
    {
217
        global $xoopsModuleConfig, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
218
219
        $new = '';
220
        $pop = '';
221
222
        $newdate = (time() - (86400 * (int)$xoopsModuleConfig['daysnew']));
223
        $popdate = (time() - (86400 * (int)$xoopsModuleConfig['daysupdated']));
224
225
        if ($xoopsModuleConfig['displayicons'] != 3) {
226
            if ($newdate < $time) {
227
                if ((int)$status > 1) {
228
                    if ($xoopsModuleConfig['displayicons'] == 1) {
229
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/update.png" alt="" align="top">';
230
                    }
231
                    if ($xoopsModuleConfig['displayicons'] == 2) {
232
                        $new = '<i>Updated!</i>';
233
                    }
234
                } else {
235
                    if ($xoopsModuleConfig['displayicons'] == 1) {
236
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/new.png" alt="" align="top">';
237
                    }
238
                    if ($xoopsModuleConfig['displayicons'] == 2) {
239
                        $new = '<i>New!</i>';
240
                    }
241
                }
242
            }
243
            if ($popdate > $time) {
244
                if ($counter >= $xoopsModuleConfig['popular']) {
245
                    if ($xoopsModuleConfig['displayicons'] == 1) {
246
                        $pop = '&nbsp;<img src ="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/popular.png" alt="" align="top">';
247
                    }
248
                    if ($xoopsModuleConfig['displayicons'] == 2) {
249
                        $pop = '<i>Popular!</i>';
250
                    }
251
                }
252
            }
253
        }
254
        $icons = $new . ' ' . $pop;
255
256
        return $icons;
257
    }
258
259
260
261
    // updaterating()
262
    // @param  $sel_id
263
    // @return updates rating data in itemtable for a given item
264
    /**
265
     * @param $sel_id
266
     */
267
    public static function updateRating($sel_id)
268
    {
269
        global $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
270
        $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('wflinks_votedata') . ' WHERE lid=' . $sel_id;
271
        $voteresult  = $xoopsDB->query($query);
272
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
273
        $totalrating = 0;
274
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
275
            $totalrating += $rating;
276
        }
277
        $finalrating = $totalrating / $votesDB;
278
        $finalrating = number_format($finalrating, 4);
279
        $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE lid = %u', $xoopsDB->prefix('wflinks_links'), $finalrating, $votesDB, $sel_id);
280
        $xoopsDB->query($sql);
281
    }
282
283
    // totalcategory()
284
    // @param integer $pid
285
    // @return
286
    /**
287
     * @param int $pid
288
     *
289
     * @return int
290
     */
291
    public static function getTotalCategory($pid = 0)
292
    {
293
        global $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
294
295
        $sql = 'SELECT cid FROM ' . $xoopsDB->prefix('wflinks_cat');
296
        if ($pid > 0) {
297
            $sql .= ' WHERE pid=0';
298
        }
299
        $result     = $xoopsDB->query($sql);
300
        $catlisting = 0;
301
        while (list($cid) = $xoopsDB->fetchRow($result)) {
302
            if (static::checkGroups($cid)) {
303
                ++$catlisting;
304
            }
305
        }
306
307
        return $catlisting;
308
    }
309
310
    // static::getTotalItems()
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...
311
    // @param integer $sel_id
312
    // @param integer $get_child
313
    // @param integer $return_sql
314
    // @return
315
    /**
316
     * @param int $sel_id
317
     * @param int $get_child
318
     * @param int $return_sql
319
     *
320
     * @return mixed
321
     */
322
    public static function getTotalItems($sel_id = 0, $get_child = 0, $return_sql = 0)
323
    {
324
        global $xoopsDB, $mytree, $_check_array;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
325
326
        if ($sel_id > 0) {
327
            $sql = 'SELECT DISTINCT a.lid, a.cid, published FROM '
328
                   . $xoopsDB->prefix('wflinks_links')
329
                   . ' a LEFT JOIN '
330
                   . $xoopsDB->prefix('wflinks_altcat')
331
                   . ' b '
332
                   . 'ON b.lid=a.lid '
333
                   . 'WHERE published > 0 AND published <= '
334
                   . time()
335
                   . ' AND (expired = 0 OR expired > '
336
                   . time()
337
                   . ') AND offline = 0 '
338
                   . ' AND (b.cid=a.cid OR (a.cid='
339
                   . $sel_id
340
                   . ' OR b.cid='
341
                   . $sel_id
342
                   . ')) ';
343
        } else {
344
            $sql = 'SELECT lid, cid, published FROM ' . $xoopsDB->prefix('wflinks_links') . ' WHERE offline = 0 AND published > 0 AND published <= ' . time() . ' AND (expired = 0 OR expired > ' . time() . ')';
345
        }
346
        if ($return_sql == 1) {
347
            return $sql;
348
        }
349
350
        $count          = 0;
351
        $published_date = 0;
352
353
        $items  = [];
0 ignored issues
show
Unused Code introduced by
$items 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...
354
        $result = $xoopsDB->query($sql);
355
        while (list($lid, $cid, $published) = $xoopsDB->fetchRow($result)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $lid 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...
Unused Code introduced by
The assignment to $cid 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...
356
            if (true === static::checkGroups()) {
357
                ++$count;
358
                $published_date = ($published > $published_date) ? $published : $published_date;
359
            }
360
        }
361
362
        $child_count = 0;
363
        if ($get_child == 1) {
364
            $items = $mytree->getAllChildId($sel_id);
365
            foreach ($items as $item) {
366
                $query2 = 'SELECT DISTINCT a.lid, a.cid, published FROM '
367
                          . $xoopsDB->prefix('wflinks_links')
368
                          . ' a LEFT JOIN '
369
                          . $xoopsDB->prefix('wflinks_altcat')
370
                          . ' b '
371
                          . 'ON b.lid=a.lid '
372
                          . 'WHERE published > 0 AND published <= '
373
                          . time()
374
                          . ' AND (expired = 0 OR expired > '
375
                          . time()
376
                          . ') AND offline = 0 '
377
                          . ' AND (b.cid=a.cid OR (a.cid='
378
                          . $item
379
                          . ' OR b.cid='
380
                          . $item
381
                          . ')) ';
382
383
                $result2 = $xoopsDB->query($query2);
384
                while (list($lid, $published) = $xoopsDB->fetchRow($result2)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $lid 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...
385
                    if ($published == 0) {
386
                        continue;
387
                    }
388
                    $published_date = ($published > $published_date) ? $published : $published_date;
389
                    ++$child_count;
390
                }
391
            }
392
        }
393
        $info['count']     = $count + $child_count;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = 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...
394
        $info['published'] = $published_date;
395
396
        return $info;
397
    }
398
399
    /**
400
     * @param string $indeximage
401
     * @param string $indexheading
402
     *
403
     * @return string
404
     */
405
    public static function getImageHeader($indeximage = '', $indexheading = '')
406
    {
407
        global $xoopsDB, $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
408
409
        if ($indeximage == '') {
410
            $result = $xoopsDB->query('SELECT indeximage, indexheading FROM ' . $xoopsDB->prefix('wflinks_indexpage'));
411
            list($indeximage, $indexheading) = $xoopsDB->fetchRow($result);
412
        }
413
414
        $image = '';
415
        if (!empty($indeximage)) {
416
            $image = static::displayImage($indeximage, "'index.php'", $xoopsModuleConfig['mainimagedir'], $indexheading);
417
        }
418
419
        return $image;
420
    }
421
422
    /**
423
     * @param string $image
424
     * @param string $path
425
     * @param string $imgsource
426
     * @param string $alttext
427
     *
428
     * @return string
429
     */
430
    public static function displayImage($image = '', $path = '', $imgsource = '', $alttext = '')
431
    {
432
        global $xoopsConfig, $xoopsUser, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
433
434
        $showimage = '';
435
        // Check to see if link is given
436
        if ($path) {
437
            $showimage = '<a href=' . $path . '>';
438
        }
439
440
        // checks to see if the file is valid else displays default blank image
441
        if (!is_dir(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
442
            && file_exists(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")) {
443
            $showimage .= "<img src='" . XOOPS_URL . "/{$imgsource}/{$image}' border='0' alt='" . $alttext . "'></a>";
444
        } else {
445
            if ($xoopsUser && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
446
                $showimage .= "<img src='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/assets/images/brokenimg.gif' alt='" . _MD_WFL_ISADMINNOTICE . "'></a>";
447
            } else {
448
                $showimage .= "<img src='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/assets/images/blank.gif' alt='" . $alttext . "'></a>";
449
            }
450
        }
451
        clearstatcache();
452
453
        return $showimage;
454
    }
455
456
    /**
457
     * @return string
458
     */
459
    public static function getLetters()
460
    {
461
        global $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
462
463
        $letterchoice = '<div>' . _MD_WFL_BROWSETOTOPIC . '</div>';
464
        $letterchoice .= '[  ';
465
        $alphabet     = [
466
            '0',
467
            '1',
468
            '2',
469
            '3',
470
            '4',
471
            '5',
472
            '6',
473
            '7',
474
            '8',
475
            '9',
476
            'A',
477
            'B',
478
            'C',
479
            'D',
480
            'E',
481
            'F',
482
            'G',
483
            'H',
484
            'I',
485
            'J',
486
            'K',
487
            'L',
488
            'M',
489
            'N',
490
            'O',
491
            'P',
492
            'Q',
493
            'R',
494
            'S',
495
            'T',
496
            'U',
497
            'V',
498
            'W',
499
            'X',
500
            'Y',
501
            'Z'
502
        ];
503
        $num          = count($alphabet) - 1;
504
        $counter      = 0;
505
        //    while (list(, $ltr) = each($alphabet)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
506
        foreach ($alphabet as $key => $ltr) {
507
            $letterchoice .= "<a href='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/viewcat.php?list=$ltr'>$ltr</a>";
508
            if ($counter == round($num / 2)) {
509
                $letterchoice .= ' ]<br>[ ';
510
            } elseif ($counter != $num) {
511
                $letterchoice .= '&nbsp;|&nbsp;';
512
            }
513
            ++$counter;
514
        }
515
        $letterchoice .= ' ]';
516
517
        return $letterchoice;
518
    }
519
520
    /**
521
     * @param $published
522
     *
523
     * @return mixed
524
     */
525
    public static function isNewImage($published)
526
    {
527
        global $xoopsModule, $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
528
529
        $oneday    = (time() - (86400 * 1));
530
        $threedays = (time() - (86400 * 3));
531
        $week      = (time() - (86400 * 7));
532
533
        $path = 'modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon';
534
535
        if ($published > 0 && $published < $week) {
536
            $indicator['image']   = "$path/linkload4.gif";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
537
            $indicator['alttext'] = _MD_WFL_NEWLAST;
538
        } elseif ($published >= $week && $published < $threedays) {
539
            $indicator['image']   = "$path/linkload3.gif";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
540
            $indicator['alttext'] = _MD_WFL_NEWTHIS;
541
        } elseif ($published >= $threedays && $published < $oneday) {
542
            $indicator['image']   = "$path/linkload2.gif";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
543
            $indicator['alttext'] = _MD_WFL_THREE;
544
        } elseif ($published >= $oneday) {
545
            $indicator['image']   = "$path/linkload1.gif";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
546
            $indicator['alttext'] = _MD_WFL_TODAY;
547
        } else {
548
            $indicator['image']   = "$path/linkload.gif";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
549
            $indicator['alttext'] = _MD_WFL_NO_FILES;
550
        }
551
552
        return $indicator;
553
    }
554
555
    /**
556
     * @param $haystack
557
     * @param $needle
558
     *
559
     * @return string
560
     */
561
    public static function searchString($haystack, $needle)
562
    {
563
        return substr($haystack, 0, strpos($haystack, $needle) + 1);
564
    }
565
566
567
    /**
568
     * @param $selected
569
     * @param $dirarray
570
     * @param $namearray
571
     */
572
    public static function getDirSelectOption($selected, $dirarray, $namearray)
573
    {
574
        echo "<select size='1' name='workd' onchange='location.href=\"upload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
575
        echo "<option value=''>--------------------------------------</option>";
576
        foreach ($namearray as $namearray => $workd) {
577
            if ($workd === $selected) {
578
                $opt_selected = 'selected';
579
            } else {
580
                $opt_selected = '';
581
            }
582
            echo "<option value='" . htmlspecialchars($namearray, ENT_QUOTES) . "' $opt_selected>" . $workd . '</option>';
583
        }
584
        echo '</select>';
585
    }
586
587
    /**
588
     * @param        $FILES
589
     * @param string $uploaddir
590
     * @param string $allowed_mimetypes
591
     * @param string $redirecturl
592
     * @param int    $num
593
     * @param int    $redirect
594
     * @param int    $usertype
595
     *
596
     * @return array|null
597
     */
598
    public static function uploadFiles(
0 ignored issues
show
Coding Style introduced by
uploadFiles uses the super-global variable $_POST 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...
599
        $FILES,
600
        $uploaddir = 'uploads',
601
        $allowed_mimetypes = '',
602
        $redirecturl = 'index.php',
603
        $num = 0,
604
        $redirect = 0,
605
        $usertype = 1)
606
    {
607
        global $FILES, $xoopsConfig, $xoopsModuleConfig, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
608
609
        $down = [];
610
//        require_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/uploader.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% 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...
611
        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
612
        if (empty($allowed_mimetypes)) {
613
            $allowed_mimetypes = wfl_getmime($FILES['userfile']['name'], $usertype);
614
        }
615
        $upload_dir = XOOPS_ROOT_PATH . '/' . $uploaddir . '/';
616
617
        $maxfilesize   = $xoopsModuleConfig['maxfilesize'];
618
        $maxfilewidth  = $xoopsModuleConfig['maximgwidth'];
619
        $maxfileheight = $xoopsModuleConfig['maximgheight'];
620
621
        $uploader = new XoopsMediaUploader($upload_dir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
622
//        $uploader->noAdminSizeCheck(1);
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...
623
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
624
            if (!$uploader->upload()) {
625
                $errors = $uploader->getErrors();
626
                redirect_header($redirecturl, 2, $errors);
627
            } else {
628
                if ($redirect) {
629
                    redirect_header($redirecturl, 1, _AM_WFL_UPLOADFILE);
630
                } else {
631
                    if (is_file($uploader->savedDestination)) {
632
                        $down['url']  = XOOPS_URL . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName);
633
                        $down['size'] = filesize(XOOPS_ROOT_PATH . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName));
634
                    }
635
636
                    return $down;
637
                }
638
            }
639
        } else {
640
            $errors = $uploader->getErrors();
641
            redirect_header($redirecturl, 1, $errors);
642
        }
643
644
        return null;
645
    }
646
647
    /**
648
     * @param $forumid
649
     *
650
     * @return mixed
651
     */
652
    public static function getForum($forumid)
653
    {
654
        global $xoopsDB, $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
655
656
        echo "<select name='forumid'>";
657
        echo "<option value='0'>----------------------</option>";
658
        if ($forumid < 4) {
659
            $result = $xoopsDB->query('SELECT forum_name, forum_id FROM ' . $xoopsDB->prefix('bb_forums') . ' ORDER BY forum_id');
660
        } else {
661
            $result = $xoopsDB->query('SELECT forum_name, forum_id FROM ' . $xoopsDB->prefix('bbex_forums') . ' ORDER BY forum_id');
662
        }
663 View Code Duplication
        while (list($forum_name, $forum_id) = $xoopsDB->fetchRow($result)) {
0 ignored issues
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...
664
            if ($forum_id == $forumid) {
665
                $opt_selected = 'selected';
666
            } else {
667
                $opt_selected = '';
668
            }
669
            echo "<option value='" . $forum_id . "' $opt_selected>" . $forum_name . '</option>';
670
        }
671
        echo '</select></div>';
672
673
        return $forumid;
674
    }
675
676
    /**
677
     * @param $heading
678
     */
679
    public static function getLinkListHeader($heading)
680
    {
681
        echo "
682
<!--        <h4 style='font-weight: bold; color: #0A3760;'>" . $heading . "</h4>\n -->
683
        <table width='100%' cellspacing='1' class='outer' style='font-size: smaller;' summary>\n
684
        <tr>\n
685
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ID . "</th>\n
686
        <th style='text-align: left;'><b>" . _AM_WFL_MINDEX_TITLE . "</th>\n
687
        <th style='text-align: left;'><b>" . _AM_WFL_CATTITLE . "</th>\n
688
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_POSTER . "</th>\n
689
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_PUBLISH . "</th>\n
690
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_EXPIRE . "</th>\n
691
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ONLINE . "</th>\n
692
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ACTION . "</th>\n
693
        </tr>\n
694
        ";
695
    }
696
697
    /**
698
     * @param $published
699
     */
700
    public static function getLinkListBody($published)
701
    {
702
        global $wfmyts, $imageArray, $xoopsModuleConfig, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
703
        xoops_load('XoopsUserUtility');
704
        $lid = $published['lid'];
705
        $cid = $published['cid'];
706
707
        $title     = "<a href='../singlelink.php?cid=" . $published['cid'] . '&amp;lid=' . $published['lid'] . "'>" . $wfmyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
708
        $maintitle = urlencode($wfmyts->htmlSpecialChars(trim($published['title'])));
0 ignored issues
show
Unused Code introduced by
$maintitle 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...
709
        $cattitle  = static::getCategoryTitle($published['cid']);
710
        $submitter = XoopsUserUtility::getUnameFromId($published['submitter']);
711
        $hwhoisurl = str_replace('http://', '', $published['url']);
712
        $submitted = formatTimestamp($published['date'], $xoopsModuleConfig['dateformat']);
0 ignored issues
show
Unused Code introduced by
$submitted 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...
713
        $publish   = ($published['published'] > 0) ? formatTimestamp($published['published'], $xoopsModuleConfig['dateformatadmin']) : 'Not Published';
714
        $expires   = $published['expired'] ? formatTimestamp($published['expired'], $xoopsModuleConfig['dateformatadmin']) : _AM_WFL_MINDEX_NOTSET;
715
        //    if ( ( $published['published'] && $published['published'] < time() ) && $published['offline'] == 0 ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
716
        //        $published_status = $imageArray['online'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
717
        //    } 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...
718
        //        $published_status = ( $published['published'] == 0 ) ? "<a href='newlinks.php'>" . $imageArray['offline'] . "</a>" : $imageArray['offline'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
719
        //    }
720
        if ($published['offline'] == 0
721
            && ($published['published'] && $published['published'] < time())
722
                           && (($published['expired'] && $published['expired'] > time()) || $published['expired'] == 0)) {
723
            $published_status = $imageArray['online'];
724
        } elseif ($published['offline'] == 0 && ($published['expired'] && $published['expired'] < time())) {
725
            $published_status = $imageArray['expired'];
726
        } else {
727
            $published_status = ($published['published'] == 0) ? "<a href='newlinks.php'>" . $imageArray['offline'] . '</a>' : $imageArray['offline'];
728
        }
729
        $icon = "<a href='main.php?op=edit&amp;lid=" . $lid . "' title='" . _AM_WFL_ICO_EDIT . "'>" . $imageArray['editimg'] . '</a>&nbsp;';
730
        $icon .= "<a href='main.php?op=delete&amp;lid=" . $lid . "' title='" . _AM_WFL_ICO_DELETE . "'>" . $imageArray['deleteimg'] . '</a>&nbsp;';
731
        $icon .= "<a href='altcat.php?op=main&amp;cid=" . $cid . '&amp;lid=' . $lid . '&amp;title=' . $wfmyts->htmlSpecialCharsStrip(trim($published['title'])) . "' title='" . _AM_WFL_ALTCAT_CREATEF . "'>" . $imageArray['altcat'] . '</a>&nbsp;';
732
        $icon .= '<a href="http://whois.domaintools.com/' . $hwhoisurl . '" target="_blank"><img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/domaintools.png" alt="WHOIS" title="WHOIS" align="absmiddle"></a>';
733
734
        echo "
735
        <tr class='txtcenter;'>\n
736
        <td class='head'><small>" . $lid . "</small></td>\n
737
        <td class='even' style='text-align: left;'><small>" . $title . "</small></td>\n
738
        <td class='even' style='text-align: left;'><small>" . $cattitle . "</small></td>\n
739
        <td class='even'><small>" . $submitter . "</small></td>\n
740
        <td class='even'><small>" . $publish . "</small></td>\n
741
        <td class='even'><small>" . $expires . "</small></td>\n
742
        <td class='even' width='4%'>" . $published_status . "</td>\n
743
        <td class='even' style='text-align: center; width: 6%; white-space: nowrap;'>$icon</td>\n
744
        </tr>\n
745
        ";
746
        unset($published);
747
    }
748
749
    /**
750
     * @param $catt
751
     *
752
     * @return mixed
753
     */
754
    public static function getCategoryTitle($catt)
755
    {
756
        global $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
757
        $sql    = 'SELECT title FROM ' . $xoopsDB->prefix('wflinks_cat') . ' WHERE cid=' . $catt;
758
        $result = $xoopsDB->query($sql);
759
        $result = $xoopsDB->fetchArray($result);
760
761
        return $result['title'];
762
    }
763
764
    public static function getLinkListFooter()
765
    {
766
        echo "<tr class='txtcenter;'>\n<td class='head' colspan='7'>" . _AM_WFL_MINDEX_NOLINKSFOUND . "</td>\n</tr>\n";
767
    }
768
769
    /**
770
     * @param        $pubrowamount
771
     * @param        $start
772
     * @param string $art
773
     * @param string $_this
774
     *
775
     * @return null
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
776
     */
777 View Code Duplication
    public static function getLinkListPageNav($pubrowamount, $start, $art = 'art', $_this = '')
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...
778
    {
779
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
780
        echo "</table>\n";
781
        if ($pubrowamount < $xoopsModuleConfig['admin_perpage']) {
782
            return false;
783
        }
784
        // Display Page Nav if published is > total display pages amount.
785
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
786
        //    $page = ( $pubrowamount > $xoopsModuleConfig['admin_perpage'] ) ? _AM_WFL_MINDEX_PAGE : '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
787
        $pagenav = new XoopsPageNav($pubrowamount, $xoopsModuleConfig['admin_perpage'], $start, 'st' . $art, $_this);
788
        echo '<div align="right" style="padding: 8px;">' . $pagenav->renderNav() . '</div>';
789
790
        return null;
791
    }
792
793
    /**
794
     * @param        $pubrowamount
795
     * @param        $start
796
     * @param string $art
797
     * @param string $_this
798
     *
799
     * @return null
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
800
     */
801 View Code Duplication
    public static function getLinkListPageNavLeft($pubrowamount, $start, $art = 'art', $_this = '')
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...
802
    {
803
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
804
        //    echo "</table>\n";
805
        if ($pubrowamount < $xoopsModuleConfig['admin_perpage']) {
806
            return false;
807
        }
808
        // Display Page Nav if published is > total display pages amount.
809
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
810
        //    $page = ( $pubrowamount > $xoopsModuleConfig['admin_perpage'] ) ? _AM_WFL_MINDEX_PAGE : '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
811
        $pagenav = new XoopsPageNav($pubrowamount, $xoopsModuleConfig['admin_perpage'], $start, 'st' . $art, $_this);
812
        echo '<div align="left" style="padding: 8px;">' . $pagenav->renderNav() . '</div>';
813
814
        return null;
815
    }
816
817
    // Retreive an editor according to the module's option "form_options"
818
819
    /**
820
     * @param $caption
821
     * @param $name
822
     * @param $value
823
     *
824
     * @return bool|\XoopsFormDhtmlTextArea|\XoopsFormEditor|\XoopsFormFckeditor|\XoopsFormHtmlarea|\XoopsFormTextArea
0 ignored issues
show
Documentation introduced by
Should the return type not be XoopsFormFckeditor|Xoops...tended|XoopsFormTinymce?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
825
     */
826
    public static function getWysiwygForm($caption, $name, $value)
827
    {
828
        global $xoopsModuleConfig, $xoopsUser, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
829
830
        $editor = false;
831
        $x22    = false;
832
        $xv     = str_replace('XOOPS ', '', XOOPS_VERSION);
833
        if (substr($xv, 2, 1) == '2') {
834
            $x22 = true;
835
        }
836
        $editor_configs           = [];
837
        $editor_configs['name']   = $name;
838
        $editor_configs['value']  = $value;
839
        $editor_configs['rows']   = 35;
840
        $editor_configs['cols']   = 60;
841
        $editor_configs['width']  = '100%';
842
        $editor_configs['height'] = '400px';
843
844
        $isadmin = ((is_object($xoopsUser) && !empty($xoopsUser))
845
                    && $xoopsUser->isAdmin($xoopsModule->mid()));
846
        if ($isadmin === true) {
847
            $formuser = $xoopsModuleConfig['form_options'];
848
        } else {
849
            $formuser = $xoopsModuleConfig['form_optionsuser'];
850
        }
851
852
        switch ($formuser) {
853
            case 'fck':
854
                if (!$x22) {
855
                    if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/fckeditor/formfckeditor.php')) {
856
                        require_once XOOPS_ROOT_PATH . '/class/xoopseditor/fckeditor/formfckeditor.php';
857
                        $editor = new XoopsFormFckeditor($editor_configs, true);
858
                    } else {
859
                        if ($dhtml) {
0 ignored issues
show
Bug introduced by
The variable $dhtml 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...
860
                            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
861
                        } else {
862
                            $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
863
                        }
864
                    }
865
                } else {
866
                    $editor = new XoopsFormEditor($caption, 'fckeditor', $editor_configs);
867
                }
868
                break;
869
870
            case 'htmlarea':
871
                if (!$x22) {
872
                    if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
873
                        require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php';
874
                        $editor = new XoopsFormHtmlarea($caption, $name, $value);
875
                    }
876
                } else {
877
                    $editor = new XoopsFormEditor($caption, 'htmlarea', $editor_configs);
878
                }
879
                break;
880
881
            case 'dhtml':
882
                if (!$x22) {
883
                    $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
884
                } else {
885
                    $editor = new XoopsFormEditor($caption, 'dhtmltextarea', $editor_configs);
886
                }
887
                break;
888
889
            case 'textarea':
890
                $editor = new XoopsFormTextArea($caption, $name, $value);
891
                break;
892
893
            case 'koivi':
894
                if (!$x22) {
895
                    if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/koivi/formwysiwygtextarea.php')) {
896
                        require_once XOOPS_ROOT_PATH . '/class/xoopseditor/koivi/formwysiwygtextarea.php';
897
                        $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, '100%', '400px');
898
                    } else {
899
                        if ($dhtml) {
900
                            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
901
                        } else {
902
                            $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
903
                        }
904
                    }
905
                } else {
906
                    $editor = new XoopsFormEditor($caption, 'koivi', $editor_configs);
907
                }
908
                break;
909
910
            case 'tinyeditor':
911
                if (!$x22) {
912
                    if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
913
                        require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
914
                        $editor = new XoopsFormTinyeditorTextArea([
915
                                                                      'caption' => $caption,
916
                                                                      'name'    => $name,
917
                                                                      'value'   => $value,
918
                                                                      'width'   => '100%',
919
                                                                      'height'  => '400px'
920
                                                                  ]);
921
                    } else {
922
                        if ($dhtml) {
923
                            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 50, 60);
924
                        } else {
925
                            $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
926
                        }
927
                    }
928
                } else {
929
                    $editor = new XoopsFormEditor($caption, 'tinyeditor', $editor_configs);
930
                }
931
                break;
932
933
            case 'dhtmlext':
934
                if (!$x22) {
935
                    if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/dhtmlext/dhtmlext.php')) {
936
                        require_once XOOPS_ROOT_PATH . '/class/xoopseditor/dhtmlext/dhtmlext.php';
937
                        $editor = new XoopsFormDhtmlTextAreaExtended($caption, $name, $value, 10, 50);
938
                    } else {
939
                        if ($dhtml) {
940
                            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 50, 60);
941
                        } else {
942
                            $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
943
                        }
944
                    }
945
                } else {
946
                    $editor = new XoopsFormEditor($caption, 'dhtmlext', $editor_configs);
947
                }
948
                break;
949
950
            case 'tinymce':
951
                if (!$x22) {
952
                    if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinymce/formtinymce.php')) {
953
                        require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinymce/formtinymce.php';
954
                        $editor = new XoopsFormTinymce([
955
                                                           'caption' => $caption,
956
                                                           'name'    => $name,
957
                                                           'value'   => $value,
958
                                                           'width'   => '100%',
959
                                                           'height'  => '400px'
960
                                                       ]);
961
                    } elseif (is_readable(XOOPS_ROOT_PATH . '/editors/tinymce/formtinymce.php')) {
962
                        require_once XOOPS_ROOT_PATH . '/editors/tinymce/formtinymce.php';
963
                        $editor = new XoopsFormTinymce([
964
                                                           'caption' => $caption,
965
                                                           'name'    => $name,
966
                                                           'value'   => $value,
967
                                                           'width'   => '100%',
968
                                                           'height'  => '400px'
969
                                                       ]);
970
                    } else {
971
                        if ($dhtml) {
972
                            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
973
                        } else {
974
                            $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
975
                        }
976
                    }
977
                } else {
978
                    $editor = new XoopsFormEditor($caption, 'tinymce', $editor_configs);
979
                }
980
                break;
981
        }
982
983
        return $editor;
984
    }
985
986
    /**
987
     * @param $countryn
988
     *
989
     * @return mixed
990
     */
991
    public static function getCountryName($countryn)
992
    {
993
        $country_array = [
994
            ''   => 'Unknown',
995
            '-'  => 'Unknown',
996
            'AD' => 'Andorra',
997
            'AE' => 'United Arab Emirates',
998
            'AF' => 'Afghanistan',
999
            'AG' => 'Antigua and Barbuda',
1000
            'AI' => 'Anguilla',
1001
            'AL' => 'Albania',
1002
            'AM' => 'Armenia',
1003
            'AN' => 'Netherlands Antilles',
1004
            'AO' => 'Angola',
1005
            'AQ' => 'Antarctica',
1006
            'AR' => 'Argentina',
1007
            'AS' => 'American Samoa',
1008
            'AT' => 'Austria',
1009
            'AU' => 'Australia',
1010
            'AW' => 'Aruba',
1011
            'AX' => 'Åland Islands',   // Added
1012
            'AZ' => 'Azerbaijan',
1013
            'BA' => 'Bosnia and Herzegovina',
1014
            'BB' => 'Barbados',
1015
            'BD' => 'Bangladesh',
1016
            'BE' => 'Belgium',
1017
            'BF' => 'Burkina Faso',
1018
            'BG' => 'Bulgaria',
1019
            'BH' => 'Bahrain',
1020
            'BI' => 'Burundi',
1021
            'BJ' => 'Benin',
1022
            'BL' => 'Saint Barthélemy',   // Added
1023
            'BM' => 'Bermuda',
1024
            'BN' => 'Brunei Darussalam',
1025
            'BO' => 'Bolivia',
1026
            'BR' => 'Brazil',
1027
            'BS' => 'Bahamas',
1028
            'BT' => 'Bhutan',
1029
            'BV' => 'Bouvet Island',
1030
            'BW' => 'Botswana',
1031
            'BY' => 'Belarus',
1032
            'BZ' => 'Belize',
1033
            'CA' => 'Canada',
1034
            'CC' => 'Cocos (Keeling) Islands',
1035
            'CD' => 'Congo (Dem. Rep.)',   // Added
1036
            'CF' => 'Central African Republic',
1037
            'CG' => 'Congo',
1038
            'CH' => 'Switzerland',
1039
            'CI' => "Cote D'Ivoire", // Removed: (Ivory Coast)
1040
            'CK' => 'Cook Islands',
1041
            'CL' => 'Chile',
1042
            'CM' => 'Cameroon',
1043
            'CN' => 'China',
1044
            'CO' => 'Colombia',
1045
            'CR' => 'Costa Rica',
1046
            'CS' => 'Czechoslovakia (former)',   // Not listed anymore
1047
            'CU' => 'Cuba',
1048
            'CV' => 'Cape Verde',
1049
            'CX' => 'Christmas Island',
1050
            'CY' => 'Cyprus',
1051
            'CZ' => 'Czech Republic',
1052
            'DE' => 'Germany',
1053
            'DJ' => 'Djibouti',
1054
            'DK' => 'Denmark',
1055
            'DM' => 'Dominica',
1056
            'DO' => 'Dominican Republic',
1057
            'DZ' => 'Algeria',
1058
            'EC' => 'Ecuador',
1059
            'EE' => 'Estonia',
1060
            'EG' => 'Egypt',
1061
            'EH' => 'Western Sahara',
1062
            'ER' => 'Eritrea',
1063
            'ES' => 'Spain',
1064
            'EU' => 'Europe',
1065
            'ET' => 'Ethiopia',
1066
            'FI' => 'Finland',
1067
            'FJ' => 'Fiji',
1068
            'FK' => 'Falkland Islands (Malvinas)',
1069
            'FM' => 'Micronesia',
1070
            'FO' => 'Faroe Islands',
1071
            'FR' => 'France',
1072
            'FX' => 'France, Metropolitan',   // Not listed anymore
1073
            'GA' => 'Gabon',
1074
            'GB' => 'Great Britain',     // Name was: Great Britain (UK)
1075
            'GD' => 'Grenada',
1076
            'GE' => 'Georgia',
1077
            'GF' => 'French Guiana',
1078
            'GG' => 'Guernsey',   // Added
1079
            'GH' => 'Ghana',
1080
            'GI' => 'Gibraltar',
1081
            'GL' => 'Greenland',
1082
            'GM' => 'Gambia',
1083
            'GN' => 'Guinea',
1084
            'GP' => 'Guadeloupe',
1085
            'GQ' => 'Equatorial Guinea',
1086
            'GR' => 'Greece',
1087
            'GS' => 'S. Georgia and S. Sandwich Isls.',
1088
            'GT' => 'Guatemala',
1089
            'GU' => 'Guam',
1090
            'GW' => 'Guinea-Bissau',
1091
            'GY' => 'Guyana',
1092
            'HK' => 'Hong Kong',
1093
            'HM' => 'Heard and McDonald Islands',
1094
            'HN' => 'Honduras',
1095
            'HR' => 'Croatia',
1096
            'HT' => 'Haiti',
1097
            'HU' => 'Hungary',
1098
            'ID' => 'Indonesia',
1099
            'IE' => 'Ireland',
1100
            'IL' => 'Israel',
1101
            'IM' => 'Isle of Man',    //  Added
1102
            'IN' => 'India',
1103
            'IO' => 'British Indian Ocean Territory',
1104
            'IQ' => 'Iraq',
1105
            'IR' => 'Iran',   //  Changed name
1106
            'IS' => 'Iceland',
1107
            'IT' => 'Italy',
1108
            'JE' => 'Jersey',
1109
            'JM' => 'Jamaica',
1110
            'JO' => 'Jordan',
1111
            'JP' => 'Japan',
1112
            'KE' => 'Kenya',
1113
            'KG' => 'Kyrgyzstan',
1114
            'KH' => 'Cambodia',
1115
            'KI' => 'Kiribati',
1116
            'KM' => 'Comoros',
1117
            'KN' => 'Saint Kitts and Nevis',
1118
            'KP' => 'Korea (North)',    // Official name: Korea, Democratic People's Republic of
1119
            'KR' => 'Korea (South)',    // Official name: Korea, Republic of
1120
            'KW' => 'Kuwait',
1121
            'KY' => 'Cayman Islands',
1122
            'KZ' => 'Kazakhstan',
1123
            'LA' => 'Laos',             // Official name: Lao People's Democratic Republic
1124
            'LB' => 'Lebanon',
1125
            'LC' => 'Saint Lucia',
1126
            'LI' => 'Liechtenstein',
1127
            'LK' => 'Sri Lanka',
1128
            'LR' => 'Liberia',
1129
            'LS' => 'Lesotho',
1130
            'LT' => 'Lithuania',
1131
            'LU' => 'Luxembourg',
1132
            'LV' => 'Latvia',
1133
            'LY' => 'Libya',            // Official name: Libyan Arab Jamahiriya
1134
            'MA' => 'Morocco',
1135
            'MC' => 'Monaco',
1136
            'MD' => 'Moldova',          // Official name: Moldova, Republic of
1137
            'ME' => 'Montenegro',       // Added
1138
            'MF' => 'Saint Martin',     // Added
1139
            'MG' => 'Madagascar',
1140
            'MH' => 'Marshall Islands',
1141
            'MK' => 'Macedonia',        // Official name: Macedonia, The Former Yugoslav Republic of
1142
            'ML' => 'Mali',
1143
            'MM' => 'Myanmar',
1144
            'MN' => 'Mongolia',
1145
            'MO' => 'Macao',            // Corrected name
1146
            'MP' => 'Northern Mariana Islands',
1147
            'MQ' => 'Martinique',
1148
            'MR' => 'Mauritania',
1149
            'MS' => 'Montserrat',
1150
            'MT' => 'Malta',
1151
            'MU' => 'Mauritius',
1152
            'MV' => 'Maldives',
1153
            'MW' => 'Malawi',
1154
            'MX' => 'Mexico',
1155
            'MY' => 'Malaysia',
1156
            'MZ' => 'Mozambique',
1157
            'NA' => 'Namibia',
1158
            'NC' => 'New Caledonia',
1159
            'NE' => 'Niger',
1160
            'NF' => 'Norfolk Island',
1161
            'NG' => 'Nigeria',
1162
            'NI' => 'Nicaragua',
1163
            'NL' => 'Netherlands',
1164
            'NO' => 'Norway',
1165
            'NP' => 'Nepal',
1166
            'NR' => 'Nauru',
1167
            'NT' => 'Neutral Zone',
1168
            'NU' => 'Niue',
1169
            'NZ' => 'New Zealand',
1170
            'OM' => 'Oman',
1171
            'PA' => 'Panama',
1172
            'PE' => 'Peru',
1173
            'PF' => 'French Polynesia',
1174
            'PG' => 'Papua New Guinea',
1175
            'PH' => 'Philippines',
1176
            'PK' => 'Pakistan',
1177
            'PL' => 'Poland',
1178
            'PM' => 'St. Pierre and Miquelon',
1179
            'PN' => 'Pitcairn',
1180
            'PR' => 'Puerto Rico',
1181
            'PS' => 'Palestinian Territory, Occupied',   // Added
1182
            'PT' => 'Portugal',
1183
            'PW' => 'Palau',
1184
            'PY' => 'Paraguay',
1185
            'QA' => 'Qatar',
1186
            'RE' => 'Reunion',
1187
            'RO' => 'Romania',
1188
            'RS' => 'Serbia',     // Added
1189
            'RU' => 'Russian Federation',
1190
            'RW' => 'Rwanda',
1191
            'SA' => 'Saudi Arabia',
1192
            'SB' => 'Solomon Islands',
1193
            'SC' => 'Seychelles',
1194
            'SD' => 'Sudan',
1195
            'SE' => 'Sweden',
1196
            'SG' => 'Singapore',
1197
            'SH' => 'St. Helena',
1198
            'SI' => 'Slovenia',
1199
            'SJ' => 'Svalbard and Jan Mayen Islands',
1200
            'SK' => 'Slovakia',              // Changed name, was: Slovak Republic
1201
            'SL' => 'Sierra Leone',
1202
            'SM' => 'San Marino',
1203
            'SN' => 'Senegal',
1204
            'SO' => 'Somalia',
1205
            'SR' => 'Suriname',
1206
            'ST' => 'Sao Tome and Principe',
1207
            'SU' => 'USSR (former)',          // Removed from ISO list, doesn' exsist anymore
1208
            'SV' => 'El Salvador',
1209
            'SY' => 'Syrian Arab Republic',   // Changed name, was: Syria
1210
            'SZ' => 'Swaziland',
1211
            'TC' => 'Turks and Caicos Islands',
1212
            'TD' => 'Chad',
1213
            'TF' => 'French Southern Territories',
1214
            'TG' => 'Togo',
1215
            'TH' => 'Thailand',
1216
            'TJ' => 'Tajikistan',
1217
            'TK' => 'Tokelau',
1218
            'TL' => 'Timor-Leste',    // Added
1219
            'TM' => 'Turkmenistan',
1220
            'TN' => 'Tunisia',
1221
            'TO' => 'Tonga',
1222
            'TP' => 'East Timor',             // Removed from ISO list, doesn' exsist anymore
1223
            'TR' => 'Turkey',
1224
            'TT' => 'Trinidad and Tobago',
1225
            'TV' => 'Tuvalu',
1226
            'TW' => 'Taiwan',         // Official name acc. to iso-list: Taiwan, Province of China
1227
            'TZ' => 'Tanzania',
1228
            'UA' => 'Ukraine',
1229
            'UG' => 'Uganda',
1230
            'UK' => 'United Kingdom',      // Doesn't exsist in iso-list ?
1231
            'UM' => 'US Minor Outlying Islands',
1232
            'US' => 'United States',
1233
            'UY' => 'Uruguay',
1234
            'UZ' => 'Uzbekistan',
1235
            'VA' => 'Vatican City State',
1236
            'VC' => 'Saint Vincent and the Grenadines',
1237
            'VE' => 'Venezuela',
1238
            'VG' => 'Virgin Islands, British',
1239
            'VI' => 'Virgin Islands, U.S.',
1240
            'VN' => 'Viet Nam',
1241
            'VU' => 'Vanuatu',
1242
            'WF' => 'Wallis and Futuna Islands',
1243
            'WS' => 'Samoa',
1244
            'YE' => 'Yemen',
1245
            'YT' => 'Mayotte',
1246
            'YU' => 'Yugoslavia',        // Removed from iso list
1247
            'ZA' => 'South Africa',
1248
            'ZM' => 'Zambia',
1249
            'ZR' => 'Zaire',             // Removed from iso list
1250
            'ZW' => 'Zimbabwe'
1251
        ];
1252
1253
        return $country_array[$countryn];
1254
    }
1255
1256
    /**
1257
     * @param $document
1258
     *
1259
     * @return mixed
1260
     */
1261
    public static function convertHtml2text($document)
1262
    {
1263
        $search = [
1264
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
1265
            "'<img.*?>'si", // Strip out img tags
1266
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
1267
            "'([\r\n])[\s]+'", // Strip out white space
1268
            "'&(quot|#34);'i", // Replace HTML entities
1269
            "'&(amp|#38);'i",
1270
            "'&(lt|#60);'i",
1271
            "'&(gt|#62);'i",
1272
            "'&(nbsp|#160);'i",
1273
            "'&(iexcl|#161);'i",
1274
            "'&(cent|#162);'i",
1275
            "'&(pound|#163);'i",
1276
            "'&(copy|#169);'i"
1277
        ]; // evaluate as php
1278
1279
        $replace = [
1280
            '',
1281
            '',
1282
            '',
1283
            "\\1",
1284
            '"',
1285
            '&',
1286
            '<',
1287
            '>',
1288
            ' ',
1289
            chr(161),
1290
            chr(162),
1291
            chr(163),
1292
            chr(169),
1293
        ];
1294
1295
        $text = preg_replace($search, $replace, $document);
1296
1297
        preg_replace_callback('/&#(\d+);/', function ($matches) {
1298
            return chr($matches[1]);
1299
        }, $document);
1300
1301
        return $text;
1302
    }
1303
1304
    //    Start functions for Google PageRank
1305
    //    Source: http://www.sws-tech.com/scripts/googlepagerank.php
1306
    //    This code is released under the public domain
1307
    /**
1308
     * @param $a
1309
     * @param $b
1310
     *
1311
     * @return float|int
1312
     */
1313
    public static function fillZeroes($a, $b)
1314
    {
1315
        $z = hexdec(80000000);
1316
        //echo $z;
1317
        if ($z & $a) {
1318
            $a >>= 1;
1319
            $a &= (~$z);
1320
            $a |= 0x40000000;
1321
            $a >>= ($b - 1);
1322
        } else {
1323
            $a >>= $b;
1324
        }
1325
1326
        return $a;
1327
    }
1328
1329
    /**
1330
     * @param $a
1331
     * @param $b
1332
     * @param $c
1333
     *
1334
     * @return array
1335
     */
1336
    public static function mix($a, $b, $c)
1337
    {
1338
        $a -= $b;
1339
        $a -= $c;
1340
        $a ^= static::fillZeroes($c, 13);
1341
        $b -= $c;
1342
        $b -= $a;
1343
        $b ^= ($a << 8);
1344
        $c -= $a;
1345
        $c -= $b;
1346
        $c ^= static::fillZeroes($b, 13);
1347
        $a -= $b;
1348
        $a -= $c;
1349
        $a ^= static::fillZeroes($c, 12);
1350
        $b -= $c;
1351
        $b -= $a;
1352
        $b ^= ($a << 16);
1353
        $c -= $a;
1354
        $c -= $b;
1355
        $c ^= static::fillZeroes($b, 5);
1356
        $a -= $b;
1357
        $a -= $c;
1358
        $a ^= static::fillZeroes($c, 3);
1359
        $b -= $c;
1360
        $b -= $a;
1361
        $b ^= ($a << 10);
1362
        $c -= $a;
1363
        $c -= $b;
1364
        $c ^= static::fillZeroes($b, 15);
1365
1366
        return [$a, $b, $c];
1367
    }
1368
1369
    /**
1370
     * @param      $url
1371
     * @param null $length
1372
     * @param int  $init
1373
     *
1374
     * @return mixed
1375
     */
1376
    public static function googleCh($url, $length = null, $init = 0xE6359A60)
1377
    {
1378
        if (null === $length) {
1379
            $length = count($url);
1380
        }
1381
        $a   = $b = 0x9E3779B9;
1382
        $c   = $init;
1383
        $k   = 0;
1384
        $len = $length;
1385
        while ($len >= 12) {
1386
            $a   += ($url[$k + 0] + ($url[$k + 1] << 8) + ($url[$k + 2] << 16) + ($url[$k + 3] << 24));
1387
            $b   += ($url[$k + 4] + ($url[$k + 5] << 8) + ($url[$k + 6] << 16) + ($url[$k + 7] << 24));
1388
            $c   += ($url[$k + 8] + ($url[$k + 9] << 8) + ($url[$k + 10] << 16) + ($url[$k + 11] << 24));
1389
            $mix = static::mix($a, $b, $c);
1390
            $a   = $mix[0];
1391
            $b   = $mix[1];
1392
            $c   = $mix[2];
1393
            $k   += 12;
1394
            $len -= 12;
1395
        }
1396
        $c += $length;
1397
        switch ($len) {              /* all the case statements fall through */
1398
            case 11:
1399
                $c += ($url[$k + 10] << 24);
1400
            // no break
1401
            case 10:
1402
                $c += ($url[$k + 9] << 16);
1403
            // no break
1404
            case 9:
1405
                $c += ($url[$k + 8] << 8);
1406
            /* the first byte of c is reserved for the length */
1407
            // no break
1408
            case 8:
1409
                $b += ($url[$k + 7] << 24);
1410
            // no break
1411
            case 7:
1412
                $b += ($url[$k + 6] << 16);
1413
            // no break
1414
            case 6:
1415
                $b += ($url[$k + 5] << 8);
1416
            // no break
1417
            case 5:
1418
                $b += $url[$k + 4];
1419
            // no break
1420
            case 4:
1421
                $a += ($url[$k + 3] << 24);
1422
            // no break
1423
            case 3:
1424
                $a += ($url[$k + 2] << 16);
1425
            // no break
1426
            case 2:
1427
                $a += ($url[$k + 1] << 8);
1428
            // no break
1429
            case 1:
1430
                $a += $url[$k + 0];
1431
            /* case 0: nothing left to add */
1432
        }
1433
        $mix = static::mix($a, $b, $c);
1434
        //echo $mix[0];
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
1435
        /*-------------------------------------------- report the result */
1436
1437
        return $mix[2];
1438
    }
1439
1440
    //converts a string into an array of integers containing the numeric value of the char
1441
1442
    /**
1443
     * @param $string
1444
     *
1445
     * @return mixed
1446
     */
1447
    public static function strord($string)
1448
    {
1449
        for ($i = 0, $iMax = strlen($string); $i < $iMax; ++$i) {
1450
            $result[$i] = ord($string{$i});
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
1451
        }
1452
1453
        return $result;
0 ignored issues
show
Bug introduced by
The variable $result 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...
1454
    }
1455
1456
    /**
1457
     * @param $url
1458
     *
1459
     * @return bool|string
1460
     */
1461
    public static function pagerank($url)
1462
    {
1463
        $pagerank = '';
1464
        $ch       = '6' . static::googleCh(static::strord('info:' . $url));
1465
        $fp       = fsockopen('www.google.com', 80, $errno, $errstr, 30);
1466
        if (!$fp) {
1467
            echo "$errstr ($errno)<br>\n";
1468
        } else {
1469
            $out = 'GET /search?client=navclient-auto&ch=' . $ch . '&features=Rank&q=info:' . $url . " HTTP/1.1\r\n";
1470
            $out .= "Host: www.google.com\r\n";
1471
            $out .= "Connection: Close\r\n\r\n";
1472
1473
            fwrite($fp, $out);
1474
1475
            while (!feof($fp)) {
1476
                $data = fgets($fp, 128);
1477
                $pos  = strpos($data, 'Rank_');
1478
                if ($pos === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
1479
                } else {
1480
                    $pagerank = substr($data, $pos + 9);
1481
                }
1482
            }
1483
            fclose($fp);
1484
        }
1485
1486
        return $pagerank;
1487
    }
1488
1489
    //  End functions for Google PageRank
1490
1491
    // Check if Tag module is installed
1492
    /**
1493
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1494
     */
1495 View Code Duplication
    public static function isTagModuleIncluded()
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...
1496
    {
1497
        static $wfl_tag_module_included;
1498
        if (!isset($wfl_tag_module_included)) {
1499
            $modulesHandler = xoops_getHandler('module');
1500
            $tag_mod        = $modulesHandler->getByDirName('tag');
1501
            if (!$tag_mod) {
1502
                $tag_mod = false;
0 ignored issues
show
Unused Code introduced by
$tag_mod 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...
1503
            } else {
1504
                $wfl_tag_module_included = $tag_mod->getVar('isactive') == 1;
1505
            }
1506
        }
1507
1508
        return $wfl_tag_module_included;
1509
    }
1510
1511
    // Add item_tag to Tag-module
1512
1513
    /**
1514
     * @param $lid
1515
     * @param $item_tag
1516
     */
1517
    public static function updateTag($lid, $item_tag)
1518
    {
1519
        global $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1520
        if (static::isTagModuleIncluded()) {
1521
            require_once XOOPS_ROOT_PATH . '/modules/tag/include/formtag.php';
1522
            $tagHandler = xoops_getModuleHandler('tag', 'tag');
1523
            $tagHandler->updateByItem($item_tag, $lid, $xoopsModule->getVar('dirname'), 0);
1524
        }
1525
    }
1526
1527
    // Check if News module is installed
1528
1529
    /**
1530
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1531
     */
1532 View Code Duplication
    public static function isNewsModuleIncluded()
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...
1533
    {
1534
        static $wfl_news_module_included;
1535
        if (!isset($wfl_news_module_included)) {
1536
            $modulesHandler = xoops_getHandler('module');
1537
            $news_mod       = $modulesHandler->getByDirName('news');
1538
            if (!$news_mod) {
1539
                $news_mod = false;
0 ignored issues
show
Unused Code introduced by
$news_mod 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...
1540
            } else {
1541
                $wfl_news_module_included = $news_mod->getVar('isactive') == 1;
1542
            }
1543
        }
1544
1545
        return $wfl_news_module_included;
1546
    }
1547
1548
    /**
1549
     * @param $banner_id
1550
     *
1551
     * @return null|string
1552
     */
1553 View Code Duplication
    public static function getBannerFromIdBanner($banner_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...
1554
    {
1555
        ###### Hack by www.stefanosilvestrini.com ######
1556
        global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1557
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
1558
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id);
1559
        list($numrows) = $db->fetchRow($bresult);
1560
        if ($numrows > 1) {
1561
            --$numrows;
1562
            mt_srand((double)microtime() * 1000000);
1563
            $bannum = mt_rand(0, $numrows);
1564
        } else {
1565
            $bannum = 0;
1566
        }
1567
        if ($numrows > 0) {
1568
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id, 1, $bannum);
1569
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
0 ignored issues
show
Unused Code introduced by
The assignment to $clickurl 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...
1570
            if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
1571
                // EMPTY
1572
            } else {
1573
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
1574
            }
1575
            /* Check if this impression is the last one and print the banner */
1576
            if ($imptotal == $impmade) {
1577
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
1578
                $sql   = sprintf('INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)', $db->prefix('bannerfinish'), $newid, $cid, $impmade, $clicks, $date, time());
1579
                $db->queryF($sql);
1580
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
1581
            }
1582
            if ($htmlbanner) {
1583
                $bannerobject = $htmlcode;
1584
            } else {
1585
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
1586
                if (stristr($imageurl, '.swf')) {
1587
                    $bannerobject = $bannerobject
1588
                                    . '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="468" height="60">'
1589
                                    . '<param name="movie" value="'
1590
                                    . $imageurl
1591
                                    . '"></param>'
1592
                                    . '<param name="quality" value="high"></param>'
1593
                                    . '<embed src="'
1594
                                    . $imageurl
1595
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
1596
                                    . '</embed>'
1597
                                    . '</object>';
1598
                } else {
1599
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="">';
1600
                }
1601
                $bannerobject .= '</a></div>';
1602
            }
1603
1604
            return $bannerobject;
1605
        }
1606
1607
        return null;
1608
    }
1609
1610
    /**
1611
     * @param $client_id
1612
     *
1613
     * @return string
1614
     */
1615 View Code Duplication
    public static function getBannerFromIdClient($client_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...
1616
    {
1617
        ###### Hack by www.stefanosilvestrini.com ######
1618
        global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1619
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
1620
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id);
1621
        list($numrows) = $db->fetchRow($bresult);
1622
        if ($numrows > 1) {
1623
            --$numrows;
1624
            mt_srand((double)microtime() * 1000000);
1625
            $bannum = mt_rand(0, $numrows);
1626
        } else {
1627
            $bannum = 0;
1628
        }
1629
        if ($numrows > 0) {
1630
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id . ' ORDER BY rand()', 1, $bannum);
1631
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
0 ignored issues
show
Unused Code introduced by
The assignment to $clickurl 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...
1632
            if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
1633
                // EMPTY
1634
            } else {
1635
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
1636
            }
1637
            /* Check if this impression is the last one and print the banner */
1638
            if ($imptotal == $impmade) {
1639
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
1640
                $sql   = sprintf('INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)', $db->prefix('bannerfinish'), $newid, $cid, $impmade, $clicks, $date, time());
1641
                $db->queryF($sql);
1642
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
1643
            }
1644
            if ($htmlbanner) {
1645
                $bannerobject = $htmlcode;
1646
            } else {
1647
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
1648
                if (stristr($imageurl, '.swf')) {
1649
                    $bannerobject = $bannerobject
1650
                                    . '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="468" height="60">'
1651
                                    . '<param name="movie" value="'
1652
                                    . $imageurl
1653
                                    . '"></param>'
1654
                                    . '<param name="quality" value="high"></param>'
1655
                                    . '<embed src="'
1656
                                    . $imageurl
1657
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
1658
                                    . '</embed>'
1659
                                    . '</object>';
1660
                } else {
1661
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="">';
1662
                }
1663
                $bannerobject .= '</a></div>';
1664
            }
1665
1666
            return $bannerobject;
1667
        }
1668
1669
        return null;
1670
    }
1671
1672
    /**
1673
     * @param $email
1674
     *
1675
     * @return mixed
1676
     */
1677 View Code Duplication
    public function convertEmail($email)
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...
1678
    {
1679
        $search = [
1680
            "/\@/",
1681
            "/\./",
1682
            "/\mailto:/",
1683
        ];
1684
1685
        $replace = [
1686
            ' AT ',
1687
            ' DOT ',
1688
            '',
1689
        ];
1690
1691
        $text = preg_replace($search, $replace, $email);
1692
1693
        return $text;
1694
    }
1695
1696
    /**
1697
     * @param $email
1698
     *
1699
     * @return mixed
1700
     */
1701 View Code Duplication
    public function printemailcnvrt($email)
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...
1702
    {
1703
        $search = [
1704
            "/\ AT /",
1705
            "/\ DOT /",
1706
        ];
1707
1708
        $replace = [
1709
            '@',
1710
            '.',
1711
        ];
1712
1713
        $text = preg_replace($search, $replace, $email);
1714
1715
        return $text;
1716
    }
1717
1718
    /**
1719
     * @param        $str
1720
     * @param        $start
1721
     * @param        $length
1722
     * @param string $trimmarker
1723
     *
1724
     * @return string
1725
     */
1726
    public static function getSubstring($str, $start, $length, $trimmarker = '...')
1727
    {
1728
        $configHandler          = xoops_getHandler('config');
1729
        $im_multilanguageConfig = $configHandler->getConfigsByCat(IM_CONF_MULILANGUAGE);
1730
1731
        if ($im_multilanguageConfig['ml_enable']) {
1732
            $tags  = explode(',', $im_multilanguageConfig['ml_tags']);
1733
            $strs  = [];
1734
            $hasML = false;
1735
            foreach ($tags as $tag) {
1736
                if (preg_match("/\[" . $tag . "](.*)\[\/" . $tag . "\]/sU", $str, $matches)) {
1737
                    if (count($matches) > 0) {
1738
                        $hasML  = true;
1739
                        $strs[] = $matches[1];
1740
                    }
1741
                }
1742
            }
1743
        } else {
1744
            $hasML = false;
1745
        }
1746
1747
        if (!$hasML) {
1748
            $strs = [$str];
1749
        }
1750
1751
        for ($i = 0; $i <= count($strs) - 1; ++$i) {
0 ignored issues
show
Bug introduced by
The variable $strs 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...
1752
            if (!XOOPS_USE_MULTIBYTES) {
1753
                $strs[$i] = (strlen($strs[$i]) - $start <= $length) ? substr($strs[$i], $start, $length) : substr($strs[$i], $start, $length - strlen($trimmarker)) . $trimmarker;
1754
            }
1755
1756
            if (function_exists('mb_internal_encoding') && @mb_internal_encoding(_CHARSET)) {
1757
                $str2     = mb_strcut($strs[$i], $start, $length - strlen($trimmarker));
1758
                $strs[$i] = $str2 . (mb_strlen($strs[$i]) != mb_strlen($str2) ? $trimmarker : '');
1759
            }
1760
1761
            // phppp patch
1762
            $DEP_CHAR = 127;
0 ignored issues
show
Unused Code introduced by
$DEP_CHAR 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...
1763
            $pos_st   = 0;
1764
            $action   = false;
1765
            for ($pos_i = 0, $pos_iMax = strlen($strs[$i]); $pos_i < $pos_iMax; ++$pos_i) {
1766
                if (ord(substr($strs[$i], $pos_i, 1)) > 127) {
1767
                    ++$pos_i;
1768
                }
1769
                if ($pos_i <= $start) {
1770
                    $pos_st = $pos_i;
1771
                }
1772
                if ($pos_i >= $pos_st + $length) {
1773
                    $action = true;
1774
                    break;
1775
                }
1776
            }
1777
            $strs[$i] = $action ? substr($strs[$i], $pos_st, $pos_i - $pos_st - strlen($trimmarker)) . $trimmarker : $strs[$i];
1778
1779
            $strs[$i] = $hasML ? '[' . $tags[$i] . ']' . $strs[$i] . '[/' . $tags[$i] . ']' : $strs[$i];
0 ignored issues
show
Bug introduced by
The variable $tags 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...
1780
        }
1781
        $str = implode('', $strs);
1782
1783
        return $str;
1784
    }
1785
    // Reusable Link Sorting Functions
1786
    // convertOrderByIn()
1787
    // @param  $orderby
1788
    // @return
1789
    /**
1790
     * @param $orderby
1791
     *
1792
     * @return string
1793
     */
1794
    public static function convertOrderByIn($orderby)
1795
    {
1796
        switch (trim($orderby)) {
1797
            case 'titleA':
1798
                $orderby = 'title ASC';
1799
                break;
1800
            case 'dateA':
1801
                $orderby = 'published ASC';
1802
                break;
1803
            case 'hitsA':
1804
                $orderby = 'hits ASC';
1805
                break;
1806
            case 'ratingA':
1807
                $orderby = 'rating ASC';
1808
                break;
1809
            case 'countryA':
1810
                $orderby = 'country ASC';
1811
                break;
1812
            case 'titleD':
1813
                $orderby = 'title DESC';
1814
                break;
1815
            case 'hitsD':
1816
                $orderby = 'hits DESC';
1817
                break;
1818
            case 'ratingD':
1819
                $orderby = 'rating DESC';
1820
                break;
1821
            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...
1822
                $orderby = 'published DESC';
1823
                break;
1824
            case 'countryD':
1825
                $orderby = 'country DESC';
1826
                break;
1827
        }
1828
1829
        return $orderby;
1830
    }
1831
1832
    /**
1833
     * @param $orderby
1834
     *
1835
     * @return string
1836
     */
1837
    public static function convertOrderByTrans($orderby)
1838
    {
1839
        if ($orderby === 'hits ASC') {
1840
            $orderbyTrans = _MD_WFL_POPULARITYLTOM;
1841
        }
1842
        if ($orderby === 'hits DESC') {
1843
            $orderbyTrans = _MD_WFL_POPULARITYMTOL;
1844
        }
1845
        if ($orderby === 'title ASC') {
1846
            $orderbyTrans = _MD_WFL_TITLEATOZ;
1847
        }
1848
        if ($orderby === 'title DESC') {
1849
            $orderbyTrans = _MD_WFL_TITLEZTOA;
1850
        }
1851
        if ($orderby === 'published ASC') {
1852
            $orderbyTrans = _MD_WFL_DATEOLD;
1853
        }
1854
        if ($orderby === 'published DESC') {
1855
            $orderbyTrans = _MD_WFL_DATENEW;
1856
        }
1857
        if ($orderby === 'rating ASC') {
1858
            $orderbyTrans = _MD_WFL_RATINGLTOH;
1859
        }
1860
        if ($orderby === 'rating DESC') {
1861
            $orderbyTrans = _MD_WFL_RATINGHTOL;
1862
        }
1863
        if ($orderby === 'country ASC') {
1864
            $orderbyTrans = _MD_WFL_COUNTRYLTOH;
1865
        }
1866
        if ($orderby === 'country DESC') {
1867
            $orderbyTrans = _MD_WFL_COUNTRYHTOL;
1868
        }
1869
1870
        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...
1871
    }
1872
1873
    /**
1874
     * @param $orderby
1875
     *
1876
     * @return string
1877
     */
1878
1879
    public static function convertOrderByOut($orderby)
1880
    {
1881
        if ($orderby === 'title ASC') {
1882
            $orderby = 'titleA';
1883
        }
1884
        if ($orderby === 'published ASC') {
1885
            $orderby = 'dateA';
1886
        }
1887
        if ($orderby === 'hits ASC') {
1888
            $orderby = 'hitsA';
1889
        }
1890
        if ($orderby === 'rating ASC') {
1891
            $orderby = 'ratingA';
1892
        }
1893
        if ($orderby === 'country ASC') {
1894
            $orderby = 'countryA';
1895
        }
1896
        if ($orderby === 'weight ASC') {
1897
            $orderby = 'weightA';
1898
        }
1899
        if ($orderby === 'title DESC') {
1900
            $orderby = 'titleD';
1901
        }
1902
        if ($orderby === 'published DESC') {
1903
            $orderby = 'dateD';
1904
        }
1905
        if ($orderby === 'hits DESC') {
1906
            $orderby = 'hitsD';
1907
        }
1908
        if ($orderby === 'rating DESC') {
1909
            $orderby = 'ratingD';
1910
        }
1911
        if ($orderby === 'country DESC') {
1912
            $orderby = 'countryD';
1913
        }
1914
1915
        return $orderby;
1916
    }
1917
}
1918