getGeneralStats()   F
last analyzed

Complexity

Conditions 42
Paths 1040

Size

Total Lines 146
Code Lines 106

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 106
c 2
b 0
f 0
dl 0
loc 146
rs 0
cc 42
nc 1040
nop 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/************************************************************************/
4
5
/* XOOPS: Web Portal System                                             */
6
/* ========================                                             */
7
/*                                                                      */
8
/* Copyright (c) 2004 by John Horne                                     */
9
/* http://xoops.ibdeeming.com                                           */
10
/*                                                                      */
11
/* By [email protected] Version 1.0 8/2004                      */
12
/*                                                                      */
13
/* This program is free software. You can redistribute it and/or modify */
14
/* it under the terms of the GNU General Public License as published by */
15
/* the Free Software Foundation; either version 2 of the License.       */
16
17
/************************************************************************/
18
19
use XoopsModules\Statistics;
20
21
/** @var Statistics\Helper $helper */
22
$helper = Statistics\Helper::getInstance();
23
$helper->loadLanguage('main');
24
// Load required configs
25
global $stats_secure_const, $configHandler, $xoopsStatConfig;
26
27
/** @var \XoopsModuleHandler $moduleHandler */
28
$moduleHandler   = xoops_getHandler('module');
29
$xoopsStatModule = $moduleHandler->getByDirname('statistics');
30
$xoopsStatConfig = $configHandler->getConfigsByCat(0, $xoopsStatModule->getVar('mid'));
31
32
$stats_secure_const['server_ip']           = get_server_ip();
33
$stats_secure_const['client_ip']           = get_client_ip();
34
$stats_secure_const['forward_ip']          = get_x_forwarded();
35
$stats_secure_const['remote_addr']         = get_remote_addr();
36
$stats_secure_const['remote_ip']           = get_ip();
37
$stats_secure_const['remote_port']         = get_remote_port();
38
$stats_secure_const['request_method']      = get_request_method();
39
$stats_secure_const['script_name']         = get_script_name();
40
$stats_secure_const['http_host']           = get_http_host();
41
$stats_secure_const['query_string']        = st_clean_string(get_query_string());
42
$stats_secure_const['get_string']          = st_clean_string(get_get_string());
43
$stats_secure_const['post_string']         = st_clean_string(get_post_string());
44
$stats_secure_const['query_string_base64'] = st_clean_string(base64_decode($stats_secure_const['query_string'], true));
45
$stats_secure_const['get_string_base64']   = st_clean_string(base64_decode($stats_secure_const['get_string'], true));
46
$stats_secure_const['post_string_base64']  = st_clean_string(base64_decode($stats_secure_const['post_string'], true));
47
$stats_secure_const['user_agent']          = get_user_agent();
48
$stats_secure_const['referer']             = get_referer();
49
$stats_secure_const['script_name']         = get_script_name();
50
$stats_secure_const['ban_time']            = time();
51
$stats_secure_const['ban_ip']              = '';
52
53
// $var == 'bots' or 'referers'
54
function setBlockedCounter($var)
55
{
56
    global $xoopsDB, $stats_secure_const, $xoopsStatConfig;
57
58
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('counter') . " SET count=count+1 WHERE (type='totalblocked' AND var='hits') OR (var='$var' AND type='blocked')");
59
60
    /* Start Detailed Statistics */
61
    $dot        = date('d-m-Y-H');
62
    $now        = explode('-', $dot);
63
    $nowHour    = $now[3];
64
    $nowYear    = $now[2];
65
    $nowMonth   = $now[1];
66
    $nowDate    = $now[0];
67
    $sql        = 'SELECT year FROM ' . $xoopsDB->prefix('stats_blockedyear') . " WHERE year='$nowYear'";
68
    $resultyear = $xoopsDB->queryF($sql);
69
    $jml        = $xoopsDB->getRowsNum($resultyear);
70
    if ($jml <= 0) {
71
        $sql = 'INSERT INTO ' . $xoopsDB->prefix('stats_blockedyear') . " VALUES ('$nowYear','0')";
72
        $xoopsDB->queryF($sql);
73
        for ($i = 1; $i <= 12; ++$i) {
74
            $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_blockedmonth') . " VALUES ('$nowYear','$i','0')");
75
            if (1 == $i) {
76
                $TotalDay = 31;
77
            }
78
            if (2 == $i) {
79
                if (true === date('L')) {
80
                    $TotalDay = 29;
81
                } else {
82
                    $TotalDay = 28;
83
                }
84
            }
85
            if (3 == $i) {
86
                $TotalDay = 31;
87
            }
88
            if (4 == $i) {
89
                $TotalDay = 30;
90
            }
91
            if (5 == $i) {
92
                $TotalDay = 31;
93
            }
94
            if (6 == $i) {
95
                $TotalDay = 30;
96
            }
97
            if (7 == $i) {
98
                $TotalDay = 31;
99
            }
100
            if (8 == $i) {
101
                $TotalDay = 31;
102
            }
103
            if (9 == $i) {
104
                $TotalDay = 30;
105
            }
106
            if (10 == $i) {
107
                $TotalDay = 31;
108
            }
109
            if (11 == $i) {
110
                $TotalDay = 30;
111
            }
112
            if (12 == $i) {
113
                $TotalDay = 31;
114
            }
115
            for ($k = 1; $k <= $TotalDay; ++$k) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $TotalDay does not seem to be defined for all execution paths leading up to this point.
Loading history...
116
                $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_blockeddate') . " VALUES ('$nowYear','$i','$k','0')");
117
            }
118
        }
119
    }
120
121
    $sql     = 'SELECT hour FROM ' . $xoopsDB->prefix('stats_blockedhour') . " WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate')";
122
    $result  = $xoopsDB->queryF($sql);
123
    $numrows = $xoopsDB->getRowsNum($result);
124
125
    if ($numrows <= 0) {
126
        for ($z = 0; $z <= 23; ++$z) {
127
            $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_blockedhour') . " VALUES ('$nowYear','$nowMonth','$nowDate','$z','0')");
128
        }
129
    }
130
131
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_blockedyear') . " SET hits=hits+1 WHERE year='$nowYear'");
132
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_blockedmonth') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth')");
133
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_blockeddate') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate')");
134
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_blockedhour') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate') AND (hour='$nowHour')");
135
}
136
137
// ************************** Begin Security Checks ******************************
138
function prematureDeath($str)
139
{
140
    if (isset($_COOKIE[$xoopsConfig['session_name']])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xoopsConfig seems to be never defined.
Loading history...
141
        setcookie($xoopsConfig['session_name'], '', time() - 42000, '/');
142
    }
143
144
    $_SESSION = [];
145
146
    session_destroy();
147
148
    exit($str);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
149
}
150
151
// check no count IP - this is when webmaster doesn't want an IP to count in stats
152
function checkNoCountIP()
153
{
154
    global $xoopsStatConfig, $stats_secure_const;
155
156
    $ret_result = false;
157
    $ip         = $stats_secure_const['remote_ip'];
158
159
    // check for filtering of IP from hits
160
    if ('1' == $xoopsStatConfig['stats_allowfilteriphits']) {
161
        // filtering is ON
162
        $filteriplist = $xoopsStatConfig['stats_filteriplist'];
163
        if (is_array($filteriplist)) { // make sure we have an array
164
            if (count($filteriplist) > 0) { // check how many items I have
165
                foreach ($filteriplist as $fipl) {
166
                    //    print( $ip."&nbsp;-&nbsp;".$fipl."<br>" );
167
                    if (preg_match('/' . $fipl . '/', $ip)) { // look at each item in list, see if it matches current IP
168
                        $ret_result = true;  // if it matches, don't count it
169
                        continue;
170
                    }
171
                }
172
            }
173
        }
174
    }
175
176
    return $ret_result;
177
}
178
179
// check block bots list
180
function checkBlockBotslist()
181
{
182
    global $stats_secure_const, $xoopsStatConfig;
183
184
    $ret_result = false;  // set default return value for function
185
186
    if ('1' == $xoopsStatConfig['stats_forbidbots']) {  // is it on?
187
        $blockedbotslist = $xoopsStatConfig['stats_botstoblock'];
188
189
        if (is_array($blockedbotslist)) {  // make sure it's an array
190
            if (count($blockedbotslist) > 0) {
191
                foreach ($blockedbotslist as $bot) {
192
                    if (preg_match('/' . $bot . '/', $stats_secure_const['user_agent'])) {
193
                        $ret_result = true;
194
                        continue;
195
                    }
196
                }
197
            }
198
        }
199
    }
200
201
    return $ret_result;
202
}
203
204
if (true === checkBlockBotslist()) {
205
    global $xoopsStatConfig;
206
207
    setBlockedCounter('bots'); /* Save the obtained values */
208
209
    exit($xoopsStatConfig['stats_customforbidmsg'] . '<br>********<br>' . $stats_secure_const['user_agent']);
210
}
211
212
// check blacklisted referers - if a match, die!
213
function checkBlacklist()
214
{
215
    global $xoopsDB, $stats_secure_const;
216
217
    $ret_result = false;
218
219
    // get any current blacklist
220
    $result = $xoopsDB->queryF('SELECT * FROM ' . $xoopsDB->prefix('stats_refer_blacklist'));
221
    [$id, $referer] = $xoopsDB->fetchRow($result);
222
    $referblacklist = unserialize(stripslashes($referer));
223
224
    if (is_array($referblacklist)) { // make sure we have an array
225
        // attempt to strip anthing but the URL i.e. http://www.abc.com instead of http://www.abc.com/dirname
226
        // this is not the same as $stats_secure_const['http_host'] above.
227
        $dnsarray = parse_url($stats_secure_const['referer']);
228
        if (!isset($dnsarray['host']) || '' == $dnsarray['host']) {
229
            $dnsarray['host'] = $stats_secure_const['referer'];
230
        }
231
232
        if (count($referblacklist) > 0) {
233
            foreach ($referblacklist as $item) {
234
                if (preg_match('/' . $item . '/', $dnsarray['host'])) {
235
                    $ret_result = true;
236
                    continue;
237
                }
238
            }
239
        }
240
    }
241
242
    return $ret_result;
243
}
244
245
if (true === checkBlacklist()) {
246
    global $xoopsDB, $stats_secure_const, $xoopsStatConfig;
247
248
    $switchval = $xoopsStatConfig['refererspam'];
249
250
    switch ($switchval) {
251
        case 'Forbidden':
252
            /* Save the obtained values */
253
            setBlockedCounter('referers');
254
            prematureDeath($xoopsStatConfig['stats_customforbidmsg'] . '<br>********<br>' . $stats_secure_const['referer']);
255
            break;
256
        case 'Reflect':
257
            /* Save the obtained values */
258
            setBlockedCounter('referers');
259
260
            preg_match("/^(http:\/\/)?([^\/]+)/i", $stats_secure_const['referer'], $matches);
261
            $prefix = $matches[1];
262
            $host   = $matches[2];
263
264
            // get last two segments of host name
265
            preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
266
            $domain_tld = $matches[0];
267
268
            header('Location: ' . $prefix . $domain_tld . '/');
269
            prematureDeath('Location: ' . $stats_secure_const['referer']);
270
            break;
271
        default:
272
            break;
273
    }
274
}
275
276
// Invalid ip check
277
if ('none' === $stats_secure_const['remote_ip']) {
278
    prematureDeath(STATS_INVALIDIP);
279
}
280
281
// Invalid request method check
282
if ('get' !== mb_strtolower($stats_secure_const['request_method']) && 'head' !== mb_strtolower($stats_secure_const['request_method']) && 'post' !== mb_strtolower($stats_secure_const['request_method'])
283
    && 'put' !== mb_strtolower($stats_secure_const['request_method'])) {
284
    prematureDeath(STATS_INVALIDMETHOD);
285
}
286
287
// DOS Attack Blocker
288
if (empty($stats_secure_const['user_agent']) || '-' == $stats_secure_const['user_agent']
289
    || !isset($stats_secure_const['user_agent'])) {
290
    prematureDeath($xoopsStatConfig['stats_customforbidmsg']);
291
}
292
// Check for UNION attack
293
if (false !== mb_stripos($stats_secure_const['query_string'], '+union+')
294
    or false !== mb_stripos($stats_secure_const['query_string'], '%20union%20')
295
    or false !== mb_stripos($stats_secure_const['query_string'], '*/union/*')
296
    or false !== mb_stripos($stats_secure_const['query_string'], ' union ')
297
    or false !== mb_stripos($stats_secure_const['query_string_base64'], '+union+')
298
    or false !== mb_stripos($stats_secure_const['query_string_base64'], '%20union%20')
299
    or false !== mb_stripos($stats_secure_const['query_string_base64'], '*/union/*')
300
    or false !== mb_stripos($stats_secure_const['query_string_base64'], ' union ')) {
301
    prematureDeath($xoopsStatConfig['stats_customforbidmsg']);
302
}
303
304
// ********************** END SECURITY CHECKS *********************************
305
306
function getRemoteAddr()
307
{
308
    global $xoopsDB, $stats_secure_const;
309
310
    $ip = $stats_secure_const['remote_ip'];
311
312
    $now_ip    = date('YmdH');
313
    $past_hour = $now_ip - 1;
314
    $resultip  = $xoopsDB->queryF('SELECT id FROM ' . $xoopsDB->prefix('stats_ip') . " WHERE ip='$ip' AND date>'$past_hour'");
315
    if ($xoopsDB->getRowsNum($resultip) > 0) {
316
        $row = $xoopsDB->fetchRow($resultip);
317
        $id  = $row[0];
318
        $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_ip') . " SET date='$now_ip', hits=hits+1 WHERE id='$id'");
319
    } else {
320
        $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_ip') . " (ip, date, hits) VALUES ('$ip', '$now_ip', '1')");
321
    }
322
}
323
324
function autoPurgeRefererList()
325
{
326
    global $xoopsDB, $xoopsStatConfig;
327
328
    $now_refer = date('YmdH');
0 ignored issues
show
Unused Code introduced by
The assignment to $now_refer is dead and can be removed.
Loading history...
329
    $timelimit = 0;
330
331
    switch ($xoopsStatConfig['autopurgereferer']) {
332
        case 'never':
333
            return;
334
        case 'fiveday':
335
            $timelimit = 120;
336
            break;
337
        case 'oneday':
338
            $timelimit = 24;
339
            break;
340
        case 'sixhour':
341
            $timelimit = 6;
342
            break;
343
        case 'twelvehour':
344
            $timelimit = 12;
345
            break;
346
    }
347
348
    $timestamp  = time() - ($timelimit * 60 * 60);
349
    $purge_date = date('Ymdh', $timestamp);
350
351
    $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('stats_refer') . " where date <= '$purge_date'");
352
}
353
354
function getRemoteReferer()
355
{
356
    global $xoopsDB, $stats_secure_const;
357
358
    // do a little house cleaning
359
    autoPurgeRefererList();
360
361
    $refer = $stats_secure_const['referer'];
362
    $ip    = get_ip();
363
364
    if ('' != $refer) {
365
        // break it down!!
366
        $dnsarray = parse_url($refer);
367
    }
368
369
    if (!isset($dnsarray['host'])) {
370
        $dnsarray['host'] = $stats_secure_const['http_host'];
371
    }
372
373
    if ('' != $dnsarray['host']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dnsarray does not seem to be defined for all execution paths leading up to this point.
Loading history...
374
        $now_refer = date('YmdH');
375
        $past_hour = $now_refer - 1;
376
377
        // figure out if we are saving hits by refer and path or just refer
378
        $resultoption = $xoopsDB->queryF('SELECT options FROM ' . $xoopsDB->prefix('newblocks') . " WHERE name='Top Referers' AND dirname='statistics'");
379
        $optionsret   = $xoopsDB->fetchRow($resultoption);
380
        $options      = unserialize(stripslashes($optionsret[0]));
0 ignored issues
show
Unused Code introduced by
The assignment to $options is dead and can be removed.
Loading history...
381
        $options      = explode('|', $optionsret[0]);
382
383
        if ((count($options) <= 1) || '' == $options[1]) {
384
            $options[1] = 0;
385
        }
386
387
        if (!isset($dnsarray['path']) || '' == $dnsarray['path']) {
388
            $pathfordb = '';
389
        } else {
390
            $pathfordb = $dnsarray['path'];
391
        }
392
393
        if (isset($dnsarray['query']) && '' != $dnsarray['query']) {
394
            $pathfordb .= '|' . st_clean_string($dnsarray['query']);
395
        } else {
396
            $querystr  = $stats_secure_const['query_string'];
397
            $pathfordb .= '|' . $querystr;
398
        }
399
400
        if (isset($dnsarray['fragment']) && '' != $dnsarray['fragment']) {
401
            $pathfordb .= '|' . $dnsarray['fragment'];
402
        }
403
404
        if (1 == $options[1]) {    // domain only, don't care about rest, but will store.  Uniqueness in query isn't as granular
405
            $resultrefer      = $xoopsDB->queryF('SELECT id FROM ' . $xoopsDB->prefix('stats_refer') . " WHERE refer='" . $dnsarray['host'] . "' AND referpath='' and date>'$past_hour' and ip='$ip'");
406
            $dnsarray['path'] = '';
407
        } else {
408
            $resultrefer = $xoopsDB->queryF('SELECT id FROM ' . $xoopsDB->prefix('stats_refer') . " WHERE refer='" . $dnsarray['host'] . "' AND referpath='" . $pathfordb . "' AND date>'$past_hour' and ip='$ip'");
409
        }
410
411
        if ($xoopsDB->getRowsNum($resultrefer) > 0) {
412
            $row = $xoopsDB->fetchRow($resultrefer);
413
            $id  = $row[0];
414
            $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_refer') . " SET date='$now_refer', hits=hits+1 WHERE id='$id' && ip='$ip'");
415
        } else {
416
            $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_refer') . " (ip, refer, date, hits, referpath) VALUES ('$ip', '" . $dnsarray['host'] . "', '$now_refer', '1', '" . $pathfordb . "')");
417
        }
418
    }
419
}
420
421
function getGeneralStats()
422
{
423
    global $xoopsDB, $stats_secure_const, $xoopsStatConfig;
424
425
    /* Get the Browser data */
426
    $user_agent = $stats_secure_const['user_agent'];
427
428
    $botarray = $xoopsStatConfig['stats_botidentities'];
429
    if (!is_array($botarray)) { // make sure it's an array
430
        // something went wrong, initialize as an array
431
        $botarray = [];
432
    }
433
434
    $pipesepbots = '/' . implode('|', $botarray) . '/i';
435
436
    if (preg_match($pipesepbots, $user_agent)) {
437
        $browser = 'Bot';
438
    } elseif (preg_match('/Nav|Gold|X11|Netscape/', $user_agent) && (false === preg_match('/MSIE|Konqueror|Slurp|AppleWeb|Firefox|Firebird|Opera/', $user_agent))) {
439
        $browser = 'Netscape';
440
    } elseif (preg_match('/Opera/', $user_agent)) {
441
        $browser = 'Opera';
442
    } elseif (preg_match('/Lynx/', $user_agent)) {
443
        $browser = 'Lynx';
444
    } elseif (preg_match('/WebTV/', $user_agent)) {
445
        $browser = 'WebTV';
446
    } elseif (preg_match('/Konqueror/', $user_agent)) {
447
        $browser = 'Konqueror';
448
    } elseif (preg_match('/AppleWeb/', $user_agent)) {
449
        $browser = 'AppleWeb';
450
    } elseif (preg_match('/Firefox/', $user_agent)) {
451
        $browser = 'Firefox';
452
    } elseif (preg_match('/Deepnet/', $user_agent)) {
453
        $browser = 'Deepnet';
454
    } elseif (preg_match('/Avant/', $user_agent)) {
455
        $browser = 'Avant';
456
    } elseif (preg_match('/MSIE/', $user_agent)) {
457
        $browser = 'MSIE';
458
    } elseif (preg_match('/Mozilla/', $user_agent)) {
459
        $browser = 'Mozilla';
460
    } else {
461
        $browser = 'Other';
462
    }
463
464
    /* Get the Operating System data */
465
466
    if (preg_match('/Win/', $user_agent)) {
467
        $os = 'Windows';
468
    } elseif (preg_match('/Mac|PPC/', $user_agent)) {
469
        $os = 'Mac';
470
    } elseif (preg_match('/Linux/', $user_agent)) {
471
        $os = 'Linux';
472
    } elseif (preg_match('/FreeBSD/', $user_agent)) {
473
        $os = 'FreeBSD';
474
    } elseif (preg_match('/SunOS/', $user_agent)) {
475
        $os = 'SunOS';
476
    } elseif (preg_match('/IRIX/', $user_agent)) {
477
        $os = 'IRIX';
478
    } elseif (preg_match('/BeOS/', $user_agent)) {
479
        $os = 'BeOS';
480
    } elseif (preg_match('/OS/2/', $user_agent)) {
481
        $os = 'OS/2';
482
    } elseif (preg_match('/AIX/', $user_agent)) {
483
        $os = 'AIX';
484
    } else {
485
        $os = 'Other';
486
    }
487
488
    /* Save the obtained values */
489
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('counter') . " SET count=count+1 WHERE (type='total' AND var='hits') OR (var='$browser' AND type='browser') OR (var='$os' AND type='os')");
490
491
    /* Start Detailed Statistics */
492
493
    $dot        = date('d-m-Y-H');
494
    $now        = explode('-', $dot);
495
    $nowHour    = $now[3];
496
    $nowYear    = $now[2];
497
    $nowMonth   = $now[1];
498
    $nowDate    = $now[0];
499
    $sql        = 'SELECT year FROM ' . $xoopsDB->prefix('stats_year') . " WHERE year='$nowYear'";
500
    $resultyear = $xoopsDB->queryF($sql);
501
    $jml        = $xoopsDB->getRowsNum($resultyear);
502
    if ($jml <= 0) {
503
        $sql = 'INSERT INTO ' . $xoopsDB->prefix('stats_year') . " VALUES ('$nowYear','0')";
504
        $xoopsDB->queryF($sql);
505
        for ($i = 1; $i <= 12; ++$i) {
506
            $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_month') . " VALUES ('$nowYear','$i','0')");
507
            if (1 == $i) {
508
                $TotalDay = 31;
509
            }
510
            if (2 == $i) {
511
                if (true === date('L')) {
512
                    $TotalDay = 29;
513
                } else {
514
                    $TotalDay = 28;
515
                }
516
            }
517
            if (3 == $i) {
518
                $TotalDay = 31;
519
            }
520
            if (4 == $i) {
521
                $TotalDay = 30;
522
            }
523
            if (5 == $i) {
524
                $TotalDay = 31;
525
            }
526
            if (6 == $i) {
527
                $TotalDay = 30;
528
            }
529
            if (7 == $i) {
530
                $TotalDay = 31;
531
            }
532
            if (8 == $i) {
533
                $TotalDay = 31;
534
            }
535
            if (9 == $i) {
536
                $TotalDay = 30;
537
            }
538
            if (10 == $i) {
539
                $TotalDay = 31;
540
            }
541
            if (11 == $i) {
542
                $TotalDay = 30;
543
            }
544
            if (12 == $i) {
545
                $TotalDay = 31;
546
            }
547
            for ($k = 1; $k <= $TotalDay; ++$k) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $TotalDay does not seem to be defined for all execution paths leading up to this point.
Loading history...
548
                $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_date') . " VALUES ('$nowYear','$i','$k','0')");
549
            }
550
        }
551
    }
552
553
    $sql     = 'SELECT hour FROM ' . $xoopsDB->prefix('stats_hour') . " WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate')";
554
    $result  = $xoopsDB->queryF($sql);
555
    $numrows = $xoopsDB->getRowsNum($result);
556
557
    if ($numrows <= 0) {
558
        for ($z = 0; $z <= 23; ++$z) {
559
            $xoopsDB->queryF('INSERT INTO ' . $xoopsDB->prefix('stats_hour') . " VALUES ('$nowYear','$nowMonth','$nowDate','$z','0')");
560
        }
561
    }
562
563
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_year') . " SET hits=hits+1 WHERE year='$nowYear'");
564
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_month') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth')");
565
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_date') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate')");
566
    $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_hour') . " SET hits=hits+1 WHERE (year='$nowYear') AND (month='$nowMonth') AND (date='$nowDate') AND (hour='$nowHour')");
567
}
568
569
function getScreenDims()
570
{
571
    global $xoopsDB;
572
573
    $sw = \Xmf\Request::getString('sw', '', 'COOKIE');
574
    $sc = \Xmf\Request::getString('sc', '', 'COOKIE');
575
576
    /**
577
     * @feature
578
     * Keeps track of visitors screen size ie 800x600
579
     */
580
    // update screen width
581
    if ('' != $sw) {
582
        switch ($sw) {
583
            case '640':
584
                $sw_id = 1;
585
                break;
586
            case '800':
587
                $sw_id = 2;
588
                break;
589
            case '1024':
590
                $sw_id = 3;
591
                break;
592
            case '1152':
593
                $sw_id = 4;
594
                break;
595
            case '1280':
596
                $sw_id = 5;
597
                break;
598
            case '1600':
599
                $sw_id = 6;
600
                break;
601
            default:
602
                $sw_id = 7;
603
                break;
604
        }
605
606
        $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_userscreen') . " SET hits=hits+1 WHERE id='$sw_id'");
607
    }
608
609
    /**
610
     * @feature
611
     * Keeps track of visitors screen colour depth
612
     */
613
    // update screen color
614
    if ('' != $sc) {
615
        switch ($sc) {
616
            case '8':
617
                $sc_id = 1;
618
                break;
619
            case '16':
620
                $sc_id = 2;
621
                break;
622
            case '24':
623
                $sc_id = 3;
624
                break;
625
            case '32':
626
                $sc_id = 4;
627
                break;
628
            default:
629
                $sc_id = 5;
630
                break;
631
        }
632
633
        $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('stats_usercolor') . " SET hits=hits+1 WHERE id='$sc_id'");
634
    }
635
}
636
637
/*******************************/
638
/* BEGIN FUNCTIONS             */
639
/*******************************/
640
function stats_getservervar($var)
641
{
642
    if (isset($_SERVER[$var])) {
643
        return $_SERVER[$var];
644
    } elseif (isset($HTTP_SERVER_VARS[$var])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $HTTP_SERVER_VARS seems to never exist and therefore isset should always be false.
Loading history...
645
        return $HTTP_SERVER_VARS[$var];
646
    } elseif (getenv($var)) {
647
        return getenv($var);
648
    }
649
650
    return 'none';
651
}
652
653
function get_remote_port()
654
{
655
    return stats_getservervar('REMOTE_PORT');
656
}
657
658
function get_request_method()
659
{
660
    return stats_getservervar('REQUEST_METHOD');
661
}
662
663
function get_script_name()
664
{
665
    return stats_getservervar('SCRIPT_NAME');
666
}
667
668
function get_http_host()
669
{
670
    return stats_getservervar('HTTP_HOST');
671
}
672
673
function st_clean_string($cleanstring)
674
{
675
    $st_fr1      = [
676
        '%25',
677
        '%00',
678
        '%01',
679
        '%02',
680
        '%03',
681
        '%04',
682
        '%05',
683
        '%06',
684
        '%07',
685
        '%08',
686
        '%09',
687
        '%0A',
688
        '%0B',
689
        '%0C',
690
        '%0D',
691
        '%0E',
692
        '%0F',
693
        '%10',
694
        '%11',
695
        '%12',
696
        '%13',
697
        '%14',
698
        '%15',
699
        '%16',
700
        '%17',
701
        '%18',
702
        '%19',
703
        '%1A',
704
        '%1B',
705
        '%1C',
706
        '%1D',
707
        '%1E',
708
        '%1F',
709
    ];
710
    $st_to1      = [
711
        '%',
712
        '',
713
        '',
714
        '',
715
        '',
716
        '',
717
        '',
718
        '',
719
        '',
720
        '',
721
        '',
722
        '',
723
        '',
724
        '',
725
        '',
726
        '',
727
        '',
728
        '',
729
        '',
730
        '',
731
        '',
732
        '',
733
        '',
734
        '',
735
        '',
736
        '',
737
        '',
738
        '',
739
        '',
740
        '',
741
        '',
742
        '',
743
        '',
744
    ];
745
    $st_fr2      = [
746
        '%20',
747
        '%21',
748
        '%22',
749
        '%23',
750
        '%24',
751
        '%25',
752
        '%26',
753
        '%27',
754
        '%28',
755
        '%29',
756
        '%2A',
757
        '%2B',
758
        '%2C',
759
        '%2D',
760
        '%2E',
761
        '%2F',
762
        '%30',
763
        '%31',
764
        '%32',
765
        '%33',
766
        '%34',
767
        '%35',
768
        '%36',
769
        '%37',
770
        '%38',
771
        '%39',
772
        '%3A',
773
        '%3B',
774
        '%3C',
775
        '%3D',
776
        '%3E',
777
        '%3F',
778
    ];
779
    $st_to2      = [
780
        ' ',
781
        '!',
782
        '"',
783
        '#',
784
        '$',
785
        '%',
786
        '&',
787
        "'",
788
        '(',
789
        ')',
790
        '*',
791
        '+',
792
        ',',
793
        '-',
794
        '.',
795
        '/',
796
        '0',
797
        '1',
798
        '2',
799
        '3',
800
        '4',
801
        '5',
802
        '6',
803
        '7',
804
        '8',
805
        '9',
806
        ':',
807
        ';',
808
        '<',
809
        '=',
810
        '>',
811
        '?',
812
    ];
813
    $st_fr3      = [
814
        '%40',
815
        '%41',
816
        '%42',
817
        '%43',
818
        '%44',
819
        '%45',
820
        '%46',
821
        '%47',
822
        '%48',
823
        '%49',
824
        '%4A',
825
        '%4B',
826
        '%4C',
827
        '%4D',
828
        '%4E',
829
        '%4F',
830
        '%50',
831
        '%51',
832
        '%52',
833
        '%53',
834
        '%54',
835
        '%55',
836
        '%56',
837
        '%57',
838
        '%58',
839
        '%59',
840
        '%5A',
841
        '%5B',
842
        '%5C',
843
        '%5D',
844
        '%5E',
845
        '%5F',
846
    ];
847
    $st_to3      = [
848
        '@',
849
        'A',
850
        'B',
851
        'C',
852
        'D',
853
        'E',
854
        'F',
855
        'G',
856
        'H',
857
        'I',
858
        'J',
859
        'K',
860
        'L',
861
        'M',
862
        'N',
863
        'O',
864
        'P',
865
        'Q',
866
        'R',
867
        'S',
868
        'T',
869
        'U',
870
        'V',
871
        'W',
872
        'X',
873
        'Y',
874
        'Z',
875
        '[',
876
        '\\',
877
        ']',
878
        '^',
879
        '_',
880
    ];
881
    $st_fr4      = [
882
        '%60',
883
        '%61',
884
        '%62',
885
        '%63',
886
        '%64',
887
        '%65',
888
        '%66',
889
        '%67',
890
        '%68',
891
        '%69',
892
        '%6A',
893
        '%6B',
894
        '%6C',
895
        '%6D',
896
        '%6E',
897
        '%6F',
898
        '%70',
899
        '%71',
900
        '%72',
901
        '%73',
902
        '%74',
903
        '%75',
904
        '%76',
905
        '%77',
906
        '%78',
907
        '%79',
908
        '%7A',
909
        '%7B',
910
        '%7C',
911
        '%7D',
912
        '%7E',
913
        '%7F',
914
    ];
915
    $st_to4      = [
916
        '`',
917
        'a',
918
        'b',
919
        'c',
920
        'd',
921
        'e',
922
        'f',
923
        'g',
924
        'h',
925
        'i',
926
        'j',
927
        'k',
928
        'l',
929
        'm',
930
        'n',
931
        'o',
932
        'p',
933
        'q',
934
        'r',
935
        's',
936
        't',
937
        'u',
938
        'v',
939
        'w',
940
        'x',
941
        'y',
942
        'z',
943
        '{',
944
        '|',
945
        '}',
946
        '`',
947
        '',
948
    ];
949
    $cleanstring = str_replace($st_fr1, $st_to1, $cleanstring);
950
    $cleanstring = str_replace($st_fr2, $st_to2, $cleanstring);
951
    $cleanstring = str_replace($st_fr3, $st_to3, $cleanstring);
952
    $cleanstring = str_replace($st_fr4, $st_to4, $cleanstring);
953
954
    return $cleanstring;
955
}
956
957
function get_query_string()
958
{
959
    if (\Xmf\Request::hasVar('QUERY_STRING', 'SERVER')) {
960
        return str_replace('%09', '%20', $_SERVER['QUERY_STRING']);
961
    } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $HTTP_SERVER_VARS seems to never exist and therefore isset should always be false.
Loading history...
962
        return str_replace('%09', '%20', $HTTP_SERVER_VARS['QUERY_STRING']);
963
    } elseif (getenv('QUERY_STRING')) {
964
        return str_replace('%09', '%20', getenv('QUERY_STRING'));
965
    }
966
967
    return 'none';
968
}
969
970
function get_get_string()
971
{
972
    $getstring = '';
973
    if (isset($_GET)) {
974
        $ST_GET = $_GET;
975
    } elseif (isset($_GET)) {
976
        $ST_GET = $_GET;
977
    } elseif (getenv('GET')) {
978
        $ST_GET = getenv('GET');
979
    } else {
980
        $ST_GET = '';
981
    }
982
    foreach ($ST_GET as $getkey => $getvalue) {
983
        if (!empty($getstring)) {
984
            $getstring .= '&' . $getkey . '=' . $getvalue;
985
        } else {
986
            $getstring .= $getkey . '=' . $getvalue;
987
        }
988
    }
989
990
    return str_replace('%09', '%20', $getstring);
991
}
992
993
function get_post_string()
994
{
995
    $poststring = '';
996
    if (isset($_POST)) {
997
        $ST_POST = $_POST;
998
    } elseif (isset($_POST)) {
999
        $ST_POST = $_POST;
1000
    } elseif (getenv('POST')) {
1001
        $ST_POST = getenv('POST');
1002
    } else {
1003
        $ST_POST = '';
1004
    }
1005
    foreach ($ST_POST as $postkey => $postvalue) {
1006
        if (!empty($poststring)) {
1007
            $poststring .= '&' . $postkey . '=' . $postvalue;
1008
        } else {
1009
            $poststring .= $postkey . '=' . $postvalue;
1010
        }
1011
    }
1012
1013
    return str_replace('%09', '%20', $poststring);
1014
}
1015
1016
function get_user_agent()
1017
{
1018
    return stats_getservervar('HTTP_USER_AGENT');
1019
}
1020
1021
function get_referer()
1022
{
1023
    return stats_getservervar('HTTP_REFERER');
1024
}
1025
1026
function get_ip()
1027
{
1028
    global $stats_secure_const;
1029
    if (mb_strpos($stats_secure_const['client_ip'], ', ') && isset($stats_secure_const['client_ip'])) {
1030
        $client_ips = explode(', ', $stats_secure_const['client_ip']);
1031
        if ('unknown' !== $client_ips[0] && 'none' !== $client_ips[0] && !empty($client_ips[0]) && !is_reserved($client_ips[0])) {
0 ignored issues
show
Bug introduced by
The function is_reserved was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1031
        if ('unknown' !== $client_ips[0] && 'none' !== $client_ips[0] && !empty($client_ips[0]) && !/** @scrutinizer ignore-call */ is_reserved($client_ips[0])) {
Loading history...
1032
            $stats_secure_const['client_ip'] = $client_ips[0];
1033
        } else {
1034
            $stats_secure_const['client_ip'] = $client_ips[1];
1035
        }
1036
    }
1037
    if (mb_strpos($stats_secure_const['forward_ip'], ', ') && isset($stats_secure_const['forward_ip'])) {
1038
        $x_forwardeds = explode(', ', $stats_secure_const['forward_ip']);
1039
        if ('unknown' !== $x_forwardeds[0] && 'none' !== $x_forwardeds[0] && !empty($x_forwardeds[0]) && !is_reserved($x_forwardeds[0])) {
1040
            $stats_secure_const['forward_ip'] = $x_forwardeds[0];
1041
        } else {
1042
            $stats_secure_const['forward_ip'] = $x_forwardeds[1];
1043
        }
1044
    }
1045
    if (mb_strpos($stats_secure_const['remote_addr'], ', ') && isset($stats_secure_const['remote_addr'])) {
1046
        $remote_addrs = explode(', ', $stats_secure_const['remote_addr']);
1047
        if ('unknown' !== $remote_addrs[0] && 'none' !== $remote_addrs[0] && !empty($remote_addrs[0]) && !is_reserved($remote_addrs[0])) {
1048
            $stats_secure_const['remote_addr'] = $remote_addrs[0];
1049
        } else {
1050
            $stats_secure_const['remote_addr'] = $remote_addrs[1];
1051
        }
1052
    }
1053
    if (isset($stats_secure_const['client_ip']) && false === mb_stripos($stats_secure_const['client_ip'], 'none')
1054
        && false === mb_stripos($stats_secure_const['client_ip'], 'unknown') /* && !is_reserved($stats_secure_const['client_ip']) */) {
1055
        return $stats_secure_const['client_ip'];
1056
    } elseif (isset($stats_secure_const['forward_ip']) && false === mb_stripos($stats_secure_const['forward_ip'], 'none')
1057
              && false === mb_stripos($stats_secure_const['forward_ip'], 'unknown') /* && !is_reserved($stats_secure_const['forward_ip']) */) {
1058
        return $stats_secure_const['forward_ip'];
1059
    } elseif (isset($stats_secure_const['remote_addr']) && false === mb_stripos($stats_secure_const['remote_addr'], 'none')
1060
              && false === mb_stripos($stats_secure_const['remote_addr'], 'unknown') /* && !is_reserved($stats_secure_const['remote_addr']) */) {
1061
        return $stats_secure_const['remote_addr'];
1062
    }
1063
1064
    return 'none';
1065
}
1066
1067
function get_server_ip()
1068
{
1069
    return stats_getservervar('SERVER_ADDR');
1070
}
1071
1072
function get_client_ip()
1073
{
1074
    return stats_getservervar('HTTP_CLIENT_IP');
1075
}
1076
1077
function get_x_forwarded()
1078
{
1079
    return stats_getservervar('HTTP_X_FORWARDED_FOR');
1080
}
1081
1082
function get_remote_addr()
1083
{
1084
    return stats_getservervar('REMOTE_ADDR');
1085
}
1086
1087
if (false === checkNoCountIP()) {
1088
    getGeneralStats();
1089
}
1090
1091
getRemoteAddr();
1092
getRemoteReferer();
1093
getScreenDims();
1094