Completed
Push — master ( fd0c8a...c024a6 )
by
unknown
03:33 queued 01:53
created

class/Admin.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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