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\base; |
||
13 | |||
14 | use nystudio107\seomatic\Seomatic; |
||
15 | |||
16 | /** |
||
17 | * @author nystudio107 |
||
18 | * @package Seomatic |
||
19 | * @since 3.3.11 |
||
20 | */ |
||
21 | abstract class NonceItem extends MetaItem implements NonceItemInterface |
||
22 | { |
||
23 | // Traits |
||
24 | // ========================================================================= |
||
25 | |||
26 | use NonceItemTrait; |
||
27 | |||
28 | // Public Methods |
||
29 | // ========================================================================= |
||
30 | |||
31 | /** |
||
32 | * @inheritdoc |
||
33 | */ |
||
34 | public function init() |
||
35 | { |
||
36 | parent::init(); |
||
37 | if (!empty(Seomatic::$settings->cspNonce)) { |
||
38 | $this->nonce = $this->generateNonce(); |
||
39 | } |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * @inheritdoc |
||
44 | */ |
||
45 | public function rules() |
||
46 | { |
||
47 | $rules = parent::rules(); |
||
48 | $rules = array_merge($rules, [ |
||
49 | [['nonce'], 'string'], |
||
50 | ]); |
||
51 | |||
52 | return $rules; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * @inheritdoc |
||
57 | */ |
||
58 | public function fields() |
||
59 | { |
||
60 | $fields = parent::fields(); |
||
61 | switch ($this->scenario) { |
||
62 | case 'render': |
||
63 | $fields = array_diff_key( |
||
64 | $fields, |
||
65 | array_flip([ |
||
66 | 'nonce', |
||
67 | ]) |
||
68 | ); |
||
69 | break; |
||
70 | } |
||
71 | |||
72 | return $fields; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * Generate a random "nonce" for use Content Security Policy implementations as per: |
||
77 | * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src |
||
78 | * |
||
79 | * @return string|null |
||
80 | */ |
||
81 | public function generateNonce() |
||
82 | { |
||
83 | $result = null; |
||
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
84 | try { |
||
85 | $result = bin2hex(random_bytes(22)); |
||
86 | } catch (\Exception $e) { |
||
87 | // That's okay |
||
88 | } |
||
89 | |||
90 | return $result; |
||
91 | } |
||
92 | } |
||
93 |