Completed
Pull Request — master (#5)
by Michael
01:37
created

Admin   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 442
Duplicated Lines 19.23 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 85
loc 442
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() 0 21 3
A ModuleInstallVersion() 0 7 1
A ModuleInstallDate() 0 7 1
A CountDays() 0 9 1
A mostactiveusers_allround() 16 34 4
A mostactiveusers_today() 15 36 4
B topratedusers() 28 47 8
A getAllUsers() 0 20 5
B doCheckUpdate() 0 37 7
F fetchURL() 0 79 25
A flatten() 0 16 4
A Smallworld_sanitize() 0 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 Admin 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 Admin, and based on these observations, apply Extract Interface, too.

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

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

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

Loading history...
32
    {
33
        global $xoopsDB;
34
        $date    = 0;
35
        $sql     = 'SELECT * FROM ' . $xoopsDB->prefix('smallworld_messages') . ' ORDER BY created LIMIT 1';
36
        $result  = $xoopsDB->queryF($sql);
37
        $counter = $xoopsDB->getRowsNum($result);
38
        if ($counter >= 1) {
39
            while (false !== ($sqlfetch = $xoopsDB->fetchArray($result))) {
40
                $date = $sqlfetch['created'];
41
            }
42
        }
43
44
        return $date;
45
    }
46
47
    /**
48
     * Get average messages sent per day
49
     * @param int $totaldays
50
     * @return int|string
51
     */
52 View Code Duplication
    public function AvgMsgDay($totaldays)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

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