|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace carono\checksum; |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
use DOMDocument; |
|
8
|
|
|
use DOMElement; |
|
9
|
|
|
use yii\base\Behavior; |
|
10
|
|
|
use yii\base\ViewEvent; |
|
11
|
|
|
use yii\web\View; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Class ChecksumBehavior |
|
15
|
|
|
* |
|
16
|
|
|
* @package carono\checksum |
|
17
|
|
|
*/ |
|
18
|
|
|
class ChecksumBehavior extends Behavior |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @return array |
|
22
|
|
|
*/ |
|
23
|
|
|
public function events() |
|
24
|
|
|
{ |
|
25
|
|
|
return [ |
|
26
|
|
|
View::EVENT_AFTER_RENDER => 'registerChecksumField' |
|
27
|
|
|
]; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param \yii\base\WidgetEvent $event |
|
32
|
|
|
*/ |
|
33
|
|
|
public function registerChecksumField(ViewEvent $event) |
|
34
|
|
|
{ |
|
35
|
|
|
/** |
|
36
|
|
|
* @var DOMElement $form |
|
37
|
|
|
* @var DOMElement $element |
|
38
|
|
|
* @var Request $request |
|
39
|
|
|
*/ |
|
40
|
|
|
if (!$event->output) { |
|
41
|
|
|
return; |
|
42
|
|
|
} |
|
43
|
|
|
$output = mb_convert_encoding($event->output, 'HTML-ENTITIES', 'UTF-8'); |
|
44
|
|
|
$document = new DOMDocument(); |
|
45
|
|
|
$document->loadHTML($output, LIBXML_NOERROR); |
|
46
|
|
|
$xpath = new \DOMXPath($document); |
|
47
|
|
|
$request = \Yii::$app->request; |
|
48
|
|
|
foreach ($xpath->query("//form[@method='post']") as $form) { |
|
49
|
|
|
$items = []; |
|
50
|
|
|
foreach ($xpath->query('//input|//select|//textarea', $form) as $element) { |
|
51
|
|
|
$items[] = $element->getAttribute('name'); |
|
52
|
|
|
} |
|
53
|
|
|
$items = array_unique($items); |
|
54
|
|
|
parse_str(implode('&', $items), $stack); |
|
55
|
|
|
$checksum = $request->setStack($stack); |
|
56
|
|
|
$input = $document->createElement('input'); |
|
57
|
|
|
$input->setAttribute('name', \Yii::$app->request->checksumParam); |
|
58
|
|
|
$input->setAttribute('value', $checksum); |
|
59
|
|
|
$input->setAttribute('type', 'hidden'); |
|
60
|
|
|
$form->appendChild($input); |
|
61
|
|
|
} |
|
62
|
|
|
$event->output = $document->saveHTML(); |
|
63
|
|
|
} |
|
64
|
|
|
} |