Completed
Pull Request — 6.0 (#2521)
by
unknown
08:27
created

Request::buildToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
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 30
    public function param($name = '', $default = null, $filter = '')
842
    {
843 30
        if (empty($this->mergeParam)) {
844 30
            $method = $this->method(true);
845
846
            // 自动获取请求变量
847 20
            switch ($method) {
848 30
                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 30
                case 'PUT':
852 30
                case 'DELETE':
853 30
                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 30
                    $vars = [];
858
            }
859
860
            // 当前请求参数和URL地址中的参数合并
861 30
            $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 30
            $this->mergeParam = true;
864
        }
865
866 30
        if (is_array($name)) {
867
            return $this->only($name, $this->param, $filter);
868
        }
869
870 30
        return $this->input($this->param, $name, $default, $filter);
871
    }
872
873
    /**
874
     * 获取包含文件在内的请求参数
875
     * @access public
876
     * @param  string|array $name 变量名
877
     * @param  string|array $filter 过滤方法
878
     * @return mixed
879
     */
880
    public function all($name = '', $filter = '')
881
    {
882
        $data = array_merge($this->param(), $this->file());
0 ignored issues
show
Bug introduced by
It seems like $this->file() can also be of type null and think\file\UploadedFile; however, parameter $arrays of array_merge() 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

882
        $data = array_merge($this->param(), /** @scrutinizer ignore-type */ $this->file());
Loading history...
Bug introduced by
It seems like $this->param() can also be of type null and object; however, parameter $arrays of array_merge() 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

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

1090
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1091
        }
1092
        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

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

1621
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1622
1623
                if (!$this->isValidIP($tempIP)) {
1624
                    $tempIP = null;
1625
                } else {
1626
                    break;
1627
                }
1628
            }
1629
1630
            // tempIP不为空,说明获取到了一个IP地址
1631
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1632
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1633
            // 否则则是伪装的
1634
            if (!empty($tempIP)) {
1635
                $realIPBin = $this->ip2bin($this->realIP);
1636
1637
                foreach ($proxyIp as $ip) {
1638
                    $serverIPElements = explode('/', $ip);
1639
                    $serverIP         = $serverIPElements[0];
1640
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1641
                    $serverIPBin      = $this->ip2bin($serverIP);
1642
1643
                    // IP类型不符
1644
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1645
                        continue;
1646
                    }
1647
1648
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1649
                        $this->realIP = $tempIP;
1650
                        break;
1651
                    }
1652
                }
1653
            }
1654
        }
1655
1656
        if (!$this->isValidIP($this->realIP)) {
1657
            $this->realIP = '0.0.0.0';
1658
        }
1659
1660
        return $this->realIP;
1661
    }
1662
1663
    /**
1664
     * 检测是否是合法的IP地址
1665
     *
1666
     * @param string $ip   IP地址
1667
     * @param string $type IP地址类型 (ipv4, ipv6)
1668
     *
1669
     * @return boolean
1670
     */
1671
    public function isValidIP(string $ip, string $type = ''): bool
1672
    {
1673
        switch (strtolower($type)) {
1674
            case 'ipv4':
1675
                $flag = FILTER_FLAG_IPV4;
1676
                break;
1677
            case 'ipv6':
1678
                $flag = FILTER_FLAG_IPV6;
1679
                break;
1680
            default:
1681
                $flag = 0;
1682
                break;
1683
        }
1684
1685
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1686
    }
1687
1688
    /**
1689
     * 将IP地址转换为二进制字符串
1690
     *
1691
     * @param string $ip
1692
     *
1693
     * @return string
1694
     */
1695
    public function ip2bin(string $ip): string
1696
    {
1697
        if ($this->isValidIP($ip, 'ipv6')) {
1698
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1699
            foreach ($IPHex as $key => $value) {
1700
                $IPHex[$key] = intval($value, 16);
1701
            }
1702
            $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

1702
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', /** @scrutinizer ignore-type */ $IPHex);
Loading history...
1703
        } else {
1704
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1705
            foreach ($IPHex as $key => $value) {
1706
                $IPHex[$key] = intval($value, 16);
1707
            }
1708
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1709
        }
1710
1711
        return $IPBin;
1712
    }
1713
1714
    /**
1715
     * 检测是否使用手机访问
1716
     * @access public
1717
     * @return bool
1718
     */
1719
    public function isMobile(): bool
1720
    {
1721
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1722
            return true;
1723
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1724
            return true;
1725
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1726
            return true;
1727
        } 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'))) {
1728
            return true;
1729
        }
1730
1731
        return false;
1732
    }
1733
1734
    /**
1735
     * 当前URL地址中的scheme参数
1736
     * @access public
1737
     * @return string
1738
     */
1739
    public function scheme(): string
1740
    {
1741
        return $this->isSsl() ? 'https' : 'http';
1742
    }
1743
1744
    /**
1745
     * 当前请求URL地址中的query参数
1746
     * @access public
1747
     * @return string
1748
     */
1749
    public function query(): string
1750
    {
1751
        return $this->server('QUERY_STRING', '');
1752
    }
1753
1754
    /**
1755
     * 设置当前请求的host(包含端口)
1756
     * @access public
1757
     * @param  string $host 主机名(含端口)
1758
     * @return $this
1759
     */
1760
    public function setHost(string $host)
1761
    {
1762
        $this->host = $host;
1763
1764
        return $this;
1765
    }
1766
1767
    /**
1768
     * 当前请求的host
1769
     * @access public
1770
     * @param bool $strict  true 仅仅获取HOST
1771
     * @return string
1772
     */
1773
    public function host(bool $strict = false): string
1774
    {
1775
        if ($this->host) {
1776
            $host = $this->host;
1777
        } else {
1778
            $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
1779
        }
1780
1781
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1782
    }
1783
1784
    /**
1785
     * 当前请求URL地址中的port参数
1786
     * @access public
1787
     * @return int
1788
     */
1789
    public function port(): int
1790
    {
1791
        return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
1792
    }
1793
1794
    /**
1795
     * 当前请求 SERVER_PROTOCOL
1796
     * @access public
1797
     * @return string
1798
     */
1799
    public function protocol(): string
1800
    {
1801
        return $this->server('SERVER_PROTOCOL', '');
1802
    }
1803
1804
    /**
1805
     * 当前请求 REMOTE_PORT
1806
     * @access public
1807
     * @return int
1808
     */
1809
    public function remotePort(): int
1810
    {
1811
        return (int) $this->server('REMOTE_PORT', '');
1812
    }
1813
1814
    /**
1815
     * 当前请求 HTTP_CONTENT_TYPE
1816
     * @access public
1817
     * @return string
1818
     */
1819 30
    public function contentType(): string
1820
    {
1821 30
        $contentType = $this->header('Content-Type');
1822
1823 30
        if ($contentType) {
1824
            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

1824
            if (strpos(/** @scrutinizer ignore-type */ $contentType, ';')) {
Loading history...
1825
                [$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

1825
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1826
            } else {
1827
                $type = $contentType;
1828
            }
1829
            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

1829
            return trim(/** @scrutinizer ignore-type */ $type);
Loading history...
1830
        }
1831
1832 30
        return '';
1833
    }
1834
1835
    /**
1836
     * 获取当前请求的安全Key
1837
     * @access public
1838
     * @return string
1839
     */
1840
    public function secureKey(): string
1841
    {
1842
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1843
            $this->secureKey = uniqid('', true);
1844
        }
1845
1846
        return $this->secureKey;
1847
    }
1848
1849
    /**
1850
     * 设置当前的控制器名
1851
     * @access public
1852
     * @param  string $controller 控制器名
1853
     * @return $this
1854
     */
1855 15
    public function setController(string $controller)
1856
    {
1857 15
        $this->controller = $controller;
1858 15
        return $this;
1859
    }
1860
1861
    /**
1862
     * 设置当前的操作名
1863
     * @access public
1864
     * @param  string $action 操作名
1865
     * @return $this
1866
     */
1867 15
    public function setAction(string $action)
1868
    {
1869 15
        $this->action = $action;
1870 15
        return $this;
1871
    }
1872
1873
    /**
1874
     * 获取当前的控制器名
1875
     * @access public
1876
     * @param  bool $convert 转换为小写
1877
     * @return string
1878
     */
1879
    public function controller(bool $convert = false): string
1880
    {
1881
        $name = $this->controller ?: '';
1882
        return $convert ? strtolower($name) : $name;
1883
    }
1884
1885
    /**
1886
     * 获取当前的操作名
1887
     * @access public
1888
     * @param  bool $convert 转换为小写
1889
     * @return string
1890
     */
1891 3
    public function action(bool $convert = false): string
1892
    {
1893 3
        $name = $this->action ?: '';
1894 3
        return $convert ? strtolower($name) : $name;
1895
    }
1896
1897
    /**
1898
     * 设置或者获取当前请求的content
1899
     * @access public
1900
     * @return string
1901
     */
1902
    public function getContent(): string
1903
    {
1904
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1905
            $this->content = $this->input;
1906
        }
1907
1908
        return $this->content;
1909
    }
1910
1911
    /**
1912
     * 获取当前请求的php://input
1913
     * @access public
1914
     * @return string
1915
     */
1916
    public function getInput(): string
1917
    {
1918
        return $this->input;
1919
    }
1920
1921
    /**
1922
     * 生成请求令牌
1923
     * @access public
1924
     * @param  string $name 令牌名称
1925
     * @param  mixed  $type 令牌生成方法
1926
     * @return string
1927
     */
1928
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1929
    {
1930
        $type  = is_callable($type) ? $type : 'md5';
1931
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1932
1933
        $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

1933
        $this->session->/** @scrutinizer ignore-call */ 
1934
                        set($name, $token);
Loading history...
1934
1935
        return $token;
1936
    }
1937
1938
    /**
1939
     * 检查请求令牌
1940
     * @access public
1941
     * @param  string $token 令牌名称
1942
     * @param  array  $data  表单数据
1943
     * @return bool
1944
     */
1945
    public function checkToken(string $token = '__token__', array $data = []): bool
1946
    {
1947
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1948
            return true;
1949
        }
1950
1951
        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

1951
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1952
            // 令牌数据无效
1953
            return false;
1954
        }
1955
1956
        // Header验证
1957
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1958
            // 防止重复提交
1959
            $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

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