Completed
Push — master ( 2e271d...4ff4ed )
by
unknown
19s queued 16s
created

SmallworldAdmin   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 433
Duplicated Lines 100 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 433
loc 433
rs 2.88
c 0
b 0
f 0
wmc 69
lcom 0
cbo 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A oldestMsg() 15 15 3
A AvgMsgDay() 11 11 2
A TotalUsers() 21 21 3
A ModuleInstallVersion() 7 7 1
A ModuleInstallDate() 7 7 1
A CountDays() 9 9 1
A mostactiveusers_allround() 34 34 4
A mostactiveusers_today() 36 36 4
B topratedusers() 47 47 8
A getAllUsers() 20 20 5
B doCheckUpdate() 37 37 7
F fetchURL() 78 78 25
A flatten() 16 16 4
A Smallworld_sanitize() 12 12 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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

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

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

1
<?php namespace Xoopsmodules\Smallworld;
2
/**
3
 * You may not change or alter any portion of this comment or credits
4
 * of supporting developers from this source code or any supporting source code
5
 * which is considered copyrighted (c) material of the original comment or credit authors.
6
 *
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
/**
13
 * SmallWorld
14
 *
15
 * @copyright    The XOOPS Project (https://xoops.org)
16
 * @copyright    2011 Culex
17
 * @license      GNU GPL (http://www.gnu.org/licenses/gpl-2.0.html/)
18
 * @package      SmallWorld
19
 * @since        1.0
20
 * @author       Michael Albertsen (http://culex.dk) <[email protected]>
21
 */
22
23 View Code Duplication
class SmallworldAdmin
0 ignored issues
show
Duplication introduced by
This class 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...
24
{
25
    /**
26
     * Get oldest message in Db
27
     * @returns time
28
     */
29
    public function oldestMsg()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

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

Loading history...
30
    {
31
        global $xoopsDB;
32
        $date = 0;
33
        $sql     = 'SELECT * FROM ' . $xoopsDB->prefix('smallworld_messages') . ' ORDER BY created LIMIT 1';
34
        $result = $xoopsDB->queryF($sql);
35
        $counter = $xoopsDB->getRowsNum($result);
36
        if ($counter >= 1) {
37
            while ($sqlfetch = $xoopsDB->fetchArray($result)) {
38
                $date = $sqlfetch['created'];
39
            }
40
        }
41
42
        return $date;
43
    }
44
45
    /**
46
     * Get average messages sent per day
47
     * @param int $totaldays
48
     * @return int|string
49
     */
50
    public function AvgMsgDay($totaldays)
51
    {
52
        global $xoopsDB;
53
        $sql = 'SELECT count( * ) / ' . $totaldays . ' AS averg FROM ' . $xoopsDB->prefix('smallworld_messages') . '';
54
        $result = $xoopsDB->queryF($sql);
55
        while ($sqlfetch = $xoopsDB->fetchArray($result)) {
56
            $avg = number_format($sqlfetch['averg'], 2, '.', ',');
57
        }
58
59
        return $avg;
0 ignored issues
show
Bug introduced by
The variable $avg 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...
60
    }
61
62
    /**
63
     * total users using smallworld
64
     * @return int
65
     */
66
    public function TotalUsers()
67
    {
68
        global $xoopsDB;
69
        $sql = 'SELECT * FROM ' . $xoopsDB->prefix('smallworld_user') . '';
70
        $result = $xoopsDB->queryF($sql);
71
        $counter = $xoopsDB->getRowsNum($result);
72
        if ($counter < 1) {
73
            $sum = 0;
74
        } else {
75
            $i = 0;
76
            while ($myrow = $xoopsDB->fetchArray($result)) {
77
                $user[$i]['username'] = $myrow['username'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$user was never initialized. Although not strictly required by PHP, it is generally a good practice to add $user = 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...
78
                ++$i;
79
            }
80
            $all = $this->flatten($user);
0 ignored issues
show
Bug introduced by
The variable $user 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...
81
            $sum = count(array_unique($all));
82
            $unique = array_unique($all);
0 ignored issues
show
Unused Code introduced by
$unique 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...
83
        }
84
85
        return $sum;
86
    }
87
88
    /**
89
     * Get version of module
90
     * @returns string
91
     */
92
    public function ModuleInstallVersion()
93
    {
94
        global $xoopsModule;
95
        $version = round($xoopsModule->getVar('version') / 100, 2);
96
97
        return $version;
98
    }
99
100
    /**
101
     * Get date when Module was installed
102
     * @return string|time
103
     */
104
    public function ModuleInstallDate()
105
    {
106
        global $xoopsModule;
107
        $date = formatTimestamp($xoopsModule->getVar('last_update'), 'm');
108
109
        return $date;
110
    }
111
112
    /**
113
     * Count total days represented in db
114
     * @return float|int|time
115
     */
116
    public function CountDays()
117
    {
118
        global $xoopsDB, $xoopsModule;
119
        $date = $this->oldestMsg();
120
        $now = time();
121
        $diff = ($now - $date) / (60 * 60 * 24);
122
123
        return $diff;
124
    }
125
126
    /**
127
     * find user with most posted messages
128
     * @returns array
129
     */
130
    public function mostactiveusers_allround()
131
    {
132
        global $xoopsDB, $xoopsUser;
133
        $sql = 'SELECT uid_fk, COUNT( * ) as cnt ';
134
        $sql .= 'FROM ( ';
135
        $sql .= 'SELECT uid_fk ';
136
        $sql .= 'FROM ' . $xoopsDB->prefix('smallworld_messages') . ' ';
137
        $sql .= 'UNION ALL SELECT uid_fk ';
138
        $sql .= 'FROM ' . $xoopsDB->prefix('smallworld_comments') . ' ';
139
        $sql .= ') AS u ';
140
        $sql .= 'GROUP BY uid_fk ';
141
        $sql .= 'ORDER BY count( * ) DESC limit 20';
142
        $result = $xoopsDB->queryF($sql);
143
        $counter = $xoopsDB->getRowsNum($result);
144
145
        if ($counter < 1) {
146
            $msg = [];
147
        } else {
148
            $msg = [];
149
            $i = 1;
150
            while ($row = $xoopsDB->fetchArray($result)) {
151
                $msg['counter'][$i] = $i;
152
                $msg['img'][$i] = "<img style='margin:0px 5px;' src = '../assets/images/" . $i . ".png'>";
153
                if ($msg['counter'][$i] > 3) {
154
                    $msg['img'][$i] = '';
155
                }
156
                $msg['cnt'][$i] = $row['cnt'];
157
                $msg['from'][$i] = $xoopsUser->getUnameFromId($row['uid_fk']);
158
                ++$i;
159
            }
160
        }
161
162
        return $msg;
163
    }
164
165
    /**
166
     * find user with most posted messages in last 24 hours
167
     * @returns array
168
     */
169
    public function mostactiveusers_today()
170
    {
171
        global $xoopsDB, $xoopsUser;
172
        $sql = 'SELECT uid_fk, COUNT( * ) as cnt ';
173
        $sql .= 'FROM ( ';
174
        $sql .= 'SELECT uid_fk ';
175
        $sql .= 'FROM ' . $xoopsDB->prefix('smallworld_messages') . ' ';
176
        $sql .= 'WHERE `created` > UNIX_TIMESTAMP(DATE_SUB( NOW( ) , INTERVAL 1 DAY )) ';
177
        $sql .= 'UNION ALL SELECT uid_fk ';
178
        $sql .= 'FROM ' . $xoopsDB->prefix('smallworld_comments') . ' ';
179
        $sql .= 'WHERE `created` > UNIX_TIMESTAMP(DATE_SUB( NOW( ) , INTERVAL 1 DAY )) ';
180
        $sql .= ') AS u ';
181
        $sql .= 'GROUP BY uid_fk ';
182
        $sql .= 'ORDER BY count( * ) DESC limit 20';
183
184
        $result = $xoopsDB->queryF($sql);
185
        $msgtoday = [];
186
187
        if (0 != $xoopsDB->getRowsNum($result)) {
188
            $i = 1;
189
            while ($row = $xoopsDB->fetchArray($result)) {
190
                $msgtoday['counter'][$i] = $i;
191
                $msgtoday['img'][$i] = "<img style='margin:0px 5px;' src = '../assets/images/" . $i . ".png'>";
192
                if ($msgtoday['counter'][$i] > 3) {
193
                    $msgtoday['img'][$i] = '';
194
                }
195
                $msgtoday['cnt'][$i] = $row['cnt'];
196
                $msgtoday['from'][$i] = $xoopsUser->getUnameFromId($row['uid_fk']);
197
                ++$i;
198
            }
199
        } else {
200
            $msgtoday = [];
201
        }
202
203
        return $msgtoday;
204
    }
205
206
    /**
207
     * Find best OR worst rated users
208
     * @param string $direction
209
     * @returns array
210
     */
211
    public function topratedusers($direction)
212
    {
213
        global $xoopsUser, $xoopsDB, $xoopsTpl;
214
        $array = [];
215
216
        if ('up' === $direction) {
217
            $sql    = 'SELECT owner, count(*) AS cnt FROM ' . $xoopsDB->prefix('smallworld_vote') . " WHERE up='1' GROUP BY owner ORDER BY cnt DESC LIMIT 20";
218
            $result = $xoopsDB->queryF($sql);
219
            $count = $xoopsDB->getRowsNum($result);
220
            $i = 1;
221
            if ($count >= $i) {
222
                while ($row = $xoopsDB->fetchArray($result)) {
223
                    $array['counter'][$i] = $i;
224
                    $array['img'][$i] = "<img height='10px' width='10px' " . "style='margin:0px 5px;' src = '../assets/images/like.png'>";
225
                    if ($array['counter'][$i] > 3) {
226
                        $array['img'][$i] = '';
227
                    }
228
                    $array['cnt'][$i] = $row['cnt'];
229
                    $array['user'][$i] = $xoopsUser->getUnameFromId($row['owner']);
230
                    ++$i;
231
                }
232
            } else {
233
                $array = [];
234
            }
235
        } else {
236
            $sql    = 'SELECT owner, count(*) AS cnt FROM ' . $xoopsDB->prefix('smallworld_vote') . " WHERE down='1' GROUP BY owner ORDER BY cnt DESC LIMIT 20";
237
            $result = $xoopsDB->queryF($sql);
238
            $count = $xoopsDB->getRowsNum($result);
239
            $i = 1;
240
            if (0 != $count) {
241
                while ($row = $xoopsDB->fetchArray($result)) {
242
                    $array['counter'][$i] = $i;
243
                    $array['img'][$i] = "<img height='10px' width='10px' " . "style='margin:0px 5px;' src = '../assets/images/dislike.png'>";
244
                    if ($array['counter'][$i] > 3) {
245
                        $array['img'][$i] = '';
246
                    }
247
                    $array['cnt'][$i] = $row['cnt'];
248
                    $array['user'][$i] = $xoopsUser->getUnameFromId($row['owner']);
249
                    ++$i;
250
                }
251
            } else {
252
                $array = [];
253
            }
254
        }
255
256
        return $array;
257
    }
258
259
    /**
260
     * Get all users to loop in admin for administration
261
     * @param string $inspect
262
     * @returns array
263
     */
264
    public function getAllUsers($inspect)
265
    {
266
        global $xoopsDB, $xoopsUser, $xoopsTpl;
267
        $data = [];
268
        if ('yes' === $inspect) {
269
            $sql = 'SELECT * FROM ' . $xoopsDB->prefix('smallworld_admin') . ' WHERE (inspect_start  + inspect_stop) >= ' . time() . ' ORDER BY username';
270
        } else {
271
            $sql = 'SELECT * FROM ' . $xoopsDB->prefix('smallworld_admin') . ' WHERE (inspect_start  + inspect_stop) < ' . time() . ' ORDER BY username';
272
        }
273
        $result = $xoopsDB->queryF($sql);
274
        $count = $xoopsDB->getRowsNum($result);
275
        if (0 != $count) {
276
            while ($row = $xoopsDB->fetchArray($result)) {
277
                $data[] = $row;
278
            }
279
        }
280
        if (!empty($data)) {
281
            return $data;
282
        }
283
    }
284
285
    /**
286
     * check server if update is available
287
     * Server currently at culex.dk
288
     * Variable $version = current smallworld version number
289
     * @return string
290
     */
291
    public function doCheckUpdate()
292
    {
293
        global $pathIcon16;
294
        $version = $this->ModuleInstallVersion();
295
        $critical = false;
296
        $update = false;
297
        $rt = '';
0 ignored issues
show
Unused Code introduced by
$rt 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...
298
        $url = 'http://www.culex.dk/updates/smallworld_version.csv';
299
        $fileC = $this->fetchURL($url, ['fopen', 'curl', 'socket']);
300
        $read = explode(';', $fileC);
301
302
        $upd_img = $pathIcon16 . '/on.png';
303
304
        if ($read[0] > $version && '1' == $read[2]) {
305
            $critical = true;
306
            $upd_img = $pathIcon16 . '/off.png';
307
        }
308
        if ($read[0] > $version && '1' != $read[2]) {
309
            $update = true;
310
            $upd_img = '../assets/images/upd_normal.png';
311
        }
312
        if ($critical) {
313
            $rt = "<div class='smallworld_update'><img src='" . $upd_img . "'>";
314
            $rt .= _AM_SMALLWORLD_UPDATE_CRITICAL_UPD . '</div>';
315
            $rt .= "<textarea class='xim_update_changelog'>" . $read[1] . '</textarea><br><br>';
316
            $rt .= _AM_SMALLWORLD_UPDATE_SERVER_FILE . "<br><a href='" . $read[3] . "'>" . $read[3] . '</a>';
317
        } elseif ($update) {
318
            $rt = "<div class='smallworld_update'><img src='" . $upd_img . "'>";
319
            $rt .= _AM_SMALLWORLD_UPDATE_NORMAL_UPD . '</div>';
320
            $rt .= "<textarea class='smallworld_update_changelog'>" . $read[1] . '</textarea><br><br>';
321
            $rt .= _AM_SMALLWORLD_UPDATE_SERVER_FILE . "<br><a href='" . $read[3] . "'>" . $read[3] . '</a>';
322
        } else {
323
            $rt = "<div class='smallworld_update'><br><img src='" . $upd_img . "'>" . _AM_SMALLWORLD_UPDATE_YOUHAVENEWESTVERSION . '</div>';
324
        }
325
326
        return $rt;
327
    }
328
329
    /**
330
     * Fetch content of comma separated text file
331
     * will attempt to use the fopen method first, then curl, then socket
332
     * @param string $url
333
     * @param array $methods
334
     * @returns string
335
     */
336
    public function fetchURL($url, $methods = ['fopen', 'curl', 'socket'])
337
    {
338
        /**
339
         *   December 21st 2010, Mathew Tinsley ([email protected])
340
         *   http://tinsology.net
341
         *
342
         *   To the extent possible under law, Mathew Tinsley has waived all copyright and related or
343
         *   neighboring rights to this work. There's absolutely no warranty.
344
         */
345
        if ('string' === gettype($methods)) {
346
            $methods = [$methods];
347
        } elseif (!is_array($methods)) {
348
            return false;
349
        }
350
        foreach ($methods as $method) {
351
            switch ($method) {
352
                case 'fopen':
353
                    //uses file_get_contents in place of fopen
354
                    //allow_url_fopen must still be enabled
355
                    if (ini_get('allow_url_fopen')) {
356
                        $contents = file_get_contents($url);
357
                        if (false !== $contents) {
358
                            return $contents;
359
                        }
360
                    }
361
                    break;
362
                case 'curl':
363
                    if (function_exists('curl_init')) {
364
                        $ch = curl_init();
365
                        curl_setopt($ch, CURLOPT_URL, $url);
366
                        curl_setopt($ch, CURLOPT_HEADER, 0);
367
                        // return the value instead of printing the response to browser
368
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
369
                        $result = curl_exec($ch);
370
                        curl_close($ch);
371
                        //return curl_exec($ch);
372
                        return $result;
373
                    }
374
                    break;
375
                case 'socket':
376
                    //make sure the url contains a protocol, otherwise $parts['host'] won't be set
377
                    if (0 !== strpos($url, 'http://') && 0 !== strpos($url, 'https://')) {
378
                        $url = 'http://' . $url;
379
                    }
380
                    $parts = parse_url($url);
381
                    if ('https' === $parts['scheme']) {
382
                        $target = 'ssl://' . $parts['host'];
383
                        $port = isset($parts['port']) ? $parts['port'] : 443;
384
                    } else {
385
                        $target = $parts['host'];
386
                        $port = isset($parts['port']) ? $parts['port'] : 80;
387
                    }
388
                    $page = isset($parts['path']) ? $parts['path'] : '';
389
                    $page .= isset($parts['query']) ? '?' . $parts['query'] : '';
390
                    $page .= isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
391
                    $page = ('' == $page) ? '/' : $page;
392
                    if ($fp = fsockopen($target, $port, $errno, $errstr, 15)) {
393
                        $headers = "GET $page HTTP/1.1\r\n";
394
                        $headers .= "Host: {$parts['host']}\r\n";
395
                        $headers .= "Connection: Close\r\n\r\n";
396
                        if (fwrite($fp, $headers)) {
397
                            $resp = '';
398
                            //while not eof and an error does not occur when calling fgets
399
                            while (!feof($fp) && false !== ($curr = fgets($fp, 128))) {
400
                                $resp .= $curr;
401
                            }
402
                            if (isset($curr) && false !== $curr) {
403
                                return substr(strstr($resp, "\r\n\r\n"), 3);
404
                            }
405
                        }
406
                        fclose($fp);
407
                    }
408
                    break;
409
            }
410
        }
411
412
        return false;
413
    }
414
415
    /**
416
     * Smallworld_sanitize(array(array) )
417
     * flatten multidimentional arrays to one dimentional
418
     * @param array $array
419
     * @return array
420
     */
421
    public function flatten($array)
422
    {
423
        $return = [];
424
        while (count($array)) {
425
            $value = array_shift($array);
426
            if (is_array($value)) {
427
                foreach ($value as $sub) {
428
                    $array[] = $sub;
429
                }
430
            } else {
431
                $return[] = $value;
432
            }
433
        }
434
435
        return $return;
436
    }
437
438
    /**
439
     * Smallworld_sanitize($string)
440
     * @param string $text
441
     * @returns string
442
     */
443
    public function Smallworld_sanitize($text)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

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

Loading history...
444
    {
445
        $text = htmlspecialchars($text, ENT_QUOTES);
446
        $myts = \MyTextSanitizer::getInstance();
447
        $text = $myts->displayTarea($text, 1, 1, 1, 1);
448
        $text = str_replace("\n\r", "\n", $text);
449
        $text = str_replace("\r\n", "\n", $text);
450
        $text = str_replace("\n", '<br>', $text);
451
        $text = str_replace('"', "'", $text);
452
453
        return $text;
454
    }
455
}
456
457
/*
458
 *  Does a sync to remove orphans from smallworld db
459
 *
460
 */
461
462
/**
463
 * Class SmallWorldDoSync
464
 */
465 View Code Duplication
class SmallWorldDoSync
0 ignored issues
show
Duplication introduced by
This class 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...
466
{
467
    /**
468
     * check for orphans (xoops_users <-> smallworld_users) and remove from smallworld
469
     * @return void
470
     */
471
    public function checkOrphans()
472
    {
473
        global $xoopsDB;
474
        $sql = 'SELECT userid FROM ' . $xoopsDB->prefix('smallworld_user') . ' WHERE userid NOT IN ( SELECT uid FROM ' . $xoopsDB->prefix('users') . ')';
475
        $result = $xoopsDB->queryF($sql);
476
        if ($result) {
477
            while ($r = $xoopsDB->fetchArray($result)) {
478
                $this->deleteAccount($r['userid']);
479
            }
480
        }
481
    }
482
483
    /**
484
     * deleteAccount function
485
     * - Delete user account and associate rows across tables
486
     * @param  int $userid
487
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|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...
488
     */
489
    public function deleteAccount($userid)
490
    {
491
        global $xoopsDB, $xoopsUser;
492
        $user = new \XoopsUser($userid);
493
        $username = $user->uname();
0 ignored issues
show
Unused Code introduced by
$username 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...
494
        $sql01 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_admin') . " WHERE userid = '" . $userid . "'";
495
        $sql02 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_comments') . " WHERE uid_fk = '" . $userid . "'";
496
        $sql03 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_followers') . " WHERE me = '" . $userid . "' OR you = '" . $userid . "'";
497
        $sql04 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_friends') . " WHERE me = '" . $userid . "' OR you = '" . $userid . "'";
498
        $sql05 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_images') . " WHERE userid = '" . $userid . "'";
499
        $sql06 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_messages') . " WHERE uid_fk = '" . $userid . "'";
500
        $sql07 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_user') . " WHERE userid = '" . $userid . "'";
501
        $sql08 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_vote') . " WHERE user_id = '" . $userid . "'";
502
        $sql09 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_complaints') . " WHERE owner = '" . $userid . "' OR byuser_id = '" . $userid . "'";
503
        $sql10 = 'DELETE FROM ' . $xoopsDB->prefix('smallworld_settings') . " WHERE userid = '" . $userid . "'";
504
505
        $result01 = $xoopsDB->queryF($sql01);
0 ignored issues
show
Unused Code introduced by
$result01 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...
506
        $result02 = $xoopsDB->queryF($sql02);
0 ignored issues
show
Unused Code introduced by
$result02 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
        $result03 = $xoopsDB->queryF($sql03);
0 ignored issues
show
Unused Code introduced by
$result03 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...
508
        $result04 = $xoopsDB->queryF($sql04);
0 ignored issues
show
Unused Code introduced by
$result04 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...
509
        $result05 = $xoopsDB->queryF($sql05);
0 ignored issues
show
Unused Code introduced by
$result05 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...
510
        $result06 = $xoopsDB->queryF($sql06);
0 ignored issues
show
Unused Code introduced by
$result06 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...
511
        $result07 = $xoopsDB->queryF($sql07);
0 ignored issues
show
Unused Code introduced by
$result07 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...
512
        $result08 = $xoopsDB->queryF($sql08);
0 ignored issues
show
Unused Code introduced by
$result08 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...
513
        $result09 = $xoopsDB->queryF($sql09);
0 ignored issues
show
Unused Code introduced by
$result09 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...
514
        $result10 = $xoopsDB->queryF($sql10);
0 ignored issues
show
Unused Code introduced by
$result10 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...
515
        // Remove picture dir
516
        $dirname = XOOPS_ROOT_PATH . '/uploads/albums_smallworld' . '/' . $userid . '/';
517
        $this->smallworld_remDir($userid, $dirname, $empty = false);
518
    }
519
520
    /**
521
     * smallworld_remDir function
522
     * - Remove user image dir in uploads.
523
     * @param  int $userid
524
     * @param  string|bool $directory
525
     * @param bool|int $empty
526
     * @return true
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|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...
527
     */
528
    public function smallworld_remDir($userid, $directory, $empty = false)
529
    {
530
        if ('' != $userid) {
531
            if ('/' === substr($directory, -1)) {
532
                $directory = substr($directory, 0, -1);
533
            }
534
535
            if (!file_exists($directory) || !is_dir($directory)) {
536
                return false;
537
            } elseif (!is_readable($directory)) {
538
                return false;
539
            } else {
540
                $directoryHandle = opendir($directory);
541
                while ($contents = readdir($directoryHandle)) {
542
                    if ('.' !== $contents && '..' !== $contents) {
543
                        $path = $directory . '/' . $contents;
544
                        if (is_dir($path)) {
545
                            $this->smallworld_remDir($userid, $path);
546
                        } else {
547
                            unlink($path);
548
                        }
549
                    }
550
                }
551
                closedir($directoryHandle);
552
                if (false === $empty) {
553
                    if (!rmdir($directory)) {
554
                        return false;
555
                    }
556
                }
557
558
                return true;
559
            }
560
        }
561
    }
562
563
    /**
564
     * SmallworldDeleteDirectory function
565
     * - Delete images from users on delete
566
     * @param  int $userid
567
     * @return true
0 ignored issues
show
Documentation introduced by
Should the return type not be 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...
568
     */
569
    public function SmallworldDeleteDirectory($userid)
570
    {
571
        $dirname = XOOPS_ROOT_PATH . '/uploads/albums_smallworld' . '/' . $userid . '/';
572
        if (is_dir($dirname)) {
573
            $dir_handle = opendir($dirname);
574
        }
575
        if (!$dir_handle) {
0 ignored issues
show
Bug introduced by
The variable $dir_handle 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...
576
            return false;
577
        }
578
        while ($file = readdir($dir_handle)) {
579
            if ('.' != $file && '..' != $file) {
580
                if (!is_dir($dirname . '/' . $file)) {
581
                    unlink($dirname . '/' . $file);
582
                } else {
583
                    $this->SmallworldDeleteDirectory($dirname . '/' . $file);
584
                }
585
            }
586
        }
587
        closedir($dir_handle);
588
        rmdir($dirname);
589
590
        return true;
591
    }
592
}
593