Completed
Pull Request — 6.0 (#2499)
by
unknown
02:14
created

Request::subDomain()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 3
b 0
f 0
nc 4
nop 0
dl 0
loc 15
ccs 7
cts 8
cp 0.875
crap 4.0312
rs 10
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use ArrayAccess;
16
use think\file\UploadedFile;
17
use think\route\Rule;
18
19
/**
20
 * 请求管理类
21
 * @package think
22
 */
23
class Request implements ArrayAccess
24
{
25
    /**
26
     * 兼容PATH_INFO获取
27
     * @var array
28
     */
29
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
30
31
    /**
32
     * PATHINFO变量名 用于兼容模式
33
     * @var string
34
     */
35
    protected $varPathinfo = 's';
36
37
    /**
38
     * 请求类型
39
     * @var string
40
     */
41
    protected $varMethod = '_method';
42
43
    /**
44
     * 表单ajax伪装变量
45
     * @var string
46
     */
47
    protected $varAjax = '_ajax';
48
49
    /**
50
     * 表单pjax伪装变量
51
     * @var string
52
     */
53
    protected $varPjax = '_pjax';
54
55
    /**
56
     * 域名根
57
     * @var string
58
     */
59
    protected $rootDomain = '';
60
61
    /**
62
     * HTTPS代理标识
63
     * @var string
64
     */
65
    protected $httpsAgentName = '';
66
67
    /**
68
     * 前端代理服务器IP
69
     * @var array
70
     */
71
    protected $proxyServerIp = [];
72
73
    /**
74
     * 前端代理服务器真实IP头
75
     * @var array
76
     */
77
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
78
79
    /**
80
     * 请求类型
81
     * @var string
82
     */
83
    protected $method;
84
85
    /**
86
     * 域名(含协议及端口)
87
     * @var string
88
     */
89
    protected $domain;
90
91
    /**
92
     * HOST(含端口)
93
     * @var string
94
     */
95
    protected $host;
96
97
    /**
98
     * 子域名
99
     * @var string
100
     */
101
    protected $subDomain;
102
103
    /**
104
     * 泛域名
105
     * @var string
106
     */
107
    protected $panDomain;
108
109
    /**
110
     * 当前URL地址
111
     * @var string
112
     */
113
    protected $url;
114
115
    /**
116
     * 基础URL
117
     * @var string
118
     */
119
    protected $baseUrl;
120
121
    /**
122
     * 当前执行的文件
123
     * @var string
124
     */
125
    protected $baseFile;
126
127
    /**
128
     * 访问的ROOT地址
129
     * @var string
130
     */
131
    protected $root;
132
133
    /**
134
     * pathinfo
135
     * @var string
136
     */
137
    protected $pathinfo;
138
139
    /**
140
     * pathinfo(不含后缀)
141
     * @var string
142
     */
143
    protected $path;
144
145
    /**
146
     * 当前请求的IP地址
147
     * @var string
148
     */
149
    protected $realIP;
150
151
    /**
152
     * 当前控制器名
153
     * @var string
154
     */
155
    protected $controller;
156
157
    /**
158
     * 当前操作名
159
     * @var string
160
     */
161
    protected $action;
162
163
    /**
164
     * 当前请求参数
165
     * @var array
166
     */
167
    protected $param = [];
168
169
    /**
170
     * 当前GET参数
171
     * @var array
172
     */
173
    protected $get = [];
174
175
    /**
176
     * 当前POST参数
177
     * @var array
178
     */
179
    protected $post = [];
180
181
    /**
182
     * 当前REQUEST参数
183
     * @var array
184
     */
185
    protected $request = [];
186
187
    /**
188
     * 当前路由对象
189
     * @var Rule
190
     */
191
    protected $rule;
192
193
    /**
194
     * 当前ROUTE参数
195
     * @var array
196
     */
197
    protected $route = [];
198
199
    /**
200
     * 中间件传递的参数
201
     * @var array
202
     */
203
    protected $middleware = [];
204
205
    /**
206
     * 当前PUT参数
207
     * @var array
208
     */
209
    protected $put;
210
211
    /**
212
     * SESSION对象
213
     * @var Session
214
     */
215
    protected $session;
216
217
    /**
218
     * COOKIE数据
219
     * @var array
220
     */
221
    protected $cookie = [];
222
223
    /**
224
     * ENV对象
225
     * @var Env
226
     */
227
    protected $env;
228
229
    /**
230
     * 当前SERVER参数
231
     * @var array
232
     */
233
    protected $server = [];
234
235
    /**
236
     * 当前FILE参数
237
     * @var array
238
     */
239
    protected $file = [];
240
241
    /**
242
     * 当前HEADER参数
243
     * @var array
244
     */
245
    protected $header = [];
246
247
    /**
248
     * 资源类型定义
249
     * @var array
250
     */
251
    protected $mimeType = [
252
        'xml'   => 'application/xml,text/xml,application/x-xml',
253
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
254
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
255
        'css'   => 'text/css',
256
        'rss'   => 'application/rss+xml',
257
        'yaml'  => 'application/x-yaml,text/yaml',
258
        'atom'  => 'application/atom+xml',
259
        'pdf'   => 'application/pdf',
260
        'text'  => 'text/plain',
261
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
262
        'csv'   => 'text/csv',
263
        'html'  => 'text/html,application/xhtml+xml,*/*',
264
    ];
265
266
    /**
267
     * 当前请求内容
268
     * @var string
269
     */
270
    protected $content;
271
272
    /**
273
     * 全局过滤规则
274
     * @var array
275
     */
276
    protected $filter;
277
278
    /**
279
     * php://input内容
280
     * @var string
281
     */
282
    // php://input
283
    protected $input;
284
285
    /**
286
     * 请求安全Key
287
     * @var string
288
     */
289
    protected $secureKey;
290
291
    /**
292
     * 是否合并Param
293
     * @var bool
294
     */
295
    protected $mergeParam = false;
296
297
    /**
298
     * 架构函数
299
     * @access public
300
     */
301 30
    public function __construct()
302
    {
303
        // 保存 php://input
304 30
        $this->input = file_get_contents('php://input');
305 30
    }
306
307 30
    public static function __make(App $app)
308
    {
309 30
        $request = new static();
310
311 30
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
312
            $header = $result;
313
        } else {
314 30
            $header = [];
315 30
            $server = $_SERVER;
316 30
            foreach ($server as $key => $val) {
317 30
                if (0 === strpos($key, 'HTTP_')) {
318
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
319 10
                    $header[$key] = $val;
320
                }
321
            }
322 30
            if (isset($server['CONTENT_TYPE'])) {
323
                $header['content-type'] = $server['CONTENT_TYPE'];
324
            }
325 30
            if (isset($server['CONTENT_LENGTH'])) {
326
                $header['content-length'] = $server['CONTENT_LENGTH'];
327
            }
328
        }
329
330 30
        $request->header = array_change_key_case($header);
0 ignored issues
show
Bug introduced by
It seems like $header can also be of type true; however, parameter $array of array_change_key_case() does only seem to accept array, 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

330
        $request->header = array_change_key_case(/** @scrutinizer ignore-type */ $header);
Loading history...
331 30
        $request->server = $_SERVER;
332 30
        $request->env    = $app->env;
333
334 30
        $inputData = $request->getInputData($request->input);
335
336 30
        $request->get     = $_GET;
337 30
        $request->post    = $_POST ?: $inputData;
338 30
        $request->put     = $inputData;
339 30
        $request->request = $_REQUEST;
340 30
        $request->cookie  = $_COOKIE;
341 30
        $request->file    = $_FILES ?? [];
342
343 30
        return $request;
344
    }
345
346
    /**
347
     * 设置当前包含协议的域名
348
     * @access public
349
     * @param  string $domain 域名
350
     * @return $this
351
     */
352
    public function setDomain(string $domain)
353
    {
354
        $this->domain = $domain;
355
        return $this;
356
    }
357
358
    /**
359
     * 获取当前包含协议的域名
360
     * @access public
361
     * @param  bool $port 是否需要去除端口号
362
     * @return string
363
     */
364
    public function domain(bool $port = false): string
365
    {
366
        return $this->scheme() . '://' . $this->host($port);
367
    }
368
369
    /**
370
     * 获取当前根域名
371
     * @access public
372
     * @return string
373
     */
374 33
    public function rootDomain(): string
375
    {
376 33
        $root = $this->rootDomain;
377
378 33
        if (!$root) {
379 33
            $item  = explode('.', $this->host());
380 33
            $count = count($item);
381 33
            $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
382
        }
383
384 33
        return $root;
385
    }
386
387
    /**
388
     * 设置当前泛域名的值
389
     * @access public
390
     * @param  string $domain 域名
391
     * @return $this
392
     */
393
    public function setSubDomain(string $domain)
394
    {
395
        $this->subDomain = $domain;
396
        return $this;
397
    }
398
399
    /**
400
     * 获取当前子域名
401
     * @access public
402
     * @return string
403
     */
404 33
    public function subDomain(): string
405
    {
406 33
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
407
            // 获取当前主域名
408 33
            $rootDomain = $this->rootDomain();
409
410 33
            if ($rootDomain) {
411 33
                $sub             = stristr($this->host(), $rootDomain, true);
412 33
                $this->subDomain = $sub ? rtrim($sub, '.') : '';
413
            } else {
414
                $this->subDomain = '';
415
            }
416
        }
417
418 33
        return $this->subDomain;
419
    }
420
421
    /**
422
     * 设置当前泛域名的值
423
     * @access public
424
     * @param  string $domain 域名
425
     * @return $this
426
     */
427
    public function setPanDomain(string $domain)
428
    {
429
        $this->panDomain = $domain;
430
        return $this;
431
    }
432
433
    /**
434
     * 获取当前泛域名的值
435
     * @access public
436
     * @return string
437
     */
438 3
    public function panDomain(): string
439
    {
440 3
        return $this->panDomain ?: '';
441
    }
442
443
    /**
444
     * 设置当前完整URL 包括QUERY_STRING
445
     * @access public
446
     * @param  string $url URL地址
447
     * @return $this
448
     */
449
    public function setUrl(string $url)
450
    {
451
        $this->url = $url;
452
        return $this;
453
    }
454
455
    /**
456
     * 获取当前完整URL 包括QUERY_STRING
457
     * @access public
458
     * @param  bool $complete 是否包含完整域名
459
     * @return string
460
     */
461
    public function url(bool $complete = false): string
462
    {
463
        if ($this->url) {
464
            $url = $this->url;
465
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
466
            $url = $this->server('HTTP_X_REWRITE_URL');
467
        } elseif ($this->server('REQUEST_URI')) {
468
            $url = $this->server('REQUEST_URI');
469
        } elseif ($this->server('ORIG_PATH_INFO')) {
470
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
471
        } elseif (isset($_SERVER['argv'][1])) {
472
            $url = $_SERVER['argv'][1];
473
        } else {
474
            $url = '';
475
        }
476
477
        return $complete ? $this->domain() . $url : $url;
478
    }
479
480
    /**
481
     * 设置当前URL 不含QUERY_STRING
482
     * @access public
483
     * @param  string $url URL地址
484
     * @return $this
485
     */
486
    public function setBaseUrl(string $url)
487
    {
488
        $this->baseUrl = $url;
489
        return $this;
490
    }
491
492
    /**
493
     * 获取当前URL 不含QUERY_STRING
494
     * @access public
495
     * @param  bool $complete 是否包含完整域名
496
     * @return string
497
     */
498
    public function baseUrl(bool $complete = false): string
499
    {
500
        if (!$this->baseUrl) {
501
            $str           = $this->url();
502
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
503
        }
504
505
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
506
    }
507
508
    /**
509
     * 获取当前执行的文件 SCRIPT_NAME
510
     * @access public
511
     * @param  bool $complete 是否包含完整域名
512
     * @return string
513
     */
514
    public function baseFile(bool $complete = false): string
515
    {
516
        if (!$this->baseFile) {
517
            $url = '';
518
            if (!$this->isCli()) {
519
                $script_name = basename($this->server('SCRIPT_FILENAME'));
520
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
521
                    $url = $this->server('SCRIPT_NAME');
522
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
523
                    $url = $this->server('PHP_SELF');
524
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
525
                    $url = $this->server('ORIG_SCRIPT_NAME');
526
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
527
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
528
                } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
529
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
530
                }
531
            }
532
            $this->baseFile = $url;
533
        }
534
535
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
536
    }
537
538
    /**
539
     * 设置URL访问根地址
540
     * @access public
541
     * @param  string $url URL地址
542
     * @return $this
543
     */
544
    public function setRoot(string $url)
545
    {
546
        $this->root = $url;
547
        return $this;
548
    }
549
550
    /**
551
     * 获取URL访问根地址
552
     * @access public
553
     * @param  bool $complete 是否包含完整域名
554
     * @return string
555
     */
556
    public function root(bool $complete = false): string
557
    {
558
        if (!$this->root) {
559
            $file = $this->baseFile();
560
            if ($file && 0 !== strpos($this->url(), $file)) {
561
                $file = str_replace('\\', '/', dirname($file));
562
            }
563
            $this->root = rtrim($file, '/');
564
        }
565
566
        return $complete ? $this->domain() . $this->root : $this->root;
567
    }
568
569
    /**
570
     * 获取URL访问根目录
571
     * @access public
572
     * @return string
573
     */
574
    public function rootUrl(): string
575
    {
576
        $base = $this->root();
577
        $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
578
579
        if ('' != $root) {
580
            $root = '/' . ltrim($root, '/');
581
        }
582
583
        return $root;
584
    }
585
586
    /**
587
     * 设置当前请求的pathinfo
588
     * @access public
589
     * @param  string $pathinfo
590
     * @return $this
591
     */
592
    public function setPathinfo(string $pathinfo)
593
    {
594
        $this->pathinfo = $pathinfo;
595
        return $this;
596
    }
597
598
    /**
599
     * 获取当前请求URL的pathinfo信息(含URL后缀)
600
     * @access public
601
     * @return string
602
     */
603
    public function pathinfo(): string
604
    {
605
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
606
            if (isset($_GET[$this->varPathinfo])) {
607
                // 判断URL里面是否有兼容模式参数
608
                $pathinfo = $_GET[$this->varPathinfo];
609
                unset($_GET[$this->varPathinfo]);
610
                unset($this->get[$this->varPathinfo]);
611
            } elseif ($this->server('PATH_INFO')) {
612
                $pathinfo = $this->server('PATH_INFO');
613
            } elseif (false !== strpos(PHP_SAPI, 'cli')) {
614
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
615
            }
616
617
            // 分析PATHINFO信息
618
            if (!isset($pathinfo)) {
619
                foreach ($this->pathinfoFetch as $type) {
620
                    if ($this->server($type)) {
621
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
622
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
623
                        break;
624
                    }
625
                }
626
            }
627
628
            if (!empty($pathinfo)) {
629
                unset($this->get[$pathinfo], $this->request[$pathinfo]);
630
            }
631
632
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
633
        }
634
635
        return $this->pathinfo;
636
    }
637
638
    /**
639
     * 当前URL的访问后缀
640
     * @access public
641
     * @return string
642
     */
643
    public function ext(): string
644
    {
645
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
646
    }
647
648
    /**
649
     * 获取当前请求的时间
650
     * @access public
651
     * @param  bool $float 是否使用浮点类型
652
     * @return integer|float
653
     */
654
    public function time(bool $float = false)
655
    {
656
        return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
657
    }
658
659
    /**
660
     * 当前请求的资源类型
661
     * @access public
662
     * @return string
663
     */
664 21
    public function type(): string
665
    {
666 21
        $accept = $this->server('HTTP_ACCEPT');
667
668 21
        if (empty($accept)) {
669 21
            return '';
670
        }
671
672
        foreach ($this->mimeType as $key => $val) {
673
            $array = explode(',', $val);
674
            foreach ($array as $k => $v) {
675
                if (stristr($accept, $v)) {
676
                    return $key;
677
                }
678
            }
679
        }
680
681
        return '';
682
    }
683
684
    /**
685
     * 设置资源类型
686
     * @access public
687
     * @param  string|array $type 资源类型名
688
     * @param  string       $val 资源类型
689
     * @return void
690
     */
691
    public function mimeType($type, $val = ''): void
692
    {
693
        if (is_array($type)) {
694
            $this->mimeType = array_merge($this->mimeType, $type);
695
        } else {
696
            $this->mimeType[$type] = $val;
697
        }
698
    }
699
700
    /**
701
     * 设置请求类型
702
     * @access public
703
     * @param  string $method 请求类型
704
     * @return $this
705
     */
706
    public function setMethod(string $method)
707
    {
708
        $this->method = strtoupper($method);
709
        return $this;
710
    }
711
712
    /**
713
     * 当前的请求类型
714
     * @access public
715
     * @param  bool $origin 是否获取原始请求类型
716
     * @return string
717
     */
718
    public function method(bool $origin = false): string
719
    {
720
        if ($origin) {
721
            // 获取原始请求类型
722
            return $this->server('REQUEST_METHOD') ?: 'GET';
723
        } elseif (!$this->method) {
724
            if (isset($this->post[$this->varMethod])) {
725
                $method = strtolower($this->post[$this->varMethod]);
726
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
727
                    $this->method    = strtoupper($method);
728
                    $this->{$method} = $this->post;
729
                } else {
730
                    $this->method = 'POST';
731
                }
732
                unset($this->post[$this->varMethod]);
733
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
734
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
735
            } else {
736
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
737
            }
738
        }
739
740
        return $this->method;
741
    }
742
743
    /**
744
     * 是否为GET请求
745
     * @access public
746
     * @return bool
747
     */
748
    public function isGet(): bool
749
    {
750
        return $this->method() == 'GET';
751
    }
752
753
    /**
754
     * 是否为POST请求
755
     * @access public
756
     * @return bool
757
     */
758
    public function isPost(): bool
759
    {
760
        return $this->method() == 'POST';
761
    }
762
763
    /**
764
     * 是否为PUT请求
765
     * @access public
766
     * @return bool
767
     */
768
    public function isPut(): bool
769
    {
770
        return $this->method() == 'PUT';
771
    }
772
773
    /**
774
     * 是否为DELTE请求
775
     * @access public
776
     * @return bool
777
     */
778
    public function isDelete(): bool
779
    {
780
        return $this->method() == 'DELETE';
781
    }
782
783
    /**
784
     * 是否为HEAD请求
785
     * @access public
786
     * @return bool
787
     */
788
    public function isHead(): bool
789
    {
790
        return $this->method() == 'HEAD';
791
    }
792
793
    /**
794
     * 是否为PATCH请求
795
     * @access public
796
     * @return bool
797
     */
798
    public function isPatch(): bool
799
    {
800
        return $this->method() == 'PATCH';
801
    }
802
803
    /**
804
     * 是否为OPTIONS请求
805
     * @access public
806
     * @return bool
807
     */
808
    public function isOptions(): bool
809
    {
810
        return $this->method() == 'OPTIONS';
811
    }
812
813
    /**
814
     * 是否为cli
815
     * @access public
816
     * @return bool
817
     */
818
    public function isCli(): bool
819
    {
820
        return PHP_SAPI == 'cli';
821
    }
822
823
    /**
824
     * 是否为cgi
825
     * @access public
826
     * @return bool
827
     */
828
    public function isCgi(): bool
829
    {
830
        return strpos(PHP_SAPI, 'cgi') === 0;
831
    }
832
833
    /**
834
     * 获取当前请求的参数
835
     * @access public
836
     * @param  string|array $name 变量名
837
     * @param  mixed        $default 默认值
838
     * @param  string|array $filter 过滤方法
839
     * @return mixed
840
     */
841 33
    public function param($name = '', $default = null, $filter = '')
842
    {
843 33
        if (empty($this->mergeParam)) {
844 33
            $method = $this->method(true);
845
846
            // 自动获取请求变量
847 22
            switch ($method) {
848 33
                case 'POST':
849 3
                    $vars = $this->post(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::post(). ( Ignorable by Annotation )

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

849
                    $vars = $this->post(/** @scrutinizer ignore-type */ false);
Loading history...
850 3
                    break;
851 33
                case 'PUT':
852 33
                case 'DELETE':
853 33
                case 'PATCH':
854
                    $vars = $this->put(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::put(). ( Ignorable by Annotation )

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

854
                    $vars = $this->put(/** @scrutinizer ignore-type */ false);
Loading history...
855
                    break;
856
                default:
857 33
                    $vars = [];
858
            }
859
860
            // 当前请求参数和URL地址中的参数合并
861 33
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::get(). ( Ignorable by Annotation )

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

861
            $this->param = array_merge($this->param, $this->get(/** @scrutinizer ignore-type */ false), $vars, $this->route(false));
Loading history...
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::route(). ( Ignorable by Annotation )

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

861
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(/** @scrutinizer ignore-type */ false));
Loading history...
862
863 33
            $this->mergeParam = true;
864
        }
865
866 33
        if (is_array($name)) {
867
            return $this->only($name, $this->param, $filter);
868
        }
869
870 33
        return $this->input($this->param, $name, $default, $filter);
871
    }
872
873
    /**
874
     * 设置路由变量
875
     * @access public
876
     * @param  Rule $rule 路由对象
877
     * @return $this
878
     */
879 33
    public function setRule(Rule $rule)
880
    {
881 33
        $this->rule = $rule;
882 33
        return $this;
883
    }
884
885
    /**
886
     * 获取当前路由对象
887
     * @access public
888
     * @return Rule|null
889
     */
890 3
    public function rule()
891
    {
892 3
        return $this->rule;
893
    }
894
895
    /**
896
     * 设置路由变量
897
     * @access public
898
     * @param  array $route 路由变量
899
     * @return $this
900
     */
901 33
    public function setRoute(array $route)
902
    {
903 33
        $this->route      = array_merge($this->route, $route);
904 33
        $this->mergeParam = false;
905 33
        return $this;
906
    }
907
908
    /**
909
     * 获取路由参数
910
     * @access public
911
     * @param  string|array $name 变量名
912
     * @param  mixed        $default 默认值
913
     * @param  string|array $filter 过滤方法
914
     * @return mixed
915
     */
916 33
    public function route($name = '', $default = null, $filter = '')
917
    {
918 33
        if (is_array($name)) {
919
            return $this->only($name, $this->route, $filter);
920
        }
921
922 33
        return $this->input($this->route, $name, $default, $filter);
923
    }
924
925
    /**
926
     * 获取GET参数
927
     * @access public
928
     * @param  string|array $name 变量名
929
     * @param  mixed        $default 默认值
930
     * @param  string|array $filter 过滤方法
931
     * @return mixed
932
     */
933 33
    public function get($name = '', $default = null, $filter = '')
934
    {
935 33
        if (is_array($name)) {
936
            return $this->only($name, $this->get, $filter);
937
        }
938
939 33
        return $this->input($this->get, $name, $default, $filter);
940
    }
941
942
    /**
943
     * 获取中间件传递的参数
944
     * @access public
945
     * @param  mixed $name 变量名
946
     * @param  mixed $default 默认值
947
     * @return mixed
948
     */
949
    public function middleware($name, $default = null)
950
    {
951
        return $this->middleware[$name] ?? $default;
952
    }
953
954
    /**
955
     * 获取POST参数
956
     * @access public
957
     * @param  string|array $name 变量名
958
     * @param  mixed        $default 默认值
959
     * @param  string|array $filter 过滤方法
960
     * @return mixed
961
     */
962 3
    public function post($name = '', $default = null, $filter = '')
963
    {
964 3
        if (is_array($name)) {
965
            return $this->only($name, $this->post, $filter);
966
        }
967
968 3
        return $this->input($this->post, $name, $default, $filter);
969
    }
970
971
    /**
972
     * 获取PUT参数
973
     * @access public
974
     * @param  string|array $name 变量名
975
     * @param  mixed        $default 默认值
976
     * @param  string|array $filter 过滤方法
977
     * @return mixed
978
     */
979
    public function put($name = '', $default = null, $filter = '')
980
    {
981
        if (is_array($name)) {
982
            return $this->only($name, $this->put, $filter);
983
        }
984
985
        return $this->input($this->put, $name, $default, $filter);
986
    }
987
988 30
    protected function getInputData($content): array
989
    {
990 30
        $contentType = $this->contentType();
991 30
        if ('application/x-www-form-urlencoded' == $contentType) {
992
            parse_str($content, $data);
993
            return $data;
994 30
        } elseif (false !== strpos($contentType, 'json')) {
995
            return (array) json_decode($content, true);
996
        }
997
998 30
        return [];
999
    }
1000
1001
    /**
1002
     * 设置获取DELETE参数
1003
     * @access public
1004
     * @param  mixed        $name 变量名
1005
     * @param  mixed        $default 默认值
1006
     * @param  string|array $filter 过滤方法
1007
     * @return mixed
1008
     */
1009
    public function delete($name = '', $default = null, $filter = '')
1010
    {
1011
        return $this->put($name, $default, $filter);
1012
    }
1013
1014
    /**
1015
     * 设置获取PATCH参数
1016
     * @access public
1017
     * @param  mixed        $name 变量名
1018
     * @param  mixed        $default 默认值
1019
     * @param  string|array $filter 过滤方法
1020
     * @return mixed
1021
     */
1022
    public function patch($name = '', $default = null, $filter = '')
1023
    {
1024
        return $this->put($name, $default, $filter);
1025
    }
1026
1027
    /**
1028
     * 获取request变量
1029
     * @access public
1030
     * @param  string|array $name 数据名称
1031
     * @param  mixed        $default 默认值
1032
     * @param  string|array $filter 过滤方法
1033
     * @return mixed
1034
     */
1035
    public function request($name = '', $default = null, $filter = '')
1036
    {
1037
        if (is_array($name)) {
1038
            return $this->only($name, $this->request, $filter);
1039
        }
1040
1041
        return $this->input($this->request, $name, $default, $filter);
1042
    }
1043
1044
    /**
1045
     * 获取环境变量
1046
     * @access public
1047
     * @param  string $name 数据名称
1048
     * @param  string $default 默认值
1049
     * @return mixed
1050
     */
1051
    public function env(string $name = '', string $default = null)
1052
    {
1053
        if (empty($name)) {
1054
            return $this->env->get();
1055
        } else {
1056
            $name = strtoupper($name);
1057
        }
1058
1059
        return $this->env->get($name, $default);
1060
    }
1061
1062
    /**
1063
     * 获取session数据
1064
     * @access public
1065
     * @param  string $name 数据名称
1066
     * @param  string $default 默认值
1067
     * @return mixed
1068
     */
1069
    public function session(string $name = '', $default = null)
1070
    {
1071
        if ('' === $name) {
1072
            return $this->session->all();
0 ignored issues
show
Bug introduced by
The method all() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1072
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1073
        }
1074
        return $this->session->get($name, $default);
0 ignored issues
show
Bug introduced by
The method get() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1074
        return $this->session->/** @scrutinizer ignore-call */ get($name, $default);
Loading history...
1075
    }
1076
1077
    /**
1078
     * 获取cookie参数
1079
     * @access public
1080
     * @param  mixed        $name 数据名称
1081
     * @param  string       $default 默认值
1082
     * @param  string|array $filter 过滤方法
1083
     * @return mixed
1084
     */
1085
    public function cookie(string $name = '', $default = null, $filter = '')
1086
    {
1087
        if (!empty($name)) {
1088
            $data = $this->getData($this->cookie, $name, $default);
1089
        } else {
1090
            $data = $this->cookie;
1091
        }
1092
1093
        // 解析过滤器
1094
        $filter = $this->getFilter($filter, $default);
1095
1096
        if (is_array($data)) {
1097
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1098
        } else {
1099
            $this->filterValue($data, $name, $filter);
1100
        }
1101
1102
        return $data;
1103
    }
1104
1105
    /**
1106
     * 获取server参数
1107
     * @access public
1108
     * @param  string $name 数据名称
1109
     * @param  string $default 默认值
1110
     * @return mixed
1111
     */
1112 21
    public function server(string $name = '', string $default = '')
1113
    {
1114 21
        if (empty($name)) {
1115
            return $this->server;
1116
        } else {
1117 21
            $name = strtoupper($name);
1118
        }
1119
1120 21
        return $this->server[$name] ?? $default;
1121
    }
1122
1123
    /**
1124
     * 获取上传的文件信息
1125
     * @access public
1126
     * @param  string $name 名称
1127
     * @return null|array|UploadedFile
1128
     */
1129
    public function file(string $name = '')
1130
    {
1131
        $files = $this->file;
1132
        if (!empty($files)) {
1133
1134
            if (strpos($name, '.')) {
1135
                [$name, $sub] = explode('.', $name);
1136
            }
1137
1138
            // 处理上传文件
1139
            $array = $this->dealUploadFile($files, $name);
1140
1141
            if ('' === $name) {
1142
                // 获取全部文件
1143
                return $array;
1144
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1145
                return $array[$name][$sub];
1146
            } elseif (isset($array[$name])) {
1147
                return $array[$name];
1148
            }
1149
        }
1150
    }
1151
1152
    protected function dealUploadFile(array $files, string $name): array
1153
    {
1154
        $array = [];
1155
        foreach ($files as $key => $file) {
1156
            if (is_array($file['name'])) {
1157
                $item  = [];
1158
                $keys  = array_keys($file);
1159
                $count = count($file['name']);
1160
1161
                for ($i = 0; $i < $count; $i++) {
1162
                    if ($file['error'][$i] > 0) {
1163
                        if ($name == $key) {
1164
                            $this->throwUploadFileError($file['error'][$i]);
1165
                        } else {
1166
                            continue;
1167
                        }
1168
                    }
1169
1170
                    $temp['key'] = $key;
1171
1172
                    foreach ($keys as $_key) {
1173
                        $temp[$_key] = $file[$_key][$i];
1174
                    }
1175
1176
                    $item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
1177
                }
1178
1179
                $array[$key] = $item;
1180
            } else {
1181
                if ($file instanceof File) {
1182
                    $array[$key] = $file;
1183
                } else {
1184
                    if ($file['error'] > 0) {
1185
                        if ($key == $name) {
1186
                            $this->throwUploadFileError($file['error']);
1187
                        } else {
1188
                            continue;
1189
                        }
1190
                    }
1191
1192
                    $array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
1193
                }
1194
            }
1195
        }
1196
1197
        return $array;
1198
    }
1199
1200
    protected function throwUploadFileError($error)
1201
    {
1202
        static $fileUploadErrors = [
1203
            1 => 'upload File size exceeds the maximum value',
1204
            2 => 'upload File size exceeds the maximum value',
1205
            3 => 'only the portion of file is uploaded',
1206
            4 => 'no file to uploaded',
1207
            6 => 'upload temp dir not found',
1208
            7 => 'file write error',
1209
        ];
1210
1211
        $msg = $fileUploadErrors[$error];
1212
        throw new Exception($msg, $error);
1213
    }
1214
1215
    /**
1216
     * 设置或者获取当前的Header
1217
     * @access public
1218
     * @param  string $name header名称
1219
     * @param  string $default 默认值
1220
     * @return string|array
1221
     */
1222 30
    public function header(string $name = '', string $default = null)
1223
    {
1224 30
        if ('' === $name) {
1225
            return $this->header;
1226
        }
1227
1228 30
        $name = str_replace('_', '-', strtolower($name));
1229
1230 30
        return $this->header[$name] ?? $default;
1231
    }
1232
1233
    /**
1234
     * 获取变量 支持过滤和默认值
1235
     * @access public
1236
     * @param  array        $data 数据源
1237
     * @param  string|false $name 字段名
1238
     * @param  mixed        $default 默认值
1239
     * @param  string|array $filter 过滤函数
1240
     * @return mixed
1241
     */
1242 33
    public function input(array $data = [], $name = '', $default = null, $filter = '')
1243
    {
1244 33
        if (false === $name) {
1245
            // 获取原始数据
1246 33
            return $data;
1247
        }
1248
1249 33
        $name = (string) $name;
1250 33
        if ('' != $name) {
1251
            // 解析name
1252
            if (strpos($name, '/')) {
1253
                [$name, $type] = explode('/', $name);
1254
            }
1255
1256
            $data = $this->getData($data, $name);
1257
1258
            if (is_null($data)) {
1259
                return $default;
1260
            }
1261
1262
            if (is_object($data)) {
1263
                return $data;
1264
            }
1265
        }
1266
1267 33
        $data = $this->filterData($data, $filter, $name, $default);
1268
1269 33
        if (isset($type) && $data !== $default) {
1270
            // 强制类型转换
1271
            $this->typeCast($data, $type);
1272
        }
1273
1274 33
        return $data;
1275
    }
1276
1277 33
    protected function filterData($data, $filter, $name, $default)
1278
    {
1279
        // 解析过滤器
1280 33
        $filter = $this->getFilter($filter, $default);
1281
1282 33
        if (is_array($data)) {
1283 33
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1284
        } else {
1285
            $this->filterValue($data, $name, $filter);
1286
        }
1287
1288 33
        return $data;
1289
    }
1290
1291
    /**
1292
     * 强制类型转换
1293
     * @access public
1294
     * @param  mixed  $data
1295
     * @param  string $type
1296
     * @return mixed
1297
     */
1298
    private function typeCast(&$data, string $type)
1299
    {
1300
        switch (strtolower($type)) {
1301
            // 数组
1302
            case 'a':
1303
                $data = (array) $data;
1304
                break;
1305
            // 数字
1306
            case 'd':
1307
                $data = (int) $data;
1308
                break;
1309
            // 浮点
1310
            case 'f':
1311
                $data = (float) $data;
1312
                break;
1313
            // 布尔
1314
            case 'b':
1315
                $data = (boolean) $data;
1316
                break;
1317
            // 字符串
1318
            case 's':
1319
                if (is_scalar($data)) {
1320
                    $data = (string) $data;
1321
                } else {
1322
                    throw new \InvalidArgumentException('variable type error:' . gettype($data));
1323
                }
1324
                break;
1325
        }
1326
    }
1327
1328
    /**
1329
     * 获取数据
1330
     * @access public
1331
     * @param  array  $data 数据源
1332
     * @param  string $name 字段名
1333
     * @param  mixed  $default 默认值
1334
     * @return mixed
1335
     */
1336
    protected function getData(array $data, string $name, $default = null)
1337
    {
1338
        foreach (explode('.', $name) as $val) {
1339
            if (isset($data[$val])) {
1340
                $data = $data[$val];
1341
            } else {
1342
                return $default;
1343
            }
1344
        }
1345
1346
        return $data;
1347
    }
1348
1349
    /**
1350
     * 设置或获取当前的过滤规则
1351
     * @access public
1352
     * @param  mixed $filter 过滤规则
1353
     * @return mixed
1354
     */
1355
    public function filter($filter = null)
1356
    {
1357
        if (is_null($filter)) {
1358
            return $this->filter;
1359
        }
1360
1361
        $this->filter = $filter;
1362
1363
        return $this;
1364
    }
1365
1366 33
    protected function getFilter($filter, $default): array
1367
    {
1368 33
        if (is_null($filter)) {
1369
            $filter = [];
1370
        } else {
1371 33
            $filter = $filter ?: $this->filter;
1372 33
            if (is_string($filter) && false === strpos($filter, '/')) {
1373
                $filter = explode(',', $filter);
1374
            } else {
1375 33
                $filter = (array) $filter;
1376
            }
1377
        }
1378
1379 33
        $filter[] = $default;
1380
1381 33
        return $filter;
1382
    }
1383
1384
    /**
1385
     * 递归过滤给定的值
1386
     * @access public
1387
     * @param  mixed $value 键值
1388
     * @param  mixed $key 键名
1389
     * @param  array $filters 过滤方法+默认值
1390
     * @return mixed
1391
     */
1392 3
    public function filterValue(&$value, $key, $filters)
1393
    {
1394 3
        $default = array_pop($filters);
1395
1396 3
        foreach ($filters as $filter) {
1397
            if (is_callable($filter)) {
1398
                // 调用函数或者方法过滤
1399
                $value = call_user_func($filter, $value);
1400
            } elseif (is_scalar($value)) {
1401
                if (is_string($filter) && false !== strpos($filter, '/')) {
1402
                    // 正则过滤
1403
                    if (!preg_match($filter, $value)) {
1404
                        // 匹配不成功返回默认值
1405
                        $value = $default;
1406
                        break;
1407
                    }
1408
                } elseif (!empty($filter)) {
1409
                    // filter函数不存在时, 则使用filter_var进行过滤
1410
                    // filter为非整形值时, 调用filter_id取得过滤id
1411
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1412
                    if (false === $value) {
1413
                        $value = $default;
1414
                        break;
1415
                    }
1416
                }
1417
            }
1418
        }
1419
1420 3
        return $value;
1421
    }
1422
1423
    /**
1424
     * 是否存在某个请求参数
1425
     * @access public
1426
     * @param  string $name 变量名
1427
     * @param  string $type 变量类型
1428
     * @param  bool   $checkEmpty 是否检测空值
1429
     * @return bool
1430
     */
1431
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1432
    {
1433
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1434
            return false;
1435
        }
1436
1437
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1438
1439
        if (is_object($param)) {
1440
            return $param->has($name);
1441
        }
1442
1443
        // 按.拆分成多维数组进行判断
1444
        foreach (explode('.', $name) as $val) {
1445
            if (isset($param[$val])) {
1446
                $param = $param[$val];
1447
            } else {
1448
                return false;
1449
            }
1450
        }
1451
1452
        return ($checkEmpty && '' === $param) ? false : true;
1453
    }
1454
1455
    /**
1456
     * 获取指定的参数
1457
     * @access public
1458
     * @param  array        $name 变量名
1459
     * @param  mixed        $data 数据或者变量类型
1460
     * @param  string|array $filter 过滤方法
1461
     * @return array
1462
     */
1463
    public function only(array $name, $data = 'param', $filter = ''): array
1464
    {
1465
        $data = is_array($data) ? $data : $this->$data();
1466
1467
        $item = [];
1468
        foreach ($name as $key => $val) {
1469
1470
            if (is_int($key)) {
1471
                $default = null;
1472
                $key     = $val;
1473
                if (!isset($data[$key])) {
1474
                    continue;
1475
                }
1476
            } else {
1477
                $default = $val;
1478
            }
1479
1480
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1481
        }
1482
1483
        return $item;
1484
    }
1485
1486
    /**
1487
     * 排除指定参数获取
1488
     * @access public
1489
     * @param  array  $name 变量名
1490
     * @param  string $type 变量类型
1491
     * @return mixed
1492
     */
1493
    public function except(array $name, string $type = 'param'): array
1494
    {
1495
        $param = $this->$type();
1496
1497
        foreach ($name as $key) {
1498
            if (isset($param[$key])) {
1499
                unset($param[$key]);
1500
            }
1501
        }
1502
1503
        return $param;
1504
    }
1505
1506
    /**
1507
     * 当前是否ssl
1508
     * @access public
1509
     * @return bool
1510
     */
1511
    public function isSsl(): bool
1512
    {
1513
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1514
            return true;
1515
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1516
            return true;
1517
        } elseif ('443' == $this->server('SERVER_PORT')) {
1518
            return true;
1519
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1520
            return true;
1521
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1522
            return true;
1523
        }
1524
1525
        return false;
1526
    }
1527
1528
    /**
1529
     * 当前是否JSON请求
1530
     * @access public
1531
     * @return bool
1532
     */
1533 21
    public function isJson(): bool
1534
    {
1535 21
        $acceptType = $this->type();
1536
1537 21
        return false !== strpos($acceptType, 'json');
1538
    }
1539
1540
    /**
1541
     * 当前是否Ajax请求
1542
     * @access public
1543
     * @param  bool $ajax true 获取原始ajax请求
1544
     * @return bool
1545
     */
1546
    public function isAjax(bool $ajax = false): bool
1547
    {
1548
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1549
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1550
1551
        if (true === $ajax) {
1552
            return $result;
1553
        }
1554
1555
        return $this->param($this->varAjax) ? true : $result;
1556
    }
1557
1558
    /**
1559
     * 当前是否Pjax请求
1560
     * @access public
1561
     * @param  bool $pjax true 获取原始pjax请求
1562
     * @return bool
1563
     */
1564
    public function isPjax(bool $pjax = false): bool
1565
    {
1566
        $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
1567
1568
        if (true === $pjax) {
1569
            return $result;
1570
        }
1571
1572
        return $this->param($this->varPjax) ? true : $result;
1573
    }
1574
1575
    /**
1576
     * 获取客户端IP地址
1577
     * @access public
1578
     * @return string
1579
     */
1580
    public function ip(): string
1581
    {
1582
        if (!empty($this->realIP)) {
1583
            return $this->realIP;
1584
        }
1585
1586
        $this->realIP = $this->server('REMOTE_ADDR', '');
1587
1588
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1589
        // 则尝试获取前端代理服务器发送过来的真实IP
1590
        $proxyIp       = $this->proxyServerIp;
1591
        $proxyIpHeader = $this->proxyServerIpHeader;
1592
1593
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1594
            // 从指定的HTTP头中依次尝试获取IP地址
1595
            // 直到获取到一个合法的IP地址
1596
            foreach ($proxyIpHeader as $header) {
1597
                $tempIP = $this->server($header);
1598
1599
                if (empty($tempIP)) {
1600
                    continue;
1601
                }
1602
1603
                $tempIP = trim(explode(',', $tempIP)[0]);
0 ignored issues
show
Bug introduced by
It seems like $tempIP can also be of type array; however, parameter $string of explode() 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

1603
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1604
1605
                if (!$this->isValidIP($tempIP)) {
1606
                    $tempIP = null;
1607
                } else {
1608
                    break;
1609
                }
1610
            }
1611
1612
            // tempIP不为空,说明获取到了一个IP地址
1613
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1614
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1615
            // 否则则是伪装的
1616
            if (!empty($tempIP)) {
1617
                $realIPBin = $this->ip2bin($this->realIP);
1618
1619
                foreach ($proxyIp as $ip) {
1620
                    $serverIPElements = explode('/', $ip);
1621
                    $serverIP         = $serverIPElements[0];
1622
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1623
                    $serverIPBin      = $this->ip2bin($serverIP);
1624
1625
                    // IP类型不符
1626
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1627
                        continue;
1628
                    }
1629
1630
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1631
                        $this->realIP = $tempIP;
1632
                        break;
1633
                    }
1634
                }
1635
            }
1636
        }
1637
1638
        if (!$this->isValidIP($this->realIP)) {
1639
            $this->realIP = '0.0.0.0';
1640
        }
1641
1642
        return $this->realIP;
1643
    }
1644
1645
    /**
1646
     * 检测是否是合法的IP地址
1647
     *
1648
     * @param string $ip   IP地址
1649
     * @param string $type IP地址类型 (ipv4, ipv6)
1650
     *
1651
     * @return boolean
1652
     */
1653
    public function isValidIP(string $ip, string $type = ''): bool
1654
    {
1655
        switch (strtolower($type)) {
1656
            case 'ipv4':
1657
                $flag = FILTER_FLAG_IPV4;
1658
                break;
1659
            case 'ipv6':
1660
                $flag = FILTER_FLAG_IPV6;
1661
                break;
1662
            default:
1663
                $flag = 0;
1664
                break;
1665
        }
1666
1667
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1668
    }
1669
1670
    /**
1671
     * 将IP地址转换为二进制字符串
1672
     *
1673
     * @param string $ip
1674
     *
1675
     * @return string
1676
     */
1677
    public function ip2bin(string $ip): string
1678
    {
1679
        if ($this->isValidIP($ip, 'ipv6')) {
1680
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1681
            foreach ($IPHex as $key => $value) {
1682
                $IPHex[$key] = intval($value, 16);
1683
            }
1684
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
0 ignored issues
show
Bug introduced by
It seems like $IPHex can also be of type true; however, parameter $values of vsprintf() does only seem to accept array, 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

1684
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', /** @scrutinizer ignore-type */ $IPHex);
Loading history...
1685
        } else {
1686
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1687
            foreach ($IPHex as $key => $value) {
1688
                $IPHex[$key] = intval($value, 16);
1689
            }
1690
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1691
        }
1692
1693
        return $IPBin;
1694
    }
1695
1696
    /**
1697
     * 检测是否使用手机访问
1698
     * @access public
1699
     * @return bool
1700
     */
1701
    public function isMobile(): bool
1702
    {
1703
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1704
            return true;
1705
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1706
            return true;
1707
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1708
            return true;
1709
        } elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) {
1710
            return true;
1711
        }
1712
1713
        return false;
1714
    }
1715
1716
    /**
1717
     * 当前URL地址中的scheme参数
1718
     * @access public
1719
     * @return string
1720
     */
1721
    public function scheme(): string
1722
    {
1723
        return $this->isSsl() ? 'https' : 'http';
1724
    }
1725
1726
    /**
1727
     * 当前请求URL地址中的query参数
1728
     * @access public
1729
     * @return string
1730
     */
1731
    public function query(): string
1732
    {
1733
        return $this->server('QUERY_STRING', '');
1734
    }
1735
1736
    /**
1737
     * 设置当前请求的host(包含端口)
1738
     * @access public
1739
     * @param  string $host 主机名(含端口)
1740
     * @return $this
1741
     */
1742
    public function setHost(string $host)
1743
    {
1744
        $this->host = $host;
1745
1746
        return $this;
1747
    }
1748
1749
    /**
1750
     * 当前请求的host
1751
     * @access public
1752
     * @param bool $strict  true 仅仅获取HOST
1753
     * @return string
1754
     */
1755
    public function host(bool $strict = false): string
1756
    {
1757
        if ($this->host) {
1758
            $host = $this->host;
1759
        } else {
1760
            $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
1761
        }
1762
1763
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1764
    }
1765
1766
    /**
1767
     * 当前请求URL地址中的port参数
1768
     * @access public
1769
     * @return int
1770
     */
1771
    public function port(): int
1772
    {
1773
        return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
1774
    }
1775
1776
    /**
1777
     * 当前请求 SERVER_PROTOCOL
1778
     * @access public
1779
     * @return string
1780
     */
1781
    public function protocol(): string
1782
    {
1783
        return $this->server('SERVER_PROTOCOL', '');
1784
    }
1785
1786
    /**
1787
     * 当前请求 REMOTE_PORT
1788
     * @access public
1789
     * @return int
1790
     */
1791
    public function remotePort(): int
1792
    {
1793
        return (int) $this->server('REMOTE_PORT', '');
1794
    }
1795
1796
    /**
1797
     * 当前请求 HTTP_CONTENT_TYPE
1798
     * @access public
1799
     * @return string
1800
     */
1801 30
    public function contentType(): string
1802
    {
1803 30
        $contentType = $this->header('Content-Type');
1804
1805 30
        if ($contentType) {
1806
            if (strpos($contentType, ';')) {
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $haystack of strpos() 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

1806
            if (strpos(/** @scrutinizer ignore-type */ $contentType, ';')) {
Loading history...
1807
                [$type] = explode(';', $contentType);
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $string of explode() 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

1807
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1808
            } else {
1809
                $type = $contentType;
1810
            }
1811
            return trim($type);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type array; 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

1811
            return trim(/** @scrutinizer ignore-type */ $type);
Loading history...
1812
        }
1813
1814 30
        return '';
1815
    }
1816
1817
    /**
1818
     * 获取当前请求的安全Key
1819
     * @access public
1820
     * @return string
1821
     */
1822
    public function secureKey(): string
1823
    {
1824
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1825
            $this->secureKey = uniqid('', true);
1826
        }
1827
1828
        return $this->secureKey;
1829
    }
1830
1831
    /**
1832
     * 设置当前的控制器名
1833
     * @access public
1834
     * @param  string $controller 控制器名
1835
     * @return $this
1836
     */
1837 15
    public function setController(string $controller)
1838
    {
1839 15
        $this->controller = $controller;
1840 15
        return $this;
1841
    }
1842
1843
    /**
1844
     * 设置当前的操作名
1845
     * @access public
1846
     * @param  string $action 操作名
1847
     * @return $this
1848
     */
1849 15
    public function setAction(string $action)
1850
    {
1851 15
        $this->action = $action;
1852 15
        return $this;
1853
    }
1854
1855
    /**
1856
     * 获取当前的控制器名
1857
     * @access public
1858
     * @param  bool $convert 转换为小写
1859
     * @return string
1860
     */
1861
    public function controller(bool $convert = false): string
1862
    {
1863
        $name = $this->controller ?: '';
1864
        return $convert ? strtolower($name) : $name;
1865
    }
1866
1867
    /**
1868
     * 获取当前的操作名
1869
     * @access public
1870
     * @param  bool $convert 转换为小写
1871
     * @return string
1872
     */
1873 3
    public function action(bool $convert = false): string
1874
    {
1875 3
        $name = $this->action ?: '';
1876 3
        return $convert ? strtolower($name) : $name;
1877
    }
1878
1879
    /**
1880
     * 设置或者获取当前请求的content
1881
     * @access public
1882
     * @return string
1883
     */
1884
    public function getContent(): string
1885
    {
1886
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1887
            $this->content = $this->input;
1888
        }
1889
1890
        return $this->content;
1891
    }
1892
1893
    /**
1894
     * 获取当前请求的php://input
1895
     * @access public
1896
     * @return string
1897
     */
1898
    public function getInput(): string
1899
    {
1900
        return $this->input;
1901
    }
1902
1903
    /**
1904
     * 生成请求令牌
1905
     * @access public
1906
     * @param  string $name 令牌名称
1907
     * @param  mixed  $type 令牌生成方法
1908
     * @return string
1909
     */
1910
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1911
    {
1912
        $type  = is_callable($type) ? $type : 'md5';
1913
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1914
1915
        $this->session->set($name, $token);
0 ignored issues
show
Bug introduced by
The method set() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1915
        $this->session->/** @scrutinizer ignore-call */ 
1916
                        set($name, $token);
Loading history...
1916
1917
        return $token;
1918
    }
1919
1920
    /**
1921
     * 检查请求令牌
1922
     * @access public
1923
     * @param  string $token 令牌名称
1924
     * @param  array  $data  表单数据
1925
     * @return bool
1926
     */
1927
    public function checkToken(string $token = '__token__', array $data = []): bool
1928
    {
1929
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1930
            return true;
1931
        }
1932
1933
        if (!$this->session->has($token)) {
0 ignored issues
show
Bug introduced by
The method has() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1933
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1934
            // 令牌数据无效
1935
            return false;
1936
        }
1937
1938
        // Header验证
1939
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1940
            // 防止重复提交
1941
            $this->session->delete($token); // 验证完成销毁session
0 ignored issues
show
Bug introduced by
The method delete() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1941
            $this->session->/** @scrutinizer ignore-call */ 
1942
                            delete($token); // 验证完成销毁session
Loading history...
1942
            return true;
1943
        }
1944
1945
        if (empty($data)) {
1946
            $data = $this->post();
1947
        }
1948
1949
        // 令牌验证
1950
        if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
1951
            // 防止重复提交
1952
            $this->session->delete($token); // 验证完成销毁session
1953
            return true;
1954
        }
1955
1956
        // 开启TOKEN重置
1957
        $this->session->delete($token);
1958
        return false;
1959
    }
1960
1961
    /**
1962
     * 设置在中间件传递的数据
1963
     * @access public
1964
     * @param  array $middleware 数据
1965
     * @return $this
1966
     */
1967
    public function withMiddleware(array $middleware)
1968
    {
1969
        $this->middleware = array_merge($this->middleware, $middleware);
1970
        return $this;
1971
    }
1972
1973
    /**
1974
     * 设置GET数据
1975
     * @access public
1976
     * @param  array $get 数据
1977
     * @return $this
1978
     */
1979
    public function withGet(array $get)
1980
    {
1981
        $this->get = $get;
1982
        return $this;
1983
    }
1984
1985
    /**
1986
     * 设置POST数据
1987
     * @access public
1988
     * @param  array $post 数据
1989
     * @return $this
1990
     */
1991
    public function withPost(array $post)
1992
    {
1993
        $this->post = $post;
1994
        return $this;
1995
    }
1996
1997
    /**
1998
     * 设置COOKIE数据
1999
     * @access public
2000
     * @param array $cookie 数据
2001
     * @return $this
2002
     */
2003
    public function withCookie(array $cookie)
2004
    {
2005
        $this->cookie = $cookie;
2006
        return $this;
2007
    }
2008
2009
    /**
2010
     * 设置SESSION数据
2011
     * @access public
2012
     * @param Session $session 数据
2013
     * @return $this
2014
     */
2015
    public function withSession(Session $session)
2016
    {
2017
        $this->session = $session;
2018
        return $this;
2019
    }
2020
2021
    /**
2022
     * 设置SERVER数据
2023
     * @access public
2024
     * @param  array $server 数据
2025
     * @return $this
2026
     */
2027
    public function withServer(array $server)
2028
    {
2029
        $this->server = array_change_key_case($server, CASE_UPPER);
2030
        return $this;
2031
    }
2032
2033
    /**
2034
     * 设置HEADER数据
2035
     * @access public
2036
     * @param  array $header 数据
2037
     * @return $this
2038
     */
2039
    public function withHeader(array $header)
2040
    {
2041
        $this->header = array_change_key_case($header);
2042
        return $this;
2043
    }
2044
2045
    /**
2046
     * 设置ENV数据
2047
     * @access public
2048
     * @param Env $env 数据
2049
     * @return $this
2050
     */
2051
    public function withEnv(Env $env)
2052
    {
2053
        $this->env = $env;
2054
        return $this;
2055
    }
2056
2057
    /**
2058
     * 设置php://input数据
2059
     * @access public
2060
     * @param string $input RAW数据
2061
     * @return $this
2062
     */
2063
    public function withInput(string $input)
2064
    {
2065
        $this->input = $input;
2066
        if (!empty($input)) {
2067
            $inputData = $this->getInputData($input);
2068
            if (!empty($inputData)) {
2069
                $this->post = $inputData;
2070
                $this->put  = $inputData;
2071
            }
2072
        }
2073
        return $this;
2074
    }
2075
2076
    /**
2077
     * 设置文件上传数据
2078
     * @access public
2079
     * @param  array $files 上传信息
2080
     * @return $this
2081
     */
2082
    public function withFiles(array $files)
2083
    {
2084
        $this->file = $files;
2085
        return $this;
2086
    }
2087
2088
    /**
2089
     * 设置ROUTE变量
2090
     * @access public
2091
     * @param  array $route 数据
2092
     * @return $this
2093
     */
2094
    public function withRoute(array $route)
2095
    {
2096
        $this->route = $route;
2097
        return $this;
2098
    }
2099
2100
    /**
2101
     * 设置中间传递数据
2102
     * @access public
2103
     * @param  string    $name  参数名
2104
     * @param  mixed     $value 值
2105
     */
2106
    public function __set(string $name, $value)
2107
    {
2108
        $this->middleware[$name] = $value;
2109
    }
2110
2111
    /**
2112
     * 获取中间传递数据的值
2113
     * @access public
2114
     * @param  string $name 名称
2115
     * @return mixed
2116
     */
2117
    public function __get(string $name)
2118
    {
2119
        return $this->middleware($name);
2120
    }
2121
2122
    /**
2123
     * 检测中间传递数据的值
2124
     * @access public
2125
     * @param  string $name 名称
2126
     * @return boolean
2127
     */
2128
    public function __isset(string $name): bool
2129
    {
2130
        return isset($this->middleware[$name]);
2131
    }
2132
2133
    // ArrayAccess
2134
    public function offsetExists($name): bool
2135
    {
2136
        return $this->has($name);
2137
    }
2138
2139
    public function offsetGet($name)
2140
    {
2141
        return $this->param($name);
2142
    }
2143
2144
    public function offsetSet($name, $value)
2145
    {}
2146
2147
    public function offsetUnset($name)
2148
    {}
2149
2150
}
2151