-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathRequest.php
1853 lines (1636 loc) · 57.2 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\web;
use Craft;
use craft\base\RequestTrait;
use craft\config\GeneralConfig;
use craft\errors\SiteNotFoundException;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\Session as SessionHelper;
use craft\helpers\StringHelper;
use craft\models\Site;
use craft\services\Sites;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\db\Exception as DbException;
use yii\di\Instance;
use yii\web\BadRequestHttpException;
use yii\web\Cookie;
use yii\web\CookieCollection;
use yii\web\NotFoundHttpException;
/** @noinspection ClassOverridesFieldOfSuperClassInspection */
/**
* @inheritdoc
* @property string $fullPath The full requested path, including the control panel trigger and pagination info.
* @property array $segments The segments of the requested path.
* @property int $pageNum The requested page number.
* @property string $token The token submitted with the request, if there is one.
* @property bool $isCpRequest Whether the control panel was requested.
* @property bool $isSiteRequest Whether the front end site was requested.
* @property bool $isActionRequest Whether a specific controller action was requested.
* @property array $actionSegments The segments of the requested controller action path, if this is an [[getIsActionRequest()|action request]].
* @property bool $isLivePreview Whether this is a Live Preview request.
* @property string $queryStringWithoutPath The request’s query string, without the path parameter.
* @property-read bool $isPreview Whether this is an element preview request.
* @property-read string|null $mimeType The MIME type of the request, extracted from the request’s content type
* @property-read bool $isGraphql Whether the request’s MIME type is `application/graphql`
* @property-read bool $isJson Whether the request’s MIME type is `application/json`
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Request extends \yii\web\Request
{
use RequestTrait;
public const CP_PATH_LOGIN = 'login';
public const CP_PATH_LOGOUT = 'logout';
public const CP_PATH_SET_PASSWORD = 'set-password';
public const CP_PATH_VERIFY_EMAIL = 'verify-email';
public const CP_PATH_UPDATE = 'update';
/**
* @inheritdoc
*/
public $ipHeaders = [
'Client-IP',
'X-Forwarded-For',
'X-Forwarded',
'X-Cluster-Client-IP',
'Forwarded-For',
'Forwarded',
];
/**
* @var int The highest page number that Craft should accept.
* @since 3.1.14
*/
public int $maxPageNum = 100000;
/**
* @var GeneralConfig|array|string
* @since 3.5.10
*/
public GeneralConfig|string|array $generalConfig;
/**
* @var Sites|array|string|null
* @since 3.5.10
*/
public string|array|null|Sites $sites = 'sites';
/**
* @var string
* @see getFullPath()
*/
private string $_fullPath;
/**
* @var string
* @see getPathInfo()
*/
private string $_path;
/**
* @var string
* @see getFullUri()
*/
private string $_fullUri;
/**
* @var string[]
*/
private array $_segments;
/**
* @var int
*/
private int $_pageNum = 1;
/**
* @var bool|null
*/
private ?bool $_isCpRequest = null;
/**
* @var bool
* @see checkIfActionRequest()
*/
private bool $_isActionRequest = false;
/**
* @var bool
* @see checkIfActionRequest()
*/
private bool $_isLoginRequest = false;
/**
* @var bool
* @see checkIfActionRequest()
*/
private bool $_checkedRequestType = false;
/**
* @var string[]|null
* @see checkIfActionRequest()
*/
private ?array $_actionSegments = null;
/**
* @var bool
*/
private bool $_isLivePreview = false;
/**
* @var bool|null
*/
private ?bool $_isMobileBrowser = null;
/**
* @var bool|null
*/
private ?bool $_isMobileOrTabletBrowser = null;
/**
* @var string|null
*/
private ?string $_ipAddress = null;
/**
* @var CookieCollection Collection of raw cookies
* @see getRawCookies()
*/
private CookieCollection $_rawCookies;
/**
* @var string|null
*/
private ?string $_craftCsrfToken = null;
/**
* @var bool
*/
private bool $_encodedQueryParams = false;
/**
* @var bool
*/
private bool $_setBodyParams = false;
/**
* @var bool|null Whether the request initially had a token
* @see getHadToken()
*/
private ?bool $_hadToken = null;
/**
* @var string|null
* @see getToken()
*/
public ?string $_token = null;
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
if (!isset($this->generalConfig)) {
$this->generalConfig = Craft::$app->getConfig()->getGeneral();
}
$this->generalConfig = Instance::ensure($this->generalConfig, GeneralConfig::class);
// Set the @webroot and @web aliases now (instead of from yii\web\Application::bootstrap())
// in case a site's base URL requires @web, and so we can include the host info in @web
if (Craft::getRootAlias('@webroot') === false) {
Craft::setAlias('@webroot', dirname($this->getScriptFile()));
$this->isWebrootAliasSetDynamically = true;
}
if (Craft::getRootAlias('@web') === false) {
Craft::setAlias('@web', $this->getHostInfo() . $this->getBaseUrl());
$this->isWebAliasSetDynamically = true;
}
// Determine the request path
$this->_path = $this->getFullPath();
// Figure out whether a site or the control panel were requested
// ---------------------------------------------------------------------
try {
$this->sites = Instance::ensure($this->sites, Sites::class);
// Only check if a site was requested if don’t know for sure that it’s a control panel request
if ($this->_isCpRequest !== true) {
if ($this->sites->getHasCurrentSite()) {
$site = $this->sites->getCurrentSite();
} else {
$site = $this->_requestedSite($siteScore);
}
if ($siteBaseUrl = $site->getBaseUrl()) {
$baseUrl = rtrim($siteBaseUrl, '/');
}
}
} catch (SiteNotFoundException $e) {
// Fail silently if Craft isn’t installed yet or is in the middle of updating
if (Craft::$app->getIsInstalled() && !Craft::$app->getUpdates()->getIsCraftUpdatePending()) {
/** @noinspection PhpUnhandledExceptionInspection */
throw $e;
}
}
// Is the jury still out on whether this is a control panel request?
if (!isset($this->_isCpRequest)) {
$this->_isCpRequest = false;
// Is it a possibility?
if ($this->generalConfig->cpTrigger || $this->generalConfig->baseCpUrl) {
// Figure out the base URL the request must have if this is a control panel request
$testBaseCpUrls = [];
if ($this->generalConfig->baseCpUrl) {
$testBaseCpUrls[] = implode('/', array_filter([rtrim($this->generalConfig->baseCpUrl, '/'), $this->generalConfig->cpTrigger]));
} else {
if (isset($baseUrl)) {
$testBaseCpUrls[] = "$baseUrl/{$this->generalConfig->cpTrigger}";
}
$testBaseCpUrls[] = $this->getBaseUrl() . "/{$this->generalConfig->cpTrigger}";
}
$siteScore = $siteScore ?? (isset($site) ? $this->_scoreSite($site) : 0);
foreach ($testBaseCpUrls as $testUrl) {
$cpScore = $this->_scoreUrl($testUrl);
if ($cpScore > $siteScore) {
$this->_isCpRequest = true;
$baseUrl = $testUrl;
$site = null;
break;
}
}
}
}
// Set the current site for the request
if ($this->sites instanceof Sites) {
$this->sites->setCurrentSite($site ?? null);
}
// If this is a control panel request and the path begins with the control panel trigger, remove it
if ($this->_isCpRequest && $this->generalConfig->cpTrigger && str_starts_with($this->_path . '/', $this->generalConfig->cpTrigger . '/')) {
$this->_path = ltrim(substr($this->_path, strlen($this->generalConfig->cpTrigger)), '/');
}
// Trim off any leading path segments that are part of the base URL
if ($this->_path !== '' && isset($baseUrl) && ($basePath = parse_url($baseUrl, PHP_URL_PATH)) !== null) {
$basePath = $this->_normalizePath($basePath);
// If Craft is running from a subfolder, chop the subfolder path off of the base path first
if (
($requestBaseUrl = $this->_normalizePath($this->getBaseUrl())) &&
str_starts_with($basePath . '/', $requestBaseUrl . '/')
) {
$basePath = ltrim(substr($basePath, strlen($requestBaseUrl)), '/');
}
if (str_starts_with($this->_path . '/', $basePath . '/')) {
$this->_path = ltrim(substr($this->_path, strlen($basePath)), '/');
}
}
// Is this a paginated request?
$pageTrigger = $this->_isCpRequest ? 'p' : $this->generalConfig->getPageTrigger();
// Is this query string-based pagination?
if (str_starts_with($pageTrigger, '?')) {
$this->_pageNum = (int)$this->getQueryParam(trim($pageTrigger, '?='), '1');
} elseif ($this->_path !== '') {
// Match against the entire path string as opposed to just the last segment so that we can support
// "/page/2"-style pagination URLs
$pageTrigger = preg_quote($pageTrigger, '/');
if (preg_match("/^(?:(.*)\/)?$pageTrigger(\d+)$/", $this->_path, $match)) {
// Capture the page num
$this->_pageNum = (int)$match[2];
// Sanitize
$this->_path = $match[1];
}
}
$this->_pageNum = min($this->_pageNum, $this->maxPageNum);
}
/**
* Returns the full request path, whether that came from the path info or the path query parameter.
*
* Leading and trailing slashes will be removed.
*
* @return string
*/
public function getFullPath(): string
{
if (isset($this->_fullPath)) {
return $this->_fullPath;
}
try {
if ($this->generalConfig->usePathInfo) {
$this->_fullPath = $this->getPathInfo(true);
if (!$this->_fullPath) {
$this->_fullPath = $this->_getQueryStringPath();
}
} else {
$this->_fullPath = $this->_getQueryStringPath();
if (!$this->_fullPath) {
$this->_fullPath = $this->getPathInfo(true);
}
}
} catch (InvalidConfigException) {
$this->_fullPath = $this->_getQueryStringPath();
}
return $this->_fullPath = $this->_normalizePath($this->_fullPath);
}
/**
* Returns the requested path, sans control panel trigger and pagination info.
*
* If $returnRealPathInfo is returned, then [[\yii\web\Request::getPathInfo()]] will be returned.
*
* @param bool $returnRealPathInfo Whether the real path info should be returned instead.
* @return string The requested path, or the path info.
* @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
*/
public function getPathInfo(bool $returnRealPathInfo = false): string
{
if ($returnRealPathInfo) {
return parent::getPathInfo();
}
return $this->_path;
}
/**
* Returns the full requested URI.
*
* @return string
* @since 3.5.0
*/
public function getFullUri(): string
{
if (isset($this->_fullUri)) {
return $this->_fullUri;
}
$baseUrl = $this->_normalizePath($this->getBaseUrl());
$path = $this->getFullPath();
return $this->_fullUri = $baseUrl . ($baseUrl && $path ? '/' : '') . $path;
}
/**
* @inheritdoc
*
* ::: warning
* Don’t include the results of this method in places that will be cached, to avoid a cache poisoning attack.
* :::
*/
public function getAbsoluteUrl(): string
{
return parent::getAbsoluteUrl();
}
/**
* Returns the segments of the requested path.
*
* ::: tip
* Note that the segments will not include the [control panel trigger](config5:cpTrigger)
* if it’s a control panel request, or the [page trigger](config5:pageTrigger)
* or page number if it’s a paginated request.
* :::
*
* ---
*
* ```php
* $segments = Craft::$app->request->segments;
* ```
* ```twig
* {% set segments = craft.app.request.segments %}
* ```
*
* @return array The Craft path’s segments.
*/
public function getSegments(): array
{
return $this->_segments ?? ($this->_segments = $this->_segments($this->_path));
}
/**
* Returns a specific segment from the Craft path.
*
* ---
*
* ```php
* $firstSegment = Craft::$app->request->getSegment(1);
* ```
* ```twig
* {% set firstSegment = craft.app.request.getSegment(1) %}
* ```
*
* @param int $num Which segment to return (1-indexed).
* @return string|null The matching segment, or `null` if there wasn’t one.
*/
public function getSegment(int $num): ?string
{
$segments = $this->getSegments();
if ($num > 0 && isset($segments[$num - 1])) {
return $segments[$num - 1];
}
if ($num < 0) {
$totalSegs = count($segments);
if (isset($segments[$totalSegs + $num])) {
return $segments[$totalSegs + $num];
}
}
return null;
}
/**
* Returns the requested page number.
*
* ---
*
* ```php
* $page = Craft::$app->request->pageNum;
* ```
* ```twig
* {% set page = craft.app.request.pageNum %}
* ```
*
* @return int The requested page number.
*/
public function getPageNum(): int
{
return $this->_pageNum;
}
/**
* Returns whether the request initially had a token.
*
* @return bool
* @throws BadRequestHttpException
* @since 3.6.0
*/
public function getHadToken(): bool
{
$this->_findToken();
return $this->_hadToken;
}
/**
* Returns the token submitted with the request, if there is one.
*
* Tokens must be sent either as a query string param named after the <config5:tokenParam> config setting (`token` by
* default), or an `X-Craft-Token` HTTP header on the request.
*
* @return string|null The token, or `null` if there isn’t one.
* @throws BadRequestHttpException if an invalid token is supplied
* @see \craft\services\Tokens::createToken()
* @see Controller::requireToken()
*/
public function getToken(): ?string
{
$this->_findToken();
return $this->_token;
}
/**
* Sets the token value.
*
* @param string|null $token
* @since 3.6.0
*/
public function setToken(?string $token): void
{
// Make sure $this->_hadToken has been set
try {
$this->_findToken();
} catch (BadRequestHttpException) {
}
$this->_token = $token;
}
/**
* Looks for a token on the request.
*
* @throws BadRequestHttpException
*/
private function _findToken(): void
{
if (isset($this->_hadToken)) {
return;
}
$this->_token = ($this->getQueryParam($this->generalConfig->tokenParam) ?? $this->getHeaders()->get('X-Craft-Token')) ?: null;
if ($this->_token && !preg_match('/^[A-Za-z0-9_-]+$/', $this->_token)) {
$this->_token = null;
$this->_hadToken = false;
throw new BadRequestHttpException('Invalid token');
}
$this->_hadToken = isset($this->_token);
}
/**
* Returns the site token submitted with the request, if there is one.
*
* Tokens must be sent either as a query string param named after the <config5:siteToken> config setting
* (`siteToken` by default), or an `X-Craft-Site-Token` HTTP header on the request.
*
* @return string|null The token, or `null` if there isn’t one.
* @since 3.6.0
*/
public function getSiteToken(): ?string
{
return $this->getQueryParam($this->generalConfig->siteToken) ?? $this->getHeaders()->get('X-Craft-Site-Token');
}
/**
* Returns whether the request has a valid site token.
*
* @return bool
* @since 4.4.6
*/
public function hasValidSiteToken(): bool
{
try {
return $this->_validateSiteToken() !== null;
} catch (BadRequestHttpException $e) {
return false;
}
}
/**
* Returns whether the control panel was requested.
*
* The result depends on whether the first segment in the URI matches the
* [control panel trigger](config5:cpTrigger).
*
* @return bool Whether the current request should be routed to the control panel.
*/
public function getIsCpRequest(): bool
{
return $this->_isCpRequest;
}
/**
* Sets whether the control panel was requested.
*
* @param bool|null $isCpRequest
* @since 3.5.0
*/
public function setIsCpRequest(?bool $isCpRequest = null): void
{
$this->_isCpRequest = $isCpRequest;
}
/**
* Returns whether the front end site was requested.
*
* The result will always just be the opposite of whatever [[getIsCpRequest()]] returns.
*
* @return bool Whether the current request should be routed to the front-end site.
*/
public function getIsSiteRequest(): bool
{
return !$this->_isCpRequest;
}
/**
* Returns whether a specific controller action was requested.
*
* There are several ways that this method could return `true`:
*
* - If the first segment in the Craft path matches the [action trigger](config5:actionTrigger)
* - If there is an `action` param in either the POST data or query string
* - If the Craft path matches the Login path, the Logout path, or the Set Password path
*
* @return bool Whether the current request should be routed to a controller action.
*/
public function getIsActionRequest(): bool
{
$this->checkIfActionRequest();
return $this->_isActionRequest;
}
/**
* Overrides whether this request should be treated as an action request.
*
* @param bool $isActionRequest
* @see checkIfActionRequest()
* @since 3.7.8
*/
public function setIsActionRequest(bool $isActionRequest): void
{
$this->_isActionRequest = $isActionRequest;
}
/**
* Returns whether this was a Login request.
*
* @return bool
* @since 3.2.0
*/
public function getIsLoginRequest(): bool
{
$this->checkIfActionRequest();
return $this->_isLoginRequest;
}
/**
* Returns the segments of the requested controller action path, if this is an [[getIsActionRequest()|action request]].
*
* @return array|null The action path segments, or `null` if this isn’t an action request.
*/
public function getActionSegments(): ?array
{
$this->checkIfActionRequest();
return $this->_isActionRequest ? $this->_actionSegments : null;
}
/**
* Returns whether this is an element preview request.
*
* ::: tip
* This will only return `true` when previewing entries at the moment. For all other element types, check
* [[getIsLivePreview()]].
* :::
*
* ---
* ```php
* $isPreviewRequest = Craft::$app->request->isPreview;
* ```
* ```twig
* {% set isPreviewRequest = craft.app.request.isPreview %}
* ```
*
* @return bool
* @since 3.2.1
*/
public function getIsPreview(): bool
{
$previewParamValue = $this->getQueryParam('x-craft-preview') ?? $this->getQueryParam('x-craft-live-preview');
if (!$previewParamValue) {
return false;
}
if (!Craft::$app->getSecurity()->validateData($previewParamValue)) {
return false;
}
// If there's a token but it expired, they're looking at the live site
return !$this->getHadToken() || $this->getToken() !== null;
}
/**
* Returns whether this is a Live Preview request.
*
* ::: tip
* As of Craft 3.2, entries use a new previewing system, so this won’t return `true` for them. Check
* [[getIsPreview()]] instead for entries.
* :::
*
* ---
* ```php
* $isLivePreview = Craft::$app->request->isLivePreview;
* ```
* ```twig
* {% set isLivePreview = craft.app.request.isLivePreview %}
* ```
*
* @return bool Whether this is a Live Preview request.
*/
public function getIsLivePreview(): bool
{
return $this->_isLivePreview;
}
/**
* Sets whether this is a Live Preview request.
*
* @param bool $isLivePreview
*/
public function setIsLivePreview(bool $isLivePreview): void
{
$this->_isLivePreview = $isLivePreview;
}
/**
* Returns the MIME type of the request, extracted from the request’s content type.
*
* @return string|null
* @since 3.5.0
*/
public function getMimeType(): ?string
{
$contentType = parent::getContentType();
if (!$contentType) {
return null;
}
// Strip out the charset & boundary, if present
if (($pos = strpos($contentType, ';')) !== false) {
$contentType = substr($contentType, 0, $pos);
}
return strtolower(trim($contentType));
}
/**
* Returns whether the request’s MIME type is `application/graphql`.
*
* @return bool
* @since 3.5.0
*/
public function getIsGraphql(): bool
{
return $this->getMimeType() === 'application/graphql';
}
/**
* Returns whether the request’s MIME type is `application/json`.
*
* @return bool
* @since 3.5.0
*/
public function getIsJson(): bool
{
return $this->getMimeType() === 'application/json';
}
/**
* Returns whether the request is coming from a mobile browser.
*
* The detection script is provided by http://detectmobilebrowsers.com. It was last updated on 2014-11-24.
*
* ---
*
* ```php
* $isMobileBrowser = Craft::$app->request->isMobileBrowser();
* ```
* ```twig
* {% set isMobileBrowser = craft.app.request.isMobileBrowser() %}
* ```
*
* @param bool $detectTablets Whether tablets should be considered “mobile”.
* @return bool Whether the request is coming from a mobile browser.
*/
public function isMobileBrowser(bool $detectTablets = false): bool
{
if ($detectTablets) {
$property = &$this->_isMobileOrTabletBrowser;
} else {
$property = &$this->_isMobileBrowser;
}
if ($property === null) {
if ($this->getUserAgent() !== null) {
$property = (
preg_match(
'/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino'
. ($detectTablets ? '|android|ipad|playbook|silk' : '') . '/i',
$this->getUserAgent()
) ||
preg_match(
'/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',
mb_substr($this->getUserAgent(), 0, 4)
)
);
} else {
$property = false;
}
}
return $property;
}
/**
* @inheritdoc
*/
public function getBodyParams(): array
{
if ($this->_setBodyParams === false) {
$params = parent::getBodyParams();
// Was a namespace passed?
$namespace = $this->getHeaders()->get('X-Craft-Namespace');
if ($namespace) {
$params = ArrayHelper::getValue($params, $namespace, []);
}
$this->setBodyParams($this->_utf8AllTheThings($params));
$this->_setBodyParams = true;
}
return parent::getBodyParams();
}
/**
* @inheritdoc
*/
public function setBodyParams($values)
{
parent::setBodyParams($values);
$this->_setBodyParams = false;
}
/**
* Returns the named request body parameter value.
*
* If the parameter does not exist, the second argument passed to this method will be returned.
*
* ---
*
* ```php
* // get $_POST['foo'], if it exists
* $foo = Craft::$app->request->getBodyParam('foo');
*
* // get $_POST['foo']['bar'], if it exists
* $bar = Craft::$app->request->getBodyParam('foo.bar');
* ```
* ```twig
* {# get $_POST['foo'], if it exists #}
* {% set foo = craft.app.request.getBodyParam('foo') %}
*
* {# get $_POST['foo']['bar'], if it exists #}
* {% set bar = craft.app.request.getBodyParam('foo.bar') %}
* ```
*
* @param string $name The parameter name.
* @param mixed $defaultValue The default parameter value if the parameter does not exist.
* @return mixed The parameter value
* @see getBodyParams()
* @see setBodyParams()
*/
public function getBodyParam($name, $defaultValue = null): mixed
{
return $this->_getParam($name, $defaultValue, $this->getBodyParams());
}
/**
* Returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t exist.
*
* ---
*
* ```php
* // get required $_POST['foo']
* $foo = Craft::$app->request->getRequiredBodyParam('foo');
*
* // get required $_POST['foo']['bar']
* $bar = Craft::$app->request->getRequiredBodyParam('foo.bar');
* ```
* ```twig
* {# get required $_POST['foo'] #}
* {% set foo = craft.app.request.getRequiredBodyParam('foo') %}
*
* {# get required $_POST['foo']['bar'] #}
* {% set bar = craft.app.request.getRequiredBodyParam('foo.bar') %}
* ```
*
* @param string $name The parameter name.
* @return mixed The parameter value
* @throws BadRequestHttpException if the request does not have the body param
* @see getBodyParam()
*/
public function getRequiredBodyParam(string $name): mixed
{
$value = $this->getBodyParam($name);
if ($value !== null) {
return $value;
}
throw new BadRequestHttpException("Request missing required body param");
}
/**
* Validates and returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t pass validation.
*
* ---
*
* ```php
* // get validated $_POST['foo']
* $foo = Craft::$app->request->getValidatedBodyParam('foo');
*
* // get validated $_POST['foo']['bar']
* $bar = Craft::$app->request->getValidatedBodyParam('foo.bar');
* ```
* ```twig
* {# get validated $_POST['foo'] #}
* {% set foo = craft.app.request.getValidatedBodyParam('foo') %}
*
* {# get validated $_POST['foo']['bar'] #}
* {% set bar = craft.app.request.getValidatedBodyParam('foo.bar') %}
* ```
*
* @param string $name The parameter name.
* @return string|null The parameter value
* @throws BadRequestHttpException if the param value doesn’t pass validation
* @see getBodyParam()
*/
public function getValidatedBodyParam(string $name): ?string
{
$value = $this->getBodyParam($name);
if ($value === null) {
return null;
}
$value = Craft::$app->getSecurity()->validateData($value);
if ($value === false) {
throw new BadRequestHttpException('Request contained an invalid body param');
}
return $value;
}
/**
* @inheritdoc
*/
public function getQueryParams(): array
{
if ($this->_encodedQueryParams === false) {
$this->setQueryParams($this->_utf8AllTheThings(parent::getQueryParams()));
$this->_encodedQueryParams = true;
}
return parent::getQueryParams();
}
/**
* Returns the named GET parameters, without the path parameter.
*
* @return array
* @since 5.0.0
*/
public function getQueryParamsWithoutPath(): array
{
$params = $this->getQueryParams();
if ($this->generalConfig->pathParam) {
unset($params[$this->generalConfig->pathParam]);
}
return $params;
}