Helpers
last analyzed

Complexity

Total Complexity 0

Size/Duplication

Total Lines 2
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
wmc 0
1
<?php
2
/**
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * php version 7.1.0
11
 *
12
 * @category  Web-security
13
 * @package   Shieldon
14
 * @author    Terry Lin <[email protected]>
15
 * @copyright 2019 terrylinooo
16
 * @license   https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT
17
 * @link      https://github.com/terrylinooo/shieldon
18
 * @see       https://shieldon.io
19
 */
20
21
declare(strict_types=1);
22
23
namespace Shieldon\Firewall;
24
25
use Psr\Http\Message\ServerRequestInterface;
26
use Psr\Http\Message\ResponseInterface;
27
use Shieldon\Firewall\Container;
28
use Shieldon\Firewall\Driver\FileDriver;
29
use Shieldon\Firewall\HttpFactory;
30
use Shieldon\Firewall\Session;
31
use function explode;
32
use function file_exists;
33
use function file_put_contents;
34
use function func_get_arg;
35
use function func_num_args;
36
use function implode;
37
use function is_array;
38
use function is_null;
39
use function md5;
40
use function microtime;
41
use function preg_split;
42
use function rand;
43
use function round;
44
use function shell_exec;
45
use function str_repeat;
46
use function str_replace;
47
use function stripos;
48
use function strtoupper;
49
use function substr;
50
use function sys_getloadavg;
51
use function time;
52
use function trim;
53
use const PHP_OS;
54
55
/**
56
 * This value will be only displayed on Firewall Panel.
57
 */
58
define('SHIELDON_FIREWALL_VERSION', '2.0');
59
60
/**
61
 * Just use PSR-4 autoloader to load those helper functions.
62
 */
63
class Helpers
64
{
65
66
}
67
68
/**
69
 *   Public methods       | Desctiotion
70
 *  ----------------------|---------------------------------------------
71
 *  __                    | Get locale message.
72
 *  _e                    | Echo string from __()
73
 *  get_user_lang         | Get user lang.
74
 *  include_i18n_file     | Include i18n file.
75
 *  mask_string           | Mask strings with asterisks.
76
 *  get_cpu_usage         | Get current CPU usage information.
77
 *  get_memory_usage      | Get current RAM usage information.
78
 *  get_default_properties| The default settings of Shieldon core.
79
 *  get_request           | Get PSR-7 HTTP server request from container.
80
 *  get_response          | Get PSR-7 HTTP response from container.
81
 *  set_request           | Set PSR-7 HTTP server request to container.
82
 *  set_response          | Set PSR-7 HTTP response to container.
83
 *  unset_global_cookie   | Unset superglobal COOKIE variable.F
84
 *  unset_global_post     | Unset superglobal POST variable.
85
 *  unset_global_get      | Unset superglobal GET variable.
86
 *  unset_global_session  | Unset superglobal SESSION variable.
87
 *  unset_superglobal     | Unset superglobal variables.
88
 *  get_ip                | Get an IP address from container.
89
 *  set_ip                | Set an IP address to container.
90
 *  get_microtimestamp    | Get the microtimestamp.
91
 *  get_session_instance  | Get a session instance.
92
 *  create_new_session_i- | Create a new session instance for current user.
93
 *  n stance              |
94
 *  get_mock_session      | For unit testing purpose.
95
 *  set_session_instance  | Set a session instance to container.
96
 *  get_session_id        | Get session ID from cookie or creating new.
97
 *  create_session_id     | Create a new session ID.
98
 *  ----------------------|---------------------------------------------
99
 */
100
101
/**
102
 * Get locale message.
103
 *
104
 * @return string
105
 */
106
function __(): string
107
{
108
    /**
109
     * Load locale string from i18n files and store them into this array
110
     * for further use.
111
     *
112
     * @var array
113
     */
114
    static $i18n;
115
116
    /**
117
     * Check the file exists for not.
118
     *
119
     * @var array
120
     */
121
    static $fileChecked;
122
123
    $num = func_num_args();
124
125
    $filename    = func_get_arg(0); // required.
126
    $langcode    = func_get_arg(1); // required.
127
    $placeholder = ($num > 2) ? func_get_arg(2) : '';
128
    $replacement = ($num > 3) ? func_get_arg(3) : [];
129
    $lang        = get_user_lang();
130
131
    if (empty($i18n[$filename]) && empty($fileChecked[$filename])) {
132
        $fileChecked[$filename] = true;
133
        $i18n[$filename] = include_i18n_file($lang, $filename);
134
    }
135
136
    // If we don't get the string from the localization file, use placeholder
137
    // instead.
138
    $resultString = $placeholder;
139
140
    if (!empty($i18n[$filename][$langcode])) {
141
        $resultString = $i18n[$filename][$langcode];
142
    }
143
144
    if (is_array($replacement)) {
145
        /**
146
         * Example:
147
         *     __('test', 'example_string', 'Search results: {0} items. Total items: {1}.', [5, 150]);
148
         *
149
         * Result:
150
         *     Search results: 5 items. Total items: 150.
151
         */
152
        foreach ($replacement as $i => $r) {
153
            $resultString = str_replace('{' . $i . '}', (string) $replacement[$i], (string) $resultString);
154
        }
155
    }
156
    
157
    return str_replace("'", '’', $resultString);
158
}
159
160
/**
161
 * Echo string from __()
162
 *
163
 * @return void
164
 */
165
function _e(): void
166
{
167
    $num = func_num_args();
168
169
    $filename    = func_get_arg(0); // required.
170
    $langcode    = func_get_arg(1); // required.
171
    $placeholder = ($num > 2) ? func_get_arg(2) : '';
172
    $replacement = ($num > 3) ? func_get_arg(3) : [];
173
174
    echo __($filename, $langcode, $placeholder, $replacement);
175
}
176
177
/**
178
 * Get user lang.
179
 *
180
 * This method is a part of  __()
181
 *
182
 * @return string
183
 */
184
function get_user_lang(): string
185
{
186
    static $lang;
187
188
    if (!$lang) {
189
        $lang = 'en';
190
191
        // Fetch session variables.
192
        $session = get_session_instance();
193
        $panelLang = $session->get('shieldon_panel_lang');
194
        $uiLang = $session->get('shieldon_ui_lang');
195
    
196
        if (!empty($panelLang)) {
197
            $lang = $panelLang;
198
        } elseif (!empty($uiLang)) {
199
            $lang = $uiLang;
200
        }
201
    }
202
203
    return $lang;
204
}
205
206
/**
207
 * Include i18n file.
208
 *
209
 * This method is a part of  __()
210
 *
211
 * @param string $lang     The language code.
212
 * @param string $filename The i18n language pack file.
213
 *
214
 * @return void
215
 */
216
function include_i18n_file(string $lang, string $filename): array
217
{
218
    $content = [];
219
    $lang = str_replace('-', '_', $lang);
220
221
    if (stripos($lang, 'zh_') !== false) {
222
        if (stripos($lang, 'zh_CN') !== false) {
223
            $lang = 'zh_CN';
224
        } else {
225
            $lang = 'zh';
226
        }
227
    }
228
229
    $file = __DIR__ . '/../../localization/' . $lang . '/' . $filename . '.php';
230
    
231
    if (file_exists($file)) {
232
        $content = include $file;
233
    }
234
235
    return $content;
236
}
237
238
/**
239
 * Mask strings with asterisks.
240
 *
241
 * @param string $str The text.
242
 *
243
 * @return string
244
 */
245
function mask_string($str): string
246
{
247
    if (filter_var($str, FILTER_VALIDATE_IP) !== false) {
248
        $tmp = explode('.', $str);
249
        $tmp[0] = '*';
250
        $tmp[1] = '*';
251
        $masked = implode('.', $tmp);
252
    } else {
253
        $masked = str_repeat('*', strlen($str) - 6) . substr($str, -6);
254
    }
255
256
    return $masked;
257
}
258
259
/**
260
 * Get current CPU usage information.
261
 *
262
 * This function is only used in sending notifications and it is unavailable
263
 * on Win system. If you are using shared hosting and your hosting provider
264
 * has disabled `sys_getloadavg` and `shell_exec`, it won't work either.
265
 *
266
 * @return string
267
 */
268
function get_cpu_usage(): string
269
{
270
    $return = '';
271
272
    // This feature is not available on Windows platform.
273
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
274
        return $return;
275
    }
276
277
    $cpuLoads = @sys_getloadavg();
278
    $cpuCores = trim(@shell_exec("grep -P '^processor' /proc/cpuinfo|wc -l"));
0 ignored issues
show
Bug introduced by
It seems like @shell_exec('grep -P '^p...' /proc/cpuinfo|wc -l') can also be of type false and null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

278
    $cpuCores = trim(/** @scrutinizer ignore-type */ @shell_exec("grep -P '^processor' /proc/cpuinfo|wc -l"));
Loading history...
279
280
    if (!empty($cpuCores) && !empty($cpuLoads)) {
281
        $return = round($cpuLoads[1] / ($cpuCores + 1) * 100, 0) . '%';
282
    }
283
    return $return;
284
}
285
286
/**
287
 * Get current RAM usage information.
288
 *
289
 * If you are using shared hosting and your hosting provider has disabled
290
 * `shell_exec`, this function may not work as expected.
291
 *
292
 * @return string
293
 */
294
function get_memory_usage(): string
295
{
296
    $return = '';
297
298
    // This feature is not available on Windows platform.
299
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
300
        return $return;
301
    }
302
303
    $freeResult = explode("\n", trim(@shell_exec('free')));
0 ignored issues
show
Bug introduced by
It seems like @shell_exec('free') can also be of type false and null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

303
    $freeResult = explode("\n", trim(/** @scrutinizer ignore-type */ @shell_exec('free')));
Loading history...
304
305
    if (!empty($freeResult)) {
306
        $parsed = preg_split("/[\s]+/", $freeResult[1]);
307
        $return = round($parsed[2] / $parsed[1] * 100, 0) . '%';
308
    }
309
    return $return;
310
}
311
312
/**
313
 * The default settings of Shieldon core.
314
 *
315
 * @return array
316
 */
317
function get_default_properties(): array
318
{
319
    return [
320
321
        'time_unit_quota' => [
322
            's' => 2,
323
            'm' => 10,
324
            'h' => 30,
325
            'd' => 60,
326
        ],
327
328
        'time_reset_limit'       => 3600,
329
        'interval_check_referer' => 5,
330
        'interval_check_session' => 5,
331
        'limit_unusual_behavior' => [
332
            'cookie'  => 5,
333
            'session' => 5,
334
            'referer' => 10,
335
        ],
336
337
        'cookie_name'         => 'ssjd',
338
        'cookie_domain'       => '',
339
        'cookie_value'        => '1',
340
        'display_online_info' => true,
341
        'display_user_info'   => false,
342
        'display_http_code'   => false,
343
        'display_reason_code' => false,
344
        'display_reason_text' => false,
345
346
        /**
347
         * If you set this option enabled, Shieldon will record every CAPTCHA fails
348
         * in a row, once that user have reached the limitation number, Shieldon will
349
         * put it as a blocked IP in rule table, until the new data cycle begins.
350
         *
351
         * Once that user have been blocked, they are still access the warning page,
352
         * it means that they are not humain for sure, so let's throw them into the
353
         * system firewall and say goodbye to them forever.
354
         */
355
        'deny_attempt_enable' => [
356
            'data_circle'     => false,
357
            'system_firewall' => false,
358
        ],
359
360
        'deny_attempt_notify' => [
361
            'data_circle'     => false,
362
            'system_firewall' => false,
363
        ],
364
365
        'deny_attempt_buffer' => [
366
            'data_circle'     => 10,
367
            'system_firewall' => 10,
368
        ],
369
370
        /**
371
         * To prevent dropping social platform robots into iptables firewall, such
372
         * as Facebook, Line and others who scrape snapshots from your web pages,
373
         * you should adjust the values below to fit your needs. (unit: second)
374
         */
375
        'record_attempt_detection_period' => 5, // 5 seconds.
376
377
        // Reset the counter after n second.
378
        'reset_attempt_counter' => 1800, // 30 minutes.
379
380
        // System-layer firewall, ip6table service watches this folder to
381
        // receive command created by Shieldon Firewall.
382
        'iptables_watching_folder' => '/tmp/',
383
    ];
384
}
385
386
/*
387
|--------------------------------------------------------------------------
388
| PSR-7 helpers.
389
|--------------------------------------------------------------------------
390
*/
391
392
/**
393
 * PSR-7 HTTP server request
394
 *
395
 * @return ServerRequestInterface
396
 */
397
function get_request(): ServerRequestInterface
398
{
399
    $request = Container::get('request');
400
401
    if (is_null($request)) {
402
        $request = HttpFactory::createRequest();
403
        Container::set('request', $request);
404
    }
405
406
    return $request;
407
}
408
409
/**
410
 * PSR-7 HTTP response.
411
 *
412
 * @return ResponseInterface
413
 */
414
function get_response(): ResponseInterface
415
{
416
    $response = Container::get('response');
417
418
    if (is_null($response)) {
419
        $response = HttpFactory::createResponse();
420
        Container::set('response', $response);
421
    }
422
423
    return $response;
424
}
425
426
/**
427
 * Set a PSR-7 HTTP server request into container.
428
 *
429
 * @param ServerRequestInterface $request The PSR-7 server request.
430
 *
431
 * @return void
432
 */
433
function set_request(ServerRequestInterface $request): void
434
{
435
    Container::set('request', $request, true);
436
}
437
438
/**
439
 * Set a PSR-7 HTTP response into container.
440
 *
441
 * @param ResponseInterface $response The PSR-7 server response.
442
 *
443
 * @return void
444
 */
445
function set_response(ResponseInterface $response): void
446
{
447
    Container::set('response', $response, true);
448
}
449
450
/*
451
|--------------------------------------------------------------------------
452
| Superglobal variables.
453
|--------------------------------------------------------------------------
454
*/
455
456
/**
457
 * Unset cookie.
458
 *
459
 * @param string|null $name The name (key) in the array of the superglobal.
460
 *
461
 * @return void
462
 */
463
function unset_global_cookie($name = null): void
464
{
465
    if (empty($name)) {
466
        $cookieParams = get_request()->getCookieParams();
467
        set_request(get_request()->withCookieParams([]));
468
469
        foreach (array_keys($cookieParams) as $name) {
470
            set_response(
471
                get_response()->withHeader(
472
                    'Set-Cookie',
473
                    "$name=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0"
474
                )
475
            );
476
        }
477
        $_COOKIE = [];
478
479
        return;
480
    }
481
482
    $cookieParams = get_request()->getCookieParams();
483
    unset($cookieParams[$name]);
484
485
    set_request(
486
        get_request()->withCookieParams(
487
            $cookieParams
488
        )
489
    );
490
491
    set_response(
492
        get_response()->withHeader(
493
            'Set-Cookie',
494
            "$name=; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0"
495
        )
496
    );
497
    // Prevent direct access to superglobal.
498
    unset($_COOKIE[$name]);
499
}
500
501
/**
502
 * Unset post.
503
 *
504
 * @param string|null $name The name (key) in the array of the superglobal.
505
 *
506
 * @return void
507
 */
508
function unset_global_post($name = null): void
509
{
510
    if (empty($name)) {
511
        set_request(get_request()->withParsedBody([]));
512
        $_POST = [];
513
514
        return;
515
    }
516
517
    $postParams = get_request()->getParsedBody();
518
    unset($postParams[$name]);
519
    set_request(get_request()->withParsedBody($postParams));
520
    unset($_POST[$name]);
521
}
522
523
/**
524
 * Unset get.
525
 *
526
 * @param string|null $name The name (key) in the array of the superglobal.
527
 *
528
 * @return void
529
 */
530
function unset_global_get($name = null): void
531
{
532
    if (empty($name)) {
533
        set_request(get_request()->withQueryParams([]));
534
        $_GET = [];
535
536
        return;
537
    }
538
539
    $getParams = get_request()->getQueryParams();
540
    unset($getParams[$name]);
541
    set_request(get_request()->withQueryParams($getParams));
542
    unset($_GET[$name]);
543
}
544
545
/**
546
 * Unset session.
547
 *
548
 * @param string|null $name The name (key) in the array of the superglobal.
549
 *
550
 * @return void
551
 */
552
function unset_global_session($name = null): void
553
{
554
    if (empty($name)) {
555
        get_session_instance()->clear();
556
        get_session_instance()->save();
557
        return;
558
    }
559
560
    get_session_instance()->remove($name);
561
    get_session_instance()->save();
562
}
563
564
/**
565
 * Unset a variable of superglobal.
566
 *
567
 * @param string|null $name The name (key) in the array of the superglobal.
568
 *                          If $name is null that means clear all.
569
 * @param string      $type The type of the superglobal.
570
 *
571
 * @return void
572
 */
573
function unset_superglobal($name, string $type): void
574
{
575
    $types = [
576
        'get',
577
        'post',
578
        'cookie',
579
        'session',
580
    ];
581
582
    if (!in_array($type, $types)) {
583
        return;
584
    }
585
586
    $method = '\Shieldon\Firewall\unset_global_' . $type;
587
    $method($name, $type);
588
}
589
590
/*
591
|--------------------------------------------------------------------------
592
| IP address.
593
|--------------------------------------------------------------------------
594
*/
595
596
/**
597
 * Get an IP address.
598
 *
599
 * @return string
600
 */
601
function get_ip(): string
602
{
603
    $ip = Container::get('ip_address');
604
    
605
    if (empty($ip)) {
606
        $ip = $_SERVER['REMOTE_ADDR'];
607
    }
608
609
    return $ip;
610
}
611
612
/**
613
 * Set an IP address.
614
 *
615
 * @param string $ip An IP address.
616
 *
617
 * @return void
618
 */
619
function set_ip(string $ip)
620
{
621
    Container::set('ip_address', $ip, true);
622
}
623
624
/*
625
|--------------------------------------------------------------------------
626
| Time.
627
|--------------------------------------------------------------------------
628
*/
629
630
/**
631
 * Get the microtimestamp.
632
 *
633
 * @return string
634
 */
635
function get_microtimestamp()
636
{
637
    $microtimestamp = explode(' ', microtime());
638
    $microtimestamp = $microtimestamp[1] . str_replace('0.', '', $microtimestamp[0]);
639
640
    return $microtimestamp;
641
}
642
643
/*
644
|--------------------------------------------------------------------------
645
| Session.
646
|--------------------------------------------------------------------------
647
*/
648
649
/**
650
 * Session
651
 *
652
 * @return Session
653
 */
654
function get_session_instance(): Session
655
{
656
    $session = Container::get('session');
657
658
    if (is_null($session)) {
659
        $session = HttpFactory::createSession(get_session_id());
660
        set_session_instance($session);
661
    }
662
663
    return $session;
664
}
665
666
/**
667
 * For unit testing purpose. Not use in production.
668
 * Create new session by specifying a session ID.
669
 *
670
 * @param string $sessionId A session ID string.
671
 *
672
 * @return void
673
 */
674
function create_new_session_instance(string $sessionId)
675
{
676
    Container::set('session_id', $sessionId, true);
677
    $session = Container::get('session');
678
679
    if ($session instanceof Session) {
680
        $session->setId($sessionId);
681
        set_session_instance($session);
682
    }
683
}
684
685
/**
686
 * For unit testing purpose. Not use in production.
687
 *
688
 * @param string $sessionId A session ID string.
689
 *
690
 * @return Session
691
 */
692
function get_mock_session($sessionId): Session
693
{
694
    Container::set('session_id', $sessionId, true);
695
696
    // Constant BOOTSTRAP_DIR is available in unit testing mode.
697
    $fileDriverStorage = BOOTSTRAP_DIR . '/../tmp/shieldon/data_driver_file';
698
    $dir = $fileDriverStorage . '/shieldon_sessions';
699
    $file = $dir . '/' . $sessionId . '.json';
700
701
    if (!is_dir($dir)) {
702
        $originalUmask = umask(0);
703
704
        if (!is_dir($dir)) {
705
            mkdir($dir, 0777, true);
706
        }
707
708
        umask($originalUmask);
709
    }
710
711
    $session = HttpFactory::createSession($sessionId);
712
713
    $driver = new FileDriver($fileDriverStorage);
714
715
    if (!file_exists($file)) {
716
        $data = [];
717
718
        // Prepare mock data.
719
        $data['id'] = $sessionId;
720
        $data['ip'] = get_ip();
721
        $data['time'] = time();
722
        $data['microtimestamp'] = get_microtimestamp();
723
        $data['data'] = '{}';
724
    
725
        $json = json_encode($data);
726
        
727
        // Check and build the folder.
728
        $originalUmask = umask(0);
729
730
        if (!is_dir($dir)) {
731
            mkdir($dir, 0777, true);
732
        }
733
734
        umask($originalUmask);
735
736
        file_put_contents($file, $json);
737
    }
738
739
    $session->init($driver);
740
741
    Container::set('session', $session, true);
742
743
    return $session;
744
}
745
746
/**
747
 * Set the Session, if exists, it will be overwritten.
748
 *
749
 * @param Session $session The session instance.
750
 *
751
 * @return void
752
 */
753
function set_session_instance(Session $session): void
754
{
755
    Container::set('session', $session, true);
756
}
757
758
/**
759
 * Get session ID.
760
 *
761
 * @return string
762
 */
763
function get_session_id(): string
764
{
765
    static $sessionId;
766
767
    if (!$sessionId) {
768
        $cookie = get_request()->getCookieParams();
769
770
        if (!empty($cookie['_shieldon'])) {
771
            $sessionId = $cookie['_shieldon'];
772
        } else {
773
            $sessionId = create_session_id();
774
        }
775
    }
776
777
    return $sessionId;
778
}
779
780
/**
781
 * Create a hash code for the Session ID.
782
 *
783
 * @return string
784
 */
785
function create_session_id(): string
786
{
787
    $hash = rand() . 'ej;1zj47vu;3e;31g642941ek62au/41' . time();
788
789
    return md5($hash);
790
}
791