|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* SEOmatic plugin for Craft CMS 3.x |
|
4
|
|
|
* |
|
5
|
|
|
* A turnkey SEO implementation for Craft CMS that is comprehensive, powerful, |
|
6
|
|
|
* and flexible |
|
7
|
|
|
* |
|
8
|
|
|
* @link https://nystudio107.com |
|
9
|
|
|
* @copyright Copyright (c) 2017 nystudio107 |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace nystudio107\seomatic\helpers; |
|
13
|
|
|
|
|
14
|
|
|
use nystudio107\seomatic\Seomatic; |
|
15
|
|
|
|
|
16
|
|
|
use Craft; |
|
17
|
|
|
use craft\helpers\App; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @author nystudio107 |
|
|
|
|
|
|
21
|
|
|
* @package Seomatic |
|
22
|
|
|
* @since 3.3.11 |
|
23
|
|
|
*/ |
|
24
|
|
|
class Nonce |
|
25
|
|
|
{ |
|
26
|
|
|
// Constants |
|
27
|
|
|
// ========================================================================= |
|
28
|
|
|
|
|
29
|
|
|
const CSP_HEADERS = [ |
|
30
|
|
|
'Content-Security-Policy', |
|
31
|
|
|
'X-Content-Security-Policy', |
|
32
|
|
|
'X-WebKit-CSP', |
|
33
|
|
|
]; |
|
34
|
|
|
|
|
35
|
|
|
// Static Methods |
|
36
|
|
|
// ========================================================================= |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param string $nonce |
|
|
|
|
|
|
40
|
|
|
* @param string $cspDirective |
|
|
|
|
|
|
41
|
|
|
*/ |
|
42
|
|
|
private static function includeNonce(string $nonce, string $cspDirective) |
|
|
|
|
|
|
43
|
|
|
{ |
|
44
|
|
|
$cspNonceType = self::getCspNonceType(); |
|
45
|
|
|
if ($cspNonceType) { |
|
46
|
|
|
$cspValue = "{$cspDirective} 'nonce-$nonce'"; |
|
47
|
|
|
foreach(self::CSP_HEADERS as $cspHeader) { |
|
|
|
|
|
|
48
|
|
|
switch ($cspNonceType) { |
|
49
|
|
|
case 'tag': |
|
|
|
|
|
|
50
|
|
|
Craft::$app->getView()->registerMetaTag([ |
|
51
|
|
|
'httpEquiv' => $cspHeader, |
|
52
|
|
|
'value' => $cspValue, |
|
53
|
|
|
]); |
|
54
|
|
|
break; |
|
55
|
|
|
case 'header': |
|
|
|
|
|
|
56
|
|
|
Craft::$app->getResponse()->getHeaders()->add($cspHeader, $cspValue . ';'); |
|
57
|
|
|
break; |
|
58
|
|
|
default: |
|
|
|
|
|
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @return string|null |
|
67
|
|
|
*/ |
|
68
|
|
|
private static function getCspNonceType() |
|
|
|
|
|
|
69
|
|
|
{ |
|
70
|
|
|
$cspNonceType = !empty(Seomatic::$settings->cspNonce) ? strtolower(Seomatic::$settings->cspNonce) : null; |
|
71
|
|
|
|
|
72
|
|
|
return $cspNonceType; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @return string|null |
|
77
|
|
|
*/ |
|
78
|
|
|
private static function getNonce() |
|
|
|
|
|
|
79
|
|
|
{ |
|
80
|
|
|
$result = null; |
|
81
|
|
|
if (self::getCspNonceType() !== null) { |
|
82
|
|
|
try { |
|
83
|
|
|
$result = bin2hex(random_bytes(22)); |
|
84
|
|
|
} catch (\Exception $e) { |
|
85
|
|
|
// That's okay |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
return $result; |
|
90
|
|
|
} |
|
91
|
|
|
|
|
92
|
|
|
} |
|
93
|
|
|
|