Completed
Push — master ( 91b0ad...7b8e46 )
by Michael
01:46
created

functions.php ➔ wfl_serverstats()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 12
nop 0
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 *
4
 * Module: WF-Links
5
 * Version: v1.0.3
6
 * Release Date: 21 June 2005
7
 * Developer: John N
8
 * Team: WF-Projects
9
 * Licence: GNU
10
 */
11
// defined('XOOPS_ROOT_PATH') || exit('Restricted access.');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
12
/**
13
 * wfs_gethandler()
14
 *
15
 * @param         $name
16
 * @param boolean $optional
17
 *
18
 * @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...
19
 */
20
function &wfl_gethandler($name, $optional = false)
0 ignored issues
show
Coding Style introduced by
wfl_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...
21
{
22
    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...
23
24
    $name = strtolower(trim($name));
25
    if (!isset($handlers[$name])) {
26
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/class_' . $name . '.php')) {
27
            require_once $hnd_file;
28
        }
29
        $class = 'wfl' . ucfirst($name) . 'Handler';
30
        if (class_exists($class)) {
31
            $handlers[$name] = new $class($GLOBALS['xoopsDB']);
32
        }
33
    }
34
    if (!isset($handlers[$name]) && !$optional) {
35
        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...
36
                        <div>Handler Name: ' . $name, E_USER_ERROR) . '</div>';
37
    }
38
39
    return isset($handlers[$name]) ? $handlers[$name] : false;
40
}
41
42
/**
43
 * @param int    $cid
44
 * @param string $permType
45
 * @param bool   $redirect
46
 *
47
 * @return bool
48
 */
49
function wfl_checkgroups($cid = 0, $permType = 'WFLinkCatPerm', $redirect = false)
50
{
51
    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...
52
53
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
54
    $gpermHandler = xoops_getHandler('groupperm');
55
    if (!$gpermHandler->checkRight($permType, $cid, $groups, $xoopsModule->getVar('mid'))) {
56
        if ($redirect === false) {
57
            return false;
58
        } else {
59
            redirect_header('index.php', 3, _NOPERM);
60
        }
61
    }
62
63
    return true;
64
}
65
66
/**
67
 * @param int $lid
68
 * @return array|bool|false
69
 */
70
function wfl_getVoteDetails($lid = 0)
71
{
72
    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...
73
74
    $sql = 'SELECT
75
        COUNT(rating) AS rate,
76
        MIN(rating) AS min_rate,
77
        MAX(rating) AS max_rate,
78
        AVG(rating) AS avg_rate,
79
        COUNT(ratinguser) AS rating_user,
80
        MAX(ratinguser) AS max_user,
81
        MAX(title) AS max_title,
82
        MIN(title) AS min_title,
83
        sum(ratinguser = 0) AS null_ratinguser
84
        FROM ' . $xoopsDB->prefix('wflinks_votedata');
85
    if ($lid > 0) {
86
        $sql .= " WHERE lid = $lid";
87
    }
88
    if (!$result = $xoopsDB->query($sql)) {
89
        return false;
90
    }
91
    $ret = $xoopsDB->fetchArray($result);
92
93
    return $ret;
94
}
95
96
/**
97
 * @param int $sel_id
98
 *
99
 * @return array|bool
100
 */
101
function wfl_calcVoteData($sel_id = 0)
102
{
103
    $ret                  = array();
104
    $ret['useravgrating'] = 0;
105
106
    $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...
107
    if ($sel_id != 0) {
108
        ' WHERE lid = ' . $sel_id;
109
    }
110
    if (!$result = $xoopsDB->query($sql)) {
111
        return false;
112
    }
113
    $ret['uservotes'] = $xoopsDB->getRowsNum($result);
114
    while (list($rating) = $xoopsDB->fetchRow($result)) {
115
        $ret['useravgrating'] += (int)$rating;
116
    }
117
    if ($ret['useravgrating'] > 0) {
118
        $ret['useravgrating'] = number_format($ret['useravgrating'] / $ret['uservotes'], 2);
119
    }
120
121
    return $ret;
122
}
123
124
/**
125
 * @param      $array
126
 * @param null $name
127
 * @param null $def
128
 * @param bool $strict
129
 * @param int  $lengthcheck
130
 *
131
 * @return array|int|mixed|null|string
132
 */
133
function wfl_cleanRequestVars($array, $name = null, $def = null, $strict = false, $lengthcheck = 15)
134
{
135
    // Sanitise $_request for further use.  This method gives more control and security.
136
    // Method is more for functionality rather than beauty at the moment, will correct later.
137
    unset($array['usercookie'], $array['PHPSESSID']);
138
139
    if (is_array($array) && $name === null) {
140
        $globals = array();
141
        foreach (array_keys($array) as $k) {
142
            $value = strip_tags(trim($array[$k]));
143
            if (strlen($value >= $lengthcheck)) {
144
                return null;
145
            }
146 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...
147
                $value = (int)$value;
148
            } else {
149
                if ($strict === true) {
150
                    $value = preg_replace('/\W/', '', trim($value));
151
                }
152
                $value = strtolower((string)$value);
153
            }
154
            $globals[$k] = $value;
155
        }
156
157
        return $globals;
158
    }
159
    if (!isset($array[$name]) || !array_key_exists($name, $array)) {
160
        return $def;
161
    } else {
162
        $value = strip_tags(trim($array[$name]));
163
    }
164 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...
165
        $value = (int)$value;
166
    } else {
167
        if ($strict === true) {
168
            $value = preg_replace('/\W/', '', trim($value));
169
        }
170
        $value = strtolower((string)$value);
171
    }
172
173
    return $value;
174
}
175
176
// toolbar()
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
177
// @return
178
/**
179
 * @param int $cid
180
 *
181
 * @return string
182
 */
183
function wfl_toolbar($cid = 0)
184
{
185
    $toolbar = '[ ';
186
    if (true === wfl_checkgroups($cid, 'WFLinkSubPerm')) {
187
        $toolbar .= "<a href='submit.php?cid=" . $cid . "'>" . _MD_WFL_SUBMITLINK . '</a> | ';
188
    }
189
    $toolbar .= "<a href='newlist.php?newlinkshowdays=7'>" . _MD_WFL_LATESTLIST . "</a> | <a href='topten.php?list=hit'>" . _MD_WFL_POPULARITY . '</a>  ]';
190
191
    return $toolbar;
192
}
193
194
// wfl_serverstats()
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
195
// @return
196
function wfl_serverstats()
197
{
198
    echo "
199
    <fieldset><legend style='font-weight: bold; color: #0A3760;'>" . _AM_WFL_LINK_IMAGEINFO . "</legend>\n
200
        <div style='padding: 8px;'>\n
201
        <div>" . _AM_WFL_LINK_SPHPINI . "</div>\n";
202
203
//    $safemode        = ini_get('safe_mode') ? _AM_WFL_LINK_ON . _AM_WFL_LINK_SAFEMODEPROBLEMS : _AM_WFL_LINK_OFF;
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
204
//    $registerglobals = (ini_get('register_globals') === '') ? _AM_WFL_LINK_OFF : _AM_WFL_LINK_ON;
205
    $links           = ini_get('file_uploads') ? _AM_WFL_LINK_ON : _AM_WFL_LINK_OFF;
206
207
    $gdlib = function_exists('gd_info') ? _AM_WFL_LINK_GDON : _AM_WFL_LINK_GDOFF;
208
    echo '<li>' . _AM_WFL_LINK_GDLIBSTATUS . $gdlib;
209
    if (function_exists('gd_info')) {
210
        if (true === $gdlib = gd_info()) {
211
            echo '<li>' . _AM_WFL_LINK_GDLIBVERSION . '<b>' . $gdlib['GD Version'] . '</b>';
212
        }
213
    }
214
    echo "<br><br>\n\n";
215
//    echo '<li>' . _AM_WFL_LINK_SAFEMODESTATUS . $safemode;
216
//    echo '<li>' . _AM_WFL_LINK_REGISTERGLOBALS . $registerglobals;
217
    echo '<li>' . _AM_WFL_LINK_SERVERUPLOADSTATUS . $links;
218
    echo '</div>';
219
    echo '</fieldset><br>';
220
}
221
222
// displayicons()
223
// @param  $time
224
// @param integer $status
225
// @param integer $counter
226
// @return
227
/**
228
 * @param     $time
229
 * @param int $status
230
 * @param int $counter
231
 *
232
 * @return string
233
 */
234
function wfl_displayicons($time, $status = 0, $counter = 0)
235
{
236
    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...
237
238
    $new = '';
239
    $pop = '';
240
241
    $newdate = (time() - (86400 * (int)$xoopsModuleConfig['daysnew']));
242
    $popdate = (time() - (86400 * (int)$xoopsModuleConfig['daysupdated']));
243
244
    if ($xoopsModuleConfig['displayicons'] != 3) {
245
        if ($newdate < $time) {
246
            if ((int)$status > 1) {
247
                if ($xoopsModuleConfig['displayicons'] == 1) {
248
                    $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/update.png" alt="" align="top">';
249
                }
250
                if ($xoopsModuleConfig['displayicons'] == 2) {
251
                    $new = '<i>Updated!</i>';
252
                }
253
            } else {
254
                if ($xoopsModuleConfig['displayicons'] == 1) {
255
                    $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/new.png" alt="" align="top">';
256
                }
257
                if ($xoopsModuleConfig['displayicons'] == 2) {
258
                    $new = '<i>New!</i>';
259
                }
260
            }
261
        }
262
        if ($popdate > $time) {
263
            if ($counter >= $xoopsModuleConfig['popular']) {
264
                if ($xoopsModuleConfig['displayicons'] == 1) {
265
                    $pop = '&nbsp;<img src ="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/popular.png" alt="" align="top">';
266
                }
267
                if ($xoopsModuleConfig['displayicons'] == 2) {
268
                    $pop = '<i>Popular!</i>';
269
                }
270
            }
271
        }
272
    }
273
    $icons = $new . ' ' . $pop;
274
275
    return $icons;
276
}
277
278
if (!function_exists('wfl_convertorderbyin')) {
279
    // Reusable Link Sorting Functions
280
    // wfl_convertorderbyin()
281
    // @param  $orderby
282
    // @return
283
    /**
284
     * @param $orderby
285
     *
286
     * @return string
287
     */
288
    function wfl_convertorderbyin($orderby)
289
    {
290
        switch (trim($orderby)) {
291
            case 'titleA':
292
                $orderby = 'title ASC';
293
                break;
294
            case 'dateA':
295
                $orderby = 'published ASC';
296
                break;
297
            case 'hitsA':
298
                $orderby = 'hits ASC';
299
                break;
300
            case 'ratingA':
301
                $orderby = 'rating ASC';
302
                break;
303
            case 'countryA':
304
                $orderby = 'country ASC';
305
                break;
306
            case 'titleD':
307
                $orderby = 'title DESC';
308
                break;
309
            case 'hitsD':
310
                $orderby = 'hits DESC';
311
                break;
312
            case 'ratingD':
313
                $orderby = 'rating DESC';
314
                break;
315
            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...
316
                $orderby = 'published DESC';
317
                break;
318
            case 'countryD':
319
                $orderby = 'country DESC';
320
                break;
321
        }
322
323
        return $orderby;
324
    }
325
}
326
if (!function_exists('wfl_convertorderbytrans')) {
327
    /**
328
     * @param $orderby
329
     *
330
     * @return string
331
     */
332
    function wfl_convertorderbytrans($orderby)
333
    {
334
        if ($orderby === 'hits ASC') {
335
            $orderbyTrans = _MD_WFL_POPULARITYLTOM;
336
        }
337
        if ($orderby === 'hits DESC') {
338
            $orderbyTrans = _MD_WFL_POPULARITYMTOL;
339
        }
340
        if ($orderby === 'title ASC') {
341
            $orderbyTrans = _MD_WFL_TITLEATOZ;
342
        }
343
        if ($orderby === 'title DESC') {
344
            $orderbyTrans = _MD_WFL_TITLEZTOA;
345
        }
346
        if ($orderby === 'published ASC') {
347
            $orderbyTrans = _MD_WFL_DATEOLD;
348
        }
349
        if ($orderby === 'published DESC') {
350
            $orderbyTrans = _MD_WFL_DATENEW;
351
        }
352
        if ($orderby === 'rating ASC') {
353
            $orderbyTrans = _MD_WFL_RATINGLTOH;
354
        }
355
        if ($orderby === 'rating DESC') {
356
            $orderbyTrans = _MD_WFL_RATINGHTOL;
357
        }
358
        if ($orderby === 'country ASC') {
359
            $orderbyTrans = _MD_WFL_COUNTRYLTOH;
360
        }
361
        if ($orderby === 'country DESC') {
362
            $orderbyTrans = _MD_WFL_COUNTRYHTOL;
363
        }
364
365
        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...
366
    }
367
}
368
if (!function_exists('wfl_convertorderbyout')) {
369
    /**
370
     * @param $orderby
371
     *
372
     * @return string
373
     */
374
    function wfl_convertorderbyout($orderby)
375
    {
376
        if ($orderby === 'title ASC') {
377
            $orderby = 'titleA';
378
        }
379
        if ($orderby === 'published ASC') {
380
            $orderby = 'dateA';
381
        }
382
        if ($orderby === 'hits ASC') {
383
            $orderby = 'hitsA';
384
        }
385
        if ($orderby === 'rating ASC') {
386
            $orderby = 'ratingA';
387
        }
388
        if ($orderby === 'country ASC') {
389
            $orderby = 'countryA';
390
        }
391
        if ($orderby === 'weight ASC') {
392
            $orderby = 'weightA';
393
        }
394
        if ($orderby === 'title DESC') {
395
            $orderby = 'titleD';
396
        }
397
        if ($orderby === 'published DESC') {
398
            $orderby = 'dateD';
399
        }
400
        if ($orderby === 'hits DESC') {
401
            $orderby = 'hitsD';
402
        }
403
        if ($orderby === 'rating DESC') {
404
            $orderby = 'ratingD';
405
        }
406
        if ($orderby === 'country DESC') {
407
            $orderby = 'countryD';
408
        }
409
410
        return $orderby;
411
    }
412
}
413
414
// updaterating()
415
// @param  $sel_id
416
// @return updates rating data in itemtable for a given item
417
/**
418
 * @param $sel_id
419
 */
420
function wfl_updaterating($sel_id)
421
{
422
    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...
423
    $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('wflinks_votedata') . ' WHERE lid=' . $sel_id;
424
    $voteresult  = $xoopsDB->query($query);
425
    $votesDB     = $xoopsDB->getRowsNum($voteresult);
426
    $totalrating = 0;
427
    while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
428
        $totalrating += $rating;
429
    }
430
    $finalrating = $totalrating / $votesDB;
431
    $finalrating = number_format($finalrating, 4);
432
    $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE lid = %u', $xoopsDB->prefix('wflinks_links'), $finalrating, $votesDB, $sel_id);
433
    $xoopsDB->query($sql);
434
}
435
436
// totalcategory()
437
// @param integer $pid
438
// @return
439
/**
440
 * @param int $pid
441
 *
442
 * @return int
443
 */
444
function wfl_totalcategory($pid = 0)
445
{
446
    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...
447
448
    $sql = 'SELECT cid FROM ' . $xoopsDB->prefix('wflinks_cat');
449
    if ($pid > 0) {
450
        $sql .= ' WHERE pid=0';
451
    }
452
    $result     = $xoopsDB->query($sql);
453
    $catlisting = 0;
454
    while (list($cid) = $xoopsDB->fetchRow($result)) {
455
        if (wfl_checkgroups($cid)) {
456
            ++$catlisting;
457
        }
458
    }
459
460
    return $catlisting;
461
}
462
463
// wfl_getTotalItems()
464
// @param integer $sel_id
465
// @param integer $get_child
466
// @param integer $return_sql
467
// @return
468
/**
469
 * @param int $sel_id
470
 * @param int $get_child
471
 * @param int $return_sql
472
 *
473
 * @return mixed
474
 */
475
function wfl_getTotalItems($sel_id = 0, $get_child = 0, $return_sql = 0)
476
{
477
    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...
478
479
    if ($sel_id > 0) {
480
        $sql = 'SELECT DISTINCT a.lid, a.cid, published FROM '
481
               . $xoopsDB->prefix('wflinks_links')
482
               . ' a LEFT JOIN '
483
               . $xoopsDB->prefix('wflinks_altcat')
484
               . ' b '
485
               . 'ON b.lid=a.lid '
486
               . 'WHERE published > 0 AND published <= '
487
               . time()
488
               . ' AND (expired = 0 OR expired > '
489
               . time()
490
               . ') AND offline = 0 '
491
               . ' AND (b.cid=a.cid OR (a.cid='
492
               . $sel_id
493
               . ' OR b.cid='
494
               . $sel_id
495
               . ')) ';
496
    } else {
497
        $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() . ')';
498
    }
499
    if ($return_sql == 1) {
500
        return $sql;
501
    }
502
503
    $count          = 0;
504
    $published_date = 0;
505
506
    $arr    = array();
0 ignored issues
show
Unused Code introduced by
$arr is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
507
    $result = $xoopsDB->query($sql);
508
    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...
509
        if (true === wfl_checkgroups()) {
510
            ++$count;
511
            $published_date = ($published > $published_date) ? $published : $published_date;
512
        }
513
    }
514
515
    $child_count = 0;
516
    if ($get_child == 1) {
517
        $arr  = $mytree->getAllChildId($sel_id);
518
        $size = count($arr);
0 ignored issues
show
Unused Code introduced by
$size 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...
519
        for ($i = 0, $iMax = count($arr); $i < $iMax; ++$i) {
520
            $query2 = 'SELECT DISTINCT a.lid, a.cid, published FROM '
521
                      . $xoopsDB->prefix('wflinks_links')
522
                      . ' a LEFT JOIN '
523
                      . $xoopsDB->prefix('wflinks_altcat')
524
                      . ' b '
525
                      . 'ON b.lid=a.lid '
526
                      . 'WHERE published > 0 AND published <= '
527
                      . time()
528
                      . ' AND (expired = 0 OR expired > '
529
                      . time()
530
                      . ') AND offline = 0 '
531
                      . ' AND (b.cid=a.cid OR (a.cid='
532
                      . $arr[$i]
533
                      . ' OR b.cid='
534
                      . $arr[$i]
535
                      . ')) ';
536
537
            $result2 = $xoopsDB->query($query2);
538
            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...
539
                if ($published == 0) {
540
                    continue;
541
                }
542
                $published_date = ($published > $published_date) ? $published : $published_date;
543
                ++$child_count;
544
            }
545
        }
546
    }
547
    $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...
548
    $info['published'] = $published_date;
549
550
    return $info;
551
}
552
553
/**
554
 * @param string $indeximage
555
 * @param string $indexheading
556
 *
557
 * @return string
558
 */
559
function wfl_imageheader($indeximage = '', $indexheading = '')
560
{
561
    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...
562
563
    if ($indeximage == '') {
564
        $result = $xoopsDB->query('SELECT indeximage, indexheading FROM ' . $xoopsDB->prefix('wflinks_indexpage'));
565
        list($indeximage, $indexheading) = $xoopsDB->fetchRow($result);
566
    }
567
568
    $image = '';
569
    if (!empty($indeximage)) {
570
        $image = wfl_displayimage($indeximage, "'index.php'", $xoopsModuleConfig['mainimagedir'], $indexheading);
571
    }
572
573
    return $image;
574
}
575
576
/**
577
 * @param string $image
578
 * @param string $path
579
 * @param string $imgsource
580
 * @param string $alttext
581
 *
582
 * @return string
583
 */
584
function wfl_displayimage($image = '', $path = '', $imgsource = '', $alttext = '')
585
{
586
    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...
587
588
    $showimage = '';
589
    // Check to see if link is given
590
    if ($path) {
591
        $showimage = '<a href=' . $path . '>';
592
    }
593
594
    // checks to see if the file is valid else displays default blank image
595
    if (!is_dir(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
596
        && file_exists(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")) {
597
        $showimage .= "<img src='" . XOOPS_URL . "/{$imgsource}/{$image}' border='0' alt='" . $alttext . "'></a>";
598
    } else {
599
        if ($xoopsUser && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
600
            $showimage .= "<img src='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/assets/images/brokenimg.gif' alt='" . _MD_WFL_ISADMINNOTICE . "'></a>";
601
        } else {
602
            $showimage .= "<img src='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/assets/images/blank.gif' alt='" . $alttext . "'></a>";
603
        }
604
    }
605
    clearstatcache();
606
607
    return $showimage;
608
}
609
610
/**
611
 * @return string
612
 */
613
function wfl_letters()
614
{
615
    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...
616
617
    $letterchoice = '<div>' . _MD_WFL_BROWSETOTOPIC . '</div>';
618
    $letterchoice .= '[  ';
619
    $alphabet     = array(
620
        '0',
621
        '1',
622
        '2',
623
        '3',
624
        '4',
625
        '5',
626
        '6',
627
        '7',
628
        '8',
629
        '9',
630
        'A',
631
        'B',
632
        'C',
633
        'D',
634
        'E',
635
        'F',
636
        'G',
637
        'H',
638
        'I',
639
        'J',
640
        'K',
641
        'L',
642
        'M',
643
        'N',
644
        'O',
645
        'P',
646
        'Q',
647
        'R',
648
        'S',
649
        'T',
650
        'U',
651
        'V',
652
        'W',
653
        'X',
654
        'Y',
655
        'Z'
656
    );
657
    $num          = count($alphabet) - 1;
658
    $counter      = 0;
659
    //    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...
660
    foreach ($alphabet as $key => $ltr) {
661
        $letterchoice .= "<a href='" . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . "/viewcat.php?list=$ltr'>$ltr</a>";
662
        if ($counter == round($num / 2)) {
663
            $letterchoice .= ' ]<br>[ ';
664
        } elseif ($counter != $num) {
665
            $letterchoice .= '&nbsp;|&nbsp;';
666
        }
667
        ++$counter;
668
    }
669
    $letterchoice .= ' ]';
670
671
    return $letterchoice;
672
}
673
674
/**
675
 * @param $published
676
 *
677
 * @return mixed
678
 */
679
function wfl_isnewimage($published)
680
{
681
    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...
682
683
    $oneday    = (time() - (86400 * 1));
684
    $threedays = (time() - (86400 * 3));
685
    $week      = (time() - (86400 * 7));
686
687
    $path = 'modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon';
688
689
    if ($published > 0 && $published < $week) {
690
        $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...
691
        $indicator['alttext'] = _MD_WFL_NEWLAST;
692
    } elseif ($published >= $week && $published < $threedays) {
693
        $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...
694
        $indicator['alttext'] = _MD_WFL_NEWTHIS;
695
    } elseif ($published >= $threedays && $published < $oneday) {
696
        $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...
697
        $indicator['alttext'] = _MD_WFL_THREE;
698
    } elseif ($published >= $oneday) {
699
        $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...
700
        $indicator['alttext'] = _MD_WFL_TODAY;
701
    } else {
702
        $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...
703
        $indicator['alttext'] = _MD_WFL_NO_FILES;
704
    }
705
706
    return $indicator;
707
}
708
709
/**
710
 * @param $haystack
711
 * @param $needle
712
 *
713
 * @return string
714
 */
715
function wfl_strrrchr($haystack, $needle)
716
{
717
    return substr($haystack, 0, strpos($haystack, $needle) + 1);
718
}
719
720
/**
721
 * @param string $header
722
 * @param string $menu
723
 * @param string $extra
724
 * @param int    $scount
725
 *
726
 * @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...
727
 */
728
function wfl_adminmenu($header = '', $menu = '', $extra = '', $scount = 4)
0 ignored issues
show
Coding Style introduced by
wfl_adminmenu uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
729
{
730
    global $xoopsConfig, $xoopsModule, $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...
731
732
    $_named_url = xoops_getenv('PHP_SELF');
733
    if ($_named_url) {
734
        $thispage = basename($_named_url);
735
    }
736
737
    if (file_exists(__DIR__ . '/../docs/' . $xoopsConfig['language'] . '/readme.html')) {
738
        $docs = '<a href="../docs/' . $xoopsConfig['language'] . '/readme.html" target="_blank">' . _AM_WFL_DOCUMENTATION . '</a> |';
739
    } elseif (file_exists(__DIR__ . '/../docs/english/readme.html')) {
740
        $docs = '<a href="../docs/english/readme.html" target="_blank">' . _AM_WFL_DOCUMENTATION . '</a> |';
741
    } else {
742
        $docs = '';
743
    }
744
745
    $op = isset($_GET['op']) ? $op = '?op=' . $_GET['op'] : '';
746
747
    echo "<h4 style='color: #2F5376;'>" . _AM_WFL_MODULE_NAME . '</h4>';
748
    echo "
749
        <table width='100%' cellspacing='0' cellpadding='0' border='0' class='outer'>\n
750
        <tr>\n
751
        <td style='font-size: 10px; text-align: left; color: #2F5376; padding: 2px 6px; line-height: 18px;'>\n
752
        <a href='../admin/index.php'>" . _AM_WFL_BINDEX . "</a> | \n
753
        <a href='../index.php'>" . _AM_WFL_GOMODULE . "</a> | \n
754
        <a href='../../system/admin.php?fct=preferences&op=showmod&mod=" . $xoopsModule->getVar('mid') . "'>" . _AM_WFL_PREFS . "</a> | \n
755
        <a href='../../system/admin.php?fct=modulesadmin&op=update&module=" . $xoopsModule->getVar('dirname') . "'>" . _AM_WFL_BUPDATE . "</a> | \n
756
        <a href='../admin/permissions.php'>" . _AM_WFL_BPERMISSIONS . "</a> | \n
757
        <a href='../admin/myblocksadmin.php'>" . _AM_WFL_BLOCKADMIN . "</a> | \n
758
        " . $docs . "
759
        <a href='../admin/about.php'>" . _AM_WFL_ABOUT . "</a> \n
760
        </td>\n
761
        </tr>\n
762
        </table><br>\n
763
        ";
764
765
    if (empty($menu)) {
766
        // You can change this part to suit your own module. Defining this here will save you form having to do this each time.
767
        $menu = array(
768
            _AM_WFL_INDEXPAGE      => 'indexpage.php',
769
            _AM_WFL_MCATEGORY      => 'category.php',
770
            _AM_WFL_MLINKS         => 'main.php?op=edit',
771
            _AM_WFL_MUPLOADS       => 'upload.php',
772
            _AM_WFL_MVOTEDATA      => 'votedata.php',
773
            _AM_WFL_MLISTPINGTIMES => 'main.php?op=pingtime',
774
            _AM_WFL_MCOMMENTS      => '../../system/admin.php?module=' . $xoopsModule->getVar('mid') . '&status=0&limit=100&fct=comments&selsubmit=Go',
775
        );
776
    }
777
778
    if (!is_array($menu)) {
779
        echo "<table width='100%' cellpadding= '2' cellspacing= '1' class='outer'>\n";
780
        echo "<tr><td class ='even' align ='center'><b>" . _AM_WFL_NOMENUITEMS . "</b></td></tr></table><br>\n";
781
782
        return false;
783
    }
784
785
    $oddnum = array(1 => '1', 3 => '3', 5 => '5', 7 => '7', 9 => '9', 11 => '11', 13 => '13');
786
    // number of rows per menu
787
    $menurows = count($menu) / $scount;
788
    // total amount of rows to complete menu
789
    $menurow = ceil($menurows) * $scount;
790
    // actual number of menuitems per row
791
    $rowcount = $menurow / ceil($menurows);
0 ignored issues
show
Unused Code introduced by
$rowcount 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...
792
    $count    = 0;
793
    for ($i = count($menu); $i < $menurow; ++$i) {
794
        $tempArray = array(1 => null);
795
        $menu      = array_merge($menu, $tempArray);
796
        ++$count;
797
    }
798
799
    // Sets up the width of each menu cell
800
    $width = 100 / $scount;
801
    $width = ceil($width);
802
803
    $menucount = 0;
804
    $count     = 0;
805
806
    // Menu table output
807
    echo "<table width='100%' cellpadding= '2' cellspacing= '1' class='outer'><tr>";
808
809
    // Check to see if $menu is and array
810
    if (is_array($menu)) {
811
        $classcounts = 0;
812
        $classcol[0] = 'even';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$classcol was never initialized. Although not strictly required by PHP, it is generally a good practice to add $classcol = 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...
813
814
        for ($i = 1; $i < $menurow; ++$i) {
815
            ++$classcounts;
816
            if ($classcounts >= $scount) {
817
                if ($classcol[$i - 1] === 'odd') {
818
                    $classcol[$i] = ($classcol[$i - 1] === 'odd' && in_array($classcounts, $oddnum)) ? 'even' : 'odd';
819
                } else {
820
                    $classcol[$i] = ($classcol[$i - 1] === 'even' && in_array($classcounts, $oddnum)) ? 'odd' : 'even';
821
                }
822
                $classcounts = 0;
823
            } else {
824
                $classcol[$i] = ($classcol[$i - 1] === 'even') ? 'odd' : 'even';
825
            }
826
        }
827
        unset($classcounts);
828
829
        foreach ($menu as $menutitle => $menulink) {
830
            if ($thispage . $op == $menulink) {
0 ignored issues
show
Bug introduced by
The variable $thispage 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...
831
                $classcol[$count] = 'outer';
832
            }
833
            echo "<td class='" . $classcol[$count] . "' class='txtcenter;' valign='middle' width='$width%'>";
834
            if (is_string($menulink)) {
835
                echo "<a href='" . $menulink . "'><small>" . $menutitle . '</small></a></td>';
836
            } else {
837
                echo '&nbsp;</td>';
838
            }
839
            ++$menucount;
840
            ++$count;
841
842
            // Break menu cells to start a new row if $count > $scount
843
            if ($menucount >= $scount) {
844
                echo '</tr>';
845
                $menucount = 0;
846
            }
847
        }
848
        echo '</table><br>';
849
        unset($count, $menucount);
850
    }
851
    // ###### Output warn messages for security ######
852
    if (is_dir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/')) {
853
        xoops_error(sprintf(_AM_WFL_WARNINSTALL1, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/'));
854
        echo '<br>';
855
    }
856
857
    $_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php';
858
    if (file_exists($_file)) {
859
        xoops_error(sprintf(_AM_WFL_WARNINSTALL2, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php'));
860
        echo '<br>';
861
    }
862
863
    $path1 = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['mainimagedir'];
864
    if (!is_dir($path1)) {
865
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path1));
866
        echo '<br>';
867
    }
868
    if (!is_writable($path1)) {
869
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path1));
870
        echo '<br>';
871
    }
872
873
    $path1_t = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['mainimagedir'] . '/thumbs';
874
    if (!is_dir($path1_t)) {
875
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path1_t));
876
        echo '<br>';
877
    }
878
    if (!is_writable($path1_t)) {
879
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path1_t));
880
        echo '<br>';
881
    }
882
883
    $path2 = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['screenshots'];
884
    if (!is_dir($path2)) {
885
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path2));
886
        echo '<br>';
887
    }
888
    if (!is_writable($path2)) {
889
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path2));
890
        echo '<br>';
891
    }
892
893
    $path2_t = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['screenshots'] . '/thumbs';
894
    if (!is_dir($path2_t)) {
895
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path2_t));
896
        echo '<br>';
897
    }
898
    if (!is_writable($path2_t)) {
899
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path2_t));
900
        echo '<br>';
901
    }
902
903
    $path3 = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['catimage'];
904
    if (!is_dir($path3)) {
905
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path3));
906
        echo '<br>';
907
    }
908
    if (!is_writable($path3)) {
909
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path3));
910
        echo '<br>';
911
    }
912
913
    $path3_t = XOOPS_ROOT_PATH . '/' . $xoopsModuleConfig['catimage'] . '/thumbs';
914
    if (!is_dir($path3_t)) {
915
        xoops_error(sprintf(_AM_WFL_WARNINSTALL3, $path3_t));
916
        echo '<br>';
917
    }
918
    if (!is_writable($path3_t)) {
919
        xoops_error(sprintf(_AM_WFL_WARNINSTALL4, $path3_t));
920
        echo '<br>';
921
    }
922
923
    echo "<h3 style='color: #2F5376;'>" . $header . '</h3>';
924
    if ($extra) {
925
        echo "<div>$extra</div>";
926
    }
927
928
    return null;
929
}
930
931
/**
932
 * @param $selected
933
 * @param $dirarray
934
 * @param $namearray
935
 */
936
function wfl_getDirSelectOption($selected, $dirarray, $namearray)
0 ignored issues
show
Unused Code introduced by
The parameter $dirarray is not used and could be removed.

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

Loading history...
937
{
938
    echo "<select size='1' name='workd' onchange='location.href=\"upload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
939
    echo "<option value=''>--------------------------------------</option>";
940
    foreach ($namearray as $namearray => $workd) {
941
        if ($workd === $selected) {
942
            $opt_selected = 'selected';
943
        } else {
944
            $opt_selected = '';
945
        }
946
        echo "<option value='" . htmlspecialchars($namearray, ENT_QUOTES) . "' $opt_selected>" . $workd . '</option>';
947
    }
948
    echo '</select>';
949
}
950
951
/**
952
 * @param        $FILES
953
 * @param string $uploaddir
954
 * @param string $allowed_mimetypes
955
 * @param string $redirecturl
956
 * @param int    $num
957
 * @param int    $redirect
958
 * @param int    $usertype
959
 *
960
 * @return array|null
961
 */
962
function wfl_uploading(
0 ignored issues
show
Coding Style introduced by
wfl_uploading 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...
963
    $FILES,
964
    $uploaddir = 'uploads',
965
    $allowed_mimetypes = '',
966
    $redirecturl = 'index.php',
967
    $num = 0,
968
    $redirect = 0,
969
    $usertype = 1
970
) {
971
    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...
972
973
    $down = array();
974
    require_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/uploader.php';
975
    if (empty($allowed_mimetypes)) {
976
        $allowed_mimetypes = wfl_retmime($FILES['userfile']['name'], $usertype);
977
    }
978
    $upload_dir = XOOPS_ROOT_PATH . '/' . $uploaddir . '/';
979
980
    $maxfilesize   = $xoopsModuleConfig['maxfilesize'];
981
    $maxfilewidth  = $xoopsModuleConfig['maximgwidth'];
982
    $maxfileheight = $xoopsModuleConfig['maximgheight'];
983
984
    $uploader = new XoopsMediaUploader($upload_dir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
985
    $uploader->noAdminSizeCheck(1);
986
    if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
987
        if (!$uploader->upload()) {
988
            $errors = $uploader->getErrors();
989
            redirect_header($redirecturl, 2, $errors);
990
        } else {
991
            if ($redirect) {
992
                redirect_header($redirecturl, 1, _AM_PDD_UPLOADFILE);
993
            } else {
994
                if (is_file($uploader->savedDestination)) {
995
                    $down['url']  = XOOPS_URL . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName);
996
                    $down['size'] = filesize(XOOPS_ROOT_PATH . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName));
997
                }
998
999
                return $down;
1000
            }
1001
        }
1002
    } else {
1003
        $errors = $uploader->getErrors();
1004
        redirect_header($redirecturl, 1, $errors);
1005
    }
1006
1007
    return null;
1008
}
1009
1010
/**
1011
 * @param $forumid
1012
 *
1013
 * @return mixed
1014
 */
1015
function wfl_getforum($forumid)
1016
{
1017
    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...
1018
1019
    echo "<select name='forumid'>";
1020
    echo "<option value='0'>----------------------</option>";
1021
    if ($forumid < 4) {
1022
        $result = $xoopsDB->query('SELECT forum_name, forum_id FROM ' . $xoopsDB->prefix('bb_forums') . ' ORDER BY forum_id');
1023
    } else {
1024
        $result = $xoopsDB->query('SELECT forum_name, forum_id FROM ' . $xoopsDB->prefix('bbex_forums') . ' ORDER BY forum_id');
1025
    }
1026 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...
1027
        if ($forum_id == $forumid) {
1028
            $opt_selected = 'selected';
1029
        } else {
1030
            $opt_selected = '';
1031
        }
1032
        echo "<option value='" . $forum_id . "' $opt_selected>" . $forum_name . '</option>';
1033
    }
1034
    echo '</select></div>';
1035
1036
    return $forumid;
1037
}
1038
1039
/**
1040
 * @param $heading
1041
 */
1042
function wfl_linklistheader($heading)
1043
{
1044
    echo "
1045
<!--        <h4 style='font-weight: bold; color: #0A3760;'>" . $heading . "</h4>\n -->
1046
        <table width='100%' cellspacing='1' class='outer' style='font-size: smaller;' summary>\n
1047
        <tr>\n
1048
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ID . "</th>\n
1049
        <th style='text-align: left;'><b>" . _AM_WFL_MINDEX_TITLE . "</th>\n
1050
        <th style='text-align: left;'><b>" . _AM_WFL_CATTITLE . "</th>\n
1051
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_POSTER . "</th>\n
1052
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_PUBLISH . "</th>\n
1053
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_EXPIRE . "</th>\n
1054
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ONLINE . "</th>\n
1055
        <th class='txtcenter;'>" . _AM_WFL_MINDEX_ACTION . "</th>\n
1056
        </tr>\n
1057
        ";
1058
}
1059
1060
/**
1061
 * @param $published
1062
 */
1063
function wfl_linklistbody($published)
1064
{
1065
    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...
1066
    xoops_load('XoopsUserUtility');
1067
    $lid = $published['lid'];
1068
    $cid = $published['cid'];
1069
1070
    $title     = "<a href='../singlelink.php?cid=" . $published['cid'] . '&amp;lid=' . $published['lid'] . "'>" . $wfmyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
1071
    $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...
1072
    $cattitle  = wfl_cattitle($published['cid']);
1073
    $submitter = XoopsUserUtility::getUnameFromId($published['submitter']);
1074
    $hwhoisurl = str_replace('http://', '', $published['url']);
1075
    $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...
1076
    $publish   = ($published['published'] > 0) ? formatTimestamp($published['published'], $xoopsModuleConfig['dateformatadmin']) : 'Not Published';
1077
    $expires   = $published['expired'] ? formatTimestamp($published['expired'], $xoopsModuleConfig['dateformatadmin']) : _AM_WFL_MINDEX_NOTSET;
1078
    //    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...
1079
    //        $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...
1080
    //    } 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...
1081
    //        $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...
1082
    //    }
1083
    if ((($published['expired'] && $published['expired'] > time()) or $published['expired'] == 0)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1084
        && ($published['published'] && $published['published'] < time())
1085
        && $published['offline'] == 0) {
1086
        $published_status = $imagearray['online'];
1087
    } elseif (($published['expired'] && $published['expired'] < time()) && $published['offline'] == 0) {
1088
        $published_status = $imagearray['expired'];
1089
    } else {
1090
        $published_status = ($published['published'] == 0) ? "<a href='newlinks.php'>" . $imagearray['offline'] . '</a>' : $imagearray['offline'];
1091
    }
1092
    $icon = "<a href='main.php?op=edit&amp;lid=" . $lid . "' title='" . _AM_WFL_ICO_EDIT . "'>" . $imagearray['editimg'] . '</a>&nbsp;';
1093
    $icon .= "<a href='main.php?op=delete&amp;lid=" . $lid . "' title='" . _AM_WFL_ICO_DELETE . "'>" . $imagearray['deleteimg'] . '</a>&nbsp;';
1094
    $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;';
1095
    $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>';
1096
1097
    echo "
1098
        <tr class='txtcenter;'>\n
1099
        <td class='head'><small>" . $lid . "</small></td>\n
1100
        <td class='even' style='text-align: left;'><small>" . $title . "</small></td>\n
1101
        <td class='even' style='text-align: left;'><small>" . $cattitle . "</small></td>\n
1102
        <td class='even'><small>" . $submitter . "</small></td>\n
1103
        <td class='even'><small>" . $publish . "</small></td>\n
1104
        <td class='even'><small>" . $expires . "</small></td>\n
1105
        <td class='even' width='4%'>" . $published_status . "</td>\n
1106
        <td class='even' style='text-align: center; width: 6%; white-space: nowrap;'>$icon</td>\n
1107
        </tr>\n
1108
        ";
1109
    unset($published);
1110
}
1111
1112
/**
1113
 * @param $catt
1114
 *
1115
 * @return mixed
1116
 */
1117
function wfl_cattitle($catt)
1118
{
1119
    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...
1120
    $sql    = 'SELECT title FROM ' . $xoopsDB->prefix('wflinks_cat') . ' WHERE cid=' . $catt;
1121
    $result = $xoopsDB->query($sql);
1122
    $result = $xoopsDB->fetchArray($result);
1123
1124
    return $result['title'];
1125
}
1126
1127
function wfl_linklistfooter()
1128
{
1129
    echo "<tr class='txtcenter;'>\n<td class='head' colspan='7'>" . _AM_WFL_MINDEX_NOLINKSFOUND . "</td>\n</tr>\n";
1130
}
1131
1132
/**
1133
 * @param        $pubrowamount
1134
 * @param        $start
1135
 * @param string $art
1136
 * @param string $_this
1137
 *
1138
 * @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...
1139
 */
1140
function wfl_linklistpagenav($pubrowamount, $start, $art = 'art', $_this = '')
1141
{
1142
    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...
1143
    echo "</table>\n";
1144
    if ($pubrowamount < $xoopsModuleConfig['admin_perpage']) {
1145
        return false;
1146
    }
1147
    // Display Page Nav if published is > total display pages amount.
1148
    require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
1149
    //    $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...
1150
    $pagenav = new XoopsPageNav($pubrowamount, $xoopsModuleConfig['admin_perpage'], $start, 'st' . $art, $_this);
1151
    echo '<div align="right" style="padding: 8px;">' . $pagenav->renderNav() . '</div>';
1152
1153
    return null;
1154
}
1155
1156
/**
1157
 * @param        $pubrowamount
1158
 * @param        $start
1159
 * @param string $art
1160
 * @param string $_this
1161
 *
1162
 * @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...
1163
 */
1164
function wfl_linklistpagenavleft($pubrowamount, $start, $art = 'art', $_this = '')
1165
{
1166
    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...
1167
    //    echo "</table>\n";
1168
    if ($pubrowamount < $xoopsModuleConfig['admin_perpage']) {
1169
        return false;
1170
    }
1171
    // Display Page Nav if published is > total display pages amount.
1172
    require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
1173
    //    $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...
1174
    $pagenav = new XoopsPageNav($pubrowamount, $xoopsModuleConfig['admin_perpage'], $start, 'st' . $art, $_this);
1175
    echo '<div align="left" style="padding: 8px;">' . $pagenav->renderNav() . '</div>';
1176
1177
    return null;
1178
}
1179
1180
// Retreive an editor according to the module's option "form_options"
1181
/**
1182
 * @param $caption
1183
 * @param $name
1184
 * @param $value
1185
 *
1186
 * @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...
1187
 */
1188
function wfl_getWysiwygForm($caption, $name, $value)
1189
{
1190
    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...
1191
1192
    $editor = false;
1193
    $x22    = false;
1194
    $xv     = str_replace('XOOPS ', '', XOOPS_VERSION);
1195
    if (substr($xv, 2, 1) == '2') {
1196
        $x22 = true;
1197
    }
1198
    $editor_configs           = array();
1199
    $editor_configs['name']   = $name;
1200
    $editor_configs['value']  = $value;
1201
    $editor_configs['rows']   = 35;
1202
    $editor_configs['cols']   = 60;
1203
    $editor_configs['width']  = '100%';
1204
    $editor_configs['height'] = '400px';
1205
1206
    $isadmin = ((is_object($xoopsUser) && !empty($xoopsUser))
1207
                && $xoopsUser->isAdmin($xoopsModule->mid()));
1208
    if ($isadmin === true) {
1209
        $formuser = $xoopsModuleConfig['form_options'];
1210
    } else {
1211
        $formuser = $xoopsModuleConfig['form_optionsuser'];
1212
    }
1213
1214
    switch ($formuser) {
1215
        case 'fck':
1216
            if (!$x22) {
1217
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/fckeditor/formfckeditor.php')) {
1218
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/fckeditor/formfckeditor.php';
1219
                    $editor = new XoopsFormFckeditor($editor_configs, true);
1220
                } else {
1221
                    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...
1222
                        $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
1223
                    } else {
1224
                        $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
1225
                    }
1226
                }
1227
            } else {
1228
                $editor = new XoopsFormEditor($caption, 'fckeditor', $editor_configs);
1229
            }
1230
            break;
1231
1232
        case 'htmlarea':
1233
            if (!$x22) {
1234
                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
1235
                    require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php';
1236
                    $editor = new XoopsFormHtmlarea($caption, $name, $value);
1237
                }
1238
            } else {
1239
                $editor = new XoopsFormEditor($caption, 'htmlarea', $editor_configs);
1240
            }
1241
            break;
1242
1243
        case 'dhtml':
1244
            if (!$x22) {
1245
                $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
1246
            } else {
1247
                $editor = new XoopsFormEditor($caption, 'dhtmltextarea', $editor_configs);
1248
            }
1249
            break;
1250
1251
        case 'textarea':
1252
            $editor = new XoopsFormTextArea($caption, $name, $value);
1253
            break;
1254
1255
        case 'koivi':
1256
            if (!$x22) {
1257
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/koivi/formwysiwygtextarea.php')) {
1258
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/koivi/formwysiwygtextarea.php';
1259
                    $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, '100%', '400px');
1260
                } else {
1261
                    if ($dhtml) {
1262
                        $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
1263
                    } else {
1264
                        $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
1265
                    }
1266
                }
1267
            } else {
1268
                $editor = new XoopsFormEditor($caption, 'koivi', $editor_configs);
1269
            }
1270
            break;
1271
1272
        case 'tinyeditor':
1273
            if (!$x22) {
1274
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
1275
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
1276
                    $editor = new XoopsFormTinyeditorTextArea(array(
1277
                                                                  'caption' => $caption,
1278
                                                                  'name'    => $name,
1279
                                                                  'value'   => $value,
1280
                                                                  'width'   => '100%',
1281
                                                                  'height'  => '400px'
1282
                                                              ));
1283
                } else {
1284
                    if ($dhtml) {
1285
                        $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 50, 60);
1286
                    } else {
1287
                        $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
1288
                    }
1289
                }
1290
            } else {
1291
                $editor = new XoopsFormEditor($caption, 'tinyeditor', $editor_configs);
1292
            }
1293
            break;
1294
1295
        case 'dhtmlext':
1296
            if (!$x22) {
1297
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/dhtmlext/dhtmlext.php')) {
1298
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/dhtmlext/dhtmlext.php';
1299
                    $editor = new XoopsFormDhtmlTextAreaExtended($caption, $name, $value, 10, 50);
1300
                } else {
1301
                    if ($dhtml) {
1302
                        $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 50, 60);
1303
                    } else {
1304
                        $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
1305
                    }
1306
                }
1307
            } else {
1308
                $editor = new XoopsFormEditor($caption, 'dhtmlext', $editor_configs);
1309
            }
1310
            break;
1311
1312
        case 'tinymce':
1313
            if (!$x22) {
1314
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinymce/formtinymce.php')) {
1315
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinymce/formtinymce.php';
1316
                    $editor = new XoopsFormTinymce(array(
1317
                                                       'caption' => $caption,
1318
                                                       'name'    => $name,
1319
                                                       'value'   => $value,
1320
                                                       'width'   => '100%',
1321
                                                       'height'  => '400px'
1322
                                                   ));
1323
                } elseif (is_readable(XOOPS_ROOT_PATH . '/editors/tinymce/formtinymce.php')) {
1324
                    require_once XOOPS_ROOT_PATH . '/editors/tinymce/formtinymce.php';
1325
                    $editor = new XoopsFormTinymce(array(
1326
                                                       'caption' => $caption,
1327
                                                       'name'    => $name,
1328
                                                       'value'   => $value,
1329
                                                       'width'   => '100%',
1330
                                                       'height'  => '400px'
1331
                                                   ));
1332
                } else {
1333
                    if ($dhtml) {
1334
                        $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 20, 60);
1335
                    } else {
1336
                        $editor = new XoopsFormTextArea($caption, $name, $value, 7, 60);
1337
                    }
1338
                }
1339
            } else {
1340
                $editor = new XoopsFormEditor($caption, 'tinymce', $editor_configs);
1341
            }
1342
            break;
1343
    }
1344
1345
    return $editor;
1346
}
1347
1348
/**
1349
 * @param $countryn
1350
 *
1351
 * @return mixed
1352
 */
1353
function wfl_countryname($countryn)
1354
{
1355
    $country_array = array(
1356
        ''   => 'Unknown',
1357
        '-'  => 'Unknown',
1358
        'AD' => 'Andorra',
1359
        'AE' => 'United Arab Emirates',
1360
        'AF' => 'Afghanistan',
1361
        'AG' => 'Antigua and Barbuda',
1362
        'AI' => 'Anguilla',
1363
        'AL' => 'Albania',
1364
        'AM' => 'Armenia',
1365
        'AN' => 'Netherlands Antilles',
1366
        'AO' => 'Angola',
1367
        'AQ' => 'Antarctica',
1368
        'AR' => 'Argentina',
1369
        'AS' => 'American Samoa',
1370
        'AT' => 'Austria',
1371
        'AU' => 'Australia',
1372
        'AW' => 'Aruba',
1373
        'AX' => 'Åland Islands',   // Added
1374
        'AZ' => 'Azerbaijan',
1375
        'BA' => 'Bosnia and Herzegovina',
1376
        'BB' => 'Barbados',
1377
        'BD' => 'Bangladesh',
1378
        'BE' => 'Belgium',
1379
        'BF' => 'Burkina Faso',
1380
        'BG' => 'Bulgaria',
1381
        'BH' => 'Bahrain',
1382
        'BI' => 'Burundi',
1383
        'BJ' => 'Benin',
1384
        'BL' => 'Saint Barthélemy',   // Added
1385
        'BM' => 'Bermuda',
1386
        'BN' => 'Brunei Darussalam',
1387
        'BO' => 'Bolivia',
1388
        'BR' => 'Brazil',
1389
        'BS' => 'Bahamas',
1390
        'BT' => 'Bhutan',
1391
        'BV' => 'Bouvet Island',
1392
        'BW' => 'Botswana',
1393
        'BY' => 'Belarus',
1394
        'BZ' => 'Belize',
1395
        'CA' => 'Canada',
1396
        'CC' => 'Cocos (Keeling) Islands',
1397
        'CD' => 'Congo (Dem. Rep.)',   // Added
1398
        'CF' => 'Central African Republic',
1399
        'CG' => 'Congo',
1400
        'CH' => 'Switzerland',
1401
        'CI' => "Cote D'Ivoire", // Removed: (Ivory Coast)
1402
        'CK' => 'Cook Islands',
1403
        'CL' => 'Chile',
1404
        'CM' => 'Cameroon',
1405
        'CN' => 'China',
1406
        'CO' => 'Colombia',
1407
        'CR' => 'Costa Rica',
1408
        'CS' => 'Czechoslovakia (former)',   // Not listed anymore
1409
        'CU' => 'Cuba',
1410
        'CV' => 'Cape Verde',
1411
        'CX' => 'Christmas Island',
1412
        'CY' => 'Cyprus',
1413
        'CZ' => 'Czech Republic',
1414
        'DE' => 'Germany',
1415
        'DJ' => 'Djibouti',
1416
        'DK' => 'Denmark',
1417
        'DM' => 'Dominica',
1418
        'DO' => 'Dominican Republic',
1419
        'DZ' => 'Algeria',
1420
        'EC' => 'Ecuador',
1421
        'EE' => 'Estonia',
1422
        'EG' => 'Egypt',
1423
        'EH' => 'Western Sahara',
1424
        'ER' => 'Eritrea',
1425
        'ES' => 'Spain',
1426
        'EU' => 'Europe',
1427
        'ET' => 'Ethiopia',
1428
        'FI' => 'Finland',
1429
        'FJ' => 'Fiji',
1430
        'FK' => 'Falkland Islands (Malvinas)',
1431
        'FM' => 'Micronesia',
1432
        'FO' => 'Faroe Islands',
1433
        'FR' => 'France',
1434
        'FX' => 'France, Metropolitan',   // Not listed anymore
1435
        'GA' => 'Gabon',
1436
        'GB' => 'Great Britain',     // Name was: Great Britain (UK)
1437
        'GD' => 'Grenada',
1438
        'GE' => 'Georgia',
1439
        'GF' => 'French Guiana',
1440
        'GG' => 'Guernsey',   // Added
1441
        'GH' => 'Ghana',
1442
        'GI' => 'Gibraltar',
1443
        'GL' => 'Greenland',
1444
        'GM' => 'Gambia',
1445
        'GN' => 'Guinea',
1446
        'GP' => 'Guadeloupe',
1447
        'GQ' => 'Equatorial Guinea',
1448
        'GR' => 'Greece',
1449
        'GS' => 'S. Georgia and S. Sandwich Isls.',
1450
        'GT' => 'Guatemala',
1451
        'GU' => 'Guam',
1452
        'GW' => 'Guinea-Bissau',
1453
        'GY' => 'Guyana',
1454
        'HK' => 'Hong Kong',
1455
        'HM' => 'Heard and McDonald Islands',
1456
        'HN' => 'Honduras',
1457
        'HR' => 'Croatia',
1458
        'HT' => 'Haiti',
1459
        'HU' => 'Hungary',
1460
        'ID' => 'Indonesia',
1461
        'IE' => 'Ireland',
1462
        'IL' => 'Israel',
1463
        'IM' => 'Isle of Man',    //  Added
1464
        'IN' => 'India',
1465
        'IO' => 'British Indian Ocean Territory',
1466
        'IQ' => 'Iraq',
1467
        'IR' => 'Iran',   //  Changed name
1468
        'IS' => 'Iceland',
1469
        'IT' => 'Italy',
1470
        'JE' => 'Jersey',
1471
        'JM' => 'Jamaica',
1472
        'JO' => 'Jordan',
1473
        'JP' => 'Japan',
1474
        'KE' => 'Kenya',
1475
        'KG' => 'Kyrgyzstan',
1476
        'KH' => 'Cambodia',
1477
        'KI' => 'Kiribati',
1478
        'KM' => 'Comoros',
1479
        'KN' => 'Saint Kitts and Nevis',
1480
        'KP' => 'Korea (North)',    // Official name: Korea, Democratic People's Republic of
1481
        'KR' => 'Korea (South)',    // Official name: Korea, Republic of
1482
        'KW' => 'Kuwait',
1483
        'KY' => 'Cayman Islands',
1484
        'KZ' => 'Kazakhstan',
1485
        'LA' => 'Laos',             // Official name: Lao People's Democratic Republic
1486
        'LB' => 'Lebanon',
1487
        'LC' => 'Saint Lucia',
1488
        'LI' => 'Liechtenstein',
1489
        'LK' => 'Sri Lanka',
1490
        'LR' => 'Liberia',
1491
        'LS' => 'Lesotho',
1492
        'LT' => 'Lithuania',
1493
        'LU' => 'Luxembourg',
1494
        'LV' => 'Latvia',
1495
        'LY' => 'Libya',            // Official name: Libyan Arab Jamahiriya
1496
        'MA' => 'Morocco',
1497
        'MC' => 'Monaco',
1498
        'MD' => 'Moldova',          // Official name: Moldova, Republic of
1499
        'ME' => 'Montenegro',       // Added
1500
        'MF' => 'Saint Martin',     // Added
1501
        'MG' => 'Madagascar',
1502
        'MH' => 'Marshall Islands',
1503
        'MK' => 'Macedonia',        // Official name: Macedonia, The Former Yugoslav Republic of
1504
        'ML' => 'Mali',
1505
        'MM' => 'Myanmar',
1506
        'MN' => 'Mongolia',
1507
        'MO' => 'Macao',            // Corrected name
1508
        'MP' => 'Northern Mariana Islands',
1509
        'MQ' => 'Martinique',
1510
        'MR' => 'Mauritania',
1511
        'MS' => 'Montserrat',
1512
        'MT' => 'Malta',
1513
        'MU' => 'Mauritius',
1514
        'MV' => 'Maldives',
1515
        'MW' => 'Malawi',
1516
        'MX' => 'Mexico',
1517
        'MY' => 'Malaysia',
1518
        'MZ' => 'Mozambique',
1519
        'NA' => 'Namibia',
1520
        'NC' => 'New Caledonia',
1521
        'NE' => 'Niger',
1522
        'NF' => 'Norfolk Island',
1523
        'NG' => 'Nigeria',
1524
        'NI' => 'Nicaragua',
1525
        'NL' => 'Netherlands',
1526
        'NO' => 'Norway',
1527
        'NP' => 'Nepal',
1528
        'NR' => 'Nauru',
1529
        'NT' => 'Neutral Zone',
1530
        'NU' => 'Niue',
1531
        'NZ' => 'New Zealand',
1532
        'OM' => 'Oman',
1533
        'PA' => 'Panama',
1534
        'PE' => 'Peru',
1535
        'PF' => 'French Polynesia',
1536
        'PG' => 'Papua New Guinea',
1537
        'PH' => 'Philippines',
1538
        'PK' => 'Pakistan',
1539
        'PL' => 'Poland',
1540
        'PM' => 'St. Pierre and Miquelon',
1541
        'PN' => 'Pitcairn',
1542
        'PR' => 'Puerto Rico',
1543
        'PS' => 'Palestinian Territory, Occupied',   // Added
1544
        'PT' => 'Portugal',
1545
        'PW' => 'Palau',
1546
        'PY' => 'Paraguay',
1547
        'QA' => 'Qatar',
1548
        'RE' => 'Reunion',
1549
        'RO' => 'Romania',
1550
        'RS' => 'Serbia',     // Added
1551
        'RU' => 'Russian Federation',
1552
        'RW' => 'Rwanda',
1553
        'SA' => 'Saudi Arabia',
1554
        'SB' => 'Solomon Islands',
1555
        'SC' => 'Seychelles',
1556
        'SD' => 'Sudan',
1557
        'SE' => 'Sweden',
1558
        'SG' => 'Singapore',
1559
        'SH' => 'St. Helena',
1560
        'SI' => 'Slovenia',
1561
        'SJ' => 'Svalbard and Jan Mayen Islands',
1562
        'SK' => 'Slovakia',              // Changed name, was: Slovak Republic
1563
        'SL' => 'Sierra Leone',
1564
        'SM' => 'San Marino',
1565
        'SN' => 'Senegal',
1566
        'SO' => 'Somalia',
1567
        'SR' => 'Suriname',
1568
        'ST' => 'Sao Tome and Principe',
1569
        'SU' => 'USSR (former)',          // Removed from ISO list, doesn' exsist anymore
1570
        'SV' => 'El Salvador',
1571
        'SY' => 'Syrian Arab Republic',   // Changed name, was: Syria
1572
        'SZ' => 'Swaziland',
1573
        'TC' => 'Turks and Caicos Islands',
1574
        'TD' => 'Chad',
1575
        'TF' => 'French Southern Territories',
1576
        'TG' => 'Togo',
1577
        'TH' => 'Thailand',
1578
        'TJ' => 'Tajikistan',
1579
        'TK' => 'Tokelau',
1580
        'TL' => 'Timor-Leste',    // Added
1581
        'TM' => 'Turkmenistan',
1582
        'TN' => 'Tunisia',
1583
        'TO' => 'Tonga',
1584
        'TP' => 'East Timor',             // Removed from ISO list, doesn' exsist anymore
1585
        'TR' => 'Turkey',
1586
        'TT' => 'Trinidad and Tobago',
1587
        'TV' => 'Tuvalu',
1588
        'TW' => 'Taiwan',         // Official name acc. to iso-list: Taiwan, Province of China
1589
        'TZ' => 'Tanzania',
1590
        'UA' => 'Ukraine',
1591
        'UG' => 'Uganda',
1592
        'UK' => 'United Kingdom',      // Doesn't exsist in iso-list ?
1593
        'UM' => 'US Minor Outlying Islands',
1594
        'US' => 'United States',
1595
        'UY' => 'Uruguay',
1596
        'UZ' => 'Uzbekistan',
1597
        'VA' => 'Vatican City State',
1598
        'VC' => 'Saint Vincent and the Grenadines',
1599
        'VE' => 'Venezuela',
1600
        'VG' => 'Virgin Islands, British',
1601
        'VI' => 'Virgin Islands, U.S.',
1602
        'VN' => 'Viet Nam',
1603
        'VU' => 'Vanuatu',
1604
        'WF' => 'Wallis and Futuna Islands',
1605
        'WS' => 'Samoa',
1606
        'YE' => 'Yemen',
1607
        'YT' => 'Mayotte',
1608
        'YU' => 'Yugoslavia',        // Removed from iso list
1609
        'ZA' => 'South Africa',
1610
        'ZM' => 'Zambia',
1611
        'ZR' => 'Zaire',             // Removed from iso list
1612
        'ZW' => 'Zimbabwe'
1613
    );
1614
1615
    return $country_array[$countryn];
1616
}
1617
1618
/**
1619
 * @param $document
1620
 *
1621
 * @return mixed
1622
 */
1623
function wfl_html2text($document)
1624
{
1625
    $search = array(
1626
        "'<script[^>]*?>.*?</script>'si", // Strip out javascript
1627
        "'<img.*?>'si", // Strip out img tags
1628
        "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
1629
        "'([\r\n])[\s]+'", // Strip out white space
1630
        "'&(quot|#34);'i", // Replace HTML entities
1631
        "'&(amp|#38);'i",
1632
        "'&(lt|#60);'i",
1633
        "'&(gt|#62);'i",
1634
        "'&(nbsp|#160);'i",
1635
        "'&(iexcl|#161);'i",
1636
        "'&(cent|#162);'i",
1637
        "'&(pound|#163);'i",
1638
        "'&(copy|#169);'i"
1639
    ); // evaluate as php
1640
1641
    $replace = array(
1642
        '',
1643
        '',
1644
        '',
1645
        "\\1",
1646
        '"',
1647
        '&',
1648
        '<',
1649
        '>',
1650
        ' ',
1651
        chr(161),
1652
        chr(162),
1653
        chr(163),
1654
        chr(169),
1655
    );
1656
1657
    $text = preg_replace($search, $replace, $document);
1658
1659
    preg_replace_callback('/&#(\d+);/', function ($matches) {
1660
        return chr($matches[1]);
1661
    }, $document);
1662
1663
    return $text;
1664
}
1665
1666
//    Start functions for Google PageRank
1667
//    Source: http://www.sws-tech.com/scripts/googlepagerank.php
1668
//    This code is released under the public domain
1669
/**
1670
 * @param $a
1671
 * @param $b
1672
 *
1673
 * @return float|int
1674
 */
1675
function zeroFill($a, $b)
1676
{
1677
    $z = hexdec(80000000);
1678
    //echo $z;
1679
    if ($z & $a) {
1680
        $a = ($a >> 1);
1681
        $a &= (~$z);
1682
        $a |= 0x40000000;
1683
        $a = ($a >> ($b - 1));
1684
    } else {
1685
        $a = ($a >> $b);
1686
    }
1687
1688
    return $a;
1689
}
1690
1691
/**
1692
 * @param $a
1693
 * @param $b
1694
 * @param $c
1695
 *
1696
 * @return array
1697
 */
1698
function mix($a, $b, $c)
1699
{
1700
    $a -= $b;
1701
    $a -= $c;
1702
    $a ^= zeroFill($c, 13);
1703
    $b -= $c;
1704
    $b -= $a;
1705
    $b ^= ($a << 8);
1706
    $c -= $a;
1707
    $c -= $b;
1708
    $c ^= zeroFill($b, 13);
1709
    $a -= $b;
1710
    $a -= $c;
1711
    $a ^= zeroFill($c, 12);
1712
    $b -= $c;
1713
    $b -= $a;
1714
    $b ^= ($a << 16);
1715
    $c -= $a;
1716
    $c -= $b;
1717
    $c ^= zeroFill($b, 5);
1718
    $a -= $b;
1719
    $a -= $c;
1720
    $a ^= zeroFill($c, 3);
1721
    $b -= $c;
1722
    $b -= $a;
1723
    $b ^= ($a << 10);
1724
    $c -= $a;
1725
    $c -= $b;
1726
    $c ^= zeroFill($b, 15);
1727
1728
    return array($a, $b, $c);
1729
}
1730
1731
/**
1732
 * @param      $url
1733
 * @param null $length
1734
 * @param int  $init
1735
 *
1736
 * @return mixed
1737
 */
1738
function GoogleCH($url, $length = null, $init = 0xE6359A60)
1739
{
1740
    if (null === $length) {
1741
        $length = count($url);
1742
    }
1743
    $a   = $b = 0x9E3779B9;
1744
    $c   = $init;
1745
    $k   = 0;
1746
    $len = $length;
1747
    while ($len >= 12) {
1748
        $a   += ($url[$k + 0] + ($url[$k + 1] << 8) + ($url[$k + 2] << 16) + ($url[$k + 3] << 24));
1749
        $b   += ($url[$k + 4] + ($url[$k + 5] << 8) + ($url[$k + 6] << 16) + ($url[$k + 7] << 24));
1750
        $c   += ($url[$k + 8] + ($url[$k + 9] << 8) + ($url[$k + 10] << 16) + ($url[$k + 11] << 24));
1751
        $mix = mix($a, $b, $c);
1752
        $a   = $mix[0];
1753
        $b   = $mix[1];
1754
        $c   = $mix[2];
1755
        $k   += 12;
1756
        $len -= 12;
1757
    }
1758
    $c += $length;
1759
    switch ($len) {              /* all the case statements fall through */
1760
        case 11:
1761
            $c += ($url[$k + 10] << 24);
1762
        // no break
1763
        case 10:
1764
            $c += ($url[$k + 9] << 16);
1765
        // no break
1766
        case 9:
1767
            $c += ($url[$k + 8] << 8);
1768
        /* the first byte of c is reserved for the length */
1769
        // no break
1770
        case 8:
1771
            $b += ($url[$k + 7] << 24);
1772
        // no break
1773
        case 7:
1774
            $b += ($url[$k + 6] << 16);
1775
        // no break
1776
        case 6:
1777
            $b += ($url[$k + 5] << 8);
1778
        // no break
1779
        case 5:
1780
            $b += $url[$k + 4];
1781
        // no break
1782
        case 4:
1783
            $a += ($url[$k + 3] << 24);
1784
        // no break
1785
        case 3:
1786
            $a += ($url[$k + 2] << 16);
1787
        // no break
1788
        case 2:
1789
            $a += ($url[$k + 1] << 8);
1790
        // no break
1791
        case 1:
1792
            $a += $url[$k + 0];
1793
        /* case 0: nothing left to add */
1794
    }
1795
    $mix = mix($a, $b, $c);
1796
    //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...
1797
    /*-------------------------------------------- report the result */
1798
1799
    return $mix[2];
1800
}
1801
1802
//converts a string into an array of integers containing the numeric value of the char
1803
/**
1804
 * @param $string
1805
 *
1806
 * @return mixed
1807
 */
1808
function strord($string)
1809
{
1810
    for ($i = 0, $iMax = strlen($string); $i < $iMax; ++$i) {
1811
        $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...
1812
    }
1813
1814
    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...
1815
}
1816
1817
/**
1818
 * @param $url
1819
 *
1820
 * @return bool|string
1821
 */
1822
function pagerank($url)
1823
{
1824
    $pagerank = '';
1825
    $ch       = '6' . GoogleCH(strord('info:' . $url));
1826
    $fp       = fsockopen('www.google.com', 80, $errno, $errstr, 30);
1827
    if (!$fp) {
1828
        echo "$errstr ($errno)<br>\n";
1829
    } else {
1830
        $out = 'GET /search?client=navclient-auto&ch=' . $ch . '&features=Rank&q=info:' . $url . " HTTP/1.1\r\n";
1831
        $out .= "Host: www.google.com\r\n";
1832
        $out .= "Connection: Close\r\n\r\n";
1833
1834
        fwrite($fp, $out);
1835
1836
        while (!feof($fp)) {
1837
            $data = fgets($fp, 128);
1838
            $pos  = strpos($data, 'Rank_');
1839
            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...
1840
            } else {
1841
                $pagerank = substr($data, $pos + 9);
1842
            }
1843
        }
1844
        fclose($fp);
1845
    }
1846
1847
    return $pagerank;
1848
}
1849
1850
//  End functions for Google PageRank
1851
1852
// Check if Tag module is installed
1853
/**
1854
 * @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...
1855
 */
1856
function wfl_tag_module_included()
1857
{
1858
    static $wfl_tag_module_included;
1859
    if (!isset($wfl_tag_module_included)) {
1860
        $modulesHandler = xoops_getHandler('module');
1861
        $tag_mod        = $modulesHandler->getByDirName('tag');
1862
        if (!$tag_mod) {
1863
            $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...
1864
        } else {
1865
            $wfl_tag_module_included = $tag_mod->getVar('isactive') == 1;
1866
        }
1867
    }
1868
1869
    return $wfl_tag_module_included;
1870
}
1871
1872
// Add item_tag to Tag-module
1873
/**
1874
 * @param $lid
1875
 * @param $item_tag
1876
 */
1877
function wfl_tagupdate($lid, $item_tag)
1878
{
1879
    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...
1880
    if (wfl_tag_module_included()) {
1881
        require_once XOOPS_ROOT_PATH . '/modules/tag/include/formtag.php';
1882
        $tagHandler = xoops_getModuleHandler('tag', 'tag');
1883
        $tagHandler->updateByItem($item_tag, $lid, $xoopsModule->getVar('dirname'), 0);
1884
    }
1885
}
1886
1887
// Check if News module is installed
1888
/**
1889
 * @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...
1890
 */
1891
function wfl_news_module_included()
1892
{
1893
    static $wfl_news_module_included;
1894
    if (!isset($wfl_news_module_included)) {
1895
        $modulesHandler = xoops_getHandler('module');
1896
        $news_mod       = $modulesHandler->getByDirName('news');
1897
        if (!$news_mod) {
1898
            $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...
1899
        } else {
1900
            $wfl_news_module_included = $news_mod->getVar('isactive') == 1;
1901
        }
1902
    }
1903
1904
    return $wfl_news_module_included;
1905
}
1906
1907
/**
1908
 * @param $banner_id
1909
 *
1910
 * @return null|string
1911
 */
1912 View Code Duplication
function wfl_getbanner_from_id_banner($banner_id)
0 ignored issues
show
Duplication introduced by
This function 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...
1913
{
1914
    ###### Hack by www.stefanosilvestrini.com ######
1915
    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...
1916
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
1917
    $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id);
1918
    list($numrows) = $db->fetchRow($bresult);
1919
    if ($numrows > 1) {
1920
        $numrows = $numrows - 1;
1921
        mt_srand((double)microtime() * 1000000);
1922
        $bannum = mt_rand(0, $numrows);
1923
    } else {
1924
        $bannum = 0;
1925
    }
1926
    if ($numrows > 0) {
1927
        $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id, 1, $bannum);
1928
        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...
1929
        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...
1930
            // EMPTY
1931
        } else {
1932
            $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
1933
        }
1934
        /* Check if this impression is the last one and print the banner */
1935
        if ($imptotal == $impmade) {
1936
            $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
1937
            $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());
1938
            $db->queryF($sql);
1939
            $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
1940
        }
1941
        if ($htmlbanner) {
1942
            $bannerobject = $htmlcode;
1943
        } else {
1944
            $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
1945
            if (stristr($imageurl, '.swf')) {
1946
                $bannerobject = $bannerobject
1947
                                . '<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">'
1948
                                . '<param name="movie" value="'
1949
                                . $imageurl
1950
                                . '"></param>'
1951
                                . '<param name="quality" value="high"></param>'
1952
                                . '<embed src="'
1953
                                . $imageurl
1954
                                . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
1955
                                . '</embed>'
1956
                                . '</object>';
1957
            } else {
1958
                $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="">';
1959
            }
1960
            $bannerobject = $bannerobject . '</a></div>';
1961
        }
1962
1963
        return $bannerobject;
1964
    }
1965
1966
    return null;
1967
}
1968
1969
/**
1970
 * @param $client_id
1971
 *
1972
 * @return string
1973
 */
1974 View Code Duplication
function wfl_getbanner_from_id_client($client_id)
0 ignored issues
show
Duplication introduced by
This function 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...
1975
{
1976
    ###### Hack by www.stefanosilvestrini.com ######
1977
    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...
1978
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
1979
    $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id);
1980
    list($numrows) = $db->fetchRow($bresult);
1981
    if ($numrows > 1) {
1982
        $numrows = $numrows - 1;
1983
        mt_srand((double)microtime() * 1000000);
1984
        $bannum = mt_rand(0, $numrows);
1985
    } else {
1986
        $bannum = 0;
1987
    }
1988
    if ($numrows > 0) {
1989
        $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id . ' ORDER BY rand()', 1, $bannum);
1990
        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...
1991
        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...
1992
            // EMPTY
1993
        } else {
1994
            $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
1995
        }
1996
        /* Check if this impression is the last one and print the banner */
1997
        if ($imptotal == $impmade) {
1998
            $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
1999
            $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());
2000
            $db->queryF($sql);
2001
            $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
2002
        }
2003
        if ($htmlbanner) {
2004
            $bannerobject = $htmlcode;
2005
        } else {
2006
            $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
2007
            if (stristr($imageurl, '.swf')) {
2008
                $bannerobject = $bannerobject
2009
                                . '<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">'
2010
                                . '<param name="movie" value="'
2011
                                . $imageurl
2012
                                . '"></param>'
2013
                                . '<param name="quality" value="high"></param>'
2014
                                . '<embed src="'
2015
                                . $imageurl
2016
                                . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
2017
                                . '</embed>'
2018
                                . '</object>';
2019
            } else {
2020
                $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="">';
2021
            }
2022
            $bannerobject = $bannerobject . '</a></div>';
2023
        }
2024
2025
        return $bannerobject;
2026
    }
2027
2028
    return null;
2029
}
2030
2031
/**
2032
 * @param $email
2033
 *
2034
 * @return mixed
2035
 */
2036 View Code Duplication
function emailcnvrt($email)
0 ignored issues
show
Duplication introduced by
This function 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...
2037
{
2038
    $search = array(
2039
        "/\@/",
2040
        "/\./",
2041
        "/\mailto:/",
2042
    );
2043
2044
    $replace = array(
2045
        ' AT ',
2046
        ' DOT ',
2047
        '',
2048
    );
2049
2050
    $text = preg_replace($search, $replace, $email);
2051
2052
    return $text;
2053
}
2054
2055
/**
2056
 * @param $email
2057
 *
2058
 * @return mixed
2059
 */
2060 View Code Duplication
function printemailcnvrt($email)
0 ignored issues
show
Duplication introduced by
This function 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...
2061
{
2062
    $search = array(
2063
        "/\ AT /",
2064
        "/\ DOT /",
2065
    );
2066
2067
    $replace = array(
2068
        '@',
2069
        '.',
2070
    );
2071
2072
    $text = preg_replace($search, $replace, $email);
2073
2074
    return $text;
2075
}
2076
2077
/**
2078
 * @param        $str
2079
 * @param        $start
2080
 * @param        $length
2081
 * @param string $trimmarker
2082
 *
2083
 * @return string
2084
 */
2085
function wfl_substr($str, $start, $length, $trimmarker = '...')
2086
{
2087
    $configHandler          = xoops_getHandler('config');
2088
    $im_multilanguageConfig = $configHandler->getConfigsByCat(IM_CONF_MULILANGUAGE);
2089
2090
    if ($im_multilanguageConfig['ml_enable']) {
2091
        $tags  = explode(',', $im_multilanguageConfig['ml_tags']);
2092
        $strs  = array();
2093
        $hasML = false;
2094
        foreach ($tags as $tag) {
2095
            if (preg_match("/\[" . $tag . "](.*)\[\/" . $tag . "\]/sU", $str, $matches)) {
2096
                if (count($matches) > 0) {
2097
                    $hasML  = true;
2098
                    $strs[] = $matches[1];
2099
                }
2100
            }
2101
        }
2102
    } else {
2103
        $hasML = false;
2104
    }
2105
2106
    if (!$hasML) {
2107
        $strs = array($str);
2108
    }
2109
2110
    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...
2111
        if (!XOOPS_USE_MULTIBYTES) {
2112
            $strs[$i] = (strlen($strs[$i]) - $start <= $length) ? substr($strs[$i], $start, $length) : substr($strs[$i], $start, $length - strlen($trimmarker)) . $trimmarker;
2113
        }
2114
2115
        if (function_exists('mb_internal_encoding') && @mb_internal_encoding(_CHARSET)) {
2116
            $str2     = mb_strcut($strs[$i], $start, $length - strlen($trimmarker));
2117
            $strs[$i] = $str2 . (mb_strlen($strs[$i]) != mb_strlen($str2) ? $trimmarker : '');
2118
        }
2119
2120
        // phppp patch
2121
        $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...
2122
        $pos_st   = 0;
2123
        $action   = false;
2124
        for ($pos_i = 0; $pos_i < strlen($strs[$i]); ++$pos_i) {
2125
            if (ord(substr($strs[$i], $pos_i, 1)) > 127) {
2126
                ++$pos_i;
2127
            }
2128
            if ($pos_i <= $start) {
2129
                $pos_st = $pos_i;
2130
            }
2131
            if ($pos_i >= $pos_st + $length) {
2132
                $action = true;
2133
                break;
2134
            }
2135
        }
2136
        $strs[$i] = $action ? substr($strs[$i], $pos_st, $pos_i - $pos_st - strlen($trimmarker)) . $trimmarker : $strs[$i];
2137
2138
        $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...
2139
    }
2140
    $str = implode('', $strs);
2141
2142
    return $str;
2143
}
2144